+ 3
Differentiate mutable vs immutable in Java. Please give detail.
Also, what is the use of this, if any?
1 Respuesta
+ 2
A mutable object, variable or reference is exactly what you are thinking: that is, capable of change.
A lot of things in Java are mutable, it is so because OOP focuses on data as objects, and objects can change attributes over time. If you lit a candle, it would have an attribute height that would diminish as the candle burned. As such, a variable name height would be, you guessed, a mutable type of data.
An immutable type of data is constant. It does not account for changes and actually, trying to change it would cause a lot of problems. For example, the color blue will always be the color blue.Even if you mixed it with, say, yellow, and no longer saw blue, if you ever wanted to think about the color blue it would still be blue regardless of you using blue or not. The color blue is Immutable.
As such, in Java, immutable data is normally reserved for constants (using the final modifier), so that it CANNOT be changed anywhere in the code. It stays as a stable reference of something. If you used a constant color.BLUE, even if you made code that mixed color.BLUE and color.YELLOW, you'd make a new color, but not change neither color.BLUE or color.YELLOW. If you needed these colors, they'd still be both blue and yellow.