Home »
Java programming language
Java Scanner nextByte() Method with Example
Scanner Class nextByte() method: Here, we are going to learn about the nextByte() method of Scanner Class with its syntax and example.
Submitted by Preeti Jain, on March 26, 2020
Scanner Class nextByte() method
Syntax:
public byte nextByte();
public byte nextByte(int rad);
- nextByte() method is available in java.util package.
- nextByte() method is used to read the next token of the input as a byte value at the implicit radix (rad) of this Scanner object.
- nextByte(int rad) method is used to read the next token of the input as a byte value at the explicit or given radix (rad) of this Scanner object.
-
These methods may throw an exception at the time of representing input as a byte.
- InputMismatchException: This exception may throw when the next token of the input mismatch.
- NoSuchElementException: This exception may throw when no such element exists
- IllegalStateException: This exception may throw when this Scanner is not opened.
- These are non-static methods, it is accessible with class object & if we try to access these methods with the class name then we will get an error.
Parameter(s):
-
In the first case, nextByte(),
- It does not accept any parameter.
-
In the second case, nextByte(int rad),
- int rad – represents the radix used to manipulate the token as a byte.
Return value:
In both the cases, the return type of the method is byte, it retrieves the byte read from the input.
Example:
// Java program is to demonstrate the example
// of nextByte() of Scanner
import java.util.*;
import java.util.regex.*;
public class NextByte {
public static void main(String[] args) {
String str = "Java Programming! 3 * 8= 24 + b";
byte b = 10;
// Instantiates Scanner
Scanner sc = new Scanner(str);
while (sc.hasNext()) {
// By using nextByte() method isto
// return the next token as a
// byte in the default radix
if (sc.hasNextByte()) {
byte next_b = sc.nextByte();
System.out.println("sc.nextByte()): " + next_b);
}
// By using nextByte(radix) is to return
// the byte value with the given radix
if (sc.hasNextByte()) {
byte next_r = sc.nextByte(9);
System.out.println("sc.nextByte(9)): " + next_r);
}
sc.next();
}
// Scanner closed
sc.close();
}
}
Output
sc.nextByte()): 3
sc.nextByte()): 24