I would like to know if using the Scanner class in conjuction with the System.console.readLine() method results in faster input read. To give you an example, I have created the following program using both of the above, only the Scanner class and only the System.console.readLine() method:
Scanner & System.console.readLine():
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.console().readLine());
while (!in.hasNextInt())
in = new Scanner(System.console().readLine());
System.out.println("This is an int: " + in.nextInt());
System.out.println("This is a single char: " + System.console().readLine());
System.out.println("This is a whole String input: " + System.console().readLine());
while (!in.hasNextInt())
in = new Scanner(System.console().readLine());
System.out.println("This is again an int: " + in.nextInt());
}
}
Scanner:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (!in.hasNextInt())
in.next();
System.out.println("This is an int: " + in.nextInt());
System.out.println("This is a single char: " + in.nextLine().charAt(0));
System.out.println("This is a whole String input: " + in.nextLine()); // copy-pasting the "\n" char will break input.
while (!in.hasNextInt())
in.next();
System.out.println("This is again an int: " + in.nextInt());
}
}
Console:
public class Test {
public static void main(String[] args) {
int input;
while (true) {
try {
input = Integer.parseInt(System.console().readLine());
break;
} catch (IllegalNumberFormat e) {}
}
System.out.println("This is an int: " + input);
System.out.println("This is a single char: " + System.console().readLine().charAt(0));
System.out.println("This is a whole String input: " + System.console().readLine());
while (true) {
try {
input = Integer.parseInt(System.console().readLine());
break;
} catch (IllegalNumberFormat e) {}
}
System.out.println("This is again an int: " + input);
}
}
Which of the above would be fastest for equal large amounts of data of each type?