Java Scanner hasNextLong() Method

The hasNextLong() is a Java Scanner class method which is used to check the next token in this scanner's input can be interpreted as a long value in the default radix or not. It returns true if it is interprated as a long value, otherwise returns false. There is two different types of Java hasNextLong() method which can be differentiated depending on its parameter. These are:

  • Java Scanner hasNextLong() Method
  • Java Scanner hasNextLong(int radix) Method

hasNextLong() Method:

This is a Java Scanner class method which is used to check the next token in this scanner's input can be interpreted as a long value in the default radix using the nextLong() method.

hasNextLong(int radix) Method:

This is an inbuilt method of Java Scanner class which is used to check the next token in this scanner's input can be interpreted as a long value in the specified radix using the nextLong() method.

Syntax

Following is the declaration of hasNextLong() method:

Parameter

DataTypeParameterDescriptionRequired/Optional
intradixIt is used to interpret the token as a long value.Required

Returns

The hasNextLong() method returns true if and only if this scanner's next token is a valid long value.

Exceptions

IllegalStateException- This method throws exception if the innvocation is done after the scanner has been closed.

IllegalArgumentException- It throws this exception if the specified radix is out of range.

Compatibility Version

Java 1.5 and above

Example 1

Output:

Is Long Value: false
Scan String: Facebook.com
Is Long Value: true
Scan String: 1234567890987654321

Example 2

Output:

Give me a bunch of numbers in a line (or 'exit')
3745327 43569 5468943
Sum is 9257839

Example 3

Output:

Found Long: ACE

Example 4

Output:

Exception in thread "main" java.lang.IllegalArgumentException: radix:598670
	at java.base/java.util.Scanner.setRadix(Scanner.java:1368)
	at java.base/java.util.Scanner.nextLong(Scanner.java:2370)
	at myPackage.ScannerHasNextLongExample4.main(ScannerHasNextLongExample4.java:10)