javajava.util.scannersystem.exit

Java - System.exit() and scanner


Assuming I have a scanner open, whether it is from System.in or from a file, and at some point in the program I'm activating System.exit(), (and didn't call to scanner.close() before), how (and if) it affects the scanner?

I was thinking since the system.exit() method shuts down the JVM, that everything associated with the scanner will be closed properly, but I didn't find any specific info about that case. For example - will the file that was opened by the scanner be unlocked ("freed" from the scanner) after System.exit()? Will all the relevant processes that are being activated at scanner.close() will be "activated" as well by the System.exit()?


Solution

  • Scanner is a stream, so when the program terminates the stream is automatically closed for you, however it is bad practice to not close streams, because in larger longer running programs they can cause problems, so yes everything closes properly but as said earlier it is bad practice.

    If you have to many streams open at a time it will crash with an outOfMemoryError, here is an example of this

    public static void main(String[] args) {
    LinkedList<Scanner> list = new LinkedList<>();
    while(true)
        list.add(new Scanner(System.in));
    }
    

    so if you dont close your streams after a long time this memory error will result, also note that this error is not caused because there are too many items in the list it is because of the streams

    EDIT:

    public static void main(String[] args) {
        Scanner first = new Scanner(System.in);
        Scanner second = new Scanner(System.in);
        int x = first.nextInt();
        int y = second.nextInt();
        System.out.println("First scan returns: " + x);
        System.out.println("Second scan returns: " + y);
        first.close();
        second.close();
    }
    

    As you can see you can open more than one System.in scanner, however when reading into a variable you have to specify what scanner object you would want to use. However of course this is pointless and i cant think of any reason why you would need more than one System.in scanner open at a time.