java.util.Scanner nextByte()

Description :

This java tutorial shows how to use the nextByte method of Scanner class of java.util package. This method is used to scan tokens in byte data type.

Method Syntax :

There are two overloaded method of Scanner nextByte() java method

java scanner nextByte overload method
Note:
Overloaded methods are those method with same name but with different method signatures


Method 1:

public byte nextByte()

Method 2:

public byte nextByte(int radix)

Parameter Input :

[table]
DataType|Parameter|Description
int|radix|the base number to scan
[/table]

Method Returns :

This method simply returns the byte token on the scanner input determined by the method argument radix.

Compatibility Version :

Requires Java 1.5 and up

Exception :

InputMismatchException

– if the next token does not match the Integer regular expression, or is out of range

NoSuchElementException

– if the invocation of nextByte method is done after the input is already exhausted

IllegalStateException

– if this scanner is closed and we still invoked the nextByte method

Discussion :

The Scanner nextByte() method simply return the byte token on the scanner buffer. There are two overloaded method of nextByte method, which accomplishes the same task. The method without a method argument is the same as calling nextByte(radix) which is the default radix of the Scanner object. The radix currently set by the Scanner object is defined using the method useRadix(radix) and can be determine using the radix() method. The return type of the nextByte method is byte thus if the radix input is 8 then the return value would be converted from octal to byte type.

Make a note that since we are scanning tokens in byte data type, there is limit on the maximum and minimum value possible. Personally i prefer using the nextInt() method instead. The Byte.MAX_VALUE and Byte.MIN_VALUE will show what is the maximum and minimum possible byte value than can be returned.  A InputMismatchException will be thrown if the byte token is out of range.

Java Code Example :

This java example source code demonstrates the use of nextByte method of Scanner class. Basically the code just scans bytes data type on the input string declared on the Scanner constructor.

Sample Output :

Running the nextByte() method example source code of Scanner class will give you the following output

java scanner nextbyte method example

java scanner nextbyte method example

Exception Scenario :

Similar Method :

  • N/A

Suggested Reading List :

References :