Monday, 25 May 2020

What is mutable and immutable for string in java?

Immutable
------------
In java , immutable means , if we assign any value to string , means after creating an object that we can not re-assign a value to that particular staring object.

Example:

  1. public class ImMutableString {
  2.  
  3. final String n;
  4.  
  5. ImMutableString(String n) {
  6. this.n = n;
  7. }
  8.  
  9. public String getN() {
  10. return n;
  11. }
  12.  
  13. // this setter can modify the name
  14. public void setN(String n) {
  15. this.n = n;
  16. }
  17.  
  18. public static void main(String[] args) {
  19.  
  20. ImMutableString obj = new ImMutableString("Amit");
  21. System.out.println(obj.getN());
  22.  
  23. // update the name, this object is mutable
  24. obj.setName("Rahul");
  25. System.out.println(obj.getN());
  26.  
  27. }
  28. }

when we are going for print this value, we will get only output as a Amit not Rahul,
This is a concept of immutable.


mutable
--------------
In java , mutable means , if we assign any value to StringBuffer or StringBuilder , means after creating an object that we can re-assign a value to that particular staring object.

Example:

 
  1. public class MutableString {
  2.  
  3. private String n;
  4.  
  5. MutableString(String n) {
  6. this.n = n;
  7. }
  8.  
  9. public String getN() {
  10. return n;
  11. }
  12.  
  13. // this setter can modify the name
  14. public void setN(String n) {
  15. this.n = n;
  16. }
  17.  
  18. public static void main(String[] args) {
  19.  
  20. MutableString obj = new MutableString("Amit");
  21. System.out.println(obj.getN());
  22.  
  23. // update the name, this object is mutable
  24. obj.setName("Rahul");
  25. System.out.println(obj.getN());
  26.  
  27. }
  28. }

when we are going for print this value, we will get only output as a Amit and  Rahul both,
This is a concept of mutable.


    

Saturday, 9 December 2017

String object is immutable ,how?

String object is immutable ,how?

We create an object of String and initialize a value to it.
We create more than one reference variable of the same object and trying to assign a new value to it.
if we assign a value to any reference variable then value will be changed of all reference variables.
So java did not gave a permission to implement String Object in this way.


What is mutable and immutable for string in java?

Immutable ------------ In java , immutable means , if we assign any value to string , means after creating an object that we can not re-assi...