Java Input and Output
Input and Output (I/O) is the way programs interact with the outside world (such as users, files, networks). This chapter will focus on the most basic I/O operations in Java: reading standard input from the console and writing standard output to the console.
Standard Output
We have actually been using standard output all along. System.out is a PrintStream object that represents the standard output stream, typically your console or terminal window.
System.out.println()
Prints what is passed to it and automatically adds a newline character at the end. This is the most commonly used output method.
System.out.println("Hello, Java!");
System.out.println("This is a new line.");System.out.print()
Prints content but does not add a newline character. Subsequent output will follow immediately after the current output.
System.out.print("Hello, ");
System.out.print("World!");
// Output will be: Hello, World!System.out.printf()
Provides formatted output, similar to C's printf function. It allows you to use format specifiers to control the output format.
%s: String%d: Decimal integer%f: Floating-point number%n: Platform-independent newline character
String name = "Alice";
int age = 30;
double height = 1.65;
System.out.printf("Name: %s, Age: %d, Height: %.2f meters%n", name, age, height);
// Output: Name: Alice, Age: 30, Height: 1.65 meters
// %.2f means the floating-point number keeps two decimal placesStandard Input
To read user input from the console, the simplest and most modern way is to use the java.util.Scanner class.
Using the Scanner Class
- Import the
Scannerclass: Addimport java.util.Scanner;at the top of your Java file. - Create a
Scannerobject: Create aScannerinstance and connect it to the standard input streamSystem.in. - Use read methods: Call methods of the
Scannerobject to read different types of data. - Close the
Scanner: After use, call theclose()method to release resources.
Common Scanner Methods:
nextLine(): Reads a complete line of text (until the user presses Enter).next(): Reads the next word (using whitespace as delimiter).nextInt(): Reads an integer.nextDouble(): Reads a double-precision floating-point number.hasNextInt()/hasNextDouble(): Checks if there is another token of the specified type in the input stream.
Example: A Simple Interactive Program
// Must import the Scanner class at the top of the file
import java.util.Scanner;
public class UserInputExample {
public static void main(String[] args) {
// 1. Create Scanner object
Scanner scanner = new Scanner(System.in);
// 2. Prompt user for input and read
System.out.print("Please enter your name: ");
String name = scanner.nextLine(); // Read entire line as string
System.out.print("Please enter your age: ");
int age = scanner.nextInt(); // Read integer
System.out.print("Please enter your salary: ");
double salary = scanner.nextDouble(); // Read floating-point number
// 3. Print collected information
System.out.println("\n--- User Information Confirmation ---");
System.out.printf("Name: %s%n", name);
System.out.printf("Age: %d%n", age);
System.out.printf("Salary: %.2f%n", salary);
// 4. Close Scanner
scanner.close();
}
}Note: When mixing
nextInt()andnextLine(), you may encounter issues. This is becausenextInt()only reads the number and leaves the newline character in the input stream. The nextnextLine()will immediately read this newline character and return an empty string. A common solution is to callscanner.nextLine()once afternextInt()to consume the extra newline character.
Introduction to File I/O
In addition to standard I/O, Java also provides powerful APIs for reading and writing files, mainly located in the java.io and java.nio packages. These APIs allow you to process file content in the form of byte streams or character streams.
We will explore in detail how to use these classes to create, read, write, and manage files in the subsequent "File Handling" chapter.