java.util.Scanner hasNextByte()

Description :

This java tutorial shows how to use the hasNextByte method of Scanner class of java.util package. This method returns true if the next byte on the scanner buffer can be translated to byte data type otherwise false.

Method Syntax :

public boolean hasNextByte()

Parameter Input :

 

DataType Parameter Description
N/A N/A N/A

 

Method Returns :

This method simply returns a boolean data type which corresponds to the scanner token that can be interpreted as byte. Return true if next token is byte otherwise false.

Compatibility Version :

Requires Java 1.5 and up

Exception :

IllegalStateExcepti0n

– the method hasNextByte method will throw this exception if the invocation is done after the scanner is already closed.

Discussion :

The Scanner hasNextByte() method to scans and check if the tokens contains a byte data type. To give an overview on byte data type, the maximum value to be considered a byte is 127 and minimum value is -128.

Java Code Example :

This java example source code demonstrates the use of hasNextByte method of Scanner class. Basically the code just checks if the tokens contains a byte.

package com.teknoscope.java.tutorial.scanner;

import java.io.FileNotFoundException;
import java.util.Scanner;

/*
 * Example java source code on the usage of
 * Scanner hasNextByte() method
 * Check if there is a byte
 */

public class ScannerHasNextByte {

	public static void main(String[] args) throws FileNotFoundException {
		// Declare File object

		// initialize the scanner
		Scanner scan = new Scanner("** Byte number is -112 **");
		// iterate through the file line by line
		while(scan.hasNext()){
			if(scan.hasNextByte()){
				System.out.println("Found a byte!");
			}
			scan.next();

		}
		scan.close();

	}
}

Sample Output :

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

java scanner hasnextbyte method example

java scanner hasnextbyte method example

Exception Scenario :

Exception in thread "main" java.lang.IllegalStateException: Scanner closed
	at java.util.Scanner.ensureOpen(Unknown Source)
	at java.util.Scanner.hasNext(Unknown Source)
	at java.util.Scanner.hasNextByte(Unknown Source)
	at java.util.Scanner.hasNextByte(Unknown Source)
	at com.teknoscope.java.tutorial.scanner.ScannerHasNextByte.main(ScannerHasNextByte.java:28)

Similar Method :

  • N/A

Suggested Reading List :

References :