Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Equals
Java String Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java String Micro Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of understanding regarding Java Strings.
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
One of the most useful methods when working with String is the equals() method. 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.