Creating Immutable Classess and Strings in Java

Creating Immutable Classess and Strings in Java

In java, string objects are immutable. Immutable simply means can’t be changed or modified.

Let's try to understand the immutability concept by the example given below:

package strings;
 
public class ImmutableEx {
 
      public static void main(String[] args) {
            // TODO Auto-generated method stub
            String s="Hemant"; 
            s.concat("Varhekar");//concat() method appends the string at the end 
            System.out.println(s);//will print Hemant because strings are immutable objects
                                          // which means s reference variable still refers to "Hemant" not to "Hemant Varhekar".
 
 
      }
 
}
 
  

As you can see in the above output We got the output : Hemant instead "Hemant Varhekar". which means s reference variable still holds value "Hemant" not to "Hemant Varhekar".

In order to concat 2 strings and used explicitly used single object to reference them from heap we need to explicitly assign it to reference variable.

In order to perform that & we need to use add the reference keyword and use the string modifier like concat accordingly.

Below is a sample code for your reference.

package strings;
 
public class ImmutableEx1 {
 
      public static void main(String[] args) {
            // TODO Auto-generated method stub
               String s="Hemant"; 
               s=s.concat(" Varhekar");  //reference of variable.
               System.out.println(s); 
      }
     
 
}
 
  

Output : Hemant Varhekar


Let’s talk about Immutable Classes in Java.


What is Immutable class :

Let’s go a bit nurdy here , Immutable classes mean’s object’s in the entire class itself can not be changed.

Writing or creating immutable classes in Java is becoming popular day by day, because of concurrency and multithreading advantage provided by immutable objects. Immutable objects offers several benefits over conventional mutable object, especially while creating concurrent Java application. Immutable object not only guarantees safe publication of object’s state, but also can be shared among other threads without any external synchronization. In fact JDK itself contains several immutable classes like StringInteger and other wrapper classes.

The best example of immutable classes is string & StringBuffer.Since the string is the immutable class here, any change in the existing string object will results in another string ie creating substring from string.

While in a case of mutable objects like string buffer, any modification can be done on the object itself. No new objects are created.

Example :

Here is complete code example of writing immutable class in Java. I have followed simplest approach and all rules for making a class immutable, including it making class final to avoid putting immutability at risk due to Inheritance and Polymorphism.


package strings;
 
// As you can see we have specified keyword final
//which means this class immutable & it's state can not be changed once created.
 
package strings;
 
// As you can see we have specified keyword final
//which means this class immutable & it's state can not be changed once created.
 
/**
 * @author HEMANT
 *
 */
/**
 * @author HEMANT
 *
 */
public final class Contracts {
      private final String name;
    private final String mobile;
 
 
    public Contracts(String name, String mobile) {
        this.name = name;
        this.mobile = mobile;
    }
 
    public String getName(){
        return name;
      //  System.out.println(name);
    }
 
    public String getMobile(){
        return mobile;
    }
 
 
    public static void main(String[] args) {
      Contracts s = new Contracts("hemant","1234566");
      System.out.println(s.getName());
      System.out.println(s.getMobile());
    }
   
 
}
 
  

Output:

hemant

1234566

Immutable objects also have certain drawbacks. To ensure immutability, methods in immutable classes may end-up creating numerous copies of the objects. For instance, every time getName () is called on the Contracts class, this method creates a copy of the Point object and returns it. For this reason, we may need to define a mutable version of the class as well, for example, a mutable Contracts class.

The String class is useful in most scenarios, if we call methods such as trim, concat, or substring in a loop, these methods are likely to create numerous (temporary) String objects. Fortunately, Java provides StringBuffer and StringBuilder classes that are mutable. They provide functionality similar to String, but you can mutate the contents within the objects. Hence, depending on the context, we can choose to use String class or one of StringBuffer or StringBuilder classes

That’s all for Immutable Strings and class . If you have any question regarding these give me a shootout in the comments section ..

See ya in the next article!!!!

#JavaTutorialForBegineer #ImmutableClass #ImmutableString




要查看或添加评论,请登录

Hemant Varhekar的更多文章

社区洞察

其他会员也浏览了