File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Question Regarding Strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Question Regarding Strings" Watch "Question Regarding Strings" New topic

Question Regarding Strings

Gary Farms

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)
James O'Dell

Joined: Apr 29, 2002
Posts: 16
In your code "s2.toUpperCase()" returns a brand new String object. It doesn't change the original s2.
Sumanta Mandal

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

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]
wood burning stoves
subject: Question Regarding Strings
It's not a secret anymore!