Unit 1 Review Field Guide

What each topic means, step by step. No answers here, only how to think about it. Back to the Unit 1 Review Lab

How the lab works

Type your name once at the top and press Save name. It is locked after that, so use the same name every time. Your progress saves on this device.

The Math class

CallWhat it givesType you get back
Math.sqrt(x)the square rootalways a double, so it prints with .0 when it is whole
Math.pow(a, b)a to the power balways a double
Math.abs(x)x with the sign removedthe same type you gave it
Math.random()a double from 0.0 up to, but not including, 1.0double
Random int from lo to hi. Count the values: hi - lo + 1. Multiply Math.random() by that count, cast to int to drop the decimal, then add lo.

Strings and +

The first index is 0. substring(a, b) starts at a and stops just before b. indexOf gives the first match, or -1.

With +, Java works left to right. If either side is a String, it joins text. If both sides are numbers, it adds. A String on the left turns every + after it into joining.

Objects, references, and null

A variable like Dog a holds an arrow (a reference), not the Dog itself. Dog b = a; copies the arrow, so both variables point to the same Dog. new Dog(...) makes a brand new object. null means the arrow points to nothing.

Calling a method on a variable that holds null crashes with a NullPointerException. Setting a variable to null is fine. The crash only happens when you use it.

Division, remainder, casting, shortcuts

Two ints divide as an int, so the decimal part is dropped, not rounded. % gives the remainder. double d = 7 / 2; does the division first as ints, so it stores 3.0. A cast like (double) 7 / 2 happens first and keeps the decimal.

x += 5 means x = x + 5. x++ adds 1.

Three kinds of errors

When it shows upName
The compiler refuses before the program runssyntax error
The program runs and crashes partwayrun-time error (an exception)
The program runs fine but the answer is wronglogic error

Algorithms: three building blocks

Sequencing is steps in a fixed order. Selection chooses between paths based on a condition. Repetition does steps again and again until a condition says stop.

In a flowchart: a rounded oval is the start or end, a rectangle is a step, a diamond is a decision, and an arrow that goes back to an earlier step makes a loop. Swapping two steps can change the result, and it depends on the steps.

Boolean expressions

OperatorMeaning
==equal to
!=not equal to
< >less than, greater than
<= >=at most, at least

Arithmetic happens first, comparison last, so 5 + 3 >= 8 is 8 >= 8. The result is a boolean.

= stores a value. == compares. For references, == asks whether two variables point to the very same object, not whether two objects look alike.

A method that returns a boolean can return the comparison itself: return x > 0;. You do not need an if statement.