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.
Here is the previous program with some more if
statements:
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."); } } |