내일배움캠프(Spring 7기)/특강

Java 동등성 / 동일성 세션

가지코딩 2025. 5. 2. 11:36
  • 일시 : 04/28(월) 14:00
  • 장소 : zoom
  • 진행 : 김기용 튜터님

1. 기본형 변수와 참조형 변수

(전체 구조)

public class Main {
    public static void main(String[] args) {
    
        CoffeeShop coffeeShop = new CoffeeShop("myCoffeeShop");
        Coffee coffeeA = coffeeShop.makeCoffee("hotCoffee", false);
        Coffee coffeeB = coffeeShop.makeCoffee("hotCoffee", false);
        Coffee coffeeC = coffeeShop.makeCoffee("iceCoffee", true);

        int a = 1;
        int b = 1;
        int c = 2;
    }
}

 

기본형 변수

  • ex. int, double, boolean 등
  • 기본형 변수는 값을 직접 저장하며 주로 Stack 메모리 영역에 저장된다.
public class Main {
    public static void main(String[] args) {
    
        int a = 1;
        int b = 1;
        int c = 2;
    }
}

 

 

참조형 변수

  • ex. String, int[], Coffee 등
  • 참조형 변수는 Heap 영역에 생성된 객체를 가리키는 변수이다.
  • 변수에는 객체의 주소가 저장되고 실제 객체는 Heap 에 존재한다.
public class Main {
    public static void main(String[] args) {
    
        Coffee coffeeA = coffeeShop.makeCoffee("hotCoffee", false);
        Coffee coffeeB = coffeeShop.makeCoffee("hotCoffee", false);
        Coffee coffeeC = coffeeShop.makeCoffee("iceCoffee", true);
    }
}


동등성과 동일성

동등성(Equality) - equals()

  • 논리적으로 같으면 같다고 판단.
  • 내용이 같은가를 비교
String a = new String("hello");
String b = new String("hello");
System.out.println(a.equals(b));  // true (내용이 같으므로 동등함)

 

 

동일성(Identity) - ==

  • 물리적으로 같으면 같다고 판단.
  • 메모리 주소가 같은가를 비교 (같은 객체인가?)
String a = new String("hello");
String b = new String("hello");
System.out.println(a == b);  // false (다른 객체이므로 동일하지 않음)