JAVA Syllabus
QUESTIONS & ANSWERS

Explain each function of Scanner Class to retrieve the tokens.

The Scanner class in Java is used to read input from various sources such as files, input streams, and strings. It provides a set of functions to retrieve tokens from the input source. Here are the different functions of Scanner class to retrieve tokens:

  1. next(): This function reads the next token from the input source and returns it as a string. It ignores any leading whitespace and stops reading at the first whitespace character.

  2. nextLine(): This function reads the next line of text from the input source and returns it as a string. It includes any whitespace characters and stops reading at the end of the line.

  3. nextInt(): This function reads the next token from the input source and tries to parse it as an integer. If the token cannot be parsed as an integer, it throws an InputMismatchException.

  4. nextDouble(): This function reads the next token from the input source and tries to parse it as a double. If the token cannot be parsed as a double, it throws an InputMismatchException.

  5. nextBoolean(): This function reads the next token from the input source and tries to parse it as a boolean. It returns true if the token is "true" (case insensitive) and false if the token is "false" (case insensitive). If the token cannot be parsed as a boolean, it throws an InputMismatchException.

  6. nextByte(): This function reads the next token from the input source and tries to parse it as a byte. If the token cannot be parsed as a byte, it throws an InputMismatchException.

  7. nextShort(): This function reads the next token from the input source and tries to parse it as a short. If the token cannot be parsed as a short, it throws an InputMismatchException.

  8. nextLong(): This function reads the next token from the input source and tries to parse it as a long. If the token cannot be parsed as a long, it throws an InputMismatchException.

These functions can be used to retrieve tokens from different types of input sources and parse them into different data types as needed.

06/03/2023, 11:33 am Read : 140 times