-1

I have this Java code:

String x = "abcgrfdhdrhfhtjfhtgdrfdjrtkkytjgykjgrthfd";
String y = "abcgrfdhdrhfhtjfhtgdrfdjrtkkytjgykjgrthfd";
System.out.println(x == y);

It prints out: true

How is this possible? Isn't String just a pointer to the first byte (character) of the string itself? Why does it act like a primitive type?

Roxana
  • 87
  • 2
  • 5

4 Answers4

4

enter image description here

S4 and S3 are String literals while S1 and S2 are String Objects.

String s1="java";//literal
String s2=new String("java");//Object

As == is used for checking whether two Strings are the same Object or not.Means referencing the same memory location or not.

akash
  • 22,664
  • 11
  • 59
  • 87
0
== operator check if the two references point to the same object or not.

Here both x and y pointing same value in Heap

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
0

It prints out: true How is this possible?

String x = "abcgrfdhdrhfhtjfhtgdrfdjrtkkytjgykjgrthfd"; 
// one String object created on the String pool.
String y = "abcgrfdhdrhfhtjfhtgdrfdjrtkkytjgykjgrthfd"; 
// y is a reference which points to the same object created abovr on the String pool.
So,
System.out.println(x == y); // true

Isn't String just a pointer to the first byte (character) of the string itself? Why does it act like a primitive type?

Well, yes. String Objects are indeed backed by a character array. But that has nothing to do with equality

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

As you know Java == compares the references, it asks whether two objects are actually the same object, not just having the same value.

String x = "abcgrfdhdrhfhtjfhtgdrfdjrtkkytjgykjgrthfd";
String y = "abcgrfdhdrhfhtjfhtgdrfdjrtkkytjgykjgrthfd";
System.out.println(x == y);

In this case you have assigned x and y to point to the exact same String. Internally the Java compiler has noticed that both x and y are being given the same value, so to save space it has created only one String object - and then both x and y point to that object.

This is why x == y..

If you changed one or the other (or both) to:

String x = new String("abcgrfdhdrhfhtjfhtgdrfdjrtkkytjgykjgrthfd");

Then you would get the result false.

Tim B
  • 40,716
  • 16
  • 83
  • 128