Convert string to int with Java

In Java to convert a string to int requires the class java.lang.Integer.

Primitive int

The returned result will be a primitive integer.

String number = "1234567890";
int result = Integer.parseInt(number);
System.out.println(result);

Integer object

The returned result will be an integer object.

String number = "1234567890";
Integer result = Integer.valueOf(number);
System.out.println(result);

Read standard input (stdin) with java.io.Console in Java

In JDK 1.6, reading standard input (stdin) changed to a simple approach using java.io.Console.

readLine takes input from FileDescriptor.in which is a handle to System.in which uses the InputStream class.

System.out.println("Enter text:");
// Note: console.readLine returns null when used from an IDE
String input = System.console().readLine();
System.out.println(input);

Using Scanner is a friendly approach when using an IDE.

Read standard input (stdin) with Scanner in Java

Since JDK 1.5 a popular way to read input from standard input (stdin) is using the Scanner class.

Scanner takes input from System.in which uses the InputStream class.

public class ReadConsoleInput {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter string:");
        String next = scanner.next();
        System.out.println("Enter int:");
        int nextInt = scanner.nextInt();
        scanner.close();

        System.out.println("String is: " + next);
        System.out.println("Int is: " + nextInt);
    }
}