We use reading string input to get words or sentences typed by a user while the program is running.
0
0
Reading string input in Java
Introduction
When you want to ask the user for their name.
When you need to get a message or comment from the user.
When you want to read commands or options typed by the user.
When you want to collect any text information from the user during the program.
Syntax
Java
import java.util.Scanner; Scanner scanner = new Scanner(System.in); String input = scanner.nextLine();
You must import java.util.Scanner to read input from the keyboard.
nextLine() reads the whole line typed by the user until they press Enter.
Examples
This reads a full line of text and stores it in the variable
name.Java
Scanner scanner = new Scanner(System.in); String name = scanner.nextLine();
This asks the user to enter their city and reads the input line.
Java
Scanner scanner = new Scanner(System.in); System.out.print("Enter your city: "); String city = scanner.nextLine();
This reads a line and then prints it back to the user.
Java
Scanner scanner = new Scanner(System.in); String sentence = scanner.nextLine(); System.out.println("You typed: " + sentence);
Sample Program
This program asks the user to type their name, reads the full line, and then greets them by name.
Java
import java.util.Scanner; public class ReadStringInput { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Please enter your name: "); String name = scanner.nextLine(); System.out.println("Hello, " + name + "!"); scanner.close(); } }
OutputSuccess
Important Notes
Always close the Scanner after use with scanner.close() to free resources.
nextLine() reads the entire line including spaces until Enter is pressed.
If you mix nextLine() with other Scanner methods like nextInt(), be careful to consume leftover newlines.
Summary
Use Scanner and nextLine() to read full string input from the user.
Remember to import java.util.Scanner and close the scanner when done.
This lets your program interact by getting text typed by the user.