The perfect place for easy learning...

Java Programming

×

Topics List


Console class in Java





In java, the java.io package has a built-in class Console used to read from and write to the console, if one exists. This class was added to the Java SE 6. The Console class implements teh Flushable interface.

In java, most the input functionalities of Console class available through System.in, and the output functionalities available through System.out.

Console class Constructors

The Console class does not have any constructor. We can obtain the Console class object by calling System.console().

Console class methods

The Console class in java has the following methods.

S.No. Methods with Description
1 void flush( )

It causes buffered output to be written physically to the console.

2 String readLine( )

It reads a string value from the keyboard, the input is terminated on pressing enter key.

3 String readLine(String promptingString, Object...args)

It displays the given promptingString, and reads a string fron the keyboard; input is terminated on pressng Enter key.

4 char[ ] readPassword( )

It reads a string value from the keyboard, the string is not displayed; the input is terminated on pressing enter key.

5 char[ ] readPassword(String promptingString, Object...args)

It displays the given promptingString, and reads a string value from the keyboard, the string is not displayed; the input is terminated on pressing enter key.

6 Console printf(String str, Object....args)

It writes the given string to the console.

7 Console format(String str, Object....args)

It writes the given string to the console.

8 Reader reader( )

It returns a reference to a Reader connected to the console.

9 PrintWriter writer( )

It returns a reference to a Writer connected to the console.

Let's look at the following example program for reading a string using Console class.

Example
import java.io.*;

public class ReadingDemo {

	public static void main(String[] args) {
		
		String name;
        Console con = System.console();
		
		if(con != null) {
			name = con.readLine("Please enter your name : ");
			System.out.println("Hello, " + name + "!!");
		}
		else {
			System.out.println("Console not available.");
		}
	}
}

Let's look at the following example program for writing to the console using Console class.

Example
import java.io.*;

public class WritingDemo {

	public static void main(String[] args) {
        
		int[] list = new int[26];
		
		for(int i = 0; i < 26; i++) {
			list[i] = i + 65;
		}
		
		for(int i:list) {
			System.out.write(i);
			System.out.write('\n');
		}		
	}
}