String Class Tutorials

public boolean equals(Object anObject)

In this tutorial I will discuss the equals() method. The equals() method compares the string value of the current instance to the string value of the instance that the reference variable parameter refers to. It is very easy to confuse the functionality of the == equality operator and the .equals() method; the == equality operator compares if two reference variables are pointing to the same object in heap memory. Watch my String Class Part 3 tutorial for further clarification on the == functionality.
For example:
String a1 = "Apples";
String a2 = new String("Apples");
System.out.println("a1.equals(a2): " + a1.equals(a2));
// true
System.out.println("a1 == a2: " + (a1 == a2)) // false



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md StringEquals
C:\Java>cd StringEquals
C:\Java\StringEquals>Notepad StringEquals.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class StringEquals {
    public static void main(String args[]) {
        String a1 = "Apples";
        String a2 = new String("Apples");
        String a3 = new String("Apples").intern(); // extra credit
        System.out.println("a1.equals(a2): " + a1.equals(a2)); // "Apples" equals "Apples"
        System.out.println("a1 == a2: " + (a1 == a2)); // reference variables point to different object instances
        System.out.println("a3 == a1: " + (a3 == a1)); // reference variables point to same object in the string literal pool.       
    }
}


Now switch back to the command prompt (CMD) and type in javac StringEquals.java and press Enter.
Now type in java StringEquals and press Enter.


C:\Java\StringEquals>javac StringEquals.java
C:\Java\StringEquals>java StringEquals
a1.equals(a2): true
a1 == a2: false
a3 == a1: true


Final thoughts

One strategy that I regularly use to solidify my knowledge of Java is to browse through the actual source code. Due to some language in their copyright file, I can't actually show the source code in my videos. The source code is contained inside of a file called src.zip located in the folder where your JDK is installed. I recommend using notepad++ to browse the class files.


Tutorials