package String1;
public class String1 {
public static String upcase(String s){
return s.toUpperCase();
}
/**
* @param args
*/
public static void main(String [] args){
String q="helloworld";
System.out.println(q);
String qq=upcase(q);
System.out.println(qq);
System.out.println(q);
}
}
通过这个实例说明:每当把String对象作为方法的参数时,都会复制一份引用,而该引用所指的对象其实一直待在单一的物理位置上,从未动过。
对于一个方法而言,参数是为该方法提供信息的,而不是想让该方法改变自己的。
Sting对象是不可变的,你可以给一个String对象加任意多的别名。因为String对象具有只读性,所以指向它的任何引用都不可能改变它的值,因此,也就不会对其他的引用有什么影响。
package String1;
import java.util.Random;
public class String2 {
public static Random rand=new Random(47);
public String toString(){//重写toString()方法
StringBuffer result=new StringBuffer("[");
for(int i=0;i<25;i++){
result.append(rand.nextInt(100));//产生的随机数在[0-100)之间
result.append(",");
}
result.delete(result.length()-1, result.length());//删除最后一个随机数后的逗号
result.append("]");
return result.toString();
}
public static void main(String [] args){
String2 str=new String2();
System.out.print(str);
}
}
StringBuffer类对字符串的操作速度超出了String类