In programming, input and output (I/O) are fundamental and crucial operations. Imagine a program that can only run by itself without communicating with the user—it would be very boring! For example, a calculator needs to know what the user wants to calculate, and a chat program needs to receive messages from the user. Java provides multiple ways to implement I/O operations. Among them, System.out is used for outputting information, and the Scanner class is used for reading user input. Let’s learn these two common methods step by step.
1. Outputting Information: Using System.out¶
In Java, System.out represents the standard output stream. The most common output methods are println(), print(), and printf(). All three display content on the console, but they differ in details.
1.1 println(): Outputs with an Automatic Newline¶
println() automatically appends a newline character (\n) after the output content. For example:
System.out.println("Hello, Java!"); // Output: Hello, Java! followed by a newline
System.out.println("I am a beginner"); // Output: I am a beginner followed by a newline
When you run this code, the console will display two lines: “Hello, Java!” and “I am a beginner”.
1.2 print(): Outputs Without a Newline¶
print() only outputs the content without adding a newline. For example:
System.out.print("Hello, "); // Output: Hello, (no newline)
System.out.print("World!"); // Output: World! (continues on the same line)
// The console will display: Hello, World!
Note that print() does not automatically add a newline, so multiple print() statements will output continuously on the same line.
1.3 printf(): Formatted Output¶
printf() outputs content in a specified format, similar to C’s printf. It uses placeholders to represent different data types, such as:
%d: Integer%s: String%f: Floating-point number (decimal)
Example:
int age = 20;
String name = "Xiaoming";
double height = 1.75;
System.out.printf("Name: %s, Age: %d, Height: %.2f meters\n", name, age, height);
// Output: Name: Xiaoming, Age: 20, Height: 1.75 meters
Here, %.2f specifies that the floating-point number should be printed with two decimal places, which is ideal for formatting numeric output.
2. Reading Input: Using the Scanner Class¶
To get user input (e.g., from the keyboard), the Scanner class in Java is a convenient tool. It is located in the java.util package and requires an import statement to use.
2.1 Import the Scanner Class¶
At the beginning of your code, import the Scanner class:
import java.util.Scanner; // Import the Scanner class
2.2 Create a Scanner Object¶
After importing, create a Scanner object to read input. The input source is typically System.in (standard input stream, i.e., keyboard input):
Scanner sc = new Scanner(System.in); // Create a Scanner object; 'sc' is the variable name
Here, sc is the “tool” we use to read input. You can call various reading methods through it.
2.3 Common Reading Methods¶
The Scanner class provides multiple methods to read different data types. Here are the most common ones:
Reading Integers: nextInt()¶
System.out.print("Please enter an integer: ");
int num = sc.nextInt(); // Read the integer input by the user
System.out.println("You entered: " + num);
Reading Strings: next() and nextLine()¶
next(): Reads a string and stops when it encounters a space or newline (does not include spaces or newlines).nextLine(): Reads a string until a newline is encountered (includes spaces).
Note: If you use nextLine() immediately after nextInt() or other “primitive type” reading methods, it may read an empty line! This is because methods like nextInt() leave a “newline character” in the input stream, and nextLine() will read this newline first, resulting in an empty string. To fix this, call nextLine() once after nextInt() to “consume” this newline.
Example:
// Read a string using next()
System.out.print("Enter your name (spaces split words, only the first word is read): ");
String name1 = sc.next(); // If input is "Zhang San", only "Zhang" is read
// Read a string using nextLine()
System.out.print("Enter your full name (can include spaces): ");
String name2 = sc.nextLine(); // If input is "Zhang San", the entire "Zhang San" is read
// Note: After nextInt(), you need to consume the newline
System.out.print("Enter your age: ");
int age = sc.nextInt();
sc.nextLine(); // Consume the newline to avoid affecting subsequent nextLine()
System.out.print("Enter your height (meters): ");
double height = sc.nextDouble(); // Correctly reads the height
Reading Floating-Point Numbers: nextDouble()¶
System.out.print("Enter a decimal: ");
double decimal = sc.nextDouble(); // Read the decimal input by the user
System.out.println("You entered: " + decimal);
2.4 Closing the Scanner (Optional)¶
After using the Scanner, it is good practice to close it to release resources (e.g., sc.close();):
sc.close(); // Close the Scanner to free resources
3. Comprehensive Example: Simple Interactive Program¶
Now, let’s combine input and output to create a complete small program that collects a user’s personal information and then outputs it.
import java.util.Scanner;
public class InputOutputDemo {
public static void main(String[] args) {
// 1. Output a welcome message
System.out.println("===== Personal Information Collection System =====");
// 2. Create a Scanner object
Scanner sc = new Scanner(System.in);
// 3. Read name
System.out.print("Enter your name: ");
String name = sc.nextLine();
// 4. Read age (note: consume the newline after reading)
System.out.print("Enter your age: ");
int age = sc.nextInt();
sc.nextLine(); // Consume the newline
// 5. Read height
System.out.print("Enter your height (meters): ");
double height = sc.nextDouble();
// 6. Output user information
System.out.println("\n===== Your Information Summary =====");
System.out.println("Name: " + name);
System.out.println("Age: " + age + " years old");
System.out.println("Height: " + height + " meters");
// 7. Close the Scanner
sc.close();
}
}
Sample Run:
===== Personal Information Collection System =====
Enter your name: Zhang San
Enter your age: 20
Enter your height (meters): 1.75
===== Your Information Summary =====
Name: Zhang San
Age: 20 years old
Height: 1.75 meters
4. Summary¶
- Output:
System.outis the core for output.println()adds a newline,print()does not, andprintf()formats output. - Input: The
Scannerclass is used to read input. Importjava.util.Scannerfirst, then create aScannerobject withScanner sc = new Scanner(System.in);. Common methods includenextInt(),nextLine(), andnext(). - Important Notes: The difference between
next()andnextLine(), and the need to usenextLine()to consume the newline afternextInt()to avoid reading empty lines.
With these basic operations, you can already implement simple interactions with users! Try different input/output combinations to quickly master them.