Immutable class, String, StringBuffer, and StringBuilder


A class their instances never changes after constructions is called immutable class. That means each and every time new unmodifiable instance is created.
In Java String is an immutable class.
String sb=new String ("Hello");
An instance of String class which is referring by “sb” reference variable that containing “Hello” cannot be modifies. String not provides method for modification. If you want to create modifiable string then java provides StringBuffer and StringBuilder class, which are described below.
The String class represents character strings. All string literals in Java programs, such as "Hello", are implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created
For example:
     String str = "Hello";
Is equivalent to:
     char data[] = { 'H','e','l','l','o'};
     String str = new String (data);
 But don’t confuse
       String sb="Hello";
       sb="Hi";
       System.out.println(sb);
Output:Hi
As I have written above, all string literals in Java programs, such as "Hello", are implemented as instances of this class.  So, again for literal “Hi” a new instance is created in java.
That means for both literal “Hello” and “Hi” different instance is created. “sb” is constant.
StringBuffer
A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
The principal operations on a StringBuffer are the append and insert. Which are overloaded so as to accept data of any type?
Example:
StringBuffer sb=new StringBuffer("Hello");
 sb.append("Indian");
 System.out.println(sb);
Output: HelloIndian
StringBuffer sb=new StringBuffer("Hello");
 sb.insert(0,"Indian");
 System.out.println(sb);
Output: IndianHello
StringBuilder
A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization.
The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type
StringBuilder sb=new StringBuilder("Hello");
sb.append("Indian");
System.out.println(sb);
Output: HelloIndian
StringBuilder sb=new StringBuilder("Hello");
 sb.insert(0,"Indian");
 System.out.println(sb);
Output: IndianHello
Guideline for Creating an Object Immutable
1.Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
 2.Make all fields final and private.
 3.Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
 4.If the instance fields include references to mutable objects, don't allow those objects to be changed: ◦Don't provide methods that modify the mutable objects.
 ◦Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods
As I have written it is guideline so, not necessary all mutable class follow all rules.
public final class Calculation {

    private final int num1,num2;
    private Calculation(int n1,int n2) {
        num1=n1;
        num2=n2;
    }
    public static Calculation getInstance(int n1, int n2) {
      
        return new Calculation(n1,n2);
    }
    public int sum(){
      
        return num1+num2;
    }

    public int getNum1() {
        return num1;
    }

    public int getNum2() {
        return num2;
    }

}

Now, Test this class

public class Main {

    public static void main(String[] args) {
        Calculation cal = Calculation.getInstance(10, 20);
        int x = cal.sum();
        System.out.println(x);
        changeValue(cal.getNum1(), cal.getNum2());
        int y = cal.sum();
        System.out.println(y);
    }
    public static void changeValue(int num1, int num2) {
        num1 = 15;
        num2 = 18;
    }
}
Output:
30
30

 So, no way you can modify an instance of Calculation which is referring by “cal” reference variable.

“If this post is helpful for you and you were confused earlier then must provide comment and also write a topic in which you have some confusion”
J2EE Guru



No comments:

Post a Comment