1/41
MIDTERm
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai | Chat |
|---|
No analytics yet
Send a link to your students to track their progress
Java Identifiers
name used for a variable, class, method, or other program element.
Can contain letters, digits, _, and $.
Cannot start with a digit.
Cannot contain spaces.
Java is case-sensitive: total, Total, and TOTAL are different.
Class names conventionally use PascalCase, such as CoinFlip.
Constants conventionally use uppercase, such as MAXIMUM.
Reserved words have special meanings and cannot be used as identifiers, such as class, public, and int.
reserved words
abstract
assert
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
enum
extends
false
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
true
try
Void
Volatile
While
Primitive data types and variables
store simple values.
Type | Stores | Example |
|---|---|---|
| Whole numbers |
|
| Decimal numbers |
|
| One character |
|
|
|
|
Other Java primitive types include byte, short, long, and float.
Declaring a variable:
data type then name ex) int score;
Initializing a variable:
int score = 10;gives it its first value.
Assignment:
stores a value in a variable
Primitive variable:
holds a value, such as int x = 5;.
Reference variable:
holds a reference to an object, such as a String or a Scanner.
Assignment statements: the two steps
int x = 5;
x = x + 3;For x = x + 3;, Java does two things:
Evaluate the right side: 5 + 3 = 8.
Store 8 in x, replacing the old value.
The final value of x is 8.
Remember: The = sign in Java means assignment, not mathematical equality.
Expressions and operator precedence
to determine what to calculate first.
Common order:
Parentheses ()
Multiplication, division, remainder: *, /, %
Addition and subtraction: +, -
Assignment: =
Operators with the same precedence are generally evaluated from left to right.
Example:
int result = 4 + 3 * 2;Multiplication first: \(3 \times 2 = 6\).
Then addition: \(4 + 6 = 10\).
So result equals 10.
Integer arithmetic vs. floating-point arithmetic
Integer division drops the fractional part when both operands are integers.
System.out.println(7 / 2); // 3
System.out.println(7.0 / 2); // 3.5
System.out.println(7 % 2); // 1/ divides.
% gives the remainder.
int / int produces integer division.
Using a double operand produces floating-point division.
This is one of the most important things to practice for code-tracing questions.
Expression trees
An expression tree shows the order in which an expression is evaluated.
Example:
4 + 3 * 2The multiplication happens first, so * is the root's right child.
+
4
*
3
2
The tree represents 4 + (3 * 2), which equals 10.
CPU
Executes instructions and performs calculations.
Main storage (memory/RAM):
Holds data and instructions while programs run.
Secondary storage:
Stores files and programs long-term, such as on an SSD or hard drive.
Byte:
A group of 8 bits.
Bit:
A binary digit, either 0 or 1.
Number of patterns with N bits
Each bit has two possibilities, so:
\[ \boxed{2^N\text{ patterns}} \]
Bits | Number of patterns |
|---|---|
1 | 2 |
2 | 4 |
3 | 8 |
4 | 16 |
8 | 256 |
Java program structure and compilation
A basic Java program:
public class Hello {
public static void main(String[] args) {
System.out.println("Hello!");
}
}Know what each part means:
public class Hello: declares a class.
main: the starting point of the program.
System.out.println(): prints output and moves to a new line.
{ }: mark the beginning and end of blocks.
//: starts a single-line comment.
/* ... */: marks a block comment.
How Java runs
Source file — Hello.java
Compiler — javac
Bytecode file — Hello.class
Java Virtual Machine (JVM) — executes the bytecode
The source file contains the code you write. The compiler translates it into bytecode, and the JVM runs that bytecode.
string literal
text enclosed in double quotation marks.
System.out.println("Hello");concatenation.
The + operator can join strings together.
System.out.println("Hello " + "there");Increment and decrement operators
x++ increments x by 1.
x-- decrements x by 1.
x += 3 adds 3 to x.
x -= 2 subtracts 2 from x.
Know the difference between prefix and postfix:
int x = 5;
int a = x++;After these statements, a is 5 and x is 6.
int x = 5;
int a = ++x;Now a is 6 and x is 6.
Postfix uses the old value first. Prefix increments first.
Widening
Converts a value to a type that can represent a broader range of values, commonly without losing information.
int x = 5;
double y = x;Here, y becomes 5.0
Narrowing
Converts to a type with a more limited representation and may lose information.
double price = 4.9;
int whole = (int) price;whole becomes 4, because the decimal part is discarded.
Type promotion
Java may promote smaller numeric types during calculations.
int x = 5;
double result = x / 2.0;The result is 2.5 because one operand is a double.
Scanner input
import java.util.Scanner;Create a Scanner:
Scanner scan = new Scanner(System.in);Method | What it reads | Example |
|---|---|---|
| A whole line of text |
|
| An integer |
|
| A decimal or other double value |
|
import java.util.Scanner;
public class Addition {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number: ");
double x = scan.nextDouble();
System.out.print("Enter another number: ");
double y = scan.nextDouble();
System.out.println("Sum = " + (x + y));
}
}String methods
Method | Purpose | Example result |
|---|---|---|
| Returns the number of characters |
|
| Returns the character at an index |
|
| Returns an uppercase version |
|
Remember: String indexing begins at 0.
For "Hello":
Character | H | e | l | l | o |
|---|---|---|---|---|---|
Index | 0 | 1 | 2 | 3 | 4 |
Math class
Method or constant | Meaning | Example |
|---|---|---|
| Square root |
|
| Random number greater than or equal to 0 and less than 1 |
|
| Approximation of pi |
|
Example:
double radius = 3.0;
double area = Math.PI * radius * radius;
System.out.println(area);Boolean expressions and relational operators
A Boolean expression evaluates to either true or false.
Operator | Meaning | Example |
|---|---|---|
| Less than |
|
| Greater than |
|
| Less than or equal to |
|
| Greater than or equal to |
|
| Equal to |
|
| Not equal to |
|
Don't confuse = with ==:
= assigns a value.
== compares values.
Logical operators
| Operator | Meaning | Example | |---|---|---|
| && | AND: both conditions must be true | true && false → false |
| || | OR: at least one condition must be true | true || false → true |
| ! | NOT: reverses a Boolean value | !true → false |
Truth tables
| A | B | A && B | A || B |
|---|---|---|---|
| true | true | true | true
| | true | false | false | true |
| false | true | false | true |
| false | false | false | false |
Simple and nested if statements
A simple if statement executes a block when a condition is true.
if (age >= 18) {
System.out.println("Adult");
}An if-else statement chooses between two paths:
if (score >= 60) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}A nested if is an if statement inside another if or else block.
if (score >= 60) {
if (score >= 90) {
System.out.println("Excellent");
} else {
System.out.println("Pass");
}
} else {
System.out.println("Fail");
}Trace the conditions in order to determine which output appears.
Block statements
a group of statements enclosed in braces { }.
if (x > 0) {
System.out.println("Positive");
System.out.println(x);
}Both statements belong to the if block. They execute only when x > 0.
Instance variable:
Belongs to an object and stores that object's data.
Local variable:
Declared inside a method or block and used there.
Parameter:
A variable in a method declaration that receives a value when the method is called.
Garbage collection:
Java automatically reclaims memory used by objects that are no longer reachable by the program.
Object references and aliases
A reference variable refers to an object. Multiple variables can refer to the same object; these variables are called aliases.
For example:
Coin first = new Coin();
Coin second = first;Both first and second refer to the same Coin object. They are not two separate coins.
If the object is modified through one reference, the change can be seen through the other reference.
Important distinction: Assigning one primitive variable to another copies its value. Assigning one object reference to another copies the reference, so both may point to the same object.
Comparing Strings
For the exam, understand the difference between comparing String objects by reference and comparing their contents.
String a = new String("hello");
String b = new String("hello");a == b checks whether the references point to the same object. Here, the result is false.
a.equals(b) checks whether the text contents match. Here, the result is true.
Use .equals() when you want to compare the text of two strings.
Writing a program that uses a formula
Your exam topics include writing programs that input numbers and use them in a formula.
A typical program follows this pattern:
Import Scanner.
Declare the class and main method.
Ask the user for input.
Read the input into variables.
Calculate the result.
Print the result.
Example: calculate the area of a rectangle.
import java.util.Scanner;
public class Rectangle {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter length: ");
double length = scan.nextDouble();
System.out.print("Enter width: ");
double width = scan.nextDouble();
double area = length * width;
System.out.println("Area = " + area);
}
}Defining and using classes
Your instructor lists Coin.java and CoinFlip.java as programs to review.
A class defines the data and behavior of a type of object. A program can create an object from that class and use it.
For example:
Coin myCoin = new Coin();Coin is the class name.
myCoin is the reference variable.
new Coin() creates a new object.
Review how a class is defined, how its instance variables work, and how another program uses the class.