Post

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 image

โœ… 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.