Input with Scanner, String basics, ++ and +=
Reading numbers and text from the keyboard, String methods (length, charAt, substring, indexOf, equals) and the increment/compound assignment operators. The first lines of writing questions and the sneakiest part of tracing are here.
This page combines two jobs: getting data from the user (Scanner) and working with text (String). There are also ++ and +=, the place where tracing questions set the most traps. In writing questions, every question that starts with “take a number from the user” wants the three Scanner lines; you should be able to write them by reflex.
Golden rules:
- The three Scanner lines:
import java.util.Scanner;,new Scanner(System.in),input.nextInt(). next()is one word,nextLine()is the whole line. After nextInt, nextLine comes back empty.- String indexes start at 0, and the last index is
length() - 1. - Strings are compared with
equals, never with==. x++uses first then increments,++xincrements first then uses.
Reading from the keyboard with Scanner
Scanner is a class in Java’s ready-made library. Before using it you write an import at the very top of the file, then you create a Scanner object.
import java.util.Scanner; // 1) import, above the class
public class Profile {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // 2) a Scanner connected to the keyboard
System.out.print("Enter age: ");
int age = input.nextInt(); // 3) read according to the type
System.out.print("Enter GPA: ");
double gpa = input.nextDouble();
System.out.print("Enter name: ");
String name = input.next();
System.out.println(name + " is " + age + ", GPA " + gpa);
}
}
In the console (when the user types 19, 3.4 and Deniz):
Enter age: 19
Enter GPA: 3.4
Enter name: Deniz
Deniz is 19, GPA 3.4
It is customary to use print (not println) for the prompt text: the cursor stays on the same line and the user types the answer next to the question.
| Method | What it reads | Example input → value |
|---|---|---|
nextInt() | an int | 42 → 42 |
nextDouble() | a double | 3.4 → 3.4 |
next() | a single word up to a space | Ali Veli → "Ali" |
nextLine() | all of the rest of the line | Ali Veli → "Ali Veli" |
nextBoolean() | true or false | true → true |
How tokens work
Scanner splits the input into pieces (tokens) at spaces. next, nextInt and nextDouble take the next piece. nextLine does not split; it takes the rest of the line as it is.
String first = input.next();
String line = input.nextLine();
System.out.println("[" + first + "]");
System.out.println("[" + line + "]");
When the input is Ali Veli Can:
[Ali]
[ Veli Can]
Notice the leading space: next took “Ali”, and nextLine took everything left, space included.
The nextLine after nextInt trap
System.out.print("Age: ");
int age = input.nextInt();
System.out.print("Full name: ");
String name = input.nextLine();
System.out.println("[" + name + "] " + age);
The user types 20 and presses Enter, and is about to type Deniz Yilmaz. But the program finishes without waiting:
Age: Full name:
[] 20
nextInt took only 20; the line break produced by the Enter key stayed in the input. nextLine saw that line break and immediately returned an empty String. The fix: put an empty input.nextLine(); in between to swallow the line break.
int age = input.nextInt();
input.nextLine(); // throw away the leftover line break
String name = input.nextLine();
Age: Full name:
[Deniz Yilmaz] 20
(Because the input was given from a file during verification, the typed values were not echoed on screen.)
PITFALL · wrong type of input. If the user types
abcwhen nextInt is expecting a number, the program crashes:java.util.InputMismatchException. This is a runtime error and does not show up at compile time.
String basics
A String is a sequence of characters. Every character has an index, and counting starts at 0.
S o f t w a r e
0 1 2 3 4 5 6 7 length() = 8, last index 7
String s = "Software";
System.out.println(s.length());
System.out.println(s.charAt(0) + " " + s.charAt(7));
System.out.println(s.substring(4)); // from 4 to the end
System.out.println(s.substring(0, 4)); // 0,1,2,3 (4 excluded)
System.out.println(s.indexOf('w') + " " + s.indexOf("ware") + " " + s.indexOf('z'));
System.out.println(s.toUpperCase() + " " + s.toLowerCase());
System.out.println(" hi ".trim() + "|");
System.out.println(s.equals("software") + " " + s.equalsIgnoreCase("software"));
System.out.println(s.charAt(s.length() - 1));
8
S e
ware
Soft
4 4 -1
SOFTWARE software
hi|
false true
e
| Method | Returns | Note |
|---|---|---|
length() | int | with parentheses! (for arrays length has none) |
charAt(i) | char | StringIndexOutOfBoundsException if i is invalid |
substring(a, b) | String | a included, b excluded; length is b - a |
substring(a) | String | from a to the end |
indexOf(x) | int | index of the first occurrence, -1 if absent |
toUpperCase(), toLowerCase() | String | a new String |
trim() | String | removes leading and trailing spaces |
equals(t) | boolean | case-sensitive |
equalsIgnoreCase(t) | boolean | ignores letter case |
A String is immutable
No String method changes the existing String. They all return a new String. If you do not assign the result somewhere, it is lost.
String t = "bau";
t.toUpperCase(); // the result was thrown away
System.out.println(t);
t = t.toUpperCase(); // assign the result to t
System.out.println(t);
bau
BAU
Concatenation
If either side of a + is a String, concatenation is done. The evaluation goes left to right, so the order decides everything.
int x = 3, y = 4;
System.out.println("x + y = " + x + y); // "x + y = 3" + 4
System.out.println("x + y = " + (x + y)); // parentheses first
System.out.println(x + y + " toplam"); // 3 + 4 first
String msg = "Skor";
msg += ": ";
msg += 90;
System.out.println(msg);
x + y = 34
x + y = 7
7 toplam
Skor: 90
Increment and decrement: ++ and —
x++ and ++x both increase x by one. The difference is which value they give inside an expression:
- Postfix
x++: gives the old value to the expression, then increments. - Prefix
++x: increments first, gives the new value to the expression.
int i = 5;
int j = i++; // j gets the old value
System.out.println(i + " " + j);
int k = ++i; // increment first, then give
System.out.println(i + " " + k);
int n = 3;
System.out.println(n++ + " " + n);
System.out.println(--n * 2);
6 5
7 7
3 4
6
line i j k explanation
int i = 5 5
int j = i++ 6 5 j took the old 5, i became 6 afterwards
int k = ++i 7 5 7 i became 7 first, k took the new 7
On a line by itself (x++; or ++x;) there is no difference between the two. The difference only shows up inside another operation.
Compound assignment
x += 3 is short for x = x + 3. The same goes for -=, *=, /=, %=.
int p = 10;
p += 5; System.out.print(p + " ");
p -= 3; System.out.print(p + " ");
p *= 2; System.out.print(p + " ");
p /= 5; System.out.print(p + " "); // 24 / 5 = 4, int division
p %= 3; System.out.println(p);
int c = 5;
c += 2.7; // hidden cast: c = (int) (c + 2.7)
System.out.println(c);
int dd = 4;
dd *= 2 + 3; // right side first: dd = dd * 5
System.out.println(dd);
15 12 24 4 1
7
20
PITFALL ·
*=takes the right side as a whole. The expressiondd *= 2 + 3isdd = dd * (2 + 3)(20), notdd = dd * 2 + 3(11). Assignment operators have the lowest precedence; the right side is always computed first.
Common mistakes
| Wrong idea | The truth |
|---|---|
import is written inside main | At the very top of the file, before the class |
next() reads the whole line | One word; use nextLine() for a line |
| nextLine after nextInt reads the name | It returns an empty String; put input.nextLine(); in between |
s.length | For a String it is a method: s.length() |
The first character is charAt(1) | charAt(0) |
substring(2, 5) is 4 characters | 3 characters: 2, 3, 4 |
s.toUpperCase(); changes s | It does not; s = s.toUpperCase(); |
if (s == "yes") | if (s.equals("yes")) |
charAt(1) + charAt(2) puts two letters side by side | Two chars are added, a number comes out |
x++ and ++x are the same everywhere | Inside an expression they give different values |
Test yourself
Exam-style questions. Solve them on paper first, then reveal the answer.
The user types 17 5 and presses Enter. What is printed?
Scanner input = new Scanner(System.in);
int a = input.nextInt();
int b = input.nextInt();
System.out.println(a / b + " " + a % b);Show answer
nextInt reads the space-separated pieces (tokens) in order: a = 17, b = 5. 17 / 5 = 3 (int division), 17 % 5 = 2. First / and %, then String concatenation.
The user types Bau 2 and presses Enter. What is printed?
String w = input.next();
int n = input.nextInt();
System.out.println(w + n + 1);Show answer
w = "Bau", n = 2. Left to right: "Bau" + 2 = "Bau2" (a String), then + 1 = "Bau21". No addition happens, because the left side is already a String.
The user types 42 is the answer and presses Enter. What is printed?
int n = input.nextInt();
String rest = input.nextLine();
System.out.println(n + "|" + rest + "|");Show answer
nextInt reads only 42 and leaves the cursor right after it. nextLine reads the rest of the line, including the leading space: " is the answer".
The user types yes. What is printed?
String answer = input.next();
System.out.println(answer == "yes");
System.out.println(answer.equals("yes"));Show answer
true
With Strings, == does not compare the contents; it compares whether the two variables point to the same object. The "yes" read by Scanner is a new object, the "yes" in the code is another object: false. Content comparison is always done with equals.
What is printed?
String s = "Bahcesehir";
System.out.println(s.length() + " " + s.charAt(3) + " " + s.substring(2, 5));Show answer
The length is 10 letters. Indexes start at 0: B0 a1 h2 c3, so charAt(3) = 'c'. substring(2, 5) takes indexes 2, 3, 4 (5 excluded): h, c, e → "hce".
What is printed?
String s = "computer";
System.out.println(s.indexOf('t') + " " + s.indexOf("put") + " " + s.indexOf('x'));Show answer
c0 o1 m2 p3 u4 t5 e6 r7. 't' is at index 5. "put" starts at index 3. 'x' is not there: indexOf returns -1 when it finds nothing.
What is printed?
String s = "java";
s.toUpperCase();
System.out.println(s + s.length());Show answer
A String is immutable. toUpperCase() produces a new String, but since the result is not assigned anywhere, it is lost; s is still "java". For uppercase you must write s = s.toUpperCase();.
What is printed?
int a = 5;
int b = a++ + ++a;
System.out.println(a + " " + b);Show answer
Left to right: a++ gives 5 as its value, then a = 6. ++a increments first: a = 7, and gives 7 as its value. b = 5 + 7 = 12, a = 7.
What is the value of x at the end?
int x = 7;
x += 3;
x -= 2;
x *= 3;
x %= 5;Show answer
7 + 3 = 10, 10 - 2 = 8, 8 * 3 = 24, 24 % 5 = 4.
What is printed?
int q = 10;
q /= 4;
q += 1.9;
System.out.println(q);Show answer
q /= 4 → 10 / 4 = 2 (int division). q += 1.9 actually means q = (int) (q + 1.9): compound assignment contains a hidden cast. 2 + 1.9 = 3.9 → 3. If you wrote the same thing as q = q + 1.9; it would not compile.
What is printed?
String s = "Hello";
System.out.println(s.charAt(1) + s.charAt(2));
System.out.println("" + s.charAt(1) + s.charAt(2));Show answer
el
charAt returns a char, not a String. 'e' (101) + 'l' (108) = 209, a numeric sum. In the second line there is "" at the start, so it is concatenation: "el".
Write a code fragment that reads a full name such as Deniz Yilmaz into full and prints the initials (DY). Assume the name has exactly one space.
Show answer
Find the position of the space with indexOf; the initials are at index 0 and at the index after the space. If you do not put "" at the start, the two chars are added and a number is printed.Scanner input = new Scanner(System.in);String full = input.nextLine();int sp = full.indexOf(' ');System.out.println("" + full.charAt(0) + full.charAt(sp + 1));For "Deniz Yilmaz" the output is DY. Here you need nextLine(), not next(), because the name contains a space.
Verification: All code snippets were run with JDK 26 (verify/SEN1001/W02b.java). The Scanner examples were run by feeding the input through stdin, like printf '19 3.4 Deniz' | java W02b.java body1; the user input shown in the console was added for readability.