Mutable ๐ Immutable, Final
โ Mutable
can be modified after initialization
encapsulate: getter, setter, private, final field
need to synchronize access for multi thread
- String Builder
- Stirng Buffer
- java.util.Date
โ Immutable
cannot be modified after initialization
ํ ์์ญ์ ์ ์ฅ๋ ๊ฐ์ ๋ณ๊ฒฝํ ์ ์๋ ๊ฒ
preferred in multi threading, as it guarantees thread saftey
๊ณต์ ์์์ด Immutableํ๋ค๋ฉด ์ฌ๋ฌ๊ฐ์ ์ฐ๋ ๋๊ฐ ์ฝ๊ณ ์จ๋ ์ ๋ฐ๋๋๊น safe!
- int
- long
- float
- double
- String
- legacy, wrapper classes
I changed value from 1 to 3. Does this mean Integer is mutable?
1
2
3
4
Integer i=1;
i=3;
//๋ฐ๊ฟจ๋๋ฐ์??
// ์๋, ํ ์์ญ์ ์๋ก์ด ๊ฐ์ฒด๊ฐ ์์ฑ๋ ๊ฒ์ด๋ค.
NO. New object in heap created. and Integer with value 1 will be discared by GC
โ Final
์ด๊ธฐํ ์ดํ์ ๊ฐ ๋ณ๊ฒฝ ๋ถ๊ฐ
immutable
1
2
final Integer i=1;
i=3; //โ compile error.
https://www.geeksforgeeks.org/mutable-and-immutable-objects-in-java-1/
This post is licensed under CC BY 4.0 by the author.