Search code examples
javaperformanceparseint

Integer.parseInt(scan.next()) or scan.nextInt()?


I oscillate with using

import java.util.Scanner;
.
.
.
Scanner scan = new Scanner(System.in);
.
.
. 
Integer.parseInt(scan.next());

or

import java.util.Scanner;
.
.
.    
Scanner scan = new Scanner(System.in);
.
.
.
scan.nextInt();    

Which one is more useful, or more precisely; which would be running faster?


Solution

  • Now granted, this is just the Sun implementation, but below is the nextInt(int radix) implementation.

    Note that it uses a special pattern (integerPattern()). This means if you use next() you'll be using your default pattern. Now if you just made a new Scanner() you'll be using a typical whitespace pattern. But if you used a different pattern, you can't be certain you'll be picking up a word. You might be picking up a line or something.

    In the general case I would highly recommend nextInt(), since it provides you with an abstraction, giving you less that's likely to go wrong, and more information when something does.

    Read this at your leisure:

    public int nextInt(int radix) {
        // Check cached result
        if ((typeCache != null) && (typeCache instanceof Integer)
        && this.radix == radix) {
            int val = ((Integer)typeCache).intValue();
            useTypeCache();
            return val;
        }
        setRadix(radix);
        clearCaches();
        // Search for next int
        try {
            String s = next(integerPattern());
            if (matcher.group(SIMPLE_GROUP_INDEX) == null)
                s = processIntegerToken(s);
            return Integer.parseInt(s, radix);
        } catch (NumberFormatException nfe) {
            position = matcher.start(); // don't skip bad token
            throw new InputMismatchException(nfe.getMessage());
        }
    }