Java Reading String Input
Table of Contents + β
In the last lesson you learned about the Java Scanner class. Now letβs read text, a job that trips up almost everyone. Type a full name like Alex Johnson and a careless program catches only Alex.
This lesson covers:
- The two methods for reading text, and when each one works.
- The one trap that quietly ruins text input.
π Reading one word with next()
next() reads a single token, which is one word with no spaces.
- It stops the moment Scanner sees a space or the Enter key.
- Good for a single-word answer.
Here is a tiny program that reads one word and prints it back.
import java.util.Scanner;
public class OneWord { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
System.out.print("Enter a word: "); String word = scanner.next(); // reads one word only
System.out.println("You typed: " + word); }}Reading it from the top:
- One
Scannerconnects toSystem.in, the keyboard. printkeeps the cursor on the same line, so the user types right next to the question.next()reads one word intoword.- We print
wordback to see what was read.
Output
Enter a word: helloYou typed: helloNow type more than one word, hello there, and press Enter.
Output
Enter a word: hello thereYou typed: hellonext() grabbed only hello and left there behind. It stops at the first space: good for one word, wrong for a full sentence.
π Reading a whole line with nextLine()
nextLine() reads the entire line up to the Enter key and hands it back as one String.
- Use it when the answer has spaces.
- It does not stop at the first space; it keeps reading until Enter.
Here is the same idea with nextLine() instead.
import java.util.Scanner;
public class WholeLine { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: "); String line = scanner.nextLine(); // reads the whole line
System.out.println("You typed: " + line); }}The only change is nextLine() in place of next(), but the result is very different.
Output
Enter a sentence: hello there friendYou typed: hello there friendNothing got dropped. Every word and space came through.
π next() vs nextLine(): the key difference
The difference is all about where the reading stops.
next()stops at the first space and reads one word.nextLine()stops at the Enter key and reads the whole line, spaces included.- Single word, like a username?
next()is fine. - Might have spaces, like a full name or address? Use
nextLine().
Letβs prove it. Same input, two methods, two different results.
import java.util.Scanner;
public class Compare { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
System.out.print("Type your full name: "); String oneWord = scanner.next(); // first word only
System.out.println("next() read: " + oneWord); }}We type a full name with a space, but read it with next().
Output
Type your full name: Alex Johnsonnext() read: AlexThe last name is gone. Now the same input with nextLine().
import java.util.Scanner;
public class CompareLine { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
System.out.print("Type your full name: "); String fullName = scanner.nextLine(); // whole line
System.out.println("nextLine() read: " + fullName); }}Output
Type your full name: Alex JohnsonnextLine() read: Alex JohnsonSame typing, different result. A name with a space is a line, not a word, so it needs nextLine().
π A worked example: ask the name and greet
This program asks for your full name and greets you. A name can have a space, so we read it with nextLine().
import java.util.Scanner;
public class Greeter { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
System.out.print("What is your full name? "); String name = scanner.nextLine();
System.out.println("Welcome, " + name + "!"); System.out.println("Nice to meet you."); }}The flow:
printkeeps the cursor on the same line.nextLine()reads the whole answer, so a space in the middle is safe.+joins the name into a friendly message to print.
Output
What is your full name? Maria GarciaWelcome, Maria Garcia!Nice to meet you.Ask, read, use. The name with its space came through because we picked the right method.
β οΈ The newline-left-in-buffer trap
This trap shows up when you read a number first, then a line of text.
- The buffer is the waiting area where typed characters sit before Java reads them.
- Type
25and press Enter: the buffer holds the25and the invisible Enter key (a newline).
This broken program reads an age with nextInt(), then a full name with nextLine().
import java.util.Scanner;
public class Trap { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: "); int age = scanner.nextInt(); // reads 25, leaves the Enter behind
System.out.print("Enter your full name: "); String name = scanner.nextLine(); // β grabs the leftover Enter, looks empty
System.out.println("Age: " + age); System.out.println("Name: " + name); }}It never lets you type the name. It rushes past and the name comes out empty.
Output
Enter your age: 25Enter your full name: Age: 25Name:What went wrong:
- You typed
25and Enter; the buffer holds25and a leftover newline. nextInt()read the25but left the newline in the buffer.nextLine()saw that leftover newline first; to it, a newline means end of line, so it read an empty line and moved on.nameended up blank.
nextLine() is not broken. The problem is the leftover Enter that nextInt() left behind.
π οΈ The fix: clear the leftover line
After reading a number, add one plain nextLine() to throw the leftover Enter away. Then the real nextLine() works.
import java.util.Scanner;
public class Fixed { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: "); int age = scanner.nextInt();
scanner.nextLine(); // β
clear the leftover Enter
System.out.print("Enter your full name: "); String name = scanner.nextLine();
System.out.println("Age: " + age); System.out.println("Name: " + name); }}We ignore that extra scanner.nextLine() on purpose. Its only job is to eat the leftover newline so the buffer is clean for the next read.
Output
Enter your age: 25Enter your full name: Maria GarciaAge: 25Name: Maria GarciaNow the program waits for the name, and the full name comes through.
A second way to dodge the trap
There is another clean fix: read everything as lines. Use nextLine() for every input, then turn the text into a number yourself with Integer.parseInt(line). If you never mix nextInt() with nextLine(), the leftover-newline trap simply cannot happen. You will see this approach in the next lesson.
π Closing the scanner
When you are done reading input, close the Scanner with close(). It tells Java you are finished with that input source and frees it up.
import java.util.Scanner;
public class CloseDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
System.out.print("Enter your city: "); String city = scanner.nextLine();
System.out.println("You live in " + city + ".");
scanner.close(); // β
done reading, close it }}Output
Enter your city: LondonYou live in London.Two notes:
- Call
close()only when completely finished reading; reading after closing crashes the program. - Closing a Scanner that wraps
System.inalso closes keyboard input for the rest of the program, so close it once, right at the end.
π§© What Youβve Learned
Nice work. You read text in almost every program, and now you can. Recap:
- β
next()reads one word and stops at the first space. - β
nextLine()reads the whole line, spaces included, up to the Enter key. - β
A full name has a space, so it needs
nextLine(), notnext(). - β Reading a number then text hits the leftover-newline trap.
- β
The fix is one extra
nextLine()to clear the Enter, or read everything as lines. - β
Close the Scanner with
close()when you are finished reading.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
What does next() read from the user?
Why: next() reads a single token, which is one word. It stops at the first space.
- 2
You need to read a full name like 'Maria Garcia'. Which method works?
Why: A full name contains a space, so you need nextLine(), which reads the entire line.
- 3
Why does nextLine() come out empty right after nextInt()?
Why: nextInt() reads the number but leaves the newline behind. The next nextLine() reads that leftover newline as an empty line.
- 4
What is the simple fix for the newline trap?
Why: Add one plain nextLine() after the number read to eat the leftover newline, then read the real text.
π Whatβs Next?
You can read text cleanly now, and you know how to dodge the newline trap. Next we focus on the other half of input: reading numbers. We will read whole numbers and decimals, handle bad input, and avoid crashes when the user types something unexpected.