Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

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 Go to all tips in Text processing


Bookmark and Share

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:

Code:

lowercase

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  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy