关于引用类类型的赋值问题

JavaCoffee 2002-11-11 09:55:23
public class StringTest
{
public static void main(String args[])
{
String s="Hello";
String t=s;
System.out.println("s:" + s + ";t:" + t);

s="Hello World!";
System.out.println("s:" + s + ";t:" + t);
}
}
---------------
编译运行后,输出显示如下:
s:Hello;t:Hello
s:Hello World!;t:Hello

可“s”和“t”为引用String的类类型,为什么在值改变后,它们的值没有同时改变呢?
我感觉好象是系统为它们各自分配了一块内存,就象原始类型一样;这是怎么回事?

而下面这个就是真正的引用类型,难道是“String”这个类特殊吗?

class TestClass
{
int x=1;
}

public class ClassTest
{
public static void main(String args[])
{
TestClass tc1=new TestClass();
TestClass tc2;
tc2=tc1;

System.out.println("tc1.x:" + tc1.x);
System.out.println("tc2.x:" + tc2.x);

tc1.x=10;

System.out.println("tc1.x:" + tc1.x);
System.out.println("tc2.x:" + tc2.x);
}
}
-------------
编译运行显示:
tc1.x:1
tc2.x:1
tc1.x:10
tc2.x:10
...全文
85 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
xiachedan 2002-11-11
  • 打赏
  • 举报
回复
同意一楼的!!!
Winuxava 2002-11-11
  • 打赏
  • 举报
回复
String 本来就是特殊。
但是你的第一个例子一点都不“特殊”。
在java中,字符串(String)是不能改变的,所以当你 s="Hello World!"的
时候,java并不是把原来在“hello”那个地址的内容改为“Hello
World!”,而是新开辟一块内存存放 “hello world!”字符串,然后把 s
指向它。而 t 很显然还是指向“hello”,得到的答案也就很合理了。
JavaCoffee 2002-11-11
  • 打赏
  • 举报
回复
test

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧