Java Input and Output - Scanner, print, println and printf

⏱️ 9 min read • Beginner Level • Lesson 19

Lesson 19 of 124 of Java Tutorial
You have completed this lesson

Completed on . You can revise this lesson or continue to the next topic.

In Java, input is commonly taken using the Scanner class, and output is displayed using methods like print(), println(), and printf().

Before learning input and output, you should understand Java variables, Java data types, and Java literals.


Scanner Class in Java

The Scanner class in Java is used to read input from different sources, such as keyboard input, files, and strings. For beginner programs, it is commonly used to take input from the keyboard using System.in.

  • Scanner belongs to the java.util package.

  • It breaks input into tokens using whitespace as the default delimiter.

  • It provides methods to read values such as int, double, String, and boolean.

Real World Uses of Input and Output

  • Taking user registration details.
  • Reading marks and calculating grades.
  • Accepting banking transactions.
  • Processing employee records.
  • Building console-based applications.

Common Methods of Scanner

Method Description
next() Reads a single word as a String.
nextLine() Reads a complete line including spaces.
nextByte() Reads a byte value.
nextShort() Reads a short value.
nextInt() Reads an int value.
nextLong() Reads a long value.
nextFloat() Reads a float value.
nextDouble() Reads a double value.
nextBoolean() Reads a boolean value.

Steps to Use Scanner in Java

  1. Import the Scanner class:
    import java.util.Scanner;
  2. Create a Scanner object:
    Scanner sc = new Scanner(System.in);
  3. Use Scanner methods to take input:
    int n = sc.nextInt();
    String name = sc.next();
  4. Close Scanner when input is complete:
    sc.close();
Important: Before using Scanner, always import: import java.util.Scanner;

Example: Taking Input Using Scanner

The following program reads a name, ID, and salary from the user using the Scanner class.

ScannerDemo.java
Copy Try Download
import java.util.Scanner;

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

        System.out.print("Enter Name: ");
        String name = sc.next();

        System.out.print("Enter ID: ");
        int id = sc.nextInt();

        System.out.print("Enter Salary: ");
        double salary = sc.nextDouble();

        System.out.println("----------");
        System.out.println("ID: " + id);
        System.out.println("Name: " + name);
        System.out.println("Salary: " + salary);

        sc.close();
    }
}

Sample Input:

Ayan
123
20000

Output:

Enter Name: Enter ID: Enter Salary: ----------
ID: 123
Name: Ayan
Salary: 20000.0
Tip: Use next() for a single word and nextLine() for a full line including spaces.

The nextLine() Pitfall After Numeric Input

A common beginner mistake happens when nextLine() is used after methods like nextInt(), nextDouble(), or nextFloat(). These numeric methods leave the newline character in the input buffer, and the next nextLine() reads that leftover newline.

Problem Example

ScannerPitfall.java
Copy Try Download
import java.util.Scanner;

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

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

        System.out.print("Enter full name: ");
        String fullName = sc.nextLine(); // reads leftover newline

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

        sc.close();
    }
}

Output:

Enter age: 25
Enter full name:
Age: 25
Name:

Fixed Example

To fix this, call an extra nextLine() after numeric input to consume the leftover newline.

ScannerFixed.java
Copy Try Download
import java.util.Scanner;

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

        System.out.print("Enter age: ");
        int age = sc.nextInt();
        sc.nextLine(); // consume leftover newline

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

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

        sc.close();
    }
}

Output:

Enter age: 25
Enter full name: Alice Johnson
Age: 25
Name: Alice Johnson

next() vs nextLine()

Method Reads Spaces Allowed?
next() Single word No
nextLine() Entire line Yes

Output Methods in Java

Java provides different methods to display output on the console. The most common output methods are print(), println(), and printf().

Method Use
System.out.print() Prints output on the same line.
System.out.println() Prints output and then moves to the next line.
System.out.printf() Prints formatted output using format specifiers.

print() does not move the cursor to a new line after printing, while println() moves the cursor to the next line.

PrintVsPrintln.java
Copy Try Download
public class PrintVsPrintln {
    public static void main(String[] args) {
        System.out.print("Hello, ");
        System.out.println("world!");
        System.out.println("Bye");
    }
}

Output:

Hello, world!
Bye

printf() Method in Java

The printf() method is used for formatted printing. It works similarly to C language printf and supports format specifiers like %d, %f, %s, and %n.

General syntax:
System.out.printf(String format, Object... args);

Common printf Format Specifiers

Specifier Meaning
%d Integer value
%f Floating-point value
%s String value
%c Character value
%b Boolean value
%n Platform-independent new line
%% Prints a percent sign
PrintfExample.java
Copy Try Download
public class PrintfExample {
    public static void main(String[] args) {
        int id = 42;
        double price = 123.456;
        String name = "Alice";

        System.out.printf("ID: %05d%n", id);
        System.out.printf("Price: %.2f%n", price);
        System.out.printf("Name: %-10s End%n", name);
    }
}

Output:

ID: 00042
Price: 123.46
Name: Alice      End
Tip: In printf(), use %n instead of \n for a platform-independent new line.

Common Mistakes

  • Forgetting to import Scanner.
  • Not creating a Scanner object.
  • Using next() when nextLine() is needed.
  • Ignoring the nextLine() pitfall after nextInt().
  • Forgetting to close Scanner.
Summary:
  • The Scanner class is used to read input in Java.
  • next() reads one word, while nextLine() reads a full line.
  • After numeric input, use an extra nextLine() before reading a full line.
  • print() prints on the same line.
  • println() prints output and moves to the next line.
  • printf() is used for formatted output.

Interview Questions ⭐

The Scanner class in Java is used to read input from different sources such as keyboard input, files, and strings. It belongs to the java.util package.

To take input using Scanner, import java.util.Scanner, create a Scanner object using new Scanner(System.in), and call methods such as nextInt(), nextDouble(), next(), or nextLine().

The next() method reads a single word until whitespace, while nextLine() reads the entire line including spaces.

After nextInt(), the newline character remains in the input buffer. The next nextLine() call reads that leftover newline. To fix it, call an extra nextLine() before reading the full line.

The print() method prints output on the same line, while println() prints output and then moves the cursor to the next line.

The printf() method in Java is used to print formatted output using format specifiers such as %d for integers, %f for floating-point values, %s for strings, and %n for a new line.

Yes, it is good practice to close a Scanner object using close() when input reading is complete to release system resources.

Next step: Learn Java Command Line Arguments

🚀 Continue to Java Command Line Arguments →

🧠 Test your understanding with a quick quiz



🚀 Quick Knowledge Check

Topic: Input-output | Language: Java

Question 1 of 5
Q1. Which class in Java is commonly used to take input from the keyboard?
Scanner sc = new Scanner(System.in);
Q2. Which printf format specifier prints a date in ISO format (yyyy-MM-dd)?
java.util.Date now = new java.util.Date();
System.out.printf("ISO date: %___%n", now);
Q3. Which of the following is the correct syntax for formatted printing using printf?
int x = 5;
System.out.____("Value: %d%n", x);
Q4. What is the correct way to fix the 'nextLine() after numeric read' pitfall?
int age = sc.nextInt();
// fix here
String name = sc.nextLine();
Q5. Which Scanner method reads a full line including spaces?
Scanner sc = new Scanner(System.in);
String line = sc._____();

🎉 Great job! Continue learning Java step by step.

Discussion

Ask questions, share suggestions, or discuss this lesson.

Please login or create an account to join the discussion and save your learning activity.

Loading comments...

Have you completed this lesson?

Mark this lesson as completed to track your learning progress. To keep track across devices, please login and save your learning progress.

Not completed yet.