当前位置: 代码迷 >> J2SE >> java String有关问题
  详细解决方案

java String有关问题

热度:264   发布时间:2016-04-24 02:25:00.0
java String问题
package J2SE; 

public class Tux extends Thread { 
static String sName = "vandeleur"; 
public static void main(String[] args){ 
Tux t = new Tux(); 
t.piggy(sName); 
System.out.println(sName); 

public void piggy(String sName){ 
sName = sName + "wiggy"; 
start(); 

public void run(){ 
for(int i = 0; i < 4; i++){ 
sName = sName + " " + i; 



运行输出是vandeleur 


public class Foo { 
public static void main(String[] args){ 
StringBuffer a = new StringBuffer("A"); 
StringBuffer b = new StringBuffer("B"); 
operate(a, b); 
System.out.println(a + "," + b); 


String s = new String("Hello"); 
modify(s); 
System.out.println(s); 

int[] c = new int[1]; 
modify(c); 
System.out.println(c[0]); 

String foo = "base"; 
foo.substring(0,3); 
foo.concat("ket"); 
foo += "ball"; 
System.out.println(foo); 

  String str = "hello"; 
str.concat("world"); 
System.out.println(str.concat("world")); 


public static void operate(StringBuffer x, StringBuffer y){ 
y.append(x); 
y = x; 

public static void modify(String s){ 
s += "world!"; 


public static void modify(int[] a){ 
a[0] ++; 



程序运行输出是 
A,BA 
Hello 

baseball 
helloworld 

哪位仁兄跟我讲讲为什么吗?

------解决方案--------------------
Tux里面是因为java的值传递,lz可以看一下下面的链接http://www.blogjava.net/jiafang83/archive/2007/10/23/155412.html里的传递基本数据类型参数的例子
public void piggy(String sName)里的sName只是一个变量,与static sName无关,你可以把它改名而不会影响程序,所以更改sName不会改变static sName
start()是在piggy里调的,会执行run()方法,run里面sName是piggy里的sName,不会改变static sName。

------解决方案--------------------
Java code
//StringBuffer 引用传递---对象作为参数,传的是地址,//operate接了地址以后,把这个地址上的内容给改了,//外面再读这个地址上的值,就发现值改了StringBuffer a = new StringBuffer("A");  StringBuffer b = new StringBuffer("B");  operate(a, b);  System.out.println(a + "," + b); //值传递String s = new String("Hello");  modify(s);  System.out.println(s);  public static void modify(String s){  s += "world!";  }  //同上,值传递int[] c = new int[1];  modify(c);  System.out.println(c[0]); public static void modify(int[] a){  a[0] ++; } String foo = "base";  foo.substring(0,3);  //foo=foo.substring(0,3) 才会改值;foo.substring(0,3); 只会把改号的值放到临时变量里 foo.concat("ket"); //同上 foo += "ball";  //等同与foo = foo + "ball";所以值变了System.out.println(foo);  String str = "hello";  str.concat("world");  System.out.println(str.concat("world"));  //str没改,str.concat("world")放到临时变量,然后输出临时变量
  相关解决方案