Java Input and Output
Input and output operations allow Java programs to communicate with users and other systems. The most basic form of I/O in Java is console I/O — reading ...
Reading from and Writing to the Console in Java
Input and output operations allow Java programs to communicate with users and other systems. The most basic form of I/O in Java is console I/O — reading text that a user types at the keyboard and displaying results on the screen. Java provides several ways to accomplish this, and choosing the right one depends on the context and the complexity of the input you need to handle.
For output, System.out is the standard output stream. The most common methods are System.out.println(), which prints a line and adds a newline character at the end, and System.out.print(), which prints without a trailing newline. System.out.printf() enables formatted output, similar to printf in C. For example, System.out.printf("Name: %s, Age: %d%n", name, age); produces formatted output using format specifiers: %s for strings, %d for integers, %f for floating-point numbers, and %n for a platform-appropriate newline.
System.err is a separate output stream reserved for error messages. Writing to System.err rather than System.out helps distinguish diagnostic information from regular program output, which is useful when redirecting output to files or pipelines in a terminal.
For reading input, the Scanner class from the java.util package is the most beginner-friendly option. To read from the keyboard, create a Scanner wrapping System.in: Scanner scanner = new Scanner(System.in);. Then call methods like scanner.nextLine() to read a whole line of text, scanner.nextInt() to read an integer, or scanner.nextDouble() to read a decimal number. Always close the Scanner when you are done with scanner.close(), or use a try-with-resources block to ensure it closes automatically.
A complete example: Scanner sc = new Scanner(System.in); System.out.print("Enter your name: "); String name = sc.nextLine(); System.out.println("Hello, " + name + "!");. This reads a name from the user and greets them.
BufferedReader combined with InputStreamReader is another option that is faster for reading large amounts of text but requires more code. It is preferred in competitive programming scenarios where speed matters.
Interview tip: A common pitfall with Scanner is mixing nextInt() and nextLine(). After calling nextInt(), the newline character the user pressed is still in the input buffer. Calling nextLine() immediately after will return an empty string instead of the next line of input. The fix is to call scanner.nextLine() once extra to consume the leftover newline before reading the actual next line.