In Java, How many ways you can take input from the console?

Solution:

In Java, there are three ways by using which, we can take input from the console.

  • Using BufferedReader class: we can take input from the console by wrapping System.in into an InputStreamReader and passing it into the BufferedReader. It provides an efficient reading as the input gets buffered. Consider the following example.

    import java.io.BufferedReader;   
    import java.io.IOException;   
    import java.io.InputStreamReader;   
    public class Person   
    {   
        public static void main(String[] args) throws IOException  
        {   
          System.out.println("Enter the name of the person");  
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));   
            String name = reader.readLine();   
            System.out.println(name);   
        }   
    }   
    

    Using Scanner class: The Java Scanner class breaks the input into tokens using a delimiter that is whitespace by default. It provides many methods to read and parse various primitive values. Java Scanner class is widely used to parse text for string and primitive types using a regular expression. Java Scanner class extends Object class and implements Iterator and Closeable interfaces. Consider the following example.

    import java.util.*;  
    public class ScannerClassExample2 {  
          public static void main(String args[]){                   
              String str = "Hello/This is JavaTpoint/My name is Abhishek.";  
              //Create scanner with the specified String Object  
              Scanner scanner = new Scanner(str);  
              System.out.println("Boolean Result: "+scanner.hasNextBoolean());        
              //Change the delimiter of this scanner  
              scanner.useDelimiter("/");  
              //Printing the tokenized Strings  
              System.out.println("---Tokenizes String---");   
            while(scanner.hasNext()){  
                System.out.println(scanner.next());  
            }  
              //Display the new delimiter  
              System.out.println("Delimiter used: " +scanner.delimiter());        
              scanner.close();  
              }  
    }  
    

    Using Console class: The Java Console class is used to get input from the console. It provides methods to read texts and passwords. If you read the password using the Console class, it will not be displayed to the user. The java.io.Console class is attached to the system console internally. The Console class is introduced since 1.5. Consider the following example.

    import java.io.Console;  
    class ReadStringTest{    
    public static void main(String args[]){    
    Console c=System.console();    
    System.out.println("Enter your name: ");    
    String n=c.readLine();    
    System.out.println("Welcome "+n);    
    }    
    }  
    
0 answers