数组转字符串
1 public static void main(String[] args) { 2 int[] arr = {54,542,231,3,21}; 3 System.out.println(array2String(arr)); 4 } 5 public static String array2String(int[] arr) { 6 StringBuffer sb = new StringBuffer(); 7 sb.append("["); 8 for (int i = 0; i < arr.length; i++) { 9 if (i == arr.length - 1) { 10 sb.append(arr[i]).append("]"); 11 } else { 12 sb.append(arr[i]).append(", "); 13 } 14 } 15 return sb.toString(); 16 }
键盘录入字符串反转
1 import java.util.Scanner; 2 3 public class test5 { 4 5 public static void main(String[] args) { 6 Scanner sc = new Scanner(System.in); 7 String line = sc.nextLine(); 8 System.out.println(rev2String(line)); 9 } 10 11 public static String rev2String(String line) { 12 StringBuffer sb = new StringBuffer(line); 13 sb.reverse(); 14 return sb.toString(); 15 16 } 17 }
StringBuffer和StringBuilder的区别
StringBuffer是jbk1.0版本的,是线程安全的,效率低
StringBuilder是jdk1.5版本的,是线程不全安的,效率高
String和StringBuffer与StringBuilder的区别
String是一个不可变的字符序列
StringBuffer,StringBuilder 是可变的字符序列
参数传递
String作为参数传递
StringBuffer作为参数传递
基本数据类型的值传递,不改变其值
引用数据类型的值传递,改变其值
String类虽然是引用数据类型,但是他当作参数传递时和基本数据类型是一样的
1 public static void main(String[] args) { 2 String s = "hello"; 3 System.out.println(s); 4 change(s); 5 System.out.println(s); 6 7 StringBuffer sb = new StringBuffer(); 8 sb.append("hello "); 9 System.out.println(sb); 10 change(sb); 11 System.out.println(sb); 12 13 } 14 15 private static void change(StringBuffer sb) { 16 sb.append("kugou"); 17 } 18 19 public static void change(String s) { 20 s += "kugou"; 21 }