This is the method that compares an object values and returns Boolean type value either 'true' or 'false'. If it returns 'true' for the both objects, it will be equal otherwise not. Here in this case you will see that both the strings come out to be same that is because they have been allocated to the same memory.
public class stringmethod{
public static void main(String[] args){
String string1 = "Hi";
String string2 = new String("Hello");
if (string1 == string2) {
System. out. println("The strings are equal. ");
} else {
System. out. println("The strings are unequal. ");
}
}
}
Wrong Wrong Wrong!
Using == compares the objects (i.e. are string1 and string2 the same object) rather than the values. Instead use equals so it will be:
public static void main(String[] args){
String string1 = "Hi";
String string2 = new String("Hello");
if (string1.equals(string2)) {
System.out.println("The strings are equal. ");
} else {
System.out.println("The strings are unequal. ");
}
}