Mutable and Immutable Objects

Mutable and Immutable words definition in English dictionary is “can change” and “cannot change” respectively. A mutable object can be changed after it’s created and an immutable object can’t.For example in java ,String is immutable object and StringBuilder is mutable. Let’s understand this through example


public class MutableVSImmutable {
    public static void main(String[] args) {

        System.out.println("------String  Output----------");
        String immuatble = "you can not change me, " +
            "if you change, new object will create ," +
            " check hashcode after change";

        System.out.print("hashcode before----> " + immuatble.hashCode());

        immuatble = immuatble + "This change will create new instance of immuatble ," +
            " old object you can not modify, " +
            "check new hashcode generated it means new object";

        System.out.println(" hashcode  after--->" + immuatble.hashCode());

        System.out.println("-----String Builder Output-----");

        StringBuilder muatble = new StringBuilder(
            "you can change me I will remain same object even after modification," +
            " check my hashcode");
        System.out.print("hashcode before---->" + muatble.hashCode());

        muatble = muatble
            .append("It will not create new object of mutable,check same hashcode,it means same object");

        System.out.println(" hashcode after---->" + muatble.hashCode());

Here is the output
------String  Output----------
 hashcode before----> -36412608 hashcode  after--->-163911166
 -----String Builder Output-----
 hashcode before---->1704856573 hashcode after---->1704856573