Scanner class
The Scanner class is used to get user input, and it is found in the java.util package.
Purpose:
1. Read user input (keyboard)
Works with System.in
Example: nextInt(), nextLine()
2. Read data from files
Can read text files line by line
3. Read different data types
int → nextInt()
double → nextDouble()
String → next(), nextLine()
boolean → nextBoolean()
4. Parse/split input
Parsing = breaking a big input into small pieces (tokens)
Tokens can be:
words
numbers
symbols
When a user types:John 25 3.75
It’s just a line of text to Java.
We need a way to separate it into meaningful pieces:
"John" → String
25 → int
3.75 → double
Scanner does this automatically.
Input Types:
import java.util.Scanner;
public class ScannerInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Your name : ");
String name= sc.nextLine();
System.out.println("Enter the Tamil mark: ");
int tamil=sc.nextInt();
System.out.println("Enter the English mark: ");
int english=sc.nextInt();
System.out.println("Enter the Science mark: ");
int sci=sc.nextInt();
System.out.println("Enter the Math mark: ");
int math=sc.nextInt();
System.out.println("Your average 345mark is "+(tamil+english+sci+math)/4);
}
}
output:
Enter Your name :
K
Enter the Tamil mark:
67
Enter the English mark:
89
Enter the Science mark:
90
Enter the Math mark:
90
Your average 345mark is 84

Why Scanner needs System.in?
Scanner sc = new Scanner(System.in);
Scanner’s purpose
Scanner is a high-level utility class in java.util.
It can read tokens, lines, integers, doubles, etc., from a source.
It handles all the parsing and splitting of input for you.
Data source requirement
Scanner needs something to read from:
Could be a file → new Scanner(new File("data.txt"))
Could be a string → new Scanner("1 2 3")
Could be the keyboard → new Scanner(System.in)
close():
Purpose
Frees system resources used by a resource (like file, stream, or scanner).
Stops further use of that resource.
When to use
Files, network streams, database connections: Always close (or use try-with-resources) to avoid real resource leaks.
Scanner(System.in): Usually don’t close, because closing also closes System.in and you can’t read from the keyboard anymore.
Effects of closing
Releases memory and system handles.
After closing, calling methods on the resource can throw exceptions (IOException, IllegalStateException).



Top comments (0)