Java System console() Method



Description

The Java System console() method returns the unique Console object associated with the current Java virtual machine, if any.

Declaration

Following is the declaration for java.lang.System.console() method

public static Console console()

Parameters

NA

Return Value

This method returns the system console, if any, otherwise null.

Exception

NA

Example: Getting Console Object and printing a statement on Console

The following example shows the usage of Java System console() method. In this example, using System.console() method, we retrieved a Console object which is then used to print a statement on console using printf() method. Lastly to reflect the changes, we've called the flush() method of the console to print the result on console.

package com.tutorialspoint;

import java.io.Console;

public class SystemDemo {

   public static void main(String[] args) {

      Console ob = System.console();

      ob.printf("Welcome to tutorialspoint...");

      // flushes the console
      ob.flush();
   }
} 

Output

Let us compile and run the above program, this will produce the following result −

Welcome to tutorialspoint...

Example: Getting Console Object and printing an int value on Console

The following example shows the usage of Java System console() method. In this example, using System.console() method, we retrieved a Console object which is then used to print a int value on console using printf() method. Lastly to reflect the changes, we've called the flush() method of the console to print the result on console.

package com.tutorialspoint;

import java.io.Console;

public class SystemDemo {

   public static void main(String[] args) {

      Console ob = System.console();

      ob.printf("%d", 123);

      // flushes the console
      ob.flush();
   }
} 

Output

Let us compile and run the above program, this will produce the following result −

123

Example: Getting Console Object and printing a float value on Console

The following example shows the usage of Java System console() method. In this example, using System.console() method, we retrieved a Console object which is then used to print a int value on console using printf() method. Lastly to reflect the changes, we've called the flush() method of the console to print the result on console.

package com.tutorialspoint;

import java.io.Console;

public class SystemDemo {

   public static void main(String[] args) {

      Console ob = System.console();

      ob.printf("%f", 123.23);

      // flushes the console
      ob.flush();
   }
} 

Output

Let us compile and run the above program, this will produce the following result −

123.230000
java_lang_system.htm
Advertisements