| Author |
Question Regarding Strings
|
Gary Farms
Greenhorn
Joined: Jul 31, 2002
Posts: 12
|
|
I understand that strings are immutable. Once a string is given a value, it's value can never change. However, when the following small program is run, it prints true. Why? Doesn't s2.toUpperCase() change s2's original value? Here's the program: class A { public static void main(String[] args) { String s1="HELLO WORLD"; String s2="hello world"; if(s1.equals(s2.toUpperCase()) == true) System.out.println("true"); } }
|
 |
James O'Dell
Greenhorn
Joined: Apr 29, 2002
Posts: 16
|
|
Gary, In your code "s2.toUpperCase()" returns a brand new String object. It doesn't change the original s2. --Jim
|
 |
Sumanta Mandal
Greenhorn
Joined: Sep 09, 2002
Posts: 4
|
|
|
s2.toUpperCase() does not change s2's original value. You may test this by printing System.out.print(s2); it after you invoke s2.toUpperCase(). In this case you are testing the equivalence with the returned value by the method toUpperCase().
|
 |
Anthony Villanueva
Ranch Hand
Joined: Mar 22, 2002
Posts: 1055
|
|
Originally posted by Gary Farms: Doesn't s2.toUpperCase() change s2's original value?
No. This method returns a new String that has the changes. Try this:
|
 |
Dave Landers
Ranch Hand
Joined: Jul 24, 2002
Posts: 401
|
|
No. s2.toUpperCase() returns a brand new string that is an upper case'ed copy of s2. s2 is unchanged. Try this: Even if you do s2 = s2.toUpperCase(); You still get a new object. The toUpperCase method creates a new String object and you assign that new reference to the thing called s2. And s2 now points to a different object. The original object (containing "hello world") is unchanged.
|
 |
Dirk Schreckmann
Sheriff
Joined: Dec 10, 2001
Posts: 7023
|
|
|
Wow! Four correct answers at the same time. Look out!
|
[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
|
 |
 |
I agree. Here's the link: jrebel
|
|
subject: Question Regarding Strings
|
|
|