0

Why String class is immutable in Java, as everytime we call certain methods on a String reference variable , new String is created?

  public class Test {

       public static void main(String [] args) {

            String s = "abc";
            s.toUpperCase(); // new String is created here.
            System.out.println(s);// prints abc instead of ABC
    }
}

2 Answers2

1

Why String class is immutable in Java, as everytime we call certain methods on a String reference variable , new String is created?

No. It's not because of creating new String. Go in reverse. Why each time time you are getting a new String ?

String backed by an char array which is final inside String class. So once you create a String, the char array never altered after the String object creation. That is the actual reason behind it.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

There are types in java, whose instances are immutable. except for String, there are BigInteger, BigDecimal and Integer, Long, Double, Float, Short, Byte .(those wrapper types).. even Boolean Those instances are immutable. If you do something changes on those instance, those instance's self won't be changed.

E.g.

Long num = 7L;
num = num + 10L;

after you run those two lines, the num would be 17, naturally. But after you ran the 2nd line, the num would be a new Long instance. Same as String

another example:

Boolean b = true;
b = false;

the b in 1st and 2nd lines are different instances too.

Immutable objects are relatively easier to design, implement and use. I guess that's why java applied the immutable design.

Kent
  • 189,393
  • 32
  • 233
  • 301