Mutable objects
Immutable objects are like variables. We not modify them once they are created. They are not final in nature. Examples: StringBuffer, StringBuilder, java.util.Date etc.
Example
class MutableStudent{ private String name; MutableStudent(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public class Main { public static void main(String[] args) { MutableStudent mutableStudent = new MutableStudent("Jai"); System.out.println("Student Name: " + mutableStudent.getName()); mutableStudent.setName("Sandy"); System.out.println("Student Name after modification: " + mutableStudent.getName()); } } |
Output
Student Name: Jai Student Name after modification: Sandy |
Immutable objects
Immutable objects are like constants. We cannot modify them once they are created. They are final in nature. Examples: String, Wrapper class objects like Integer, Long and etc.
Example
final class ImmutableStudent{ private String name; MutableStudent(String name) { this.name = name; } public String getName() { return name; } } public class Main { public static void main(String[] args) { MutableStudent mutableStudent = new MutableStudent("Jai"); System.out.println("Student Name: " + mutableStudent.getName()); //mutableStudent.setName("Sandy"); No setter method, so no modification } } |
Java interview questions on String Handling
- Why string objects are immutable in java?
- How many ways we can create the string object?
- Why java uses the concept of string literal?
- String vs StringBuffer vs StringBuilder in java
- How to create immutable class in java?
- What is the purpose of toString() method in java?
- Is string a keyword in java?
- Is string a primitive type or derived type?
- What is string constant pool in java?
- What are mutable and immutable objects in java?
- What is string intern in java?
- Can we call string class methods using string literals?