Immutable string in java - java

i have basic confusion .
String s2=new String("immutable");
System.out.println(s2.replace("able","ability"));
s2.replace("able", "abled");
System.out.println(s2);
In first print statement it is printing immutability but it is immutable right? why so?
and
in next printing statement it is not replaced> any answers welcome..

System.out.println(s2.replace("able","ability"));
In above line, A new string returned and printed.
Because String#replce()
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
s2.replace("able", "abled");
It does the replace operation but,not assigned the result back.So the original String remains the same.
You see the result if you assign the result.
like
String replacedString = s2.replace("able", "abled");
System.out.println(replacedString );
or
s2= s2.replace("able", "abled");
System.out.println(s2);
Update:
When you write line
System.out.println(s2.replace("able","ability"));
That s2.replace("able","ability") resolved and returned String passed to that function.

The replace(String,String) method returns a new String. The second call to replace() returns the replacement but you don't assign it to anything, then when you print out the immutable s2 again, you see the unchanged value.

String#replace returns the resulting String without modifying the original (immutable) String value...
You will get the same result if you assign the result to another String, for example
String s2=new String("immutable");
String s3 = s2.replace("able","ability");
System.out.println(s3);
s2.replace("able", "abled");
System.out.println(s2);
Will give you the same out put...

Lets look at line - 2:
System.out.println(s2.replace("able","ability"));
This will print immutability, this is because
s2.replace("able","ability")
will return another string, which is fed like:
System.out.println(tempStr);
But in third statement,
s2.replace("able", "abled");
There is no assignment to another variable, so a string is returned but not assigned to any variable. Hence lost, but s2 remain as is.

Immutable objects are simply objects whose state (the object's data) cannot change after construction
Your code s2.replace("able","ability"), it return a new String and nothing happen for s2.
And because replace function return a new String, so you can print the result by System.out.println(s2.replace("able","ability"));
String is Immutable, but String have a lot of methods that you can use as Rvalue
See also:
Immutable objects
RValue
String#replace

String s2=new String("immutable");
1)When ever we create a String as above a new object is created.If we are trying to modify it, a new object is created with the content we are providing and our String s2 is not modified.
2)If we need the modified value in the s2 object then replace the above code as..
String s2=new String("immutable");//Creates a new object with content 'immutable'
System.out.println(s2.replace("able","ability"));//creates a new object with new content as //immutability
s2=s2.replace("able", "abled");//Here also it creates a new object,Since we are assigning it //to s2,s2 will be pointing to newly created object.
System.out.println(s2);//prints the s2 String value.

Related

Pass-by-value (StringBuilder vs String) [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 7 years ago.
I do not understand why System.out.println(name) outputs Sam without being affected by the method's concat function, while System.out.println(names) outputs Sam4 as a result of the method's append method. Why is StringBuilder affected and not String? Normally, calling methods on a reference to an object affects the caller, so I do not understand why the String result remains unchanged. Thanks in advance
public static String speak(String name) {
name = name.concat("4");
return name;
}
public static StringBuilder test(StringBuilder names) {
names = names.append("4");
return names;
}
public static void main(String[] args) {
String name = "Sam";
speak(name);
System.out.println(name); //Sam
StringBuilder names = new StringBuilder("Sam");
test(names);
System.out.println(names); //Sam4
}
Because when you call speak(name);, inside speak when you do
name = name.concat("4");
it creates a new object because Strings are immutable. When you change the original string it creates a new object,I agree that you are returning it but you are not catching it.
So essentially what you are doing is :
name(new) = name(original) + '4'; // but you should notice that both the names are different objects.
try
String name = "Sam";
name = speak(name);
Of course now I think there is no need to explain why it's working with StringBuilder unless if you don't know that StringBuilder is mutable.
Looking at the Javadoc for String, one will read that
[...] String objects are immutable [...].
This means concat(String) does not change the String itself, but constructs a new String.
StringBuilders, on the other hand, are mutable. By calling append(CharSequence), the object itself is mutated.
Because String is immutable and hence String#concat does not modify the original String instance, it only returns a new String while the original is left unmodified, while StringBuilder is mutable and the change is reflected in the StringBuilder instance passed as parameter.
Okay, what is speak method doing?
First of all,
name.concat("4");
creates new object, which is equal to name, concatenated with "4".
So, the line
name = name.concat(4);
redefines local (for speak method) variable name.
Then you return the reference to this new value with
return name;
So, the original variable, passed within method is not modified, but the method returns modified value.
In the test method you actually modify variable without modifying the reference (the StringBuilder class is mutable, so variable if this type can be modified).
Then we can see another question arising: why StringBuilder.append returns value, where it can seem redundant. The answer to this question lies in the description of "builder" pattern, for which it is the usual way of implementing modification methods. See wikipedia on Builder pattern.
String is immutable in java. As soon as you invoke concat method on name. A new string is created and while you are playing with the old reference in System.out.println(name).If you want to use the modified string you should explicitly return the reference.
While StringBuilder is mutable and it returns the same reference always.
When you invoke speak(name) it computes the new value, but discards it.
If you replace it with
name = speak(name);
the result will be the one you expect.
With the StringBuilder, the object you pass is mutable: so
names.append(names);
changes the state of the current object (it also returns a reference to the same object, which is just a convenience to allow you to write code like names.append(...).append(...) etc.). So in the case of the StringBuilder, the object you are referencing when you call the method has actually changed, hence you see the changes.
In your method speak, the concat method returns a new String, the original object it was called on is unchanged (strings are immutable). As documented:
If the length of the argument string is 0, then this String object is returned. Otherwise, a String object is returned that represents a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string.
Calling name.concat("4") is the equivalent of name + "4".
In your test method the append method modifies the content of the StringBuilder. As documented:
The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.
In your main method both name and names are still the same object as before the method call, but the content of name is unchanged as strings are immutable, while the content of names has been changed.
If instead you had used the return values of both methods, then you would have the result you were expecting.
First of all, String is an immutable class in Java. An immutable class is simply a class whose instances cannot be modified. All information in an instance is initialized when the instance is created and the information can not be modified.
Second, in java parameters are sent by values and not by reference.
In your method 'test' you don't need names = names.append("4"), instead names.append("4") will be enough .
If you check java docs for String object, you will see that most of the methods there, including concat, will generate a new String.
So to have on output Sam4 also for the String, you will need in main method to have this name = speak(name).
String
String is immutable ( once created can not be changed )object . The
object created as a String is stored in the Constant String Pool .
Every immutable object in Java is thread safe ,that implies String is
also thread safe . String can not be used by two threads
simultaneously. String once assigned can not be changed.
String demo = " hello " ; // The above object is stored in constant
string pool and its value can not be modified.
demo="Bye" ; //new "Bye" string is created in constant pool and
referenced by the demo variable // "hello" string still
exists in string constant pool and its value is not overrided but we
lost reference to the "hello"string
StringBuilder
StringBuilder is same as the StringBuffer , that is it stores the
object in heap and it can also be modified . The main difference
between the StringBuffer and StringBuilder is that StringBuilder is
also not thread safe. StringBuilder is fast as it is not thread safe
.
For more details check this
Conclusion:
You don't need to re-assign the value again to StringBuilder as it is already a reference
test method should be
public static void test(StringBuilder names) {
names.append("4");
}
but speak should be
String name = "Sam";
name = speak(name);

Are Strings overwritable?

My textbook says a String is not over-writable or immutable, i.e, once you enter the value of a String you can't change it. But today when I was running the following code, the String str gets muted as the compiler does not give any error and the new String a's value is successfully entered into str.
class Test
{
static void main()
{
String str = "something";
String a ="anything";
str = a; //str is being over written without any error
System.out.println(str);
}
}
The output is : anything
So, is my book wrong ?
If my book is not wrong please give an example to show that Strings are immutable
The book is correct. When you say str = a you are not changing anything about the String 'something'. You should distinguish between str and something, they are not the same. "something" here is a String object in memory, whereas str is just the reference to that string. Same with the reference a.
When you say:
str = a
You are not changing something, you are in fact saying, "change the reference str to point to whatever the reference a is pointing to." The Strings remain the same, the references change.
On a similar note, this is why you may see in your book that concatenating Strings is expensive, as doing something like:
str = str + a
Would again not be changing the existing Strings, but instead creating a new String object which is equal to the concatenation of the String that the reference str is referring to and the String that the reference a is referring to.
You need to understand what immutable means. In your scenario you are just changing references.
str = a;
will make both a and str to point to String "anything". The Text Book is correct. String is immutable and can not be overwritten. If you check the JavaDoc for String. Most of the methods return a String. This is because any operation in a String will not change that String object but will result in a new String being created. Effectively you can never change a String after you create it. By Change I mean append new characters, remove characters without a new String object being created.
As many answers already point out is that you only change references. Immutable means you cannot change the string itself. for example you do:
String a = "anything";
System.out.println(a); // -> anything
a.substring(3);
System.out.println(a); // -> anything : this is because the String itself is
// immutable.
a = a.substring(3);
System.out.println(a); // -> thing : this is what immutable means to edit a string
// you must reassign it or assign it
// to a new variable
You're changing the reference of str to a. So str effectively becomes a's value.
they are just pointer to that string. so when you do str =a , you just assign pointer of a to str.
The contents of the String object is not being changed. What's happening is that a new String object is being assigned to the variable. The old String object still exists in memory but you just can't refer to it any more. The 'str' variable now refers to the String object containing "anything" but the String containing "something" still exists as it did before. Try assigning 'str' to another variable first and then, after assigning 'a' to 'str', check that other variable and you'll see that it still says "something", proving that that String was not overwritten.
In Java, the value of a variable is never an object, but a reference. Relevant to your case, the type String on the a variable says the variable is allowed to contain only references to String objects.
You can update the value in the variable, sure; but that won't touch the object it is referring to.
Strings are constant; their values cannot be changed after they are created.
The String object is created and stored on constant pool or literal pool.
In your case, when you say,
String str="something"; // An object is created on constant pool with value 'something' and reference 'str' is pointing to it.
String a="anything"; // An object is created on constant pool with value 'anything' and reference 'a' is pointing to it.
And when you do, str=a; then 'str' actually start pointed to 'a', but the object with value as 'something' remains on constant pool with the same value.

How to access the object of String pool

Can we able to access the object in String pool which is does not not have any reference.
Here is code :
String str ="abc";
str.toUpperCase();
System.out.println(str); // System.out.println(str.toUpperCase());
Output : abc
Here I am performing the toUpperCase() operation on str. In String pool one object will be created for this str.toUpperCase();. Can we able to access this object.? if yes how?
This is where java documentation is used .... Refer http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#toUpperCase()
str.toUpperCase() returns a string converted to upper case, you have to assign it to another string variable or do a self assignment, so you can access it later.
String str ="abc"; // 1
str.toUpperCase(); // 2
System.out.println(str); // 3
in above code
First line will create new Object of String with value "abc" and assign it to the reference variable str.
Second line will create the new Object of String because String class is immutable so original Object str will not change. but here we are not assigning the new object which is created in line 2 so it will be lost somewhere in Heap area.
That is why in line 3 printing value is "abc".
if you want to use the new Object created by str.toUpperCase() than have to assign that in a new reference variable.
or
alternative option is update the original String Object like this
str = str.toUpperCase();
but in above operation, the original Object str containing the value "abc" will be lost in the Heap area !!!!!
You can find details about working with String by example here.

Strings [= new String vs = ""]

So my question is in relation to declaring and assigning strings.
The way I usually declare strings is by doing the following:
String s1 = "Stackoverflow";
And then if I ever need to change the value of s1 I would do the following:
s1 = "new value";
Today I found another way of doing it and declaring a string would go like:
String s2 = new String("Stackoverflow");
And then changing the value would be:
s2 = new String("new value");
My question is what is the difference between the two or is it simply preferential. From looking at the code the fourth line
s2 = new String ("new value");
I'm assuming that doing that would create a new memory location and s2 would then point to it so I doubt it would be used to change the value but I can see it being used when declaring a string.
From the javadoc :
Initializes a newly created String object so that it represents the
same sequence of characters as the argument; in other words, the newly
created string is a copy of the argument string. Unless an explicit
copy of original is needed, use of this constructor is unnecessary
since Strings are immutable.
So no, you have no reason not to use the simple literal.
Simply do
String s1 = "Stackoverflow";
Historically, this constructor was mainly used to get a lighter copy of a string obtained by splitting a bigger one (see this question). Now, There's no normal reason to use it.
String s1 = "Stackoverflow"; // declaring & initializing s1
String s2 = new String("Stackoverflow"); // declaring & initializing s2
in above cases you are declaring & initializing String object.
The difference between
//first case
String s2 = new String("new String"); // declaring & initializing s2 with new memory
// second case
s2 = "new String" // overwriting previous value of s2
is in the first case you are creating a new object, i-e; allocating memory for a new object which will be refrenced by s2. The previous address to which s2 was pointing/referencing hasn't released the memory yet which will be gc when the program ends or when system needs to.
The good programming practice (second case) is to initialize an object once, and if you want to change its value either assign null to it and then allocate new memory to it or in case of string you can do like this
s2= "new String";
String s1 = "Stackoverflow";
This line will create a new object in the String pool if it does not exist already. That means first it will first try searching for "Stackoverflow" in the String pool, if found then s1 will start pointing to it, if not found then it will create a new object and s1 will refer to it.
String s2 = new String("Stackoverflow");
Will always create a new String object, no matter if the value already exists in the String pool. So the object in the heap would then have the value "Stackovrflow" and s2 will start pointing to it.
s2 = new String("new value");
This will again create a new Object and s2 will start pointing to it. The earlier object that s2 was pointing to is not open for garbage collection (gc).
Let me know if this helps.
The main difference is that the constructor always creates a totally new instance of String containing the same characters than the original String.
String s1 = "Stackoverflow";
String s2 = "Stackoverflow";
Then s1 == s2 will return true
String s1 = "Stackoverflow";
String s2 = new String("Stackoverflow");
Then s1 == s2 will return false
Just using the double quotes option is often better:
With a constructors you might create two instance of String.
Easier to read and less confusing
#user2612619 here i want to say is .. when ever ur creating object with "new" operator it always falls in heap memory . so wenever u have same content but different objects than also it will create new objects on heap by this u cant save memory ....
but in order to save memory java people brought concept of immutable where we can save memory .. if u r creating a different object with same content .. string will recognize dat difference and creates only one object with same content and points the two references to only one object ..
i can solve ur doubts from this figure ..
case 1:
String s = new String("stackoverflow");
String s1 = new String("stackoverflow");
as they are two different objects on heap memory with two different values of hashcode .. so s==s1 (is reference comparison) it is false .. but s.equals(s1) is content comparison ..so it is true
case 2:
String s = "stackoverflow";
String s1 = "stackoverflow";
here objects fall in scp(string constant pool memory)
same object for two different refernces .. so hashcode also same .. same reference value .. so s==s1 is true here [u can observe from figure clearly]
s.equals(s1) is true as content comparison.. this is very beautiful concept .. u will love it wen u solve some problems ... all d best
Creating String object Directly:
String s1 = "Hip Hop"
will create a string object but first JVM checks the String constant or literal pool and if the string does not exist, it creates a new String object “Hip jop” and a reference is maintained in the pool. The variable s1 also refers the same object. Now, if we put a statement after this:
String s2 = "Hip Hop"
JVM checks the String constant pool first and since the string already exists, a reference to the pooled instance is returned to s2.
System.out.println(s1==s2) // comparing reference and it will print true
java can make this optimization since strings are immutable and can be shared without fear of data corruption.
Creating String Object using new
String s3 = new String("Hip Hop")
For new keyword, a String object is created in the heap memory wither or not an equal string object already exists in the pool and s3 will refer to the newly created one.
System.out.println(s3==s2) // two reference is different, will print false
String objects created with the new operator do not refer to objects in the string pool but can be made to using String’s intern() method. The java.lang.String.intern() returns an interned String, that is, one that has an entry in the global String literal pool. If the String is not already in the global String literal pool, then it will be added to the pool.
String s4 = s3.intern();
Systen.out.println(s4 == s2); // will print `true` because s4 is interned,
//it now have the same reference to "Hip Hop" as s2 or s1
But try:
Systen.out.println(s4 == s3) // it will be false,
As the reference of s4, s2 and s1 is the reference to the pooled instance while s3 is referring to the created object in heap memory.
use of new for creting string:
prior to OpenJDK 7, Update 6, Java String.susbtring method had potential memory leak. substring method would build a new String object keeping a reference to the whole char array, to avoid copying it. You could thus inadvertently keep a reference to a very big character array with just a one character string. If we want to have minimal strings after substring, we use the constructor taking another string :
String s2 = new String(s1.substring(0,1));
The issue is resolved in JDK 7 update 6. So No need to create string with new any more for taking advantage provided by String literal pool mechanism.
Referance:
String literal pool
using new to prevent memory leak for using substring

Immutability of Strings in Java

Consider the following example.
String str = new String();
str = "Hello";
System.out.println(str); //Prints Hello
str = "Help!";
System.out.println(str); //Prints Help!
Now, in Java, String objects are immutable. Then how come the object str can be assigned value "Help!". Isn't this contradicting the immutability of strings in Java? Can anybody please explain me the exact concept of immutability?
Edit:
Ok. I am now getting it, but just one follow-up question. What about the following code:
String str = "Mississippi";
System.out.println(str); // prints Mississippi
str = str.replace("i", "!");
System.out.println(str); // prints M!ss!ss!pp!
Does this mean that two objects are created again ("Mississippi" and "M!ss!ss!pp!") and the reference str points to a different object after replace() method?
str is not an object, it's a reference to an object. "Hello" and "Help!" are two distinct String objects. Thus, str points to a string. You can change what it points to, but not that which it points at.
Take this code, for example:
String s1 = "Hello";
String s2 = s1;
// s1 and s2 now point at the same string - "Hello"
Now, there is nothing1 we could do to s1 that would affect the value of s2. They refer to the same object - the string "Hello" - but that object is immutable and thus cannot be altered.
If we do something like this:
s1 = "Help!";
System.out.println(s2); // still prints "Hello"
Here we see the difference between mutating an object, and changing a reference. s2 still points to the same object as we initially set s1 to point to. Setting s1 to "Help!" only changes the reference, while the String object it originally referred to remains unchanged.
If strings were mutable, we could do something like this:
String s1 = "Hello";
String s2 = s1;
s1.setCharAt(1, 'a'); // Fictional method that sets character at a given pos in string
System.out.println(s2); // Prints "Hallo"
Edit to respond to OP's edit:
If you look at the source code for String.replace(char,char) (also available in src.zip in your JDK installation directory -- a pro tip is to look there whenever you wonder how something really works) you can see that what it does is the following:
If there is one or more occurrences of oldChar in the current string, make a copy of the current string where all occurrences of oldChar are replaced with newChar.
If the oldChar is not present in the current string, return the current string.
So yes, "Mississippi".replace('i', '!') creates a new String object. Again, the following holds:
String s1 = "Mississippi";
String s2 = s1;
s1 = s1.replace('i', '!');
System.out.println(s1); // Prints "M!ss!ss!pp!"
System.out.println(s2); // Prints "Mississippi"
System.out.println(s1 == s2); // Prints "false" as s1 and s2 are two different objects
Your homework for now is to see what the above code does if you change s1 = s1.replace('i', '!'); to s1 = s1.replace('Q', '!'); :)
1 Actually, it is possible to mutate strings (and other immutable objects). It requires reflection and is very, very dangerous and should never ever be used unless you're actually interested in destroying the program.
The object that str references can change, but the actual String objects themselves cannot.
The String objects containing the string "Hello" and "Help!" cannot change their values, hence they are immutable.
The immutability of String objects does not mean that the references pointing to the object cannot change.
One way that one can prevent the str reference from changing is to declare it as final:
final String STR = "Hello";
Now, trying to assign another String to STR will cause a compile error.
Light_handle I recommend you take a read of Cup Size -- a story about variables and Pass-by-Value Please (Cup Size continued). This will help a lot when reading the posts above.
Have you read them? Yes. Good.
String str = new String();
This creates a new "remote control" called "str" and sets that to the value new String() (or "").
e.g. in memory this creates:
str --- > ""
str = "Hello";
This then changes the remote control "str" but does not modify the original string "".
e.g. in memory this creates:
str -+ ""
+-> "Hello"
str = "Help!";
This then changes the remote control "str" but does not modify the original string "" or the object that the remote control currently points to.
e.g. in memory this creates:
str -+ ""
| "Hello"
+-> "Help!"
Lets break it into some parts
String s1 = "hello";
This Statement creates string containing hello and occupy space in memory i.e. in Constant String Pool and and assigned it to reference object s1
String s2 = s1;
This statement assigns the same string hello to new reference s2
__________
| |
s1 ---->| hello |<----- s2
|__________|
Both references are pointing to the same string so output the same value as follows.
out.println(s1); // o/p: hello
out.println(s2); // o/p: hello
Though String is immutable, assignment can be possible so the s1 will now refer to new value stack.
s1 = "stack";
__________
| |
s1 ---->| stack |
|__________|
But what about s2 object which is pointing to hello it will be as it is.
__________
| |
s2 ---->| hello |
|__________|
out.println(s1); // o/p: stack
out.println(s2); // o/p: hello
Since String is immutable Java Virtual Machine won't allow us to modify string s1 by its method. It will create all new String object in pool as follows.
s1.concat(" overflow");
___________________
| |
s1.concat ----> | stack overflow |
|___________________|
out.println(s1); // o/p: stack
out.println(s2); // o/p: hello
out.println(s1.concat); // o/p: stack overflow
Note if String would be mutable then the output would have been
out.println(s1); // o/p: stack overflow
Now you might be surprised why String has such methods like concat() to modify. Following snippet will clear your confusion.
s1 = s1.concat(" overflow");
Here we are assigning modified value of string back to s1 reference.
___________________
| |
s1 ---->| stack overflow |
|___________________|
out.println(s1); // o/p: stack overflow
out.println(s2); // o/p: hello
That's why Java decided String to be a final class Otherwise anyone can modify and change the value of string.
Hope this will help little bit.
The string object that was first referenced by str was not altered, all that you did was make str refer to a new string object.
The String will not change, the reference to it will. You are confusing immutability with the concept of final fields. If a field is declared as final, once it has been assigned, it cannot be reassigned.
Regarding the replace part of your question, try this:
String str = "Mississippi";
System.out.println(str); //Prints Mississippi
String other = str.replace("i", "!");
System.out.println(str); //still prints Mississippi
System.out.println(other); // prints M!ss!ss!pp!
Though java tries to ignore it, str is nothing more than a pointer. This means that when you first write str = "Hello";, you create an object that str points to. When you reassign str by writing str = "Help!";, a new object is created and the old "Hello" object gets garbage collected whenever java feels like it.
Immutability implies that the value of an instantiated object cannot change, you can never turn "Hello" into "Help!".
The variable str is a reference to an object, when you assign a new value to str you aren't changing the value of the object it references, you are referencing a different object.
String class is immutable, and you can not change value of immutable object.
But in case of String, if you change the value of string than it will create new string in string pool and than your string reference to that value not the older one. so by this way string is immutable.
Lets take your example,
String str = "Mississippi";
System.out.println(str); // prints Mississippi
it will create one string "Mississippi" and will add it to String pool
so now str is pointing to Mississippi.
str = str.replace("i", "!");
System.out.println(str); // prints M!ss!ss!pp!
But after above operation,
one another string will be created "M!ss!ss!pp!"
and it will be add to String pool. and
now str is pointing to M!ss!ss!pp!, not Mississippi.
so by this way when you will alter value of string object it will create one more object and will add it to string pool.
Lets have one more example
String s1 = "Hello";
String s2 = "World";
String s = s1 + s2;
this above three line will add three objects of string to string pool.
1) Hello
2) World
3) HelloWorld
For those wondering how to break String immutability in Java...
Code
import java.lang.reflect.Field;
public class StringImmutability {
public static void main(String[] args) {
String str1 = "I am immutable";
String str2 = str1;
try {
Class str1Class = str1.getClass();
Field str1Field = str1Class.getDeclaredField("value");
str1Field.setAccessible(true);
char[] valueChars = (char[]) str1Field.get(str1);
valueChars[5] = ' ';
valueChars[6] = ' ';
System.out.println(str1 == str2);
System.out.println(str1);
System.out.println(str2);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
Output
true
I am mutable
I am mutable
Use:
String s = new String("New String");
s.concat(" Added String");
System.out.println("String reference -----> "+s); // Output: String reference -----> New String
If you see here I use the concat method to change the original string, that is, "New String" with a string " Added String", but still I got the output as previous, hence it proves that you can not change the reference of object of String class, but if you do this thing by StringBuilder class it will work. It is listed below.
StringBuilder sb = new StringBuilder("New String");
sb.append(" Added String");
System.out.println("StringBuilder reference -----> "+sb);// Output: StringBuilder reference -----> New String Added String
Like Linus Tolvards said:
Talk is cheap. Show me the code
Take a look at this:
public class Test{
public static void main(String[] args){
String a = "Mississippi";
String b = "Mississippi";//String immutable property (same chars sequence), then same object
String c = a.replace('i','I').replace('I','i');//This method creates a new String, then new object
String d = b.replace('i','I').replace('I','i');//At this moment we have 3 String objects, a/b, c and d
String e = a.replace('i','i');//If the arguments are the same, the object is not affected, then returns same object
System.out.println( "a==b? " + (a==b) ); // Prints true, they are pointing to the same String object
System.out.println( "a: " + a );
System.out.println( "b: " + b );
System.out.println( "c==d? " + (c==d) ); // Prints false, a new object was created on each one
System.out.println( "c: " + c ); // Even the sequence of chars are the same, the object is different
System.out.println( "d: " + d );
System.out.println( "a==e? " + (a==e) ); // Same object, immutable property
}
}
The output is
a==b? true
a: Mississippi
b: Mississippi
c==d? false
c: Mississippi
d: Mississippi
a==e? true
So, remember two things:
Strings are immutable until you apply a method that manipulates and creates a new one (c & d cases).
Replace method returns the same String object if both parameters are the same
String is immutable. Which means that we can only change the reference.
String a = "a";
System.out.println("String a is referencing to "+a); // Output: a
a.concat("b");
System.out.println("String a is referencing to "+a); // Output: a
a = a.concat("b");
System.out.println("String a has created a new reference and is now referencing to "+a); // Output: ab
In Java, objects are generally accessed by references. In your piece of code str is a reference which is first assigned to "Hello" (an automatic created object or fetched from constant pool) and then you assigned another object "Help!" to same reference. A point to note is the reference is the same and modified, but objects are different. One more thing in your code you accessed three objects,
When you called new String().
When you assigned "hello".
When you assigned "help!".
Calling new String() creates a new object even if it exists in string pool, so generally it should not be used. To put a string created from new String () into string pool you can try the intern() method.
I hope this helps.
Immutability I can say is that you cannot change the String itself. Suppose you have String x, the value of which is "abc". Now you cannot change the String, that is, you cannot change any character/s in "abc".
If you have to change any character/s in the String, you can use a character array and mutate it or use StringBuilder.
String x = "abc";
x = "pot";
x = x + "hj";
x = x.substring(3);
System.out.println(x);
char x1[] = x.toCharArray();
x1[0] = 's';
String y = new String(x1);
System.out.println(y);
Output:
hj
sj
Or you can try:
public class Tester
{
public static void main(String[] args)
{
String str = "Mississippi";
System.out.println(str); // prints Mississippi
System.out.println(str.hashCode());
str = str.replace("i", "!");
System.out.println(str); // prints M!ss!ss!pp!
System.out.println(str.hashCode());
}
}
This will show how the hashcode changes.
String is immutable means that you cannot change the object itself, but you can change the reference to the object. When you called a = "ty", you are actually changing the reference of a to a new object created by the String literal "ty". Changing an object means to use its methods to change one of its fields (or the fields are public and not final, so that they can be updated from outside without accessing them via methods), for example:
Foo x = new Foo("the field");
x.setField("a new field");
System.out.println(x.getField()); // prints "a new field"
While in an immutable class (declared as final, to prevent modification via inheritance)(its methods cannot modify its fields, and also the fields are always private and recommended to be final), for example String, you cannot change the current String but you can return a new String, i.e:
String s = "some text";
s.substring(0,4);
System.out.println(s); // still printing "some text"
String a = s.substring(0,4);
System.out.println(a); // prints "some"
Here immutability means that instance can point to other reference but the original content of the string would not be modified at the original reference.
Let me explain by first example given by you.
First str is pointing to "Hello" ,its Ok upto this.
Second time its pointing to "Help!".
Here str started pointing to "Help!" and the reference of "Hello" string is lost and we can not get that back.
In fact when str would try to modify the existing content,then another new string will be generated and str will start to point at that reference.
So we see that string at original reference is not modified but that is safe at its reference and instance of object started pointing at different reference so immutability is conserve.
Super late to the answer, but wanted to put a concise message from author of the String class in Java
Strings are constant; their values cannot be changed after they are
created. String buffers support mutable strings. Because String
objects are immutable they can be shared.
It can be derived from this documentation that anything that changes string, returns different object (which could be new or interned and old).
The not so subtle hint about this should come from the function signature.
Think about it, 'Why did they make a function on an object return an object instead of status?'.
public String replace(char oldChar, char newChar)
Also one more source which makes this behaviour explicit (From replace function documentation)
Returns a new string resulting from replacing all occurrences of
oldChar in this string with newChar.
Source: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace(char,%20char)
author Lee Boynton
author Arthur van Hoff
author Martin Buchholz
author Ulf Zibis
Source: JavaDoc of String.
The Object string - methods itself is made to be "immutable".
This action produces no changes: "letters.replace("bbb", "aaa");"
But assigning data does cause changes to the Strings content to change:
letters = "aaa";
letters=null;
System.out.println(letters);
System.out.println(oB.hashCode());
System.out.println(letters);
letters = "bbbaaa";
System.out.println(oB.hashCode());
System.out.println(letters);
//The hashcode of the string Object doesn't change.
If HELLO is your String then you can't change HELLO to HILLO. This property is called immutability property.
You can have multiple pointer String variable to point HELLO String.
But if HELLO is char Array then you can change HELLO to HILLO. Eg,
char[] charArr = 'HELLO';
char[1] = 'I'; //you can do this
Programming languages have immutable data variables so that it can be used as keys in key, value pair.
I would explain it with simple example
consider any character array : e.g. char a[]={'h','e','l','l','o'};
and a string :
String s="hello";
on character array we can perform operations like printing only last three letters using iterating the array;
but in string we have to make new String object and copy required substring and its address will be in new string object.
e.g.
***String s="hello";
String s2=s.substrig(0,3);***
so s2 will have "hel";
String in Java in Immutable and Final just mean it can't be changed or modified:
Case 1:
class TestClass{
public static void main(String args[]){
String str = "ABC";
str.concat("DEF");
System.out.println(str);
}
}
Output: ABC
Reason: The object reference str is not changed in fact a new object
"DEF" is created which is in the pool and have no reference at all
(i.e lost).
Case 2:
class TestClass{
public static void main(String args[]){
String str="ABC";
str=str.concat("DEF");
System.out.println(str);
}
}
Output: ABCDEF
Reason: In this case str is now referring to a new object "ABCDEF"
hence it prints ABCDEF i.e. previous str object "ABC" is lost in pool with no reference.
Because String is immutable so changes will not occur if you will not assign the returned value of function to the string.so in your question assign value of swap function  returned value to s.
s=swap(s, n1, n2) ;then the value of string s will change.
I was also getting the unchanged value when i was writing the program to get some permutations string(Although it is not giving all the permutations but this is for example to answer your question)
Here is a example.
> import java.io.*;  public class MyString { public static void
> main(String []args)throws IOException {  BufferedReader br=new
> BufferedReader(new InputStreamReader(System.in));  String
> s=br.readLine().trim(); int n=0;int k=0;  while(n!=s.length()) {
> while(k<n){  swap(s,k,n); System.out.println(s); swap(s,k,n); k++; }
> n++; } }  public static void swap(String s,int n1,int n2) { char temp;
> temp=s.charAt(n1); StringBuilder sb=new StringBuilder(s);
> sb.setCharAt(n1,s.charAt(n2)); sb.setCharAt(n2,temp); s=sb.toString();
> } }
but i was not getting the permuted values of the string from above code.So I assigned the returned value of the swap function to the string and got changed values of string. after assigning the returned value i got the permuted values of string.
/import java.util.*; import java.io.*; public class MyString { public static void main(String []args)throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 
String s=br.readLine().trim(); int n=0;int k=0; 
while(n!=s.length()){ while(k<n){ s=swap(s,k,n); 
System.out.println(s); s=swap(s,k,n); k++; } n++; } } 
public static String swap(String s,int n1,int n2){
char temp; temp=s.charAt(n1); StringBuilder sb=new StringBuilder(s); sb.setCharAt(n1,s.charAt(n2)); sb.setCharAt(n2,temp); s=sb.toString(); return s; } }
public final class String_Test {
String name;
List<String> list=new ArrayList<String>();
public static void main(String[] args) {
String_Test obj=new String_Test();
obj.list.add("item");//List will point to a memory unit- i.e will have one Hashcode value #1234
List<String> list2=obj.list; //lis1 also will point to same #1234
obj.list.add("new item");//Hashcode of list is not altered- List is mutable, so reference remains same, only value in that memory location changes
String name2=obj.name="Myname"; // name2 and name will point to same instance of string -Hashcode #5678
obj.name = "second name";// String is Immutable- New String HAI is created and name will point to this new instance- bcoz of this Hashcode changes here #0089
System.out.println(obj.list.hashCode());
System.out.println(list2.hashCode());
System.out.println(list3.hashCode());
System.out.println("===========");
System.out.println(obj.name.hashCode());
System.out.println(name2.hashCode());
}
}
Will produce out put something like this
1419358369
1419358369
103056
65078777
Purpose of Immutable object is that its value should not be altered once assigned.
It will return new object everytime you try to alter it based on the implementation.
Note: Stringbuffer instead of string can be used to avoid this.
To your last question :: u will have one reference , and 2 strings in string pool..
Except the reference will point to m!ss!ss!pp!

Categories