If you have ever asked a Java program for a number and then suddenly gotten an empty string when you asked for a name you are not cursed. You hit the classic Scanner newline bug. This guide explains what Scanner next and nextLine actually do and how to avoid the hollow string surprise with simple, reliable patterns.
Keep it short and nerdy. Scanner next reads the next token separated by whitespace. That means one word or one token with no spaces. Scanner nextLine reads the remainder of the current line up to the newline character. That means a full line including spaces. Use next for single word input and nextLine for full line input such as addresses or sentences.
Scanner scan = new Scanner(System.in)
String token = scan.next()
String full = scan.nextLine()
The gotcha happens when you mix numeric reads like nextInt or nextDouble with nextLine. Numeric reads stop before the newline and leave that newline sitting in the input buffer. When you call nextLine right after a numeric read you just consume that leftover newline which returns an empty string. It looks like the program forgot how to read a name. It did not forget. It was polite and consumed your leftover newline.
System.out.println("Enter age")
int age = scan.nextInt()
System.out.println("Enter name")
String name = scan.nextLine() // name becomes empty string
Pick one of these depending on your style and the scale of your code.
System.out.println("Enter age")
int age = scan.nextInt()
scan.nextLine() // discard leftover newline
System.out.println("Enter name")
String name = scan.nextLine()
System.out.println("Enter age")
String ageLine = scan.nextLine()
int age = Integer.parseInt(ageLine)
System.out.println("Enter name")
String name = scan.nextLine()
The Scanner newline bug is not a bug in Java it is a feature of how token based and line based reads interact. Once you know the pattern you can avoid the empty string surprise and write console input that behaves like an adult. If you want to be extra tidy parse lines and validate inputs so users do not test your patience with letters where numbers belong.
Happy debugging and may your input buffers be forever clean.
I know how you can get Azure Certified, Google Cloud Certified and AWS Certified. It's a cool certification exam simulator site called certificationexams.pro. Check it out, and tell them Cameron sent ya!
This is a dedicated watch page for a single video.