Home » Java programming language

Java Scanner hasNextByte() Method with Example

Scanner Class hasNextByte() method: Here, we are going to learn about the hasNextByte() method of Scanner Class with its syntax and example.
Submitted by Preeti Jain, on March 26, 2020

Scanner Class hasNextByte() method

Syntax:

    public boolean hasNextByte();
    public boolean hasNextByte(int rad);
  • hasNextByte() method is available in java.util package.
  • hasNextByte() method is used to check whether this Scanner has next token in its input can be manipulated as a byte in the implicit radix (rad) or not.
  • hasNextByte(int rad) method is used to check whether this Scanner has next token in its input can be manipulated as a byte in the explicit or given radix (rad) or not.
  • These methods may throw an exception at the time of representing input as a byte.
    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, hasNextByte(),
    • It does not accept any parameter.
  • In the second case, hasNextByte(int rad),
    • int rad – represents the radix used to manipulate as a byte.

Return value:

In both the cases, the return type of the method is boolean, it returns true when this Scanner input is a valid byte otherwise it returns false.

Example:

// Java program is to demonstrate the example
// of hasNextByte() method of Scanner

import java.util.*;
import java.util.regex.*;

public class HasNextByte {
 public static void main(String[] args) {
  String str = "Java Programming! 3 * 8= 24";

  // Instantiates Scanner
  Scanner sc = new Scanner(str);

  while (sc.hasNext()) {
   // By using hasNextByte() method is to
   // check whether this object next token
   // represents byte or not in the default 
   // radix
   boolean status = sc.hasNextByte();
   System.out.println("sc.hasNextByte(): " + status);


   // By using hasNextByte() method is to
   // check whether this object next token
   // represents byte in the given radix
   // or not
   status = sc.hasNextByte(2);
   System.out.println("sc.hasNextByte(2): " + status);
   sc.next();
  }
  // Scanner closed
  sc.close();
 }
}

Output

sc.hasNextByte(): false
sc.hasNextByte(2): false
sc.hasNextByte(): false
sc.hasNextByte(2): false
sc.hasNextByte(): true
sc.hasNextByte(2): false
sc.hasNextByte(): false
sc.hasNextByte(2): false
sc.hasNextByte(): false
sc.hasNextByte(2): false
sc.hasNextByte(): true
sc.hasNextByte(2): false


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.