Definition
📌 Input & Output
Java prints output with System.out.println() (or print() without a newline).
Syntax
syntax
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
String s = sc.nextLine();Example
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.");
}
}Output
outputEnter your age: 20
You are 20 years old.
Important Points
Scannermust be imported:import java.util.Scanner;.nextInt(),nextDouble(), andnextLine()read different types of input.- Mixing
nextInt()andnextLine()can cause a subtle bug where a leftover newline is read as empty input. System.out.print()doesn't add a newline;println()does.
Common Mistakes
- Forgetting to import
java.util.Scanner. - Calling
nextLine()right afternextInt()without consuming the leftover newline first. - Not closing the
Scannerin larger programs (a resource-leak habit worth avoiding).
Interview Tip
🎯 Before your interview
The
nextInt()/nextLine() mixing bug is a classic "gotcha" question in Java interviews — know how to explain and fix it.
