Java Basic Input and Output
In Java, the java.util
package provides classes for handling input and output. The most commonly used classes are Scanner
for input and System.out
and System.err
for output.
To use these classes, you need to import the java.util
package at the beginning of your code.
import java.util.*;
Reading Input using Scanner Class
The `Scanner` class is used to read input from various sources like files, strings, and even the console. Here is an example of using `Scanner` to read input from the console:import java.util.Scanner; public class InputExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter your name: "); String name = scanner.nextLine(); System.out.print("Enter your age: "); int age = scanner.nextInt(); System.out.println("Your name is " + name + " and you are " + age + " years old."); scanner.close(); } }
In this example, we create a new Scanner
object that reads input from the console (System.in
). We then use the nextLine()
method to read a line of text input for the user's name, and the nextInt()
method to read the user's age as an integer. The input is then printed to the console using System.out.println()
.
It's important to note that the Scanner
class provides several methods for reading different types of input, including next()
, nextLine()
, nextInt()
, nextDouble()
, and others.
Writing Output using System.out and System.err
The `System.out` and `System.err` objects are used for writing output to the console. Here is an example of using `System.out` to write output:public class OutputExample { public static void main(String[] args) { int x = 10; System.out.println("The value of x is " + x); System.out.printf("The value of x is %d\n", x); } }
In this example, we use the println()
method to print a message to the console, and the printf()
method to print a formatted message. The %d
in the formatted string is a placeholder for the value of x
.
The System.err
object is similar to System.out
, but is typically used for printing error messages.
public class ErrorExample { public static void main(String[] args) { System.err.println("An error occurred!"); } }
In this example, we use the println()
method of System.err
to print an error message to the console.
It's important to note that output to the console is buffered, which means that the output may not appear immediately. To ensure that output is displayed immediately, you can use the flush()
method of the PrintStream
class, which is the parent class of both System.out
and System.err
.
System.out.flush(); System.err.flush();
This will ensure that any buffered output is immediately displayed on the console.