Basic constructs (Java)

From LiteratePrograms
Jump to: navigation, search
Other implementations: AmigaE | C | C++ | Java | Unlambda

This article describes some basic constructs in the Java programming language. This is not a tutorial, just a collection of example code. The Java Tutorial is the standard place to go for a tutorial introduction to the Java language.

Contents

[edit] Loops

There are 3 standard ways to create a loop in Java.

The for-loop is the most commonly used.

The following example will print the numbers from 0 to 9 on separate lines.

<<for loop>>=
System.out.println("For loop");
for(int i = 0; i < 10; i++) {
    System.out.println(i);
}
System.out.println();

Here is an example of a while-loop. The output is exactly the same as in the for-loop example.

<<while loop>>=
System.out.println("While loop");
int j = 0;
while(j < 10) {
    System.out.println(j);
    j++;
}
System.out.println();

The do-while-loop works like the while-loop, except the test expression is evaluated after the code block.

<<do-while loop>>=
System.out.println("Do-while loop");
int k = 0;
do {
    System.out.println(k);
    k++;
} while (k < 10);
System.out.println();
<<loops>>=
public void loops()
{
    for loop

    while loop

    do-while loop
}

Note: Sometimes infinite (never ending) loops might be useful. You can write them as for(;;), while(true).

[edit] Simple I/O

Unfortunately, compared with similar languages like C, Java's I/O is rather more challenging than it should be. Most programs dealing with input/output require the java.io package.

<<import java.io>>=
import java.io.*;

Java has a very rich IO system. Here we illustrate the two most commonly required IO methods: standard input and output (input from keyboard, output to console) and text-file IO.

<<input and output>>=
void io() throws IOException
{
  String line = null;

  standard input and output

  file input and output
}

[edit] Standard input/output

Output to the console (stdout) and the error stream (stderr) is relatively simple in Java and is handled by the methods println(String) and print(String) of the java.io.PrintStream methods of the system objects java.lang.System.out and java.lang.System.err.

System.out.print("Hello World!");

prints Hello World! and

System.out.println("Hello World!");

prints Hello World!<NEWLINE> (that is println adds the system-specific new-line character sequence to the text of the argument). A useful additional method call is System.out.println() which prints only the new line character. For portability it is safer to use println than to use the C-like convention System.out.print("Hello World!\n");

In Java, intput from the keyboard (stdin) is more of a challenge! For reasons of flexibility, the Java IO system is designed so that different sources and sinks of data can easily be combined. For this purpose it makes use of the Decorator pattern which makes it relatively simple to wrap a suitable IO processor around any source of data (for example a file, keyboard or network connection). Unfortunately, the designers of the language failed to provide a simple-to-use object for the simplest form of IO of all: text from the keyboard. The object java.lang.System.in, which represents the keyboard, is a java.io.InputStream, an object which cannot be used directly to input lines of text. To make it useful as a source of strings, System.in has to be decorated by an InputStreamReader which itself has to be decorated by a BufferedStreamReader:

<<create source of input>>=
BufferedReader in = new BufferedReader(
    new InputStreamReader(System.in));

Once we have done this, we can read a line from the keyboard using the method in.readLine().

<<standard input and output>>=
System.out.println("Standard I/O");
create source of input
System.out.print("Type a line of text (enter with Return): ");
line = in.readLine();
System.out.println("You entered: " + line);
System.out.println();

[edit] File reading writing

This code will read the first line of the file input.txt and write the same line to output.txt.

[edit] Create a File to Read and Write

Let's create a file for testing purposes.

<<input.txt>>=
Now is the Winter of our Discontent
Made glorious Summer by this son of Yorke;

[edit] Reading from a Text File

To read a text file it has to be opened. In Java this is achieved decorating a FileReader with a BufferedReader. The filename is passed to the FileReader as a constructor argument.

<<open input file>>=
BufferedReader fin = new BufferedReader(
    new FileReader("input.txt"));

To read a line from the file, we simply call readLine() on the BufferedReader. If we have reached the end of the line, readLine returns null:

<<read first line from input file>>=
line = fin.readLine();
if (line == null) 
    throw new EOFException("Unexpected End of File encountered while reading \"input.txt\"");


Closing an input file is a simple as calling the close() method on the BufferedReader. This will also close the FileReader and hence the file.

<<close input file>>=
fin.close();

[edit] Writing a Text File

Opening a file for writing is similar to the procedure for opening a file for reading. This time we decorate a FileWriter with a BufferedWriter, and decorate the BufferedWriter in turn with a PrintWriter.

<<open output file>>=
PrintWriter fout = new PrintWriter(
    new BufferedWriter(
        new FileWriter("output.txt")));

We can use fout.println to print the line to this new file.

<<write line to output file>>=
fout.println(line);

Now close the PrintWriter which closes the file.

<<close output file>>=
fout.close();

[edit] Handling IO Exceptions

Java has support for exceptions built-into the language, and an exception handler built-in to the runtime system. IO operations should make use of try-catch blocks to ensure that any IO errors are handled by the exception handler. As we can't actually do anything useful if this progam fails (which will most likely be due to file permissions), we simply print an error message and rethrow the exception which will cause the program to close and print a stack trace.

<<file input and output>>=
try {
    open input file
    read first line from input file
    close input file
}
catch (IOException e) {
    System.err.println("ERROR: Cannot read \"input.txt\"");
    throw e;
}

try {
    open output file
    write line to output file
    close output file
}
catch (IOException e) {
    System.err.println("ERROR: Cannot write to \"output.txt\"");
    throw e;
}

[edit] Command line arguments

Java is always executed by starting the virtual machine and passing it the class that contains the main method:

 java AClass [command line arguments]

The optional command line arguments are passed to the body of the main method via an array of strings which is conventionally named args.

<<main method>>=
public static void main(String[] args) throws Exception
{
    BasicConstructs bc = new BasicConstructs();

    validate command-line arguments

    process command-line arguments
 
    System.exit(0);
}

Array access is used to access the arguments. The number of arguments to process will be accessible via the field args.length. Unlike C, this number does not include the command itself (which will always be java classname).

<<process command-line arguments>>=
for (int i = 0; i < args.length; i++) {
    if ( "loops".equals(args[i]) ) bc.loops();
    else if ( "io".equals(args[i]) ) bc.io();
    else {
       unexpected command-line argument
    }
}

When the wrong number of arguments are passed to the program:

<<validate command-line arguments>>=
if (args.length < 1) {
    System.err.println("ERROR: Wrong number of arguments");
    bc.usage();
}

or incorrect or unexpected arguments are encountered while processing the command-line arguments:

<<unexpected command-line argument>>=
System.err.println("ERROR: Unexpected command line argument: " + args[i]);
bc.usage();

programs normally display an error mesage, along with a usage message showing the allowed arguments.

<<display usage message>>=
private void usage()
{
    System.err.println("Usage java BasicConstructs loops|io");
    System.exit(1);
}

[edit] The Program

<<BasicConstructs.java>>=
import java.io

public class BasicConstructs {

    loops

    input and output

    display usage message

    main method
}

[edit] Reference

Bruce Eckel, Thinking in Java, 4th Ed., Prentice Hall, 2006.

[edit] See also

Download code
hijacker
hijacker
hijacker
hijacker