Variables

1. Member variable (Instance variable)

Declared in a class, but outside a method

Class A {

 String name; 

}                  
  • Class의 일원

  • Class μ•ˆμ—μ„œ μ„ μ–Έλœ λ³€μˆ˜

  • Instanceκ°€ 생성될 λ•Œ 생성됨

  • Instance λ³€μˆ˜μ˜ 값을 μ½μ–΄μ˜€κ±°λ‚˜, μ €μž₯ν•˜λ €λ©΄ Instanceλ₯Ό λ¨Όμ € 생성해야 함!

  • μ΄ˆκΈ°κ°’μ„ μ„€μ •ν•˜μ§€ μ•ŠμœΌλ©΄ μžλ™ default μ΄ˆκΈ°ν™”κ°€ 됨

    ex) String name = null; ν•  ν•„μš” μ—†μŒ!

2. Local variable

Public Static Void main(~~~) {  

	String name;

}
  • ν•¨μˆ˜μ˜ 일원

  • method(ν•¨μˆ˜) μ•ˆμ—μ„œ μ„ μ–Έλœ λ³€μˆ˜

    • method λ‚΄μ—μ„œλ§Œ μ‚¬μš© κ°€λŠ₯

  • methodκ°€ μ‹€ν–‰ 될 λ•Œ memoryλ₯Ό ν• λ‹Ή λ°›μœΌλ©°, λλ‚˜λ©΄ μ†Œλ©Έλ˜μ–΄ μ‚¬μš©ν•  수 μ—†λ‹€

  • default μ΄ˆκΈ°ν™”κ°€ μ•ˆλ¨

    ex) String name = null; ν•΄μ€˜μ•Ό 함

3. Class variable (Static variable)

Declared with the static keyword in a class, but outside a method, constructor, or block

  • Instance variable에 static만 뢙이면 됨

  • μΈμŠ€ν„΄μŠ€ λ³€μˆ˜λŠ” 각각 κ³ μœ ν•œ 값을 κ°€μ§€μ§€λ§Œ, 클래슀 λ³€μˆ˜λŠ” λͺ¨λ“  μΈμŠ€ν„΄μŠ€κ°€ κ³΅ν†΅λœ 값을 κ³΅μœ ν•˜κ²Œ 됨

    • ν•œ 클래슀의 λͺ¨λ“  μΈμŠ€ν„΄μŠ€λ“€μ΄ 곡톡적인 값을 κ°€μ Έμ•Όν•  λ•Œ 클래슀 λ³€μˆ˜λ‘œ μ„ μ–Έν•œλ‹€!

  • ν΄λž˜μŠ€κ°€ λ‘œλ”©λ  λ•Œ μƒμ„±λ˜μ–΄(= λ©”λͺ¨λ¦¬μ— λ”± ν•œλ²ˆλ§Œ 올라감) μ’…λ£Œ 될 λ•Œ κΉŒμ§€ μœ μ§€λœλ‹€

  • public 을 뢙이면 같은 ν”„λ‘œκ·Έλž¨ λ‚΄μ—μ„œ μ–΄λ””μ„œλ“  μ ‘κ·Όν•  수 μžˆλŠ” μ „μ—­ λ³€μˆ˜κ°€ 됨

  • μΈμŠ€ν„΄μŠ€ λ³€μˆ˜μ˜ 접근법과 λ‹€λ₯΄κ²Œ μΈμŠ€ν„΄μŠ€λ₯Ό μƒμ„±ν•˜μ§€ μ•Šκ³  ν΄λž˜μŠ€μ΄λ¦„ & ν΄λž˜μŠ€λ³€μˆ˜λͺ…을 ν†΅ν•΄μ„œ μ ‘κ·Ό

Null Assign을 ν•˜λŠ” 이유 (from docs.oracle)

: Assign null to Variables That Are No Longer Needed

Explicitly assigning a null value to variables that are no longer needed helps the garbage collector to identify the parts of memory that can be safely reclaimed. Although Java provides memory management, it does not prevent memory leaks or using excessive amounts of memory.

An application may induce memory leaks by not releasing object references. Doing so prevents the Java garbage collector from reclaiming those objects, and results in increasing amounts of memory being used. Explicitly nullifying references to variables after their use allows the garbage collector to reclaim memory.

One way to detect memory leaks is to employ profiling tools and take memory snapshots after each transaction. A leak-free application in steady state will show a steady active heap memory after garbage collections.

λ‹€ μ“°κ³  λ‚œ μžμ›μ€ null assign을 ν•΄μ•Όν•œλ‹€!

-> null assign을 ν•˜μ§€ μ•ŠμœΌλ©΄ μžμ›μ„ 많이 λ¨Ήμ–΄μ„œ μ„±λŠ₯이 μ•ˆμ’‹μ•„μ§€κΈ° λ•Œλ¬Έ!

But, null assign ν•œλ‹€κ³  λͺ¨λ“  μžμ›μ΄ λ°˜λ‚©λ˜λŠ”κ²Œ μ•„λ‹ˆλ‹€

input.close();

Input = null;

-> μ΄λ ‡κ²Œ ν•΄μ•Ό λ‹€ λ°˜λ‚© ν•  수 있음

Last updated