1 · Foundations · lesson 6 of 41
Reading Input
Scanner for the console, and a peek at System.in.
Java
import java.util.Scanner;
public class Ask {
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
System.out.print("Your name: ");
String name = in.nextLine();
System.out.println("Hello, " + name);
}
}
}TIP
try-with-resources auto-closes the Scanner even if an exception is thrown.
Key takeaways
- ✓Scanner wraps System.in for line/token/number reads.
- ✓Close I/O resources — try-with-resources handles it for you.