Java Input and Output

Discover how to handle user input and display output in Java using System.out and Scanner.

What You Will Learn

  • How to print output using System.out.print() and System.out.println()
  • How to read user input using the Scanner class
  • How to format output using printf() and format()

1. Printing Output in Java

Java provides two main methods for displaying output:

  • System.out.println() – prints text and moves to a new line
  • System.out.print() – prints text without a new line

Try this example:

public class OutputDemo {
    public static void main(String[] args) {

        System.out.println("Welcome to VINAR TECH Java Tutorial!");
        System.out.print("This is printed on the same line. ");
        System.out.println("This appears after print().");
    }
}

2. Taking User Input using Scanner

The Scanner class is used to accept input from the user. It belongs to the java.util package.

Try example:

import java.util.Scanner;

public class ScannerDemo {
    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("Enter your age:");
        int age = scanner.nextInt();

        System.out.println("Hello " + name + ", your age is " + age + ".");
        
        scanner.close();
    }
}
Common Scanner Methods
  • nextLine() – reads a full line of text
  • nextInt() – reads an integer
  • nextFloat() – reads a floating-point number
  • nextBoolean() – reads true/false

3. Formatting Output

Use System.out.printf() or String.format() to create formatted output.

Try example:

public class FormatDemo {
    public static void main(String[] args) {

        String product = "Laptop";
        int quantity = 3;
        double price = 49999.50;

        System.out.printf("Item: %s | Qty: %d | Price: %.2f%n", product, quantity, price);
    }
}
Common Format Specifiers
  • %s – String
  • %d – Integer
  • %f – Floating numbers
  • %.2f – Floating value with 2 decimal places
  • %n – New line
Sidebar Ad Space
Advertisement Space