LESSON 02 - TOPIC 1: Java Basics - Packages, Types, Operators, Input/Output, Control Structures, and Errors/Exceptions
Accompanying code files:
- N/A
Jump to Homework
As we've mentioned before, there are several different Java packages you can utilize that often have built-in methods or classes that work really well, so you don't have to re-invent the wheel. Here's how to import them:
import packagename.*; // imports all classes in this package
import packagename.Classname; // imports specific class from this package
In Eclipse, you can create your own packages as well, and place related classes in them. Classes in the same package have access to each others' public methods, constructors etc. without having to import them.
We will now be going over basic built-in types and operations in Java that are common in plenty of other programming languages. As with every language, it is important to get the syntax right so that the compiler is able to translate our instructions into machine language.
- the name of a class, method, etc., which obeys a certain naming convention depending on whether it is a constructor, method, variable etc., as mentioned in the previous lesson
- in general, identifiers are any sequence of letters, digits, and the underscore character
- they are also case-sensitive and may not begin with a digit
Anything that is declared in Java has a type, and the built-in (primitive) ones in the AP subset are:
int
: an integerboolean
: either true or falsedouble
: a double precision floating-point number
You can also convert variables to a specific type by casting:
int total, n; // the comma separates 2 identifiers (total and n), both of which are ints
double average;
average = (double) total/n;
average = total/(double) n; // this also works
int num = 5;
double realNum = num; // num will automatically be cast to double in this case since an integer can clearly be a double
double cost = 10.95
int numDollars = (int) cost; // Without the explicit cast, an error will occur
Note that casting a double to an int will truncate it, not round it off.
- ints are stored in Java exactly, as a string of bits (binary digits)
- the Java built-in integral type, byte, uses one byte (eight bits) of storage, the short(not in AP subset) uses two bytes, and the long(not in AP subset) uses eight bytes
- ints in Java use four bytes (32 bits), where the one bit will be for the sign (i.e. positive/negative)
- this means that the largest possible integer stored is 2^31 - 1, and in general, an n-bit integer uses n/8 bytes of storage and stores integers from -2^(n-1) to 2^(n-1)-1
- the Java constant
Integer.MAX_VALUE
holds the max value an int can hold (2^31 - 1), and theInteger.MIN_VALUE
constant holds the minimum value an int can hold (-2^31) - if you attempt to store a value bigger than those constants, you will get an overflow error
- the two built-in types in Java that store real numbers are the float(not in AP subset) which uses four bytes and the double, which uses eight
- in doubles, one bit is used for the sign as well, and if floating-point numbers are converted to binary, most cannot be represented exactly, leading to round-off errors, which are compounded by arithmetic operations
- no exception will be thrown for these errors, but if an operation gives an undefined result (e.g. if you take the square root of a negative number),
NaN
(not a number) will be returned, and if an operation returns an infinitely large/small number (e.g. dividing by zero),Infinity
or-Infinity
will be returned
- FUN FACT: Binary is used by computers because the values 0 and 1 can represent on/off signals. Computers run on electricity, which can be controlled using switches or logic gates. This is known as data representation.
- Binary is just a form of expressing numbers with a base of 2 (with digits 0 and 1), rather than the standard decimal format we are used to that expresses numbers with a base of 10 (with digits 0 - 9)
- Similarly, hexadecimal (hex) uses a base of 16 (with digits 0 - 9, and A-F), and octal uses a base of 8 (with digits 0 - 7)
- Hex tends to be the standard for storing numbers due to its compactness and ease of conversion to/from binary, and are often denoted using the prefix
0x
or0X
e.g.0xC2A
- The images below show how to convert decimal to binary and vice versa, and binary to hex and vice versa:
Operator | Meaning | Example |
---|---|---|
+ | addition | 3 + x |
- | subtraction | p - q |
* | multiplication | 6 * i |
/ | division | 10 / 4 (returns 2, not 2.5!) |
% | mod (remainder) | 11 % 8 (returns 3) |
- These operators can be applied to ints and doubles, and if an operation involves both, a double result will be returned.
- If division involves two ints, truncation will result, but if at least one is a double, regular floating-point division is used (no trunctation)
- What is modulo (mod) and when/why would we use it? Consider the method below that finds the number of factors of a given integer (NOTE: you may want to understand the rest of this lecture to help you understand this example better):
public int numFactors(int num) {
total = 1; // starts with 1, since every integer has 1 as a factor
n = num; // stores the original input number
while (n != 1) { // keep looping while n is not 1
if ((num % n) == 0) // if the remainder of num / n is equal to 0 i.e. no remainder, so the result is a whole number
total++; // then that value of n is a factor of num, so increment the total number of factors by 1
n--; // decrement the value of n by 1 to test the next value. This is executed every loop until the exit condition (n == 1) is reached, at which point the loop will stop.
}
return total; // returns the total number of factors
}
Arithmetic operators follow the standard precedence rules (order of operations, BEDMAS), and are operated from left to right (however, casting has the highest priority):
- parentheses, from innermost to outermost
*
,/
,%
+
,-
(lowest priority)
- These are used for boolean expressions that return booleans
- Should only be used for primitive types (e.g. ints, doubles, booleans), not user-defined types
- Do not directly compare floating-point values, since they cannot always be represented exactly in computer memory
Operator | Meaning | Example |
---|---|---|
== | equal to | if (x == 100) |
!= | not equal to | if (age != 19) |
> | greater than | if (salary > 30000) |
< | less than | if (grade < 65) |
>= | greater than or equal to | if (age >= 16) |
<= | less than or equal to | if (height <= 6) |
- Also used for boolean expressions that return booleans
- Work similar to set notation used in mathematical probability
Operator | Meaning | Example |
---|---|---|
! | NOT | if (!found) |
&& | AND | if (x < 3 && y > 4) |
|| | OR | if (age < 2 || height < 4) |
- For compound boolean expressions, using truth tables are really useful.
&& | T | F |
---|---|---|
T | T | F |
F | F | F |
|| | T | F |
---|---|---|
T | T | T |
F | T | F |
! | |
---|---|
T | F |
F | T |
- Expressions are evaluated left to right, and as soon as the value of the entire expression is known even before the entire expression is evaluated, evaluation stops automatically and the result is returned (short-circuit evaluation)
- e.g.
if (numScores != 0 && scoreTotal/numScores > 90)
will not throw a run-timeArithmeticException
(division-by-zero) if the value of numScores is 0, because thenumScores != 0
will evaluate tofalse
and without having to evaluate second expression
Operator | Example | Meaning |
---|---|---|
= | x = 2 | simple assignment |
+= | x += 4 | x = x + 4 |
-= | y -= 6 | y = y - 6 |
*= | p *= 5 | p = p * 5 |
/= | n /= 10 | n = n / 10 |
%= | n %= 10 | n = n % 10 |
- other than the simple assignment operator, all of these are compound assignment operators
- chaining of assignment statements is allowed, e.g.
next = prev = sum = 0;
Operator | Example | Meaning |
---|---|---|
++ | i++ | i is incremented by 1 |
-- | i-- | i is decremented by 1 |
Priority | Operators |
---|---|
1 | !, ++, -- |
2 | *, /, % |
3 | +, - |
4 | <, >, <=, >= |
5 | ==, != |
6 | && |
7 | || |
8 | =, +=, -=, *=, /=, %= |
- Input methods will not be on the AP exam
- The only output methods you need to know are
System.out.print
(prints without going to a new line) andSystem.out.println
(prints and then goes to a new line), which print an item (e.g. a string, number, boolean) to the console
- These are used to print special characters. There are several, but you only need to know these 3 for the exam:
Escape Sequence | Meaning |
---|---|
\n | new line |
\" | double quote |
\ | backslash |
These allow you to make statements of a program run in a non-sequential order and consist of 2 general types: decision-making and iteration
These include the if
, if...else
, and switch
(not in AP subset) statements that allow selective control of which path to follow based on the truth value of boolean expressions.
// IF Statements (1 case)
if (boolean expression) {
// statements that evaluate if and only if expression evaluates to true
}
// IF...ELSE Statements (2 cases)
if (boolean expression) {
// statements that evaluate if expression evaluates to true
} else {
// statements that evaluate otherwise (i.e. if expression evaluates to false)
}
// NESTED IF Statement (Sequential cases)
if (boolean expr1)
if (boolean expr2) // expr2 will only be evaluated if and only if expr1 evaluates to true
statement;
// equivalent to:
if (boolean expr1 && boolean expr2)
statement;
// EXTENDED IF Statement (Multiple possible cases)
if (boolean expr1) // 1st case
statement; // evaluated if above case is true, after which any cases below will not be evaluated
else if (boolean expr2) // 2nd case
statement;
else if (boolean expr3) // 3rd case
statement; // evaluated if above case is true, after which any cases below will not be evaluated
else
statement; // evaluated when none of the above cases occur
// Notice that for the sake of efficiency, the 1st case should preferably be the case you anticipate to be most frequent/likely, and the rest should follow in descending order of frequency/likelihood
As the name suggests, these control structures allow the computer to perform a specific set of tasks repeatedly: the for
loop, the while
loop, and the do...while
loop (not in AP exam)
Allow you to specify the start, end, and incrementation between each iteration
for (initialization; termination condition; update statement) {
// statements in the loop body to be executed from start to end in specified number of increments
}
These are useful for iterating over every element in an array or collection
for (SomeType element : collection) {
// statements in the loop body to be executed for each element of some type in the collection
}
- These hide the index variable that is used with arrays
- They should be used for accessing elements, not replacing/removing them as you traverse along the collection
- What if there is a case when you want to exit the loop before the specified termination point? Use the
break
statement to break out of the loop!
for (int i = 0; i < 10; i++) {
// statements for each iteration
if (condition where the loop should be exited)
break; // loop is existed and remaining iterations will not take place
}
These are useful when you don't necessarily know how many iterations you will need to perform the operations
while (boolean expression) {
// statements in the loop body to be executed if and only if the boolean expression is true
}
Note that since you are not declaring a specific termination condition, the statements in the loop body should eventually result in the boolean expression evaluating to false, or you will create an infinite loop that never finishes being executed!
// while loop that is equivalent to the last for loop above
int i = 0;
while (i < 10) {
// statements for each iteration
if (condition where loop should be exited)
break; // yes, breaks can be used for while loops too!
i++; // incrementation step, so we know that the boolean expression will eventually evaluate to false
// end of loop body so loop body is executed again from the start with new value of i
}
These are NOT part of the AP subset, but you may prefer to use them (vs. writing out each step) when trying to figure out what a program is doing or planning what a method you should do before you write it on the exam. For fun, here's a good example of how they can be used. The following image shows the control flow of the for loop and its equivalent while loop from the example above:
- an exception is an error that occurs during the execution of a Java program
- an unchecked exception is one that is automatically handled by Java's standard exception-handling methods, which terminate execution. The ones in the AP subset are:
Exception | Example that causes it |
---|---|
ArithmeticException | dividing by zero |
NullPointerException | invoking a method with a null reference |
ArrayIndexOutOfBoundsException | using a negative index to access an array element (not possible) |
IndexOutOfBoundsException | using an index to access an array element that does not exist (larger than length of array) |
IllegalArgumentException | when parameter doesn't satisfy a method's precondition e.g. length cannot be negative |
public double getRectangleArea (double length, double width) {
if (length <= 0 || width <= 0) {
throw new IllegalArgumentException("Length/width must be greater than zero"); // Optional error message that you can specify (or not, but it will be useful when debugging) that gets printed to the console
} else {
return length * width;
}
}
- conversely, a checked exception (not part of AP subset) is one where you provide code to handle the exception, e.g. using a
try
/catch
/finally
statement, or an explicitthrow new ...Exception
statement - exceptions are not necessarily caused by bugs in the code e.g. an unexpected end of file could be due to a broken network connection
Assignments:
- since some of you are struggling with the Eclipse setup, I am not assigning homework for this week (because you were likely unable to do the work from last class or are still in the process of completing it).
Prep for Next Class:
- keep working at the Eclipse and GitHub setup, and we will go through any setup issues for a bit at the beginning of the next class and starting our first lab!