Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Reading Data from Keyboard Using Console Class in Java



The Console class is part of the Java.io package and is used to read input from the keyboard or user and write output to the console. Unlike Scanner, the Console class provides methods to read text and passwords. If you read a password using the Console class, it will not be displayed to the user (without showing the typed characters).

To use the Console class, we need its object, and the Console object is obtained by calling System.console() as shown below -

Console console = System.console();

Note: If you try to execute the program in a non-interactive environment like an IDE, it doesn't work. It returns null when we run in IDEs like Eclipse or IntelliJ. There are commonly used methods of the Console class, and they are -

  • Java readLine() Method

  • Java readPassword() Method

Java readLine() Method

The Console class provides a method named readLine() that reads a single line from the keyboard and returns it in the form of a String.

Example

The following Java program reads input using the Console class and creates a Student object.

import java.io.Console;
import java.io.IOException;
class Student {
   String name;
   int age;
   float percent;
   boolean isLocal;
   char grade;
   Student(String name, int age, float percent, boolean isLocal, char grade) {
      this.name = name;
      this.age = age;
      this.percent = percent;
      this.isLocal = isLocal;
      this.grade = grade;
   }
   public void displayDetails() {
      System.out.println("Details..............");
      System.out.println("Name: "+this.name);
      System.out.println("Age: "+this.age);
      System.out.println("Percent: "+this.percent);
      if(this.isLocal) {
         System.out.println("Nationality: Indian");
      }else {
         System.out.println("Nationality: Foreigner");
      }
      System.out.println("Grade: "+this.grade);
   }
}
public class ReadData {
   public static void main(String args[]) throws IOException {
      Console console = System.console();
      if (console == null) {
         System.out.println("Console is not supported");
         System.exit(1);
      }
      System.out.println("Enter your name: ");
      String name = console.readLine();
      System.out.println("Enter your age: ");
      int age = Integer.parseInt(console.readLine());
      System.out.println("Enter your percent: ");
      float percent = Float.parseFloat(console.readLine());
      System.out.println("Are you local (enter true or false): ");
      boolean isLocal = Boolean.parseBoolean(console.readLine());
      System.out.println("Enter your grade(enter A, or, B or, C or, D): ");
      char grade = console.readLine().toCharArray()[0];
      Student std = new Student(name, age, percent, isLocal, grade);
      std.displayDetails();
   }
}

Output

Enter your name:
Krishna
Enter your age:
26
Enter your percent:
86
Are you local (enter true or false):
true
Enter your grade(enter A, or, B or, C or, D):
A
Details..............
Name: Krishna
Age: 26
Percent: 86.0
Nationality: Indian
Grade: A

Java readPassword() Method

The readPassword() method of the Console class is used to read without echoing text like ( password) or input from the keyboard. It returns the entered password as a character array (char[]), not a String.

Example

The following program privately reads a username and a password from the console using the Console class. It uses readPassword() to hide the typed password.

import java.io.Console;
import java.util.Arrays;

public class PasswordExample {
   public static void main(String[] args) {
      Console console = System.console();

      if (console == null) {
         System.out.println("Console not available. Run in a terminal.");
         System.exit(1);
      }

      String username = console.readLine("Enter username: ");
      char[] password = console.readPassword("Enter password: ");

      System.out.println("Username: " + username);
      System.out.println("Password length: " + password.length + " characters");

      // Clear password from memory
      Arrays.fill(password, ' ');
   }
}

Output

Enter username: admin
Enter password: 
Username: admin
Password length: 8 characters

Accepting Formatted Input Values

The readLine() and readPassword() methods of the Console class have other variants that accept a format string and variable-length arguments (of object type). These are used to format the input string read from the console as required. The following is the syntax -

readPassword(String fmt, Object... args)
readLine(String fmt, Object... args)

Where,

  • fmt: is a format string which acts as a place holder for the respective arguments (e.g., %s for strings, %d for integers).
  • args: arguments that hold the input values.

These variants provide a formatted output to the user before reading input (text or password) and by using readPassword() without echoing to console.

Example

Following is the example -

import java.io.Console;

public class ConsoleExample {
   public static void main(String[] args) {
      Console console = System.console();
      
      String name = console.readLine("Enter your %s: ", "name");
      String city = console.readLine("Enter your %s: ", "city");
      
      // Hiding mobile number input using readPassword()
      char[] mobileChars = console.readPassword("Enter your %s: ", "mobile number");
      String mobile = new String(mobileChars);
      
      System.out.println();
      System.out.println(name + " from " + city + " mobile no. is " + mobile);
   }
}

Following is the output of the above code -

Enter your name: manisha
Enter your city: hyderabd
Enter your mobile number:

manisha from hyderabd mobile no. is 3422563663
Updated on: 2025-05-08T10:00:29+05:30

726 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements