Input and output

Getting input from the user

In Java, you can use the Scanner class to get input from the user. Here's an example:

import java.util.Scanner;

public class InputExample {
    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 the above example, we use the Scanner class to get input from the user. We first create a new Scanner object and pass in System.in to indicate that we want to get input from the standard input stream (i.e. the user).

We then use the nextLine() method to get a string input from the user, and the nextInt() method to get an integer input from the user. We store the input in the name and age variables, respectively.

Displaying output to the user

In Java, you can use the System.out.println() method to display output to the user. Here's an example:

public class OutputExample {
    public static void main(String[] args) {
        String name = "Alice";
        int age = 25;

        System.out.println("Hello, " + name + "! You are " + age + " years old.");
    }
}

In the above example, we use the System.out.println() method to display output to the user. We pass in a string that contains the message we want to display, as well as the variables name and age.

Using formatted output

In Java, you can use the System.out.printf() method to display formatted output to the user. Here's an example:

public class FormatExample {
    public static void main(String[] args) {
        String name = "Alice";
        int age = 25;

        System.out.printf("Hello, %s! You are %d years old.\n", name, age);
    }
}

In the above example, we use the System.out.printf() method to display formatted output to the user. We pass in a format string that contains placeholders for the variables name and age. The %s placeholder is used for strings, and the %d placeholder is used for integers. We then pass in the values of name and age as additional arguments to the method. The character is used to add a newline after the message.

Last updated