Basic input and output

Objectives

  • Perform basic output in Java
  • Perform basic input in Java

Output

System.out.print() examples

  • System.out.println() is the same as System.out.print(), but it adds a newline after whatever it prints.
  • If nothing is contained within the parentheses, then nothing is printed - which means that System.out.println() will actually end up outputting a newline character.
  • The argument in the parentheses will be converted to a String before being output.
  • System.out.print() knows how to turn its argument into a String.
  • System.out.print("a"); System.out.println("b"); // outputs: ab\n
  • int n = 5; System.out.println("The value is " + n); // outputs: The value is 5\n
  • int n = 5; System.out.println("The value is ", n); // Syntax error, only 0 or 1 argument is allowed
  • System.out.print(64 / (3 + 1)); // outputs: 16 (and stays on the same line)

Special characters in output

Output strings may often need to contain special characters that are not possible to type into the source code. The language has escape sequences to represent some of those characters. The escape sequences available in Java are listed in the table below. The demonstration program TestEscape.java demonstrates the use of escape sequences.

characterescape seq
newline\n
carriage return (no newline)\r
tab\t
backspace\b
backslash\\
single quote\'
double quote\"

In-class spinner to demonstrate '\r' usage: TestSpin.java

Ouput examples

Display a greeting on the screen: System.out.println("Hello, world!"); Display the same greeting, but use two statements to do it: System.out.print("Hello"); System.out.println(", world!"); Display a variable's value: double rate = 15.75; System.out.println(rate); Display a string and a variable's value: System.out.println("The rate is " + rate); Display a string and a variable's value formatted to two decimal positions: System.out.printf("The rate is %.2f\n", rate); Display a string and a variable's value formatted to seven columns with two decimal positions: System.out.printf("The rate is %7.2f\n", rate);

Input

Please note that it is good form to prompt the user for input. Prompting means displaying text before asking for input when using a text environment. Generally, you will want to use print instead of println for prompts so the user's cursor will stay on the same line as the prompt.

Input examples (using the Scanner class)

Set up a new Scanner object: import java.util.Scanner; // at very beginning of source code Scanner kbd = new Scanner(System.in); Get a string from the user: String name; System.out.print("Enter your name: "); name = kbd.nextLine(); Get an integer from the user: int age; System.out.print("Enter your age: "); age = kbd.nextInt(); Get a double precision floating-point number from the user: double rate; System.out.print("Enter your hourly wage: "); rate = kbd.nextDouble();

External resources