Scanner close() method in Java with Examples
The close() method ofjava.util.Scanner class closes the scanner which has been opened. If the scanner is already closed then on calling this method, it will have no effect.
Syntax:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Return Value: The function does not return any value.
Below programs illustrate the above function:
Program 1:
Reference:https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#close()
Closes this scanner.
Returns the this is currently using to match delimiters.
Attempts to find the next occurrence of the specified pattern ignoring delimiters.
Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.
Attempts to find the next occurrence of the specified pattern.
Attempts to find the next occurrence of a pattern constructed from the specified string, ignoring delimiters.
Returns true if this scanner has another token in its input.
Returns true if the next complete token matches the specified pattern.
Returns true if the next token matches the pattern constructed from the specified string.
Returns true if the next token in this scanner's input can be interpreted as a using the method.
Returns true if the next token in this scanner's input can be interpreted as a in the default radix using the method.
Returns true if the next token in this scanner's input can be interpreted as a in the specified radix using the method.
Returns true if the next token in this scanner's input can be interpreted as a boolean value using a case insensitive pattern created from the string "true|false".
Returns true if the next token in this scanner's input can be interpreted as a byte value in the default radix using the method.
Returns true if the next token in this scanner's input can be interpreted as a byte value in the specified radix using the method.
Returns true if the next token in this scanner's input can be interpreted as a double value using the method.
Returns true if the next token in this scanner's input can be interpreted as a float value using the method.
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the method.
Returns true if the next token in this scanner's input can be interpreted as an int value in the specified radix using the method.
Returns true if there is another line in the input of this scanner.
Returns true if the next token in this scanner's input can be interpreted as a long value in the default radix using the method.
Returns true if the next token in this scanner's input can be interpreted as a long value in the specified radix using the method.
Returns true if the next token in this scanner's input can be interpreted as a short value in the default radix using the method.
Returns true if the next token in this scanner's input can be interpreted as a short value in the specified radix using the method.
Returns the last thrown by this 's underlying .
Returns this scanner's locale.
Returns the match result of the last scanning operation performed by this scanner.
Finds and returns the next complete token from this scanner.
Returns the next token if it matches the specified pattern.
Returns the next token if it matches the pattern constructed from the specified string.
Scans the next token of the input as a .
Scans the next token of the input as a .
Scans the next token of the input as a .
Scans the next token of the input into a boolean value and returns that value.
Scans the next token of the input as a .
Scans the next token of the input as a .
Scans the next token of the input as a .
Scans the next token of the input as a .
Scans the next token of the input as an .
Scans the next token of the input as an .
Advances this scanner past the current line and returns the input that was skipped.
Scans the next token of the input as a .
Scans the next token of the input as a .
Scans the next token of the input as a .
Scans the next token of the input as a .
Returns this scanner's default radix.
The remove operation is not supported by this implementation of .
Resets this scanner.
Skips input that matches the specified pattern, ignoring delimiters.
Skips input that matches a pattern constructed from the specified string.
Returns the string representation of this .
Sets this scanner's delimiting pattern to the specified pattern.
Sets this scanner's delimiting pattern to a pattern constructed from the specified .
Sets this scanner's locale to the specified locale.
Sets this scanner's default radix to the specified radix.
A breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various methods.
For example, this code allows a user to read a number from :
As another example, this code allows types to be assigned from entries in a file :
The scanner can also use delimiters other than whitespace. This example reads several items in from a string:
prints the following output:
The same output can be generated with this code, which uses a regular expression to parse all four tokens at once:
The default whitespace delimiter used by a scanner is as recognized by .. The method will reset the value of the scanner's delimiter to the default whitespace delimiter regardless of whether it was previously changed.
A scanning operation may block waiting for input.
The and methods and their primitive-type companion methods (such as and ) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both and methods may block waiting for further input. Whether a method blocks has no connection to whether or not its associated method will block.
The , , and methods operate independently of the delimiter pattern. These methods will attempt to match the specified pattern with no regard to delimiters in the input and thus can be used in special circumstances where delimiters are not relevant. These methods may block waiting for more input.
When a scanner throws an , the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
Depending upon the type of delimiting pattern, empty tokens may be returned. For example, the pattern will return no empty tokens since it matches multiple instances of the delimiter. The delimiting pattern could return empty tokens since it only passes one space at a time.
A scanner can read text from any object which implements the interface. If an invocation of the underlying readable's method throws an then the scanner assumes that the end of the input has been reached. The most recent thrown by the underlying readable can be retrieved via the method.
When a is closed, it will close its input source if the source implements the interface.
A is not safe for multithreaded use without external synchronization.
Unless otherwise mentioned, passing a parameter into any method of a will cause a to be thrown.
A scanner will default to interpreting numbers as decimal unless a different radix has been set by using the method. The method will reset the value of the scanner's radix to regardless of whether it was previously changed.
Localized numbers
An instance of this class is capable of scanning numbers in the standard formats as well as in the formats of the scanner's locale. A scanner's initial locale is the value returned by the method; it may be changed via the method. The method will reset the value of the scanner's locale to the initial locale regardless of whether it was previously changed.
The localized formats are defined in terms of the following parameters, which for a particular locale are taken from that locale's object, , and its and object, .
- LocalGroupSeparator
- The character used to separate thousands groups, i.e.,
- LocalDecimalSeparator
- The character used for the decimal point, i.e.,
- LocalPositivePrefix
- The string that appears before a positive number (may be empty), i.e.,
- LocalPositiveSuffix
- The string that appears after a positive number (may be empty), i.e.,
- LocalNegativePrefix
- The string that appears before a negative number (may be empty), i.e.,
- LocalNegativeSuffix
- The string that appears after a negative number (may be empty), i.e.,
- LocalNaN
- The string that represents not-a-number for floating-point values, i.e.,
- LocalInfinity
- The string that represents infinity for floating-point values, i.e.,
Number syntax
The strings that can be parsed as numbers by an instance of this class are specified in terms of the following regular-expression grammar, where Rmax is the highest digit in the radix being used (for example, Rmax is 9 in base 10).
- NonAsciiDigit:
- A non-ASCII character c for which returns true
- Non0Digit:
- RmaxNonASCIIDigit
- Digit:
- RmaxNonASCIIDigit
- GroupedNumeral:
- Non0DigitDigitDigit
- LocalGroupSeparatorDigitDigitDigit
- Numeral:
- DigitGroupedNumeral
- Integer:
- Numeral
- LocalPositivePrefixNumeralLocalPositiveSuffix
- LocalNegativePrefixNumeralLocalNegativeSuffix
- DecimalNumeral:
- Numeral
- NumeralLocalDecimalSeparatorDigit
- LocalDecimalSeparatorDigit
- Exponent:
- Digit
- Decimal:
- DecimalNumeralExponent
- LocalPositivePrefixDecimalNumeralLocalPositiveSuffixExponent
- LocalNegativePrefixDecimalNumeralLocalNegativeSuffixExponent
- HexFloat:
- NonNumber:
- LocalNanLocalInfinity
- SignedNonNumber:
- NonNumber
- LocalPositivePrefixNonNumberLocalPositiveSuffix
- LocalNegativePrefixNonNumberLocalNegativeSuffix
- Float:
- DecimalHexFloatSignedNonNumber
Whitespace is not significant in the above regular expressions.
- Since:
- 1.5
Java.util.Scanner.close() Method
Description
The java.util.Scanner.close() method closes this scanner.If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close method will be invoked. If this scanner is already closed then invoking this method will have no effect.
Declaration
Following is the declaration for java.util.Scanner.close() method
public void close()Parameters
NA
Return Value
This method does not return any value.
Exception
NA
Example
The following example shows the usage of java.util.Scanner.close() method.
Live Demo
package com.tutorialspoint; import java.util.*; public class ScannerDemo { public static void main(String[] args) { String s = "Hello World! 3 + 3.0 = 6"; // create a new scanner with the specified String Object Scanner scanner = new Scanner(s); // print the next line of the string System.out.println("" + scanner.nextLine()); // close the scanner System.out.println("Closing Scanner..."); scanner.close(); System.out.println("Scanner Closed."); } }Let us compile and run the above program, this will produce the following result −
Hello World! 3 + 3.0 = 6 Closing Scanner... Scanner Closed.java_util_scanner.htm
Close java scanner
Java Scanner close() Method
next →← prev
The close() is a method of Java Scanner class which is used to closes this scanner.
Syntax
Following is the declaration of close() method:
Parameter
This method does not accept any parameter.
Returns
The close() method does not return any value.
Exceptions
NA
Compatibility Version
Java 1.5 and above
Example 1
Output:
Example 2
Output:
Example 3
Output:
Next TopicJava Scanner Class
← prevnext →
Best Java code snippets using java.util.Scanner.close(Showing top 20 results out of 5,328)
Refine search
- Common ways to obtain Scanner
private void myMethod () {
}
You will also like:
- Modern driveways designs
- Nlxf des moines
- Counselor for women
- Wolf run anime
- Minecraft shower ideas
- Mens fidget spinner ring
- Presonus studio one sale
- Basketball memes funny
- 62te transmission upgrades
Close a Scanner in Java
- Close a in Java After Printing the Standard Input From the User
- Close a in Java After Printing a Specified String That Has New Line Characters in Between
- Use the Method to Close in Java After Reading the Contents of a File
In this tutorial, we will learn how to close a scanner in Java, and when we should use it. The class has a method that is especially available to close the opened scanner. Even if we don’t call the method explicitly, the interface will be invoked, closing the stream. It is a good practice to close a scanner explicitly.
Below are the examples that show how and when we can use the method.
Close a in Java After Printing the Standard Input From the User
In the code below, we have created a object that takes the standard input from the user in the constructor. The method returns the input that was skipped. It reads the entire line of input till the end of the line, including spaces and line separators.
The input is printed, and then we close the by calling the method on the object . After the is closed, if we want to use like we are doing below with , it will throw an exception because the stream or has been closed.
Output:
Close a in Java After Printing a Specified String That Has New Line Characters in Between
In this example, we will separate the string into different lines using and . is used to indicate a new line, and as the notices a new line, it goes to a new line and then prints it. Thus the output has all the three subjects in in different lines.
This is one of the situations when we might want to call the method as we don’t want the to scan any further new lines.
Output:
Use the Method to Close in Java After Reading the Contents of a File
It is recommended to always close the when we are reading a file. It ensures that no input or output stream is opened, which is not in use. The following example shows how we can read a string from the file and then close the once the operation has been done.
Output:
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.