String lit1 = "String Literal" ; String lit2 = "String Literal" ; if ( lit1.equals( lit2 ) ) System.out.println("TRUE"); else System.out.println("FALSE");
In this case there is only one object (a string literal) which both lit1 and lit2 refer to. So equals() detects equivalent data and returns true.
lit1
lit2
equals()
Here is the previous program with some more if statements:
if
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( "This WILL print."); if ( str1 .equals( str2 ) ) System.out.println( "This WILL print."); if ( msgA == msgB ) System.out.println( "This will NOT print."); if ( msgA .equals( msgB ) ) System.out.println( "This WILL print."); } }
Say that you know that thing1.equals( thing2 ) is FALSE.
thing1.equals( thing2 )
What can you then say about ( thing1 == thing2 ) ?
( thing1 == thing2 )