Basic Input and Output in Java

In this tutorial, you’ll learn how to handle input from the user and display output to the console using Java.

Using the Scanner Class for Input

The Scanner class is used to get user input. To use the Scanner class, create an instance of the class:


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter your name:");
        String name = scanner.nextLine();
        System.out.println("Hello, " + name);
    }
}
      

Reading Different Types of Input

The Scanner class provides methods to read different types of input:

  • nextLine(): Reads a string input.
  • nextInt(): Reads an integer input.
  • nextDouble(): Reads a double input.

Formatting and Displaying Output

Use the System.out.println() method to display output to the console. You can also use the printf() method to format output:


public class Main {
    public static void main(String[] args) {
        int age = 30;
        double salary = 1000.50;
        System.out.printf("Age: %d, Salary: %.2f", age, salary);
    }
}
      

Continue exploring our beginner tutorials to learn more about Java programming.

 

Scroll to Top