Example Continued

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        
String lit1 = "String Literal" ;
String lit2 = "String Literal" ;
if ( lit1.equals( lit2 ) )
System.out.println("TRUE");
else
System.out.println("FALSE");

Answer:

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.

Example Continued

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.");
  }

}

QUESTION 26:

Say that you know that thing1.equals( thing2 ) is FALSE.

What can you then say about ( thing1 == thing2 ) ?