Input & Output
Java prints output with System.out.println() (or print() without a newline). For reading input from the keyboard, Java uses the Scanner class from java.util.
💡 Key insight
You must import java.util.Scanner before you can read keyboard input in Java — it's not available by default like println is.
Syntax
syntax
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
String s = sc.nextLine();Example
sc.nextInt() reads a whole number typed by the user and returns it as an int.
java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = sc.nextInt();
System.out.println("You are " + age + " years old.");
}
}outputEnter your age: 20
You are 20 years old.
Try it yourself
Copy this example into the Java compiler and run it — try changing a value and see what happens.
