This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes string immutable? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "string immutable?" Watch "string immutable?" New topic
Author

string immutable?

jacob deiter
Ranch Hand

Joined: Apr 02, 2008
Posts: 576
I read a article in that String class are immutable.
String a=�a�;
String h=�h�;

String class is immutable, that means that one an instance of String class is created, the string it contais cannot be changed, only reference will change to point to a
different string.

If two references point to same instance then If I change the values of in one, does not affect other reference?
Duc Vo
Ranch Hand

Joined: Nov 20, 2008
Posts: 254
I read a article in that String class are immutable.
.....
If two references point to same instance then If I change the values of in one, does not affect other reference?


They are immutable, how do you change the value in one instance?


“Everything should be as simple as it is, but not simpler.” Albert Einstein
jacob deiter
Ranch Hand

Joined: Apr 02, 2008
Posts: 576
then what is use of

String a=�a�;
String h=�h�;

than

String a=new String("a");
String h=new String("h");
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

We don't use the second one.
jacob deiter
Ranch Hand

Joined: Apr 02, 2008
Posts: 576
why could you please in detail.I read a book ,this is not given clearly.
Can you assist in this >?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14194
    
  20

String objects are immutable. What that means is that you cannot change the contents of a String object. You can have to variables referencing the same String object, but since the String object itself cannot be changed, you can't get strange effects.

Because String objects are immutable, the Java compiler can safely implement an optimization trick. If you write a program in which you use the same literal string more than once, for example like this:

Then the Java compiler is smart enough to create only one String object with the content "Hello", and make the variables 'one' and 'two' refer to that single String object. This is good, because it saves memory.

If you do this:

Then you are explicitly creating two String objects with the same content "Hello". This is less memory-efficient.

There's no use ever to using new String("...") in a Java program, so you should never write code that does that.
[ November 21, 2008: Message edited by: Jesper Young ]

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
 
GeeCON Prague 2014
 
subject: string immutable?