Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question Regarding Strings

 
Gary Farms
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gary,
In your code "s2.toUpperCase()" returns a brand new String object. It doesn't change the original s2.
--Jim
 
Sumanta Mandal
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wow! Four correct answers at the same time. Look out!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic