Home » Java solved programs » Core java programs

How to accept input from keyboard in java?



Here, we are going to learn how to write a program in java that will accept input from keyboard?
Submitted by Preeti Jain, on March 11, 2018

There are various ways to accept input from keyboard in java,

  1. Using Scanner Class
  2. Using Console Class
  3. Using InputStreamReader and BufferedReader Class

1) Accept input using Scanner class in java

import java.util.Scanner;  

class ScannerClass{    
	public static void main(String args[]){ 
		/* Scanner is a class of java.util package */  
		Scanner sc = new Scanner(System.in);    
		System.out.println("Enter Hobbies "); 

		/*next() is a method of scanner class 
		which takes input from keyboard */   
		
		String hobbies = sc.next();    
		System.out.println("Your Hobbies are " +hobbies);    
	}  
}

Output

D:\Java Articles>java ScannerClass
Enter Hobbies
Hockey,Volleyball
Your Hobbies are Hockey,Volleyball

2) Accept input using Console class in java

import java.io.Console;  

class ConsoleClass{    
	public static void main(String args[]){
		/* Console is a class of java.util package */  

		Console con = System.console();    
		System.out.println("Enter programming skills "); 

		/*readLine() is a method of Console class 
		which takes input from keyboard */   

		String skills = con.readLine();    
		System.out.println("Your skills are "+skills);    
	}    
}

Output

D:\Java Articles>java ConsoleClass
Enter programming skills
c,c++,java,python
Your skills are c,c++,java,python  

3) Accept input using InputStreamReader and BufferedReader class in java

import java.io.*;  

class InputStreamReaderClass{  
	public static void main(String args[])throws Exception{  
		InputStreamReader isr = new InputStreamReader(System.in);  
		BufferedReader br = new BufferedReader(isr);  		  
		System.out.println("Enter programming skills");  
		String skills = br.readLine();  
		System.out.println(" Your Skills are "+skills);  
	}  
}

Output

D:\Java Articles>java InputStreamReaderClass
Enter programming skills
c,c++,java,android
Your Skills are c,c++,java,android





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions





© https://www.includehelp.com (2015-2018), Some rights reserved.




Like other websites, this site uses cookies to deliver relevant ads based on your interest, by using our website, you acknowledge that you have read our privacy policy.
Close