Java Programming Fundamentals: IS 247 Review

1. JAVA FUNDAMENTALS: VARIABLES, IDENTIFIERS, AND DATA TYPES
  • Identifier Rules & Common Traps

    • Allowed Characters: Letters (a–z, A–Z), digits (0–9), underscores (_), and dollar signs ($).

    • Syntax Rules: Cannot start with a digit, cannot be a reserved keyword (class, static, public, int), and cannot be literal constants (true, false, null).

    • Tracing / Error Identification:

    • 2ndScore: INVALID (starts with numeric digit 22).

    • class, null: INVALID (reserved keyword / literal constant).

    • _count, total$, studentName: VALID.

  • Primitive Data Types

    • Integer Types: byte (8-bit8\text{-bit}), short (16-bit16\text{-bit}), int (32-bit32\text{-bit}, default choice, range −2,147,483,648-2,147,483,648 to +2,147,483,647+2,147,483,647), long (64-bit64\text{-bit}).

    • Floating-Point Types: float (32-bit32\text{-bit}), double (64-bit64\text{-bit}, default decimal choice).

    • Selection Rule: Use int for whole numbers and double for decimals unless constrained.

  • Primitive vs. Reference Variables

    • Primitive Variables: Store actual values directly in memory location (e.g., int x = 25;).

    • Reference Variables: Store a memory address pointing to the object in heap memory (e.g., String city = "Baltimore";).

  • Operators & Quick Tracing

    • Augmented Assignment: x += 8; is shorthand for x = x + 8;.

    • Logical Operators: ! (NOT), && (AND - both true), || (OR - at least one true), ^ (XOR - exactly one true).

    • Condition Tracing Example:

    • Given radius = 5 and valid = true:

    • Evaluate: radius > 0 && valid && radius != 10

    • Step 1: radius > 0 (5>05 > 0) evaluates to true.

    • Step 2: valid is true.

    • Step 3: radius != 10 (5≠105 \neq 10) evaluates to true.

    • Result: true && true && true yields true.

2. CONTROL FLOW: DECISIONS AND LOOPS
  • Decision Control Structures & Pitfalls

    • if, if-else, if-else-if: Evaluates top-down; executes only the first true branch.

    • switch Statement: Evaluates integral, char, or String expressions.

    • Execution Trap: Missing break statements cause fall-through execution into subsequent cases regardless of condition evaluation.

  • Loop Design & Tracing

    • while Loop (Pretest): Condition checked before each iteration (executes 00 or more times).

    • Infinite Loop Bug: Missing counter update inside the loop body (e.g., while (i < 10) { System.out.println(i); } never increments i).

    • do-while Loop (Post-test): Loop body executes first, condition tested at end (executes at least 11 time). Ideal for user prompts/menus.

    • for Loop (Counted Pretest): Combines initialization, test, and update (for (int i = 0; i < 100; i++)). Ideal when iteration count is known.

3. METHODS, PARAMETERS, AND OVERLOADING
  • Method Structure & Value Passing

    • Header Structure: public static ReturnType methodName(ParameterType paramName)

    • Void vs. Value-Returning: void methods perform tasks without returning values; value-returning methods must execute a matching return statement.

    • Formal Parameters vs. Arguments: Formal parameters are placeholders in method header (num1); arguments are actual values passed during invocation (x).

    • Pass-By-Value Rule: Java passes copies of primitive values or copies of object reference addresses. Modifying object fields inside a method mutates the object referenced by the caller.

  • Method Overloading Rules

    • Overloaded methods share the same method name but possess different parameter lists (varying parameter count, data types, or sequence).

    • Compile Error Trap: Changing only the return type without altering the parameter list causes a compilation error.

4. STRINGS AND RANDOM NUMBER GENERATION
  • String Immutability Pitfall

    • String objects are immutable. Methods like .toUpperCase() return a brand-new String object and do NOT modify the original object in place.

    • Tracing Example:

    • String a = "java"; String b = a.toUpperCase();

    • Result: Variable a remains "java", while b references a new object containing "JAVA".

  • Random Number Bounded Ranges

    • Random rand = new Random();

    • rand.nextInt(n): Generates a random integer in range [0,n−1][0, n - 1].

    • Die Roll Simulation: rand.nextInt(6) + 1 generates values from 11 to 66 (shifts range [0,5][0, 5] to [1,6][1, 6]).

5. ARRAYS AND ARRAY PROCESSING
  • Array Declaration & Allocation

    • Syntax: int[] numbers = new int[6];

    • Allocated in heap memory with fixed size. Default initial values: 00 for numeric types, false for boolean, and null for reference objects.

  • Zero-Based Indexing & Boundary Traps

    • Elements accessed via zero-based index ranging from 00 to length−1\text{length} - 1.

    • Execution Error Trap: Accessing array[array.length] throws ArrayIndexOutOfBoundsException.

    • Loop Traversal: Always use < array.length in loop conditions (for (int i = 0; i < numbers.length; i++)).

6. OBJECT-ORIENTED PROGRAMMING (OOP) & CLASS DESIGN
  • Core OOP Concepts

    • Class: Blueprint defining common fields and methods.

    • Object: Instance created from a class template using new.

    • Encapsulation: Hiding internal field state with private modifier and exposing controlled public accessors (getters) and mutators (setters).

    • Abstraction: Exposing essential interface features while hiding complex internal details.

    • Inheritance: Subclass deriving attributes and behaviors from a superclass.

    • Polymorphism: Ability of a reference variable to process objects of different subclass types dynamically.

  • Constructor Rules & Traps

    • Shares exact name with class and has no return type (not even void).

    • Default Constructor Trap: If a class defines no constructors at all, Java inserts an implicit no-argument default constructor. If any custom constructor is written, Java does NOT provide a default no-arg constructor. Calling new ClassName() without an explicit no-arg constructor then results in a compile error.

  • The this Keyword & Field Shadowing

    • this is an internal reference pointing to the current object instance.

    • Shadowing Resolution: Resolves parameter name collisions with instance fields (this.length = length;). Writing length = length; without this merely reassigns the parameter to itself.

  • Instance vs. Static Members

    • Instance Members: Belong to individual object instances; each instance holds separate copies.

    • Static Members: Declared with static keyword; shared across all instances at class level (ClassName.staticMethod()).

7. INHERITANCE AND POLYMORPHISM
  • Inheritance Mechanics & super()

    • Subclass inherits from superclass using extends (public class Child extends Parent).

    • private superclass members exist in memory within subclass instances but are not directly accessible (must use public/protected methods).

    • Constructor Execution Order: Superclass constructor always executes first. Explicit call super(...) must be the very first line inside the subclass constructor.

  • Overriding vs. Overloading

    • Overriding: Subclass redefines method with exact same name and parameter signature as superclass method. @Override annotation forces compiler verification.

    • Placing final on a superclass method prevents subclasses from overriding it.

    • Overloading: Methods sharing same name but possessing different parameter signatures.

  • Polymorphism & Dynamic Binding

    • Polymorphic declaration: GradedActivity exam = new FinalExam(50, 7);

    • Compile-Time Restriction: Compiler permits calling only methods declared in the reference type (GradedActivity). Calling subclass-only methods directly causes a compile error.

    • Runtime Dynamic Binding: The JVM executes overridden method versions based on the actual object type referenced in heap memory at runtime.

8. ABSTRACT CLASSES AND INTERFACES
  • Abstract Classes

    • Declared with abstract keyword (public abstract class Shape).

    • Cannot be instantiated directly using new.

    • May contain abstract methods (headers ending in semicolon without body). Concrete subclasses must override all abstract methods.

  • Interfaces

    • Defined with interface keyword and implemented via implements.

    • All methods default strictly to public abstract; fields default strictly to public static final constants.

    • Multiple Implementation: Classes can extend only 11 superclass, but can implement multiple interfaces (implements Relatable, Displayable).

9. EXCEPTION HANDLING
  • Hierarchy & Types

    • Root class: Throwable. Derived subclasses: Error (unrecoverable system failure, do not catch) and Exception.

    • Unchecked Exceptions (RuntimeException & subclasses): Results from logic defects (ArithmeticException, NullPointerException, IndexOutOfBoundsException). Compiler does not enforce handling.

    • Checked Exceptions (Direct Exception subclasses like IOException, FileNotFoundException): Compiler forces handling via try-catch OR explicit method declaration using throws clause.

  • Control Flow in try-catch-finally

    • Catch Block Ordering: Catch blocks must be listed from most specific (subclass) to most general (superclass). Reversing order causes compiler errors.

    • finally Block: Executes unconditionally after try/catch execution finishes, whether an exception occurred or not.

  • throw Statement vs. throws Clause

    • throws: Signature clause declaring checked exceptions that a method propagates up the call stack (public void readFile() throws IOException).

    • throw: Executable statement inside method body that instantiates and throws an exception object (throw new IllegalArgumentException("Invalid");).

10. ADVANCED FILE INPUT AND OUTPUT (FILE I/O)
  • Text File I/O

    • Reading: Scanner scnr = new Scanner(new File("data.txt")); processed with hasNext(), nextInt(), nextLine().

    • Writing: PrintWriter out = new PrintWriter("output.txt"); using println().

    • Crucial Step: Must invoke .close() on output stream to flush output buffers and save data to disk.

  • Binary File I/O

    • Stores primitive data in raw binary representation matching internal memory.

    • Writing: Wrap FileOutputStream inside DataOutputStream (writeInt(), writeDouble(), writeUTF()).

    • Reading: Wrap FileInputStream inside DataInputStream and invoke read methods (readInt(), readDouble(), readUTF()) in exact sequence written.

  • Random Access & Serialization

    • RandomAccessFile: Enables non-sequential byte jumps using seek(long pos). Modes: "r" (read-only) or "rw" (read-write).

    • Object Serialization: Process of converting object instances to byte streams. Object class must implement Serializable marker interface (contains no methods or fields). Uses ObjectOutputStream and ObjectInputStream.

1. Type mismatch

int x = "hello";       // ❌
double x = 5;          // ✅

2. Undeclared variable

System.out.println(score);   // ❌ if score was never declared

3. Invalid identifier

int 2score;    // ❌ starts with a digit
int class;     // ❌ reserved keyword

4. Missing return

public int getNum() {
    // ❌ no return statement
}

5. Wrong method arguments

void print(int x) { }

print("5");    // ❌ wrong parameter type

6. Overloading mistake

Methods can only be overloaded by changing the parameter list.

int test(int x) { }
double test(int x) { }    // ❌ return type alone is not overloading

7. Constructor mistake

class Dog {
    Dog(String name) { }
}

Dog d = new Dog();    // ❌ no no-argument constructor exists

8. super() mistake

Child() {
    int x = 5;
    super();    // ❌ super() must be first
}

9. Abstract class

Shape s = new Shape();    // ❌ cannot instantiate an abstract class

10. Inheritance / interface mistake

class Dog extends Animal implements Pet

Remember:

  • extends → class inheritance

  • implements → interface


  • A class can extend only one superclass.


  • A class can implement multiple interfaces.