String Methods

Equals

🙋 Need help? Ask an expert now!

One of the most useful methods when working with String is the equals() method. Previously, we explained how to compare int and other data types by using the "==" operator. However, every String is an object, which means the "==" operator checks whether or not the reference (not value) for the String objects are the same. Because of this distinction, we need the equals method to check whether or not they hold the same String value (basically the text). The syntax for the equals method is stringname.equals(stringname). Take a look at the difference between the equals method and the "==" operator when working with strings below.

EqualsMethodExample.java
package exlcode;

public class EqualsMethodExample {

  public static String exampleVariableOne = "Ant";
  public static String exampleVariableTwo = new String("Ant");
  // tests to see if the value for both Strings are equal
  // and assigns it to boolean variables
  public static boolean exampleVariableThree = exampleVariableOne.equals(exampleVariableTwo);
  public static boolean exampleVariableFour = exampleVariableOne == exampleVariableTwo;

  public static void main(String[] args) {
    System.out.println(exampleVariableThree);
    System.out.println(exampleVariableFour);
  }
}

When using the "==" operator to compare the strings, we receive a result of "false" because the strings reference two different objects that are held in different memory spaces. However, if a statement like String varTwo = varOne; is called after String varOne = "Java";, the reference for the variable varTwo is the same as the reference of varOne, meaning that the "==" operator has a result of "true". This only works if the first String is directly assigned to the value of the second String.

Edit Me on GitHub!

Application Question

Consider the following code segment:

String varOne = "abc";
            String varTwo = varOne;
            String varThree = varTwo;
            

After this code is executed, which of the following statements will evaluate to true?

I. varOne.equals(varThree)
II. varOne == varTwo
III. varOne == varThree