Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java.io.FilterOutputStream Class in Java
Next article icon

Java.io.Console class in Java

Last Updated : 11 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

The Java.io.Console class provides methods to access the character-based console device, if any, associated with the current Java virtual machine. The Console class was added to java.io by JDK 6.

Important Points:

  • It is used to read from and write to the console, if one exists.
  • Console is primarily a convenience class because most of its functionality is available through System.in and System.out. However, its use can simplify some types of console interactions, especially when reading strings from the console.
  • Console supplies no constructors. Instead, a Console object is obtained by calling System.console( ), which is shown here:
    static  Console console( )

    If a console is available, then a reference to it is returned. Otherwise, null is returned. A console will not be available in all cases. Thus, if null is returned, no console I/O is possible.

  • It provides methods to read text and password. If you read password using Console class, it will not be displayed to the user.The java.io.Console class is attached with system console internally.

Important Methods:

  • writer : Retrieves the unique PrintWriter object associated with this console.
    Syntax:
    public PrintWriter writer()   Returns: The printwriter associated with this console
  • reader : Retrieves the unique Reader object associated with this console.
    Syntax:
    public Reader reader()    Returns: The reader associated with this console  
  • format : Writes a formatted string to this console’s output stream using the specified format string and arguments.
    Syntax:
    public Console format(String fmt, Object... args)  Parameters:  fmt - A format string as described in Format string syntax  args - Arguments referenced by the format specifiers in the format string.   If there are more arguments than format specifiers, the extra arguments are ignored.  Returns:This console  Throws: IllegalFormatException   
  • printf : A convenience method to write a formatted string to this console’s output stream using the specified format string and arguments.
    Syntax:
    public Console printf(String format, Object... args)  Parameters:  format - A format string as described in Format string syntax.  args - Arguments referenced by the format specifiers in the format string.   If there are more arguments than format specifiers, the extra arguments are ignored.  Returns:This console  Throws:IllegalFormatException   
  • readLine : Provides a formatted prompt, then reads a single line of text from the console.
    Syntax:
    public String readLine(String fmt,Object... args)   Parameters:  fmt - A format string as described in Format string syntax.  args - Arguments referenced by the format specifiers in the format string.   If there are more arguments than format specifiers, the extra arguments are ignored.  Returns: A string containing the line read from the console,   not including any line-termination characters, or null   if an end of stream has been reached.  Throws:  IllegalFormatException  IOError - If an I/O error occurs.  
  • readLine : Reads a single line of text from the console.
    Syntax:
    public String readLine()   Returns: A string containing the line read from the console,   not including any line-termination characters, or null   if an end of stream has been reached.  Throws: IOError   
  • readPassword: Provides a formatted prompt, then reads a password or passphrase from the console with echoing disabled.
    Syntax:
    public char[] readPassword(String fmt,Object... args)  Parameters:  fmt - A format string as described in Format string syntax for the prompt text.  args - Arguments referenced by the format specifiers in the format string.  Returns: A character array containing the password or passphrase read   from the console, not including any line-termination characters, or null   if an end of stream has been reached.  Throws:  IllegalFormatException   IOError
  • readPassword : Reads a password or passphrase from the console with echoing disabled
    Syntax:
    public char[] readPassword()  Returns: A character array containing the password or passphrase   read from the console, not including any line-termination characters, or null   if an end of stream has been reached.  Throws:IOError
  • flush : Flushes the console and forces any buffered output to be written immediately .
    Syntax:
    public void flush()  Specified by: flush in interface Flushable

Program:




// Java Program to demonstrate Console Methods
  
import java.io.*;
class ConsoleDemo 
{
    public static void main(String args[]) 
    {
        String str;
          
        //Obtaining a reference to the console.
        Console con = System.console();
          
        // Checking If there is no console available, then exit.
        if(con == null) 
        {
            System.out.print("No console available");
            return;
        }
          
        // Read a string and then display it.
        str = con.readLine("Enter your name: ");
        con.printf("Here is your name: %s\n", str);
  
        //to read password and then display it
        System.out.println("Enter the password: ");
        char[] ch=con.readPassword();
  
        //converting char array into string
        String pass = String.valueOf(ch);
        System.out.println("Password is: " + pass);
    }
}
 
 

Output:

Enter your name: Nishant Sharma  Here is your name: Nishant Sharma  Enter the password:   Password is: dada  

Note: System.console() returns null in an online IDE



Next Article
Java.io.FilterOutputStream Class in Java

N

Nishant Sharma
Improve
Article Tags :
  • Java
  • Java-I/O
Practice Tags :
  • Java

Similar Reads

  • Java.io.InputStream Class in Java
    Java InputStream class is the superclass of all the io classes i.e. representing an input stream of bytes. It represents an input stream of bytes. Applications that are defining a subclass of the Java InputStream class must provide a method, that returns the next byte of input. A reset() method is i
    3 min read
  • Java.io.Writer class in Java
    This abstract class for writing to character streams. The only methods that a subclass must implement are write(char[], int, int), flush(), and close(). Most subclasses, however, will override some of the methods defined here in order to provide higher efficiency, additional functionality, or both.
    4 min read
  • Java.io.FilterOutputStream Class in Java
    java.io.FilterInputStream Class in Java Java.io.FilterOutputStream class is the superclass of all those classes which filters output streams. The write() method of FilterOutputStream Class filters the data and write it to the underlying stream, filtering which is done depending on the Streams. Decla
    5 min read
  • Compiler Class in Java
    Compiler Class provides support and related services to Java code to Native Code. Native code is a form of code that can be said to run in a virtual machine (for example, [JVM]Java Virtual Machine). Declaration: public final class Compiler extends ObjectMethods of Java Compiler Class 1. command() Th
    2 min read
  • Java.io.DataInputStream class in Java | Set 2
    Java.io.DataInputStream class in Java | Set 1 More Methods: byte readByte() : Reads and returns one input byte. Syntax:public final byte readByte() throws IOException Returns: the next byte of this input stream as a signed 8-bit byte. Throws: EOFException IOException float readFloat() : Reads four i
    3 min read
  • Java.io.DataInputStream class in Java | Set 1
    A data input stream enables an application to read primitive Java data types from an underlying input stream in a machine-independent way(instead of raw bytes). That is why it is called DataInputStream - because it reads data (numbers) instead of just bytes. An application uses a data output stream
    3 min read
  • Java.io.OutputStream class in Java
    This abstract class is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink. Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output. Constructo
    2 min read
  • Java.io.StringWriter class in Java
    Java StringWriter class creates a string from the characters of the String Buffer stream. Methods of the StringWriter class in Java can also be called after closing the Stream as this will raise no IO Exception. Declaration in Java StringWriter Classpublic class StringWriter extends WriterConstructo
    6 min read
  • Java.io.StringReader class in Java
    StringReader class in Java is a character stream class whose source is a string. It inherits Reader Class. Closing the StringReader is not necessary, it is because system resources like network sockets and files are not used. Let us check more points about StringReader Class in Java. Declare StringR
    4 min read
  • Java.lang.Class class in Java | Set 1
    Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences