In Java, the Scanner class is used to take input from the user. It is very useful when we want to read data like numbers, strings, or characters from the keyboard.
The Scanner class belongs to the java.util package, so we must import it before using it.
To use Scanner, we need to create its object.
Here, System.in is used to take input from the keyboard.
The nextLine() method reads a full line of text.
The next() method reads only one word (until space).
The nextInt() method reads an integer value.
The nextDouble() method reads a decimal (double) number.
The nextFloat() method reads a float value.
The nextLong() method reads a long value.
The nextBoolean() method reads a boolean value (true or false).
The hasNextInt() method checks if the next input is an integer.
Sometimes after using nextInt() or nextDouble(), the nextLine() method may skip input.
To solve this, add an extra sc.nextLine(); after numeric input.
After using Scanner, it is good practice to close it.
The Scanner class provides many methods like nextInt(), nextLine(), nextDouble(), and more to take user input.
It is one of the most commonly used classes in Java programming.
Tip: Always close the Scanner object after use to avoid resource leaks.