Java allow user's to give input for a java program and expect the output accordingly. In this module we will learn how to take the input from user in java using the object of Scanner class. There are many ways to take the input from user, that we will learn later.
Table of Contents
[hide]In our previous tutorial we have learnt how to take the input from command line. If not then kindly have a look at Java Command Line Arguments. Now we will learn about taking the user input using object of Scanner class.
Scanner class lies within java.util package that means we have to import java.util package before we can use the object of Scanner class.
It is used to read input of Primitive data types (int, char, byte, float, double, long) in Java. Below is the syntax for creating object of Scanner class.
// Java program to read an integer using System.in
import java.util.*;
public class ReadInputExample{
public static void main(String args[]){
Scanner sc= new Scanner(System.in); // object of Scanner class created
System.out.print("Enter your age ");
int age = sc.nextInt(); // it will read user input
System.out.println("Your age is : " + age);
}
}
// Java program to read an integer using System.in
import java.util.*;
public class ReadInputExample{
public static void main(String args[]){
Scanner sc= new Scanner(System.in); // object of Scanner class created
System.out.print("Enter your College name ");
String name= sc.nextLine(); // it will read user input
System.out.println("Your College name is : " + name);
}
}
In the above examples given we have used nextInt() and nextLine() methods to read integer and string. You can also read other types using the given table below under section Java Scanner Class methods. Give a try yourself.
There are various methods provided by Java Scanner class to read different Primitive data types.
Methods | Short Description |
nextInt() | It is used to read the int value provided by the user |
nextByte() | It is used to read the byte value provided by the user |
nextFloat() | It is used to read the float value provided by the user |
nextShort() | It is used to read the short value provided by the user |
nextLong() | It is used to read the long value provided by the user |
nextDouble() | It is used to read the double value provided by the user |
nextLine() | It is used to read the String value provided by the user |
nextBoolean() | It is used to read the boolean value provided by the user |
In this module we have learnt how to get the User Input in Java and Java Scanner Class methods. This was the last module of Java Basics.
Now we will learn about Java Control Statements in the next tutorial.