Java’s Scanner vs String.split() vs StringTokenizer; which should I use?

Did some metrics around these in a single threaded model and here are the results I got. ~~~~~~~~~~~~~~~~~~Time Metrics~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~ Tokenizer | String.Split() | while+SubString | Scanner | ScannerWithCompiledPattern ~ ~ 4.0 ms | 5.1 ms | 1.2 ms | 0.5 ms | 0.1 ms ~ ~ 4.4 ms | 4.8 ms | 1.1 ms … Read more

Integer.parseInt(scanner.nextLine()) vs scanner.nextInt()

There are 2 observations : Using myScannerInstance.nextInt() leaves behind a new line character. So, if you call nextLine() after nextInt(), the nextLine() will read the new line character instead of the actual data. Consequently, you will have to add another nextLine() after the nextInt() to gobble up that dangling new-line character. nextLine() doesn’t leave behind … Read more

Scanner is never closed

I am assuming you are using java 7, thus you get a compiler warning, when you don’t close the resource you should close your scanner usually in a finally block. Scanner scanner = null; try { scanner = new Scanner(System.in); //rest of the code } finally { if(scanner!=null) scanner.close(); } Or even better: use the … Read more