Basic Input / Output


A String is a sequence of characters. In Java String is a class from which you make String objects, like:
String name = "Alan Turing";
String course = "CS 303E";
String ssn = "123456789";

A String has an associated length. To obtain the length of a String do:

int nameLen = name.length();

You can also concatenate two Strings to get a third String using the + operator.

String zip9 = "78712" + "-" + "1059";

You can convert data that is entered as a primitive type into a String by using the valueOf() method.

int i = 10;
String ten = String.valueOf ( i );

Basic Output

There are no I/O statements in the Java language. The I/O methods belong to classes in the package. Any source or destination for I/O is considered a stream of bytes. There are three objects that can be used for input and output.

The System.out object has two methods - print() and println(). The println() method will print a carriage return and line feed after printing so that the next output will be printed on a new line. The method print() will keep the cursor on the same line after printing.

In Java 1.5 you can also use the method printf(). The advantage of using the printf() method is that you can now format your output easily. The structure of the printf syntax is as follows:

  System.out.printf (format, args);

Here is a complete specification of the format string. Let us look at a couple of examples at how this is used:

  int i = 10;
  double x = 3.1415;
  System.out.printf ("The value of i is %d \n", i);
  System.out.printf ("The value of x is %4.2f \n", x);

Basic Input

In Java 1.5 we have the new Scanner class. It has methods of the form hasNext() that returns a boolean if there is more input. There are also methods of the form next() that read primitive types and strings. The Scanner object breaks the input into tokens using whitespace as delimiter. Other delimiters can also be used. Here is a short code snippet that shows the use of the Scanner class.

The following program snippet shows how to read and write to the console.

import java.util.*;

public class CalcArea
  public static void main ( String args[] ) 
    System.out.print ( "Enter the radius: " );

    Scanner sc = new Scanner (;

    double radius = sc.nextDouble();

    double area = 3.14159 * radius * radius;

    System.out.println ( "Area is: " + area );