Java.io.Console.reader() Method

Advertisements


Description

The java.io.Console.reader() method retrieve the unique Reader object associated with this console.

Declaration

Following is the declaration for java.io.Console.reader() method:

public Reader reader()

Parameters

  • NA

Return Value

This method returns the reader associated with the console.

Exception

  • NA

Example

The following example shows the usage of java.io.Console.reader() method.

package com.tutorialspoint;

import java.io.Console;
import java.util.Scanner;

public class ConsoleDemo {
   public static void main(String[] args) {
      
      Console cnsl = null;
      Scanner scan = null;
      
      try{
         // creates a console object
         cnsl = System.console();

         // if console is not null
         if (cnsl != null) {
            
            // prints
            System.out.print("Enter name : ");
            
            // create new scanner object
            scan = new Scanner(cnsl.reader());
            
            // read till the end of data
            while (scan.hasNext()) {
               
               // read next
               String str = scan.next();
               
               // print
               System.out.println(str);
            }
         }      
      }catch(Exception ex){
         
         // if any error occurs
         ex.printStackTrace();      
      }
   }
}

Let us compile and run the above program, this will produce the following result:

Enter name : Master Programmer
Master Programmer



Advertisements
Advertisements