Simple Input/Output in Java

last updated 1/20/04

This page gives a quick overview of simple interactive input and output techniques for Java programs in CS 2.

"Import"-ant

The following import statements are required for the code below.

import java.io.*; //needed for console i/o
import javax.swing.*; //needed for gui (pop up) interfaces


Command line input

Command line input to a program is through the argument list from the Unix/DOS command. You need to have the String array parameter in your main method:

public class myClass {
...
    public static void main (String args[ ]) {
      // args[0] is a string of the first argument (delimited by blanks)
      // args[1] is a string of the second argument
     System.out.println ("The second argument in the command line is "+args[1]);
...}
}

Console input/output

This is input and output within a DOS window or at the Java Console (if your browser has the console enabled and displayed). This is typically associated with Java applications, although applets can perform console I/O as well.

Console output

Console input

This section describes how to read lines from the console. Very simple input from the console is limited to character-by-character input.

Any routine that uses the bufferedReader class is requred to handle/throw the IOException as well.

...
public static void main(String [] args) throws IOException {
...
    String line; // hold the input line
    BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
...
     line = input.readLine(); //read first line
...  //process line
    line = input.readLine(); //get second line
...  //process it

Pop up window input/output

Pop up window input

String input;
input = JOptionPane.showInputDialog("prompt string");

Pop up window output

JOptionPane.showMessageDialog(null, "messageString",
"titleOfBox", JOptionPane.INFORMATION_MESSAGE);