Command Line I/O

Command Line I/O

Command Line I/O refers to the interaction between a user and a program through the command-line interface (CLI) or terminal. It involves reading input data from the user and displaying output on the screen.

In Java, command line I/O is implemented using the System class, which provides three standard streams:

System.in: This stream represents the standard input stream, which is usually connected to the keyboard. It is an instance of the InputStream class.

System.out: This stream represents the standard output stream, which is usually connected to the console or terminal. It is an instance of the PrintStream class.

System.err: This stream represents the standard error stream, which is also usually connected to the console or terminal. It is an instance of the PrintStream class.

To read input from the user, the Scanner class can be used. It provides various methods for reading different types of data, such as nextInt(), nextDouble(), nextLine(), etc. Here’s an example of reading user input from the command line using Scanner:

import java.util.Scanner;

public class CommandLineInputExample {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print(“Enter your name: “);

        String name = scanner.nextLine();

        System.out.print(“Enter your age: “);

        int age = scanner.nextInt();

        System.out.println(“Hello ” + name + “, you are ” + age + ” years old.”);

    }

}

In this example, we first create a Scanner object and pass the standard input stream as the argument to its constructor. Then we prompt the user to enter their name and age, read the input using the scanner’s nextLine() and nextInt() methods, and finally print a message using the input values.

To display output to the user, we can use the System.out.println() method or any other methods provided by the PrintStream class. Here’s an example:

public class CommandLineOutputExample {

    public static void main(String[] args) {

        int a = 10;

        int b = 20;

        int sum = a + b;

        System.out.println(“The sum of ” + a + ” and ” + b + ” is ” + sum);

    }

}

In this example, we simply calculate the sum of two integers and print the result to the console using the System.out.println() method.

Apply for Core Java Developer Certification Now!!

https://www.vskills.in/certification/certified-core-java-developer

Back to Tutorial

Get industry recognized certification – Contact us

Menu