Variables, Strings, the Math class, and what "calling a method" really means.
Home โ Unit 1
Java has two kinds of data. Primitives (int,
double, boolean) store the value itself. Objects
(like String) store a reference โ an arrow pointing at the data.
Half the tricky MC questions in this unit are really testing whether you know which one
you're holding.
int score = 42; // the box holds 42 itself
String name = "Ada"; // the box holds an arrow to "Ada"
When both sides are int, Java throws away the decimal. It does not round.
int a = 7 / 2; // 3, not 3.5 โ decimal chopped off
double b = 7 / 2; // 3.0 (!) โ division happens as ints FIRST
double c = 7.0 / 2; // 3.5 โ one double makes it real division
int r = 7 % 2; // 1 โ the remainder (mod)
String indices start at 0, and substring(a, b) goes from
index a up to but not including b.
String s = "crash course";
s.length() // 12 โ count of characters
s.substring(0, 5) // "crash" โ indices 0,1,2,3,4
s.substring(6) // "course" โ from 6 to the end
s.indexOf("course") // 6 โ where it starts (-1 if missing)
s.equals("crash") // false โ ALWAYS use equals, never ==
int total = 9;
double avg = total / 4;
System.out.println(avg);
s.substring(2, 5) if String s = "computer";?a and b hold the same text?Math.random() return?== to compare Strings โ works in some tests, fails on the exam.5 / 2 is 2, and double x = 5 / 2 is 2.0.substring โ the second index is excluded.s.toUpperCase(); does nothing to s โ Strings are immutable; you must assign: s = s.toUpperCase();A couple of 1-on-1 sessions now beats months of confusion later. Online anywhere, in person in Orange County.
Ask about tutoring →