Re: If String is immutable, then why does this work?
"IOANNIS" <alien@ath.forthnet.gr> wrote in message
news:1146803151.869827@athnrd02...
George wrote:
Dear All,
My understanding is that String objects are immutable, thus you can not
change them but any changes will be saved in a different object of the
same class.
I have written the following simple programme, that converts the string
Hellow World to upper case and prints it.
public class Test{
public static void main(String[] args){
String str1=new String("Hello World");
str1 = str1.toUpperCase();
System.out.println(str1);
}
}
If str1 is immutable as a String object, then how can we save the results
of the conversion back to the same object? Should that not be a different
one? What am I missing here?
Thanks,
George
Computers are useless. They can only give you answers.
Pablo Picasso (1881-1973)
Both replies explain this issue.
It is basically a different object.
Here's a way to find it out.
Use the hashCode() method defined in Object class.
This is a very important method for the JVM. It returns an int that "sort
of" tries to identify uniquely all objects.
The idea is that if two objects are equal according the .equals() method
then they MUST have the same hashCode The opposite doesn't work. You can
have two different objects with the same hashCode() (usually by overriding
the method).
In your code extract you can do this!
public class Test{
public static void main(String[] args){
String str1=new String("Hello World");
System.out.println(str1+str1.hashCode());
str1 = str1.toUpperCase();
System.out.println(str1+ str1.hashCode());
}
}
Here's my sample output:
Hello World-862545276
HELLO WORLD568232580
This is a risky test, as it's possible for two different objects to have
the same hashcode. Much simpler is to use the == operator:
<untestedCode>
public class Test{
public static void main(String[] args){
String str1 = "Hello World";
System.out.println(str1 == str1.toUpperCase());
}
}
</untestedCode>
The above should print "false", indicating that they are indeed different
objects. In fact, you can go further and see that when you call
toUpperCase(), the original object was not modified (which is normal, since
it's immutable):
<untestedCode>
public class Test{
public static void main(String[] args){
String str1 = "Hello World";
System.out.println(str1);
System.out.println(str1.toUpperCase());
System.out.println(str1);
}
}
</untestedCode>
The above should print out:
<output>
Hello World
HELLO WORLD
Hello World
</output>
Thus showing that the original String has not been modified.
- Oliver