Substrings

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        

Answer:

      if ( line.length() > colNum && line.charAt( colNum ) != ' ' )
        System.out.println( counter + ":/t" + line );

The short-circuit operation of && means that line.length() > colNum is tested first. If this result is false, then the next part of the condition is not tested (since the result of AND will be false regardless of its result). So line.charAt( colNum ) is only performed when it is certain that the line contains a character at index colNum

Substrings

A substring of a string is a sequence of characters from the original string. The characters are in the same order as in the original string and no characters are skipped. For example, the following are all substrings of the string "applecart":

apple
cart
pple
e
lecar

You have previously seen (in chapter 9) the substring() method of String objects:

public String substring(int beginIndex )

This method creates a new substring that consists of the characters from character number beginIndex to the end of the string. For example

"applecart".substring(5)

contains the characters "cart" .

bug Remember: character numbering starts with zero. The leftmost character of a string is character zero. The rightmost character is character length-1.

QUESTION 18:

What is printed by the following code:

String source = "applecart";
String sub = source.substring(6);
System.out.println( sub );
System.out.println( source );