Strings and the Class Scanner

In this lesson, we will see how the class Scanner is used with strings.

We introduced the standard class Scanner in the lesson Simple Input from the Keyboard. At that time, we learned how to use it to input numbers typed at the keyboard into our program. In particular, we saw and used the Scanner methods nextInt and nextDouble. It might surprise you to learn that all input to a program, including numeric data, is read as a string. Methods such as nextInt and nextDouble convert the strings they read to the appropriate numeric data.

Using Scanner to read a string

We now will see how to read data as a string and retain it as a String object.

The methods nextLine and next

Both nextLine and next are methods in the class Scanner. The method nextLine reads to the end of a line of user input and returns it as a string. The method next reads the next group of contiguous characters that are not white space and returns it as a string.

For example, consider the following statements:

Get hands-on with 1200+ tech skills courses.