Java 中对String的操作

 

 

Java里数字转字符串前面自动补0的实现。

/** * Java里数字转字符串前面自动补0的实现。 * */ public class TestStringFormat { public static void main(String[] args) { int youNumber = 1; // 0 代表前面补充0 // 4 代表长度为4 // d 代表参数为正数型 String str = String.format("%04d", youNumber); System.out.println(str); // 0001 } }  

 

当参数是String类型,而且在参数中改变了它的值的情况

public class TestString { public static void main(String[] args){ String str1 = "hello"; str1 = str1 +"world"; System.out.println("String str+/"world/": "+str1); String str2 = "hello"; add(str2); System.out.println("String funcation: "+str2); StringBuffer str3 = new StringBuffer("hello"); add(str3); System.out.println("StringBuffer funcation: "+str3); } public static void add(String str){ str += "world"; } public static void add(StringBuffer strb){ strb.append("world"); } } 

结果:

String str+"world": helloworld

String funcation: hello

StringBuffer funcation: helloworld

 

由此可见:当String的变量作为参数传递到函数中,即使函数中改变了它的值,但对函数外是没有影响。

(这个是String的特例,其他引用类型一般都会产生影响的)

 

 

 

 

你可能感兴趣的:(java,String,Class)