Skip to main content

Posts

Showing posts from March, 2018

Why String is immutable or final in Java?

Why string is immutable in java? If you are preparing for a java interview then this is one of the most interesting questions you will be encountered. Immutability means once created can not be changed. If someone changes the string object then new object will be created. For Java world, String Class is heart of Java language. If we talk about another programming languages then we can see that String is most widely used.  The string is immutable and final in Java and java runtime maintains a String constant pool that makes it a very very special class. There are multiple reasons that String is designed to be immutable and final in Java. Here I am going to explain you some of the reasons behind String immutablility. 1. String pool (String intern pool) is a special area in heap memory. When a string is created and the string already exists in the pool then the reference of the already existing string will be returned instead of creating new string object. The following code wi...