-2

What is "==" in Java ? Why can i only compare numerical data type with it and characters can be compared. But not the string data types. What does it provide when i compare two strings?

Sooner
  • 458
  • 1
  • 4
  • 13

4 Answers4

1

== compares reference equality: it returns true if its operands have the same value on the stack. (that is, they are either the same numerical quantity or they point to the same object)

Strings are objects, so here we're asking whether they point to the same object on the stack. This will be true if we're talking about String literals defined in code: If we have

String s1 = "Hello";
String s2 = "Hello";

then s1 == s2 => true

However, if one of the Strings is obtained by some run-time process, for example user input, then it will not be reference-identical, even if the contents of the two Strings are the same.

Jon Kiparsky
  • 7,499
  • 2
  • 23
  • 38
0

In Java == compare reference two reference value. If left side reference equals to right side reference will return true else false.

When you come to compare String(objects) you should use equals()

Why?

String a= new String("a");
String b= new String("a");

Here a and b are same by value but they have two different reference.

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

If you compare to objects (strings are objects) you will compare the reference of both objects.

Jens
  • 67,715
  • 15
  • 98
  • 113
0

The '==' operator in Java is used to compare similar variables (like an integer and another integer). For an over-complicated reason, Strings are considered 'Object' type variables. To compare strings use the operator variableString.equals(otherString);

hesto2
  • 315
  • 2
  • 5