Mutable Vs Immutable


Have you ever heard this statement?
Strings are Immutable. Yes if you have ever learned Java. 😇

But do you know why?. Ok, Today we are going to find out.

When you take an object, it can be changed after it has assigned a value. Then it is mutable
Once an object is assigned a value, if it can't be changed Then we call it an Immutable Object

But if it is how a string is immutable. I remember I've changed the value of a string

String name = "Ravinda";
name = "Roshan"

See you don't get any trouble doing that. and if you print the value you get the value as Roshan here.
So what the hell are you saying???? 😡😡

Ok, Calm Down, I'll Explain by taking this example.


public class Student {

 private String nameOne;
 
 private void testThis()
 {
  nameOne = "Ravinda";
  System.out.println(nameOne.hashCode());
  
  nameOne = "Roshan";
  
  System.out.println(nameOne.hashCode());
 }
 
 public static void main(String[] args)
 {
  Student std = new Student();
  std.testThis();
 }
}

-1644869399
-1841337057


See It is not the same object. once you assign a value to it, it's a new object now. The below picture depicts what happened.

Now you can understand what happened actually. I'm not going to describe it further. You should understand it by now. 

Now let's change our code a bit. 

public class Student {

 private String nameOne;
 
 private void testThis()
 {
  nameOne = "Ravinda";
  System.out.println(nameOne.hashCode());
  
  String nameTwo = "Ravinda";
  
  System.out.println(nameTwo.hashCode());
 }
 
 public static void main(String[] args)
 {
  Student std = new Student();
  std.testThis();
 }
}

Come on.. guess the output. It's two fields referencing the same String object. Isn't it. 

So the two hash codes should be the same...

-1644869399
-1644869399 

The below diagram depicts what has happened here...






Comments

Popular Posts