Home Elementary Selections Math Loops Methods

Week 1: Revision - Java Basics

Liang Chapters 1-5: Elementary Programming, Selections, Math, Loops, Methods

Elementary Programming

A Java program is executed from the main method. Variables store data values. Every variable has a data type that determines the size and layout of its memory. (Liang, Ch. 2)

Primitive Data Types

Java has eight primitive data types (Liang, Table 2.2):

TypeSizeRangeDefault
byte8 bits-128 to 1270
short16 bits-32,768 to 32,7670
int32 bits-2^31 to 2^31 - 10
long64 bits-2^63 to 2^63 - 10L
float32 bits~7 decimal digits0.0f
double64 bits~15 decimal digits0.0
char16 bitsUnicode 0 to 65,535'\u0000'
boolean1 bittrue or falsefalse

Type Casting

Widening (implicit): byte → short → int → long → float → double. Narrowing (explicit): requires a cast operator. (Liang, Section 2.15)

double d = 3.14; int i = (int) d; // i becomes 3 (truncation, not rounding)

Constants

A constant is declared using the final keyword. Once assigned, its value cannot be changed. (Liang, Section 2.6)

final double PI = 3.14159;

Example: ComputeArea (Liang, Listing 2.1)

import java.util.Scanner; public class ComputeArea { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a number for radius: "); double radius = input.nextDouble(); double area = radius * radius * 3.14159; System.out.println("The area for the circle of radius " + radius + " is " + area); } }
Q1: What is the result of (int) 3.9?
A) 4
B) 3
C) 3.9
D) Compilation error
Casting a double to int truncates the decimal part (does not round). So (int) 3.9 = 3. (Liang, Section 2.15)
Q2: Which data type would you use to store a student's GPA (e.g., 3.85)?
A) int
B) double
C) boolean
D) char
A GPA like 3.85 is a decimal number. The double type stores 64-bit floating-point values. (Liang, Section 2.9)

Trace the Code

int x = 10; int y = x / 3; double z = x / 3; System.out.println(y + " " + z);

What is the output?

Find the Bug

double temperature; System.out.println("Temperature is " + temperature);
What is the error?
A) Variable temperature might not have been initialized
B) Missing semicolon
C) Wrong data type
Local variables must be initialized before use. The compiler will report "variable temperature might not have been initialized." (Liang, Section 2.5)

Section Score

0 / 0

Selections

Selection statements let you choose which action to perform based on conditions. Java provides if, if-else, nested if, switch, and the conditional expression operator. (Liang, Ch. 3)

if-else Statement

if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else grade = 'F';

switch Statement

The switch statement matches a variable against a list of constant values. (Liang, Section 3.13)

switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; default: System.out.println("Other"); }

Conditional Expression

The ternary operator condition ? expr1 : expr2 provides a shorthand for if-else. (Liang, Section 3.14)

int max = (a > b) ? a : b;

Operator Precedence (Liang, Table 3.7)

From highest to lowest: !* / %+ -< <= > >=== !=&&||= += -=

Q1: What is the value of x after: int x = (5 > 3) ? 10 : 20;?
A) 10
B) 20
C) 5
D) 3
Since 5 > 3 is true, the expression evaluates to 10. (Liang, Section 3.14)
Q2: What happens if you forget break in a switch case?
A) Compilation error
B) Fall-through: subsequent cases execute until a break is found
C) Only the matched case runs
D) Runtime error
Without break, execution falls through to the next case(s). This is called fall-through behavior. (Liang, Section 3.13)

Trace the Code

int x = 5; if (x > 3) if (x > 10) System.out.println("A"); else System.out.println("B"); else System.out.println("C");

What is the output?

Section Score

0 / 0

Mathematical Functions

Java provides the Math class with many useful methods for performing mathematical operations. All methods in the Math class are static. (Liang, Ch. 4)

Common Math Methods

MethodDescriptionExample
Math.pow(a, b)a raised to power bMath.pow(2, 3) = 8.0
Math.sqrt(x)Square rootMath.sqrt(16) = 4.0
Math.abs(x)Absolute valueMath.abs(-5) = 5
Math.max(a, b)Larger of two valuesMath.max(3, 7) = 7
Math.min(a, b)Smaller of two valuesMath.min(3, 7) = 3
Math.random()Random double in [0, 1)(int)(Math.random() * 10)
Math.ceil(x)Round upMath.ceil(2.1) = 3.0
Math.floor(x)Round downMath.floor(2.9) = 2.0
Math.round(x)Round to nearestMath.round(2.5) = 3
Q1: What is Math.ceil(-2.1)?
A) -3.0
B) -2.0
C) -2.1
D) -1.0
Math.ceil rounds up (toward positive infinity). ceil(-2.1) = -2.0. (Liang, Section 4.2)

Trace the Code

System.out.println((int)Math.pow(2, 3) + (int)Math.sqrt(9));

What is the output?

Section Score

0 / 0

Loops

Loops enable your program to execute statements repeatedly. Java provides three loop statements: while, do-while, and for. (Liang, Ch. 5)

while Loop

int count = 0; while (count < 5) { System.out.println("Count is: " + count); count++; }

do-while Loop

The do-while loop executes the body at least once before checking the condition. (Liang, Section 5.3)

int n = 0; do { System.out.println(n); n++; } while (n < 3);

for Loop

for (int i = 0; i < 5; i++) { System.out.print(i + " "); } // Output: 0 1 2 3 4

Nested Loops Example

for (int i = 1; i <= 3; i++) { for (int j = 1; j <= i; j++) { System.out.print("* "); } System.out.println(); } // Output: // * // * * // * * *

break and continue

break immediately terminates the loop. continue skips the current iteration and moves to the next one. (Liang, Section 5.8)

Q1: How many times does this loop execute? for (int i = 1; i <= 10; i += 3)
A) 3
B) 4
C) 10
D) 5
i takes values 1, 4, 7, 10 (4 iterations). When i becomes 13, the condition fails. (Liang, Section 5.4)
Q2: What is the difference between while and do-while?
A) while is faster
B) do-while cannot use break
C) do-while always executes at least once
D) No difference
do-while checks the condition after executing the body, guaranteeing at least one execution. (Liang, Section 5.3)

Trace the Code

int sum = 0; for (int i = 1; i <= 5; i++) { if (i % 2 == 0) continue; sum += i; } System.out.println(sum);

What is the output?

Find the Bug

int i = 0; while (i < 10) System.out.println(i); i++;
What is the bug?
A) Missing braces causes infinite loop (only println is in the loop)
B) Wrong initial value of i
C) Should use for loop instead
Without braces, only the first statement (println) is in the loop body. The i++ is outside the loop, so i never changes and the loop runs forever. (Liang, Section 5.2)

Section Score

0 / 0

Methods

A method is a collection of statements grouped together to perform an operation. Methods help with code reuse and modular programming. (Liang, Ch. 6)

Defining a Method

public static int max(int num1, int num2) { if (num1 > num2) return num1; else return num2; }

Method Signature

A method signature consists of the method name and parameter list. The return type is NOT part of the signature. (Liang, Section 6.4)

Method Overloading

Overloading means defining multiple methods with the same name but different parameter lists. The compiler determines which method to call based on arguments. (Liang, Section 6.8)

public static int max(int a, int b) { return (a > b) ? a : b; } public static double max(double a, double b) { return (a > b) ? a : b; } public static int max(int a, int b, int c) { return max(max(a,b),c); }

Scope of Variables

A local variable is declared inside a method and is only accessible within that method. A variable declared in a for loop header is only accessible inside the loop. (Liang, Section 6.9)

Q1: What is the return type of a method that does not return a value?
A) int
B) null
C) void
D) empty
A void method does not return a value. You cannot use return with a value inside a void method. (Liang, Section 6.3)
Q2: Can two overloaded methods have the same parameter types but different return types?
A) Yes, always
B) No, that causes a compilation error
C) Only with static methods
Overloaded methods must differ in parameter lists. The return type alone is not sufficient to distinguish two methods. (Liang, Section 6.8)

Trace the Code

public static void main(String[] args) { int a = 5; change(a); System.out.println(a); } public static void change(int x) { x = x * 2; }

What is the output?

Find the Bug

public static int sum(int n) { int result = 0; for (int i = 1; i <= n; i++) result += i; }
What is the bug?
A) Missing return statement
B) Wrong loop condition
C) result should be double
The method has return type int but no return statement. It should have "return result;" at the end. (Liang, Section 6.4)

Section Score

0 / 0

Week 1

Elementary Selections Math Functions Loops Methods