Sobes.tech
Middle+

How should string variables be compared in Java?

sobes.tech AI

Answer from AI

In Java, to compare strings, you should use the equals() method rather than the == operator.

  • == compares object references, meaning it checks whether the variables point to the same object in memory.
  • equals() compares the contents of the strings.

Example:

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

System.out.println(a == b);       // false, different objects
System.out.println(a.equals(b));  // true, same content

If you need to compare strings ignoring case, use equalsIgnoreCase().

For sorting or lexicographical comparison, you can use compareTo().