In case you are writing a Java program and wish to read the input from the user, you make use of Scanner Class in Java. In this article, I will give you a brief insight into Scanner class and its various methods. In this article, I will be covering the below-mentioned topics:
What is the Scanner class?
The Scanner class is mainly used to get the user input, and it belongs to the java.util package. In order to use the Scanner class, you can create an object of the class and use any of the Scanner class methods. In the below example, I am using the nextLine() method, which is used to read Strings.
import java.util.Scanner;// Import the Scanner class public class Example { public static void main(String[] args) { Scanner s = new Scanner(System.in);// Create a Scanner object System.out.println("Enter username"); String name = s.nextLine();// Read user input System.out.println("name is: " + name);;// Output user input } }
This is how you can use Scanner class in Java. Now let’s move further and look at the various methods of Scanner class.
Scanner Class Methods
There are various methods of Scanner class which can be used for various data types. Take a look at the below table to know about these methods.
Now let’s take an example to demonstrate the above methods.
Examples
import java.util.Scanner; public class Example { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("Enter name, age and salary"); // String input String name = s.nextLine(); // Numerical input int age = s.nextInt(); double salary = s.nextDouble(); // Output input by user System.out.println("Name: "+ name); System.out.println("Age: "+ age); System.out.println("Salary: "+ salary); } }
When you run the above code, it will ask you to enter the above details like name age and salary. And it will display the output. So that was all about Scanner Class in Java. With this, we come to the end of this article. I hope you found it informative. If you wish to learn more, you can check out our other Java Blogs as well.
Check out the Java Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer.
Got a question for us? Please mention it in the comments section of this “ Scanner Class in Java” article and we will get back to you as soon as possible.