The Length of a String

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 ring = "One ring to rule them all, "
String find = "One ring to find them."
ring = ring + find;

Answer:

No. The String objects don't change. The reference variable ring is changed in the third statement to refer to a different String than originally. (Its original String becomes garbage, which is collected by the garbage collector.)

The Length of a String

The length of a string is the number of characters it contains, including space characters and punctuation. For example:

String length
"element" 7
"x" 1
"" 0
"Look Homeward" 13
" Look Out " 13

An empty string has length zero. The length() method of a String returns its length:

public int length(); 

The method takes no parameters, but the () is needed when it is used.

QUESTION 13:

Inspect the following code:

String stringA = "Alphabet " ;
String stringB = "Soup" ;
String stringC = stringA + stringB;

System.out.println( stringC.length() ) ;

What does the code print?