Console I/O in Java


To print to the Java console

System.out.println(arg); // Adds a return at the end.
Or:
System.out.print(arg); // Cursor stays on the same line.
The argument can be any primitive type, a String, an Object, or a (one dimensional) character array. In addition, if the argument is an object that has a toString method, that method is automatically called by method println. (Both String and Object have toString methods. Since classObjectis the superclass of all other objects, every class has a default toString method, but unless redefined inside the class, it returns the hash code of the object.)


To read from the keyboard

Usually the BufferedReader is set up with a single statement:
BufferedReader br= new BufferedReader(
    new InputStreamReader(System.in));
Beware! Your program should only have one BufferedReader reading from the keyboard. If you want to read from the keyboard in more than one place, either create the BufferedReader in the main method and pass it around as a parameter, or make it a public static variable. If you have more than one BufferedReader attached to the keyboard, Java doesn't know which one should get the input.








Escape Sequences

Enclosing any of the following in double quotes ("\n") will make it a String of one character. Single quotes (for example, '\n') will parse the interior as a character.

Escape Sequence Character
\\backslash \
\"double quote "
\'single quote '
\nnewline
\rcarriage return
\ttab
\fform feed
\bbackspace