Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Text lesson

Bonus! Taking Input Using Console Class

[post-views]

 

In this lesson, you will learn.

  • Taking Input using System.console()

 

System.console()

  • System.console() in Java provides a convenient way to interact with the console, allowing you to read text and passwords securely.
  • System.console() returns null in environments where no console is available, such as in an integrated development environment (IDE) like Eclipse or IntelliJ.
  • This method works best when you run your Java program from a command line or terminal.

 

Example 1: Reading a String

import java.io.Console;

public class ConsoleExample {
    public static void main(String[] args) {
        Console console = System.console();
        if (console == null) {
            System.out.println("No console available");
            return;
        }

        String input = console.readLine("Enter your name: ");
        System.out.println("Hello, " + input + "!");
    }
}

 

Example 2: Reading a Password

System.console() offers the ability to read passwords securely without echoing the entered characters on the console.

import java.io.Console;

public class PasswordExample {
    public static void main(String[] args) {
        Console console = System.console();
        if (console == null) {
            System.out.println("No console available");
            return;
        }

        char[] passwordArray = console.readPassword("Enter your password: ");
        String password = new String(passwordArray);

        System.out.println("Password entered is: " + password);
    }
}

 

 


 

End of the lesson….enjoy learning

 

Student Ratings and Reviews

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review