Scanner Class and Output in Java

The Scanner class is widely used in Java to take user input, and Java provides three main methods (print(), println(), and printf()) for displaying output effectively.


Scanner Class in Java

  • There are so many classes to take input from the keyboard, Scanner class is one of them.

  • The Java Scanner class breaks input into tokens using a whitespace delimiter by default and provides methods to read various primitive types.

  • Scanner class extends Object and implements Iterator and Closeable interfaces.

Common Methods of Scanner
Method Description
next() to read String
nextLine() to read String including spaces
nextByte() to read byte
nextShort() to read short
nextInt() to read int
nextLong() to read long
nextFloat() to read float
nextDouble() to read double
nextBoolean() to read boolean

Before using these methods, create a Scanner object.

  1. Import the class:
    import java.util.Scanner;
  2. Create object wherever needed:
    Scanner sc = new Scanner(System.in);
  3. Call methods to take input:
    int n = sc.nextInt();
    String name = sc.next(); or String name = sc.nextLine();
Example: Scanner Input
ScannerDemo.java Copy Code
import java.util.Scanner;  // Import the Scanner class from java.util package

class ScannerDemo {  
    public static void main(String args[]) {  
        // Create a Scanner object to read input from keyboard
        Scanner sc = new Scanner(System.in);        
        
        // Prompt the user to enter a name
        System.out.print("Enter Name:");  
        String name = sc.next();  // Read a single word string from user input

        // Prompt the user to enter an integer ID
        System.out.print("Enter ID:");  
        int id = sc.nextInt();  // Read an integer from user input

        // Prompt the user to enter a salary
        System.out.print("Enter Salary:");  
        double sal = sc.nextDouble();  // Read a double value from user input

        // Print a separator
        System.out.println("----------"); 

        // Display the entered values
        System.out.println("ID: " + id);  
        System.out.println("Name: " + name);  
        System.out.println("Salary: " + sal);  

        // Close the Scanner object to free resources
        sc.close();  
    }  
}
                        

Enter Name:Ayan
Enter ID:123
Enter Salary:20000
----------
ID:123
Name:Ayan
Salary:20000.0
                        

Output Methods: print, println, and printf:


In Java, there are several ways to output data to the console:

  • System.out.print() → Prints text on the same line without moving to a new line.
  • System.out.println() → Prints text and moves the cursor to a new line after output.
  • System.out.printf() → Prints formatted text using format specifiers, similar to C's printf. Example specifiers: %d (integer), %f (floating-point), %s (string).
  • To start a new line in printf, use %n instead of \n for platform-independent newline.
Example: Difference between print and println:
System.out.print("Hello, ");  // stays on the same line
System.out.println("world!"); // moves to next line after printing
System.out.println("Bye");            
Output:
Hello, world!
Bye
            

printf (Formatted Printing):


Signature: System.out.printf(String format, Object... args)

Key Features:
Powerful C-style formatting: width, precision, alignment, thousands separators, dates, etc.
Returns the PrintStream so you can chain calls: System.out.printf("x=%d%n", x).printf("y=%d%n", y);
System.out.format(...) is an exact synonym.

General Format Specifier Syntax:
%[argument_index$][flags][width][.precision]conversion
Common Conversions:
  • %d - integer (decimal)
  • %f - floating point (default 6 decimals)
  • %e - scientific notation
  • %g - compact (scientific or decimal)
  • %s - string
  • %c - char
  • %b - boolean
  • %x - hex integer
  • %n - newline
  • %t - date/time (with additional letters)
  • %% - literal %
Useful Flags:
  • - : left align within width
  • + : show sign
  • 0 : zero pad
  • , : grouping separator (e.g., 1,234)
  • ( : negative numbers in parentheses (Locale-specific)
Examples:

// Print integer with width and zero-padding
System.out.printf("ID: %05d%n", 42); // Output: ID: 00042

// Print floating-point with 2 decimal places
System.out.printf("Price: %.2f%n", 123.456); // Output: Price: 123.46

// Print string left-aligned within 10 characters
System.out.printf("Name: %-10s End%n", "Alice"); // Output: Name: Alice      End

// ISO and custom date/time formatting
java.util.Date now = new java.util.Date();
System.out.printf("ISO date: %tF%n", now);           // yyyy-MM-dd
System.out.printf("Time: %tT%n", now);               // HH:mm:ss
System.out.printf("Custom: %1$td/%1$tm/%1$tY %1$tR%n", now); 
// Note the reuse of the 1st argument via %1$...
    

Next: Java Type Casting



🚀 Quick Knowledge Check

Topic: Input-output | Language: Java

Q1. 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);
Q2. Which of the following is the correct syntax for formatted printing using printf?
int x = 5;
System.out.____("Value: %d%n", x);
Q3. What is the correct way to fix the 'nextLine() after numeric read' pitfall?
int age = sc.nextInt();
// fix here
String name = sc.nextLine();
Q4. Which class in Java is commonly used to take input from the keyboard?
Scanner sc = new Scanner(System.in);
Q5. Which Scanner method reads a full line including spaces?
Scanner sc = new Scanner(System.in);
String line = sc._____();