Input and Output

Introduction

Input and Output (I/O) operations allow Java programs to read data from users and display results. Java provides several classes for console I/O.


Reading Input Using Scanner

Import Scanner:

import java.util.Scanner;

Create Scanner Object:

Scanner input = new Scanner(System.in);

Reading Different Types:

import java.util.Scanner;

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

        // Reading String
        System.out.print("Enter name: ");
        String name = input.nextLine();

        // Reading int
        System.out.print("Enter age: ");
        int age = input.nextInt();

        // Reading double
        System.out.print("Enter marks: ");
        double marks = input.nextDouble();

        // Reading boolean
        System.out.print("Is student? ");
        boolean isStudent = input.nextBoolean();

        System.out.println("\nDetails:");
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Marks: " + marks);
        System.out.println("Student: " + isStudent);

        input.close();
    }
}

Scanner Methods

MethodDescriptionExample
next()Reads single wordString word = input.next();
nextLine()Reads full lineString line = input.nextLine();
nextInt()Reads integerint num = input.nextInt();
nextDouble()Reads doubledouble d = input.nextDouble();
nextFloat()Reads floatfloat f = input.nextFloat();
nextBoolean()Reads booleanboolean b = input.nextBoolean();
nextByte()Reads bytebyte b = input.nextByte();
nextShort()Reads shortshort s = input.nextShort();
nextLong()Reads longlong l = input.nextLong();

Output Using System.out

System.out.print("Hello");
System.out.print(" World");
// Output: Hello World

println() - With newline:

System.out.println("Hello");
System.out.println("World");
// Output:
// Hello
// World

printf() - Formatted output:

String name = "John";
int age = 25;
double marks = 85.75;

System.out.printf("Name: %s\n", name);
System.out.printf("Age: %d\n", age);
System.out.printf("Marks: %.2f\n", marks);

// Output:
// Name: John
// Age: 25
// Marks: 85.75

Format Specifiers

SpecifierTypeExample
%sStringprintf("%s", "Hello")
%dIntegerprintf("%d", 100)
%fFloat/Doubleprintf("%f", 10.5)
%.2f2 decimal placesprintf("%.2f", 10.567) → 10.57
%cCharacterprintf("%c", 'A')
%bBooleanprintf("%b", true)
%nNewlineprintf("Line1%nLine2")

Common Input Pattern

import java.util.Scanner;

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

        System.out.print("Enter first number: ");
        int a = sc.nextInt();

        System.out.print("Enter second number: ");
        int b = sc.nextInt();

        int sum = a + b;
        int product = a * b;

        System.out.println("Sum: " + sum);
        System.out.println("Product: " + product);

        sc.close();
    }
}

Important Points

1. next() vs nextLine():

Scanner sc = new Scanner(System.in);

// next() reads until space
String word = sc.next();  // Input: "Hello World" → Reads "Hello"

// nextLine() reads entire line
String line = sc.nextLine();  // Input: "Hello World" → Reads "Hello World"

2. Buffer Problem:

Scanner sc = new Scanner(System.in);

int age = sc.nextInt();     // Reads number, leaves \n in buffer
String name = sc.nextLine(); // Reads leftover \n (empty string)

// Solution: Add extra nextLine()
int age = sc.nextInt();
sc.nextLine();  // Consume leftover newline
String name = sc.nextLine();  // Now reads correctly

3. Always Close Scanner:

Scanner sc = new Scanner(System.in);
// ... use scanner ...
sc.close();  // Good practice

Using BufferedReader (Alternative)

import java.io.*;

public class BufferedReaderExample {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter name: ");
        String name = br.readLine();

        System.out.print("Enter age: ");
        int age = Integer.parseInt(br.readLine());

        System.out.println("Name: " + name);
        System.out.println("Age: " + age);

        br.close();
    }
}

Quick Examples

Example 1: Sum of Numbers

import java.util.Scanner;

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

        System.out.print("Enter two numbers: ");
        int a = sc.nextInt();
        int b = sc.nextInt();

        System.out.println("Sum = " + (a + b));
        sc.close();
    }
}

Example 2: Name and Greeting

import java.util.Scanner;

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

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

        System.out.println("Hello, " + name + "!");
        sc.close();
    }
}

Exam Tips

Remember:

  1. Import java.util.Scanner
  2. Create Scanner: Scanner sc = new Scanner(System.in);
  3. Use appropriate method: nextInt(), nextDouble(), nextLine()
  4. Close scanner: sc.close()
  5. nextLine() after nextInt() reads leftover newline
  6. print() - no newline, println() - with newline
  7. printf() for formatted output
  8. Format: %d (int), %f (float), %s (string), %.2f (2 decimals)

Common Questions:

  • How to read input in Java?
  • Difference between next() and nextLine()
  • Scanner methods for different types
  • How to format output?
  • What is printf()?