Taking Input and Printing Output

Site Admin · 11 Sep 2026 · 10 views

Printing Output

System.out.println("one line");        // prints then moves to new line
System.out.print("same line ");        // prints without new line
System.out.printf("Age: %d, Score: %.2f%n", 21, 87.5); // formatted

The format specifiers used in printf:

  • %d integer, %f decimal number, %s string, %n new line.

Reading Input with Scanner

import java.util.Scanner;

public class InputDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = sc.nextLine();

        System.out.print("Enter your age: ");
        int age = sc.nextInt();

        System.out.println("Hello " + name + ", you are " + age);
        sc.close();
    }
}

Common Scanner Methods

  • nextLine() - reads a whole line as a String.
  • next() - reads the next word.
  • nextInt(), nextDouble() - read numbers.
  • hasNextInt() - checks whether the next token is an integer.
Scanner sc = new Scanner(System.in);
if (sc.hasNextInt()) {
    int number = sc.nextInt();
    System.out.println("You entered " + number);
}

Taking input examples

Key Points

  • println adds a new line, print does not, printf formats.
  • Scanner(System.in) is the standard way to read console input.
  • Call close() on the scanner when done.
Share this post:

Comments (0)

Please login or register to comment.