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.