Which of these is an immutable class in Java?

Java MCQ: Which of these is an immutable class in Java?

a) StringBuilder
b) String
c) int
d) CharSequence

Answer:

b) String

Explanation:

In Java, the String class is immutable, meaning that once a String object is created, its value cannot be changed. Immutability is a key characteristic of the String class, which ensures that String objects are safe to use in a multi-threaded environment and that they can be shared across different parts of a program without the risk of unexpected modifications.

When you perform an operation on a String, such as concatenation, Java does not modify the original String. Instead, it creates a new String object that contains the result of the operation. The original String remains unchanged. For example:


String str1 = "Hello";
String str2 = str1.concat(" World");
System.out.println(str1); // Outputs: Hello
System.out.println(str2); // Outputs: Hello World

In this example, the concat method creates a new String object str2 with the value “Hello World”, while str1 remains “Hello”. This immutability is crucial for performance optimization and security. For example, String objects are often used as keys in hash-based collections like HashMap, and their immutability ensures that the hash code remains consistent across the lifespan of the object.

On the other hand, classes like StringBuilder and StringBuffer are mutable, meaning their contents can be modified after they are created. These classes are often used when a lot of string manipulation is required, as they offer better performance for such operations. However, when thread safety and immutability are required, String is the preferred choice.

Reference links:

https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top