-2

Why does the code snippet 1 evaluate to true while code snippet 2 print false considering both Strings and Arrays are objects?

String s1 = "abc";
String s2 = "abc";
System.out.println (s1 == s2);

Code Snippet 2:

int [] arr = {0,1,2};
int [] arr2 = {0,1,2};
System.out.println (arr == arr2);

Thanks in advance!

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94

1 Answers1

2

They are both objects, but Java reuses objects for strings where it makes sense.

[...] Java String Pool — the special memory region where Strings are stored by the JVM.

Thanks to the immutability of Strings in Java, the JVM can optimize the amount of memory allocated for them by storing only one copy of each literal String in the pool. This process is called interning.

When we create a String variable and assign a value to it, the JVM searches the pool for a String of equal value.

If found, the Java compiler will simply return a reference to its memory address, without allocating additional memory.

If not found, it’ll be added to the pool (interned) and its reference will be returned.

Source

Community
  • 1
  • 1
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
  • thank you. So, it turns out that String is an exception! – user9249390 Jan 25 '18 at 22:52
  • @user9249390 Not only `String`, even `Integer` (as long as value is between `-128` and `127` or something like that) is drawn from a cache. Note that I'm talking about the object `Integer`, not the primitive `int`. – Zabuzard Jan 26 '18 at 00:04