String lit1 = "String Literal" ; String lit2 = "String Literal" ;
if ( lit1.equals( lit2 ) ) System.out.println("TRUE"); else System.out.println("FALSE");
TRUE
There is only one object (a string literal) which both
lit1 and lit2 refer to.
So equals()
detects equivalent data and returns true.
Here is the previous program with some more if statements:
public class LiteralEgTwo
{
public static void main ( String[] args )
{
String str1 = "String literal" ; // create a literal
String str2 = "String literal" ; // str2 refers to the same literal
String msgA = new String ("Look Out!"); // create an object
String msgB = new String ("Look Out!"); // create another object
if ( str1 == str2 )
System.out.println( "Case 1: This WILL print.");
if ( str1 .equals( str2 ))
System.out.println( "Case 2: This WILL print.");
if ( msgA == msgB )
System.out.println( "Case 3: This will NOT print.");
if ( msgA .equals( msgB ))
System.out.println( "Case 4: This WILL print.");
}
}
The program prints:
Case 1: This WILL print. Case 2: This WILL print. Case 4: This WILL print.
Say that you know that thing1.equals( thing2 ) is FALSE.
What can you then say about ( thing1 == thing2 ) ?