In Java, which expression reads a single character from standard input using a Scanner?

Prepare for the Computer Programming Test. Study with flashcards and multiple choice questions, each question has hints and explanations. Get ready for your exam!

Multiple Choice

In Java, which expression reads a single character from standard input using a Scanner?

Explanation:
Reading a single character with a Scanner comes from first grabbing the next input token as a String and then taking its first character. The method next() reads the next word up to whitespace and returns it as a String, and charAt(0) gives you the very first character of that token. So scanner.next().charAt(0) effectively reads one character from standard input. Using charAt(1) would fetch the second character, which isn’t reliable if the user enters only one character. There is no nextChar() method on Scanner, and read() isn’t a Scanner method either (read is for streams), so those options don’t match the API.

Reading a single character with a Scanner comes from first grabbing the next input token as a String and then taking its first character. The method next() reads the next word up to whitespace and returns it as a String, and charAt(0) gives you the very first character of that token. So scanner.next().charAt(0) effectively reads one character from standard input.

Using charAt(1) would fetch the second character, which isn’t reliable if the user enters only one character. There is no nextChar() method on Scanner, and read() isn’t a Scanner method either (read is for streams), so those options don’t match the API.

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy