Java String comparison equals() vs ==

Introduction

The equals() method and the == operator perform two different operations.

The equals() method compares the characters inside a String object.

The == operator checks if two object references to the same instance.

// equals() vs ==
public class Main {
  public static void main(String args[]) {
    String s1 = "Hello";
    String s2 = new String(s1);

    System.out.println(s1 + " equals " + s2 + " -> " +  
                       s1.equals(s2));/*from www.  j  a v a2s  .c o  m*/
    System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
  }
}



PreviousNext

Related