1. Introduction
In Java, objects are categorized based on their ability to be changed after they are created. Objects that cannot be changed after creation are called immutable, while objects that can be changed are known as mutable.
2. Key Points
1. Immutable objects do not allow their state to be modified after they have been created.
2. Mutable objects have fields that can be changed, methods that can alter the state, or both.
3. String objects in Java are immutable, whereas StringBuilder and StringBuffer are mutable.
4. Immutable objects are inherently thread-safe as they cannot be changed after creation.
3. Differences
Immutable | Mutable |
---|---|
State cannot be modified after creation. | State can be modified after creation. |
Typically do not provide setters. | Provide setters to change fields. |
Are thread-safe by default. | May require synchronization to be thread-safe. |
Can be good keys for a Map and safe to share between threads. | May not be suitable as Map keys if their states change and are not inherently safe to share between threads without proper synchronization. |
4. Example
// Example of Immutable object - String
String s = "Hello";
s.concat(" World"); // This does not change the String referenced by 's'
System.out.println(s); // Will print "Hello"
// Example of Mutable object - StringBuilder
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // This changes the internal state of the StringBuilder object
System.out.println(sb); // Will print "Hello World"
Output:
Hello Hello World
Explanation:
1. The String object 's' does not change when concat is called, because Strings are immutable. Any change produces a new String object.
2. The StringBuilder object 'sb' changes its internal state with the append method, showing mutability as it allows changes to its state after creation.
5. When to use?
- Use immutable objects when you need objects that do not change over time, which simplifies development and debugging, and enhances performance by reducing the need for synchronization.
- Mutable objects are useful when you have data that is expected to change frequently or when performance is a concern, such as in high-volume environments where object creation (and subsequent garbage collection) would be too costly.
Comments
Post a Comment
Leave Comment