1. We can use Scanner class of java.util package to read input from the keyboard or a text file.
  2. When the scanner class receives input,it breaks the input into several pieces called tokens.
  3. These tokens can be retrieved from the scanner object using the following methods.
Method Description
next() To read a String
nextByte() To read a byte value
nextInt() To read a int value
nextFloat() To read a float value
nextLong() To read a long value
nextDouble() To read a double value

Syntax:

Scanner sc=new Scanner(System.in);

Example:1 Program to accept different types of data separated by space.

import java.util.Scanner;

class Test {

	public static void main(String[] args) throws Exception {

		System.out.print("Enter id name sal:");
		Scanner sc=new Scanner(System.in);
		int id=sc.nextInt();
		String name=sc.next();
		float sal=sc.nextFloat();
		System.out.println("Id:"+id);
		System.out.println("Name:"+name);
		System.out.println("sal:"+sal);
	}
}
/*
Output:
Enter id name sal:890 Test 344
Id:890
Name:Test
sal:344.0
*/

Example:2

import java.util.Scanner;

class Test {

	public static void main(String[] args) throws Exception {

		String text = "Have a nice day";
		Scanner sc = new Scanner(text);
		String text1 = sc.next();
		String text2 = sc.next();
		String text3 = sc.next();
		String text4 = sc.next();
		System.out.println(text1);
		System.out.println(text2);
		System.out.println(text3);
		System.out.println(text4);
		sc.close();
	}
}
/*
Output:
Have
a
nice
day

*/

Example:3