|
|
|
1000 Java Tips ebook
|
|
 

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java
programming articles and tips. Please take your copy here.
Take your copy of free "Java Technology Screensaver"!. |
|
Java String is immutable, but why String Class has those methods...
|
JavaFAQ Home » Text processing

Question: I know from Java Lessons that String is immutable. But if all strings are immutable, why the String class has different method on strings modification?
For example look at this code snippet:
| Code: |
String lc = "lowercase";
lc.toUpperCase();
System.out.println(lc);
|
produces printout:
It seems very stupid to have methods that a priori will not work. Why the String class has such methods?
Answer: That's right - strings are immutable and every time when you write "String lc" you get new immutable string. Also methods which has return type String also create absolutelly new String.
So if you rewrite your code snippet like this:
| Code: |
String lc = "lowercase";
String new_lc = lc.toUpperCase();
System.out.println(new_lc);
|
you will get printout:
LOWERCASE
In my example you assign function's result to new string and it differs from original string. Probably you understand now how you should use methods from the String Class. You have to assign their's result to new String.
Even if you assign it to the same variable name, like this (!!!!!) it works:
| Code: |
lc = lc.toUpperCase();
|
You get printout:
LOWERCASE
It is interesting result, is not it?
Reference: class String description in SUN's API: String Printer Friendly Page
Send to a Friend
..
Search here again if you need more info!
|
|
|