Java – Why nextLine() and not nextString()?

Why nextLine() and not nextString()?… here is a solution to the problem.

Why nextLine() and not nextString()?

I’m new to Java and just starting to learn the language.

There is one thing I don’t understand. I have to use nextInt() to get an Int from the user. However, when I need to get the string, I have to write nextLine().

Why is that?

P.S: That sounds like a silly question, but I need to know :-).

Solution

Consider this: nextLine returns everything as a string until the next closing line (\n). If it’s called nextString, do you think you’ll retrieve everything? In that case, you would post the question “Why does nextString() stop at the end”

tl; dr This is because it searches for the end row (\n).

UPD: In documentation, it calls the “skipped” section. IE。 The cursor goes to the next line and returns everything that was “skipped”. The default output is String, so you have it: everything is skipped as String.

Related Problems and Solutions