Two Strings that are == are always equal()

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        

How would the program change if the second statement were changed to:

String str2 = "STRING LITERAL" ;    // small difference

Answer:

Now, since the second literal is not identical to the first, two literal string objects are created, and variables str1 and str2 refer to different objects.

Two Strings that are == are always equal()

== determines if two variables refer to the same object. It is common in the real world (and in programs) for an object to have several names, for example "Mark Twain" and "Samuel Clemens" are two names for the same author.

one object, two references

Consider two strings:

String strA = new String ("The Gingham Dog"); 
String strB = strA;
  • Since there is only one object, strA == strB is true.
  • Since both reference variables point to an object with the same data, strA.equals( strB ) is true.

If == is true, then so does equals().

QUESTION 25:

In the code that follows, will equals() report true or false?

String lit1 = "String Literal" ; 
String lit2 = "String Literal" ; 

if ( lit1.equals( lit2 ) )
  System.out.println("TRUE");
else
  System.out.println("FALSE");