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?