
The Java Scanner class belongs to the java.util package and was added in the Java programming language during its 1.5 release. It is mainly used to get input from users and convert that input into basic data types like int, double, or String. This class is a helpful tool for breaking down data using regular expressions to create tokens, making it easier for programmers to work with it.
| Java Scanner Class Input Types | |
| Method | Description |
| nextBoolean() | Reads the next input and returns it as either true or false. It is used to handle boolean values. |
| nextByte() | Reads the next input as a byte value (small integer). Useful for handling small numerical data within the byte range. |
| nextDouble() | Reads the next input as a double-precision floating-point number. Ideal for situations where higher precision is needed for decimal values. |
| nextFloat() | Reads the next input as a single-precision floating-point number. Suitable for capturing float values when less precision is acceptable. |
| nextInt() | Reads the next input as an integer. Useful for working with whole numbers. |
| nextLine() | Reads the entire next line of input, including spaces and characters. Perfect for capturing text data. |
| nextLong() | Reads the next input as a long integer. Useful for handling larger whole numbers that are outside the range of “nextInt()”. |
| nextShort() | Reads the next input as a short integer. Ideal for smaller numerical values when memory constraints are important. |
| Java Scanner Class Declaration |
| Scanner scannerName = new Scanner(inputSource); |
| Java Scanner Class Examples |
| // Java program to read data of various types using Scanner import java.util.Scanner; public class ScannerDemo1 { public static void main(String[] args) { // Create a Scanner object to read input from the console Scanner PW = new Scanner(System.in); // Prompt the user for input and read the values // String input System.out.print("Enter your name: "); String name = PW.nextLine(); // Character input System.out.print("Enter your gender (M/F): "); char gender = PW.next().charAt(0); // Integer input System.out.print("Enter your age: "); int age = PW.nextInt(); // Long input System.out.print("Enter your mobile number: "); long mobileNo = PW.nextLong(); // Double input System.out.print("Enter your CGPA: "); double cgpa = PW.nextDouble(); // Print the values to check if the input was correctly obtained System.out.println("\n--- User Details ---"); System.out.println("Name: " + name); System.out.println("Gender: " + gender); System.out.println("Age: " + age); System.out.println("Mobile Number: " + mobileNo); System.out.println("CGPA: " + cgpa); // Close the Scanner object PW.close(); } } |
Sample Output:
![]() |