Column Checker

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:

String singleA = "A" ;
String singleB = new String( "B" );

System.out.println( singleA.length() );
System.out.println( singleA.concat( singleB ) );

outputs:

1
AB

The following

char oneC = 'C' ;
char oneD = new char( 'B' );

System.out.println( oneC.length() );
System.out.println( oneD.concat( oneC ) );

will not even compile. Line two will not compile because a char is not an object, and so has no constructor. The remaining lines will not compile because a char primitive has no methods.

Column Checker

Here is a program that checks that every line of a text file has a space character in column 10. This might be used to verify the correct formatting of columnar data or of assembly language source programs.

import java.util.Scanner;
import java.io.*;

class ColumnCheck
{
  public static void main (String[] arg)
  {
    final int colNum = 10;
    int counter = 0;
    String line = null;
    Scanner scan = new Scanner( System.in );
   
    while ( scan.hasNext() )
    {    
      line = scan.nextLine() ;
      counter = counter +1;
      if ( line.length() > colNum && line.charAt( colNum ) != ' ' )
        System.out.println( counter + ":/t" + line );
    }    
  }
}    

The program is used with redirection (see Chapter 21):

C:/>javac ColumnCheck.java

C:/>java ColumnCheck < datafile.txt

A better program would ask the user for several column numbers to check.

QUESTION 17:

Will the program crash if a line has fewer than 10 characters? Inspect the statement

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

How is the short-circuit nature of && used here?