Before the questions, make sure you can: write the common escape sequences and say what each one
produces; explain the difference between a primitive variable and a reference variable, and draw
both in memory; state why String objects are immutable; use length, charAt,
substring, indexOf, equals, equalsIgnoreCase, compareTo,
toUpperCase and trim correctly, including their index conventions; explain why
== is the wrong way to compare strings; and read mixed numbers and lines from the keyboard
with Scanner without falling into the nextLine trap.
The char type and escape sequences
A char holds one 16-bit Unicode character written between single quotes. Characters have
numeric codes ('A' is 65, 'a' is 97, '0' is 48), so they can be compared with
< and > and used in arithmetic, and consecutive letters or digits have consecutive
codes — which is why ch - '0' converts a digit character to its numeric value.
\n |
newline | \t |
tab |
|---|---|---|---|
\" |
double quote | \' |
single quote |
| ` | |||
| ` | backslash | \r |
carriage return |
Primitive versus reference variables
A primitive variable contains its value. A reference variable contains the address of an object stored elsewhere in memory (on the heap); the variable itself holds no characters, no fields, only a way to reach them.
int n = 5; // the box called n contains 5
String s = "Hello"; // the box called s contains a reference to a String object
String t = s; // t now refers to the SAME object (aliasing)
String u = null; // u refers to no object at all
Calling a method on a null reference throws a NullPointerException at run time. Two
consequences appear again and again in exams: assigning a reference copies the reference,
not the object; and == on references compares addresses, not contents.
String is a class, and its objects are immutable
String is not a primitive. A String object can be created without new, because a
literal in quotes is itself an object, and identical literals are shared through the
string pool:
String a = "Java"; // from the pool
String b = "Java"; // the SAME pooled object: a == b is true
String c = new String("Java");// a NEW object: a == c is false, a.equals(c) is true
Every “modifying” method returns a new string and leaves the original untouched:
String s = "hello";
s.toUpperCase(); // result thrown away: s is still "hello"
s = s.toUpperCase(); // now s refers to "HELLO"
Essential String methods
| Method | Result for String s = "Java Programming"; |
|---|---|
s.length() |
16 — a method with parentheses, unlike array.length |
s.charAt(0) |
'J' — indices run from 0 to length()-1 |
s.substring(5) |
"Programming" — from index 5 to the end |
s.substring(0, 4) |
"Java" — start inclusive, end exclusive |
s.indexOf("gram") |
8; returns -1 when not found |
s.equals("java programming") |
false; equalsIgnoreCase gives true |
s.compareTo("Java") |
positive: s comes after "Java" alphabetically |
s.toUpperCase() |
"JAVA PROGRAMMING" |
s.trim() |
removes leading and trailing whitespace |
s.replace('a','o') |
"Jovo Progromming" |
s.concat("!") or s + "!" |
"Java Programming!" |
s.isEmpty() |
false; true only when the length is 0 |
An out-of-range index throws StringIndexOutOfBoundsException at run time.
Comparing strings
if (name == "Ali") // WRONG: compares references
if (name.equals("Ali")) // RIGHT: compares contents
if ("Ali".equals(name)) // RIGHT and null-safe
compareTo returns a negative number, zero, or a positive number according to dictionary
order; it is what you use to sort names.
Reading input with Scanner
import java.util.Scanner; // required, at the top of the file
Scanner input = new Scanner(System.in); // create the object once
System.out.print("Name: ");
String name = input.nextLine(); // the whole line, spaces included
System.out.print("Age: ");
int age = input.nextInt(); // one int token
double gpa = input.nextDouble();
input.nextLine(); // consume the rest of the line!
String city = input.nextLine();
next() |
one word (up to the next whitespace) |
|---|---|
nextLine() |
everything up to and including the end of the line |
nextInt(), nextDouble() |
one numeric token; throws InputMismatchException on bad input |
hasNextInt() |
true if the next token can be read as an int — used for validation |
nextInt reads the number but leaves the newline character in the buffer. The next
nextLine therefore returns an empty string. Cure: call input.nextLine() once
immediately after the last nextInt/nextDouble to discard the leftover newline.
'A'is achar,"A"is aString.s.length()has parentheses; arraylengthdoes not.substring(a, b)includesaand excludesb; its length isb - a.- Strings are immutable: methods return new strings.
- Compare content with
equals, never with==. - After
nextInt, flush the line beforenextLine.
s.toUpperCase();on its own line changes nothing.s.charAt(s.length())always throws — the last index islength() - 1.- Forgetting
import java.util.Scanner;. - Calling a method on a variable that is still
null.
Ready? Close the notes and practise.
38 questions. Predict the output before you check — that is the skill the exam measures.