본문 바로가기
Programming/Java

equals 와 == 연산자

by d-e-v-j 2024. 7. 23.
반응형

Java 에서 equals와 == 연산자는 다른 목적과 기능을 갖고 있다.


1. == 연산자

두 변수가 같은 객체를 참조하는지 비교.

 

  • 기본 데이터 타입: == 연산자는 두 값이 같은지 비교
int a = 5;
int b = 5;
System.out.println(a == b);  // true
  • 객체 타입: == 연산자는 두 객체가 같은 객체를 참조하는지 비교
String str1 = new String("hello");
String str2 = new String("hello");
System.out.println(str1 == str2);  // false

2. equals 메서드

두 객체가 논리적으로 동일한지
  • 객체 타입: 두 객체의 내용을 비교
String str1 = new String("hello");
String str2 = new String("hello");
System.out.println(str1.equals(str2));  // true

 


주로 if문에 자주 쓰이는데 

헷갈려서 반대로 쓰는 경우가 없게하자.

728x90
반응형
LIST

'Programming > Java' 카테고리의 다른 글

TCP 소켓 통신  (0) 2024.07.30
Camel Case , Snake Case, Pascal Case 에 대하여  (0) 2024.07.26
Box Class  (2) 2024.07.22
Get 방식과 Post 방식  (0) 2024.07.18
Java 란 무엇일까?  (0) 2024.07.18