How to close a Scanner in Java?

To close a Scanner in Java, call the close() method.

Here is an example:

Scanner scanner = new Scanner("Hello\nWorld!");

System.out.println(scanner.nextLine()); // Hello
System.out.println(scanner.nextLine()); // World!

scanner.close();