๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿš€ Development/Java

[Java ์ž๋ฐ”] == equals ์ฐจ์ด

by Jay Din 2023. 7. 17.
728x90
๋ฐ˜์‘ํ˜•

Java์—์„œ int์™€ boolean๊ณผ ๊ฐ™์€ ์ผ๋ฐ˜์ ์ธ ๋ฐ์ดํ„ฐ ํƒ€์ž…์˜ ๋น„๊ต๋Š” == ์ด๋ผ๋Š” ์—ฐ์‚ฐ์ž๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋น„๊ตํ•œ๋‹ค.

ํ•˜์ง€๋งŒ String์ฒ˜๋Ÿผ Class์˜ ๊ฐ’์„ ๋น„๊ตํ•  ๋•Œ๋Š” equals() ๋ผ๋Š” ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๋น„๊ตํ•œ๋‹ค.

์ด์— ๋Œ€ํ•ด ์ข€ ๋” ์ž์„ธํžˆ ํŒŒํ—ค์ณ๋ณด์ž.

 

String ๋ณ€์ˆ˜ ์ƒ์„ ์‹œ ์ฃผ์†Œ ํ• ๋‹น

String ๋ณ€์ˆ˜๋ฅผ ์ƒ์„ฑํ•  ๋•Œ๋Š” ๋‘๊ฐ€์ง€ ๋ฐฉ๋ฒ•์ด ์žˆ๋‹ค.

1. ๋ฆฌํ„ฐ๋Ÿด(literal)์„ ์ด์šฉํ•œ ๋ฐฉ์‹
2. new ์—ฐ์‚ฐ์ž๋ฅผ ์ด์šฉํ•œ ๋ฐฉ์‹
๋ฆฌํ„ฐ๋Ÿด(literal) string constant pool*์ด๋ผ๋Š” ์˜์—ญ์— ์กด์žฌ
new๋ฅผ ํ†ตํ•ด ์ƒ์„ฑ Heap ์˜์—ญ์— ์กด์žฌ
String str1 = "apple";	// ๋ฆฌํ„ฐ๋Ÿด ์ด์šฉ
String str2 = new String("banana");	// new ์—ฐ์‚ฐ์ž ์ด์šฉ

๋ฆฌํ„ฐ๋Ÿด(literal) ์ž‘๋™ ์›๋ฆฌ

String์„ ๋ฆฌํ„ฐ๋Ÿด๋กœ ์„ ์–ธํ•˜๋ฉด ๋‚ด๋ถ€์ ์œผ๋กœ String์˜ intern()๋ฉ”์„œ๋“œ๊ฐ€ ํ˜ธ์ถœ๋œ๋‹ค.

intern() ๋ฉ”์„œ๋“œ๋Š” ์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด์ด string constant pool์— ์กด์žฌํ•˜๋Š”์ง€ ๊ฒ€์ƒ‰ํ•œ๋‹ค.

์กด์žฌํ•˜๋ฉด ๊ทธ ์ฃผ์†Œ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๊ณ  ์—†๋‹ค๋ฉด string constant pool์— ๊ฐ’์„ ๋„ฃ๊ณ  ์ƒˆ๋กœ์šด ์ฃผ์†Œ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

 

๋ฐ˜์‘ํ˜•

== equals ์ฐจ์ด

== ์ฃผ์†Œ๊ฐ’ ๋น„๊ต
equals() ๋Œ€์ƒ์˜ ๊ฐ’ ์ž์ฒด ๋น„๊ต

String.java, StringLatin1.java

์œ„ ์ฝ”๋“œ๋ฅผ ๋ณด๋ฉด,

== ํ‚ค์›Œ๋“œ๋กœ ๊ฐ์ฒด๊ฐ€ ๊ฐ–๋‹ค๋ฉด ๋” ํ™•์ธํ•˜์ง€ ์•Š๊ณ  true๋ฅผ ๋ฆฌํ„ดํ•œ๋‹ค.

๊ฐ์ฒด๊ฐ€ ๋‹ค๋ฅธ ๊ฒฝ์šฐ ์ธ์ž๊ฐ€ String์ด๋ผ๋ฉด ๋ฌธ์ž์—ด์„ ๋น„๊ตํ•˜์—ฌ ๋™์ผํ•œ์ง€์— ๋Œ€ํ•œ ๊ฒฐ๊ณผ๋ฅผ ๋ฆฌํ„ดํ•˜๊ณ  ์žˆ๋‹ค.

 

Call by value, Call by reference ์ฐจ์ด

๊ธฐ๋ณธ ํƒ€์ž…์˜ int, charํ˜• ๋“ฑ์€ Call by Value ํ˜•ํƒœ๋กœ ๊ธฐ๋ณธ์ ์œผ๋กœ ๋Œ€์ƒ์— ์ฃผ์†Œ๊ฐ’์„ ๊ฐ€์ง€์ง€ ์•Š๋Š” ํ˜•ํƒœ๋กœ ์‚ฌ์šฉ๋œ๋‹ค.

ํ•˜์ง€๋งŒ String์€ ์ผ๋ฐ˜์ ์ธ ํƒ€์ž…์ด ์•„๋‹ˆ๋ผ ํด๋ž˜์Šค๋‹ค.

ํด๋ž˜์Šค๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ Call by Reference ํ˜•ํƒœ๋กœ ์ƒ์„ฑ ์‹œ ์ฃผ์†Œ๊ฐ’์ด ๋ถ€์—ฌ๋œ๋‹ค.

์ฆ‰, Stringํƒ€์ž…์„ ์„ ์–ธํ–ˆ์„ ๋•Œ ๊ฐ™์€ ๊ฐ’์„ ๋ถ€์—ฌํ•˜๋”๋ผ๋„ ์„œ๋กœ๊ฐ„์˜ ์ฃผ์†Œ๊ฐ’์ด ๋‹ค๋ฅธ ๊ฒƒ์ด๋‹ค.

== ๋กœ ๋ฌธ์ž์—ด์„ ๋น„๊ต ํ•˜์ง€ ์•Š๋Š” ์ด์œ 

public class HelloWorld {
	public static void main(String[] args) {
		String s1 = "HelloWorld";
		String s2 = new String("HelloWorld");
		
		if(s1 == s2) {
			System.out.print("O");
		}else {
			System.out.print("X");
		}
    }
}
// ์‹คํ–‰๊ฒฐ๊ณผ
// X
๋ฐ˜์‘ํ˜•

 

 

๋ฌธ์ž์—ด equals() ๋น„๊ต

public class HelloWorld {
	public static void main(String[] args) {
		String s1 = "HelloWorld";
		String s2 = new String("HelloWorld");
		
		if(s1.equals(s2)) {
			System.out.print("O");
		}else {
			System.out.print("X");
		}
    }
}
// ์‹คํ–‰๊ฒฐ๊ณผ
// O

String ํด๋ž˜์Šค์•ˆ์— ์žˆ๋Š” equals๋ผ๋Š” ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด

๋‘ ๋น„๊ต ๋Œ€์ƒ์˜ ์ฃผ์†Œ๊ฐ’์ด ์•„๋‹Œ ๋ฐ์ดํ„ฐ๊ฐ’์„ ๋น„๊ตํ•œ๋‹ค.

 


์ฐธ๊ณ 

https://sudo-minz.tistory.com/93

728x90
๋ฐ˜์‘ํ˜•

'๐Ÿš€ Development > Java' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Java ์ž๋ฐ”] WORA(Write Once Run Anywhere) ์ด๋ž€?  (0) 2023.07.13
Java ๋ž€? Java ์†Œ๊ฐœ  (0) 2023.07.05