package Pack1;
import java.util.Scanner;
public class my_inputs {
public static void main(String[] args) {
Scanner my_input = new Scanner(System.in); // Scanner object created
System.out.println("Enter input: ");
int my_int = my_input.nextInt(); // Collecting integer input
System.out.println("You entered: " + my_int);
my_input.close();
}
}Console Interaction:
Enter input:
42
You entered: 42
| Data Type | Scanner Method | Example Valid User Input |
|---|---|---|
int |
my_input.nextInt() |
42, -150 |
String (1 word) |
my_input.next() |
Rama (stops at space) |
String (full line) |
my_input.nextLine() |
Rama Rao (reads until Enter) |
boolean |
my_input.nextBoolean() |
true or false (case-insensitive) |
double / float |
nextDouble() / nextFloat() |
99.95, 3.5 |
char |
my_input.next().charAt(0) |
A (extracts index 0 of token) |
long / short / byte |
nextLong() / nextShort() / nextByte() |
9000000000, 3200, 120 |
If you enter 30 and 40 and write System.out.println("Sum: " + my_int1 + my_int2);, Java concatenates them as strings and prints 3040! Store int sum = my_int1 + my_int2; (or use parentheses (my_int1 + my_int2)) so Java performs mathematical addition:
package Pack1;
import java.util.Scanner;
public class my_inputs {
public static void main(String[] args) {
Scanner my_input = new Scanner(System.in);
System.out.println("Enter first input: ");
int my_int1 = my_input.nextInt();
System.out.println("Enter second input: ");
int my_int2 = my_input.nextInt();
// Caution: "Sum: " + my_int1 + my_int2 concatenates as strings ("3040")!
// Compute mathematical sum first (or wrap in parentheses):
int sum = my_int1 + my_int2;
System.out.println("Sum of two inputs: " + sum);
my_input.close();
}
}Console Interaction:
Enter first input:
30
Enter second input:
40
Sum of two inputs: 70
Use my_input.next() to read single-word tokens (such as First Name and Last Name), and call my_input.close(); when finished reading all inputs:
package Pack1;
import java.util.Scanner;
public class my_inputs {
public static void main(String[] args) {
Scanner my_input = new Scanner(System.in);
System.out.println("Enter First Name: ");
String my_str1 = my_input.next(); // Reads a single word (up to whitespace)
System.out.println("Enter Last Name: ");
String my_str2 = my_input.next();
System.out.println("Welcome " + my_str1 + " " + my_str2);
my_input.close();
}
}Console Interaction:
Enter First Name:
Rama
Enter Last Name:
Rao
Welcome Rama Rao
Because Scanner does not have a dedicated nextChar() method, read a single character using my_input.next().charAt(0) (see String.charAt()). Here are all seven remaining primitive types in action:
package Pack1;
import java.util.Scanner;
public class my_inputs {
public static void main(String[] args) {
// Demonstrating all primitive Scanner methods using an in-memory input stream:
Scanner my_input = new Scanner("true 99.95 3.5f A 9000000000 3200 120");
boolean my_boolean = my_input.nextBoolean();
double my_double = my_input.nextDouble();
float my_float = my_input.nextFloat();
char my_char = my_input.next().charAt(0); // First character of token!
long my_long = my_input.nextLong();
short my_short = my_input.nextShort();
byte my_byte = my_input.nextByte();
my_input.close();
System.out.println("boolean=" + my_boolean + ", double=" + my_double + ", float=" + my_float);
System.out.println("char=" + my_char + ", long=" + my_long + ", short=" + my_short + ", byte=" + my_byte);
}
}Terminal Output:
boolean=true, double=99.95, float=3.5
char=A, long=9000000000, short=3200, byte=120
When a user types 25 and presses Enter, nextInt() reads 25 but leaves the trailing newline character (\n) in the buffer. If you immediately call nextLine(), it consumes that empty \n and returns an empty string ""! Add an extra sc.nextLine(); right after nextInt() to clear the newline:
import java.util.Scanner;
public class NextLineAfterNextIntFix {
public static void main(String[] args) {
Scanner sc = new Scanner("25\nHyderabad India\n");
int age = sc.nextInt();
sc.nextLine(); // CRITICAL: Consumes the leftover newline after 25!
String city = sc.nextLine(); // Now reads the full line "Hyderabad India"
System.out.println("Age: " + age + " | City: " + city);
sc.close();
}
}Terminal Output:
Age: 25 | City: Hyderabad India
If a user types letters like "abc" when nextInt() is waiting for a number, Java throws an InputMismatchException. Guard numeric reads with a while (!sc.hasNextInt()) loop:
import java.util.Scanner;
public class SafeIntValidation {
public static void main(String[] args) {
Scanner sc = new Scanner("abc 85");
while (!sc.hasNextInt()) {
System.out.println("Invalid integer skipped: " + sc.next());
}
int validScore = sc.nextInt();
System.out.println("Accepted valid integer: " + validScore);
sc.close();
}
}Terminal Output:
Invalid integer skipped: abc
Accepted valid integer: 85
| Method | Delimiter / Stop Rule | Consumes Newline (
)? |
|---|---|---|
next() / nextInt() |
Whitespace (space, tab, newline) | No (leaves trailing
in buffer) |
nextLine() |
Line break (
or
) |
Yes (consumes and strips
) |
Calling my_input.close() closes the underlying System.in keyboard stream for the entire JVM process! Once closed, even creating a brand-new new Scanner(System.in) later in your program will fail to read any input. Only call close() at the very end of main().
On European OS locales where commas are used as decimal separators (99,95), typing 99.95 with a dot throws InputMismatchException unless you configure my_input.useLocale(Locale.US);.
import java.util.Scanner;
public class MyInputsFullDemo {
public static void main(String[] args) {
Scanner sc = new Scanner("30 40 GradeA");
int a = sc.nextInt(), b = sc.nextInt();
char ch = sc.next().charAt(5);
sc.close();
if ((a + b) == 70 && ch == 'A') {
System.out.println("All Java Scanner user input checks passed! sum=70, grade=" + ch);
}
}
}Terminal Output:
All Java Scanner user input checks passed! sum=70, grade=A
next() reads only a single whitespace-delimited token (stopping at the first space or tab), whereas nextLine() reads the entire line of text including spaces up to the Enter key.
Unlike System and String (which live in java.lang), Scanner lives in the java.util package and must be imported explicitly.
Yes! You can pass a String (new Scanner("10 20")) or a java.io.File object (new Scanner(new File("data.txt"))) to the Scanner constructor.
Call my_input.useDelimiter(","); (or my_input.useDelimiter(",\s*");) to tokenize comma-separated values.
Use BufferedReader when reading millions of lines in competitive programming or high-throughput logs where raw I/O speed matters more than built-in token parsing.
byte, short, int, long, float, and double.String.Scanner to read text files from disk.hasNext() and hasNextInt().Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.