C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Introduction to Java

Read full line input incl. spaces using Scanner - Java Program

import java.util.Scanner;

 

public class ReadFullLine {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

 

        System.out.print("Enter your full name or sentence: ");

        String fullLine = sc.nextLine(); // Reads entire line including spaces

 

        System.out.println("You entered: " + fullLine);

 

        sc.close();

    }

}

Output

 
OUTPUT 1:
Enter your full name or sentence: Anand Rao
You entered: Anand Rao

OUTPUT 2:
Enter your full name or sentence: Hello World! Welcome to Java.
You entered: Hello World! Welcome to Java.

Explanation

1. Using Scanner

Scanner sc = new Scanner(System.in);

Scanner reads input from the keyboard.

2. Reading full line

String fullLine = sc.nextLine();

  • nextLine() reads the entire line including spaces
  • Stops reading only when the user presses Enter

Note: next() only reads input up to the first space, so it is not suitable for full sentences.

3. Display input

System.out.println("You entered: " + fullLine);

Prints exactly what the user typed.

4. Close Scanner

sc.close();