Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Java Console Class

In this tutorial, we will learn about Console class in Java. The Java Console class is used to get input from the console. This class provides various methods to read text from the console.

Syntax

This is the syntax declaration of the Console class.

public final class Console extends Object implements Flushable  

Java Console class methods

Method Description
Reader reader() It is used to retrieve the reader object associated with the console.
String readLine() It is used to read a single line of text from the console.
String readLine(String fmt, Object... args) It provides a formatted prompt then reads the single line of text from the console.
char[] readPassword() It is used to read password that is not being displayed on the console.
char[] readPassword(String fmt, Object... args) It provides a formatted prompt then reads the password that is not being displayed on the console.
Console format(String fmt, Object... args) It is used to write a formatted string to the console output stream.
Console printf(String format, Object... args) It is used to write a string to the console output stream.
It is used to write a string to the console output stream. It is used to retrieve the PrintWriter object associated with the console.
void flush() It is used to flushes the console.

Java Console Example

In the following example, we are reading data from the user using readLine() method. readLine() method is used to read a single line of text from the console.

package studytonight;
import java.io.Console;
public class StudyTonight 
{
	public static void main(String args[])
	{
		Console console=System.console();    
		System.out.println("Enter your name: ");    
		String user=console.readLine();    
		System.out.println("Hello "+user);    
	}
}


Enter your name: Studytonight
Hello Studytonight

Java Console Example to read password

In the following example, we are reading the password from a user using readPassword() method, while reading this password will not be displayed on the console.

package studytonight;
import java.io.Console;
public class StudyTonight 
{
	public static void main(String args[])
	{
		Console console=System.console();    
		System.out.println("Enter your password: ");    
		char[] ch=console.readPassword();    
		String pass=String.valueOf(ch);
		System.out.println("Password: "+pass);    
	}
}


Enter your password:
Password: 786

Conclusion

In this example, we learned about the Console class in Java. The Java Console class is be used to get input from the console. This class provides various methods to read text from the console. If we read the password using the Console class, it will not be displayed on the Console.