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 ).class,null: INVALID (reserved keyword / literal constant)._count,total$,studentName: VALID.
Primitive Data Types
Integer Types:
byte(),short(),int(, default choice, range to ),long().Floating-Point Types:
float(),double(, default decimal choice).Selection Rule: Use
intfor whole numbers anddoublefor 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 forx = x + 8;.Logical Operators:
!(NOT),&&(AND - both true),||(OR - at least one true),^(XOR - exactly one true).Condition Tracing Example:
Given
radius = 5andvalid = true:Evaluate:
radius > 0 && valid && radius != 10Step 1:
radius > 0() evaluates totrue.Step 2:
validistrue.Step 3:
radius != 10() evaluates totrue.Result:
true && true && trueyieldstrue.
2. CONTROL FLOW: DECISIONS AND LOOPS
Decision Control Structures & Pitfalls
if,if-else,if-else-if: Evaluates top-down; executes only the firsttruebranch.switchStatement: Evaluates integral,char, orStringexpressions.Execution Trap: Missing
breakstatements cause fall-through execution into subsequent cases regardless of condition evaluation.
Loop Design & Tracing
whileLoop (Pretest): Condition checked before each iteration (executes or more times).Infinite Loop Bug: Missing counter update inside the loop body (e.g.,
while (i < 10) { System.out.println(i); }never incrementsi).do-whileLoop (Post-test): Loop body executes first, condition tested at end (executes at least time). Ideal for user prompts/menus.forLoop (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:
voidmethods perform tasks without returning values; value-returning methods must execute a matchingreturnstatement.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
Stringobjects are immutable. Methods like.toUpperCase()return a brand-newStringobject and do NOT modify the original object in place.Tracing Example:
String a = "java"; String b = a.toUpperCase();Result: Variable
aremains"java", whilebreferences a new object containing"JAVA".
Random Number Bounded Ranges
Random rand = new Random();rand.nextInt(n): Generates a random integer in range .Die Roll Simulation:
rand.nextInt(6) + 1generates values from to (shifts range to ).
5. ARRAYS AND ARRAY PROCESSING
Array Declaration & Allocation
Syntax:
int[] numbers = new int[6];Allocated in heap memory with fixed size. Default initial values: for numeric types,
falseforboolean, andnullfor reference objects.
Zero-Based Indexing & Boundary Traps
Elements accessed via zero-based index ranging from to .
Execution Error Trap: Accessing
array[array.length]throwsArrayIndexOutOfBoundsException.Loop Traversal: Always use
< array.lengthin 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
privatemodifier and exposing controlledpublicaccessors (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
thisKeyword & Field Shadowingthisis an internal reference pointing to the current object instance.Shadowing Resolution: Resolves parameter name collisions with instance fields (
this.length = length;). Writinglength = length;withoutthismerely 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
statickeyword; 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).privatesuperclass 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.
@Overrideannotation forces compiler verification.Placing
finalon 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
abstractkeyword (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
interfacekeyword and implemented viaimplements.All methods default strictly to
public abstract; fields default strictly topublic static finalconstants.Multiple Implementation: Classes can extend only 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) andException.Unchecked Exceptions (
RuntimeException& subclasses): Results from logic defects (ArithmeticException,NullPointerException,IndexOutOfBoundsException). Compiler does not enforce handling.Checked Exceptions (Direct
Exceptionsubclasses likeIOException,FileNotFoundException): Compiler forces handling viatry-catchOR explicit method declaration usingthrowsclause.
Control Flow in
try-catch-finallyCatch Block Ordering: Catch blocks must be listed from most specific (subclass) to most general (superclass). Reversing order causes compiler errors.
finallyBlock: Executes unconditionally after try/catch execution finishes, whether an exception occurred or not.
throwStatement vs.throwsClausethrows: 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 withhasNext(),nextInt(),nextLine().Writing:
PrintWriter out = new PrintWriter("output.txt");usingprintln().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
FileOutputStreaminsideDataOutputStream(writeInt(),writeDouble(),writeUTF()).Reading: Wrap
FileInputStreaminsideDataInputStreamand invoke read methods (readInt(),readDouble(),readUTF()) in exact sequence written.
Random Access & Serialization
RandomAccessFile: Enables non-sequential byte jumps usingseek(long pos). Modes:"r"(read-only) or"rw"(read-write).Object Serialization: Process of converting object instances to byte streams. Object class must implement
Serializablemarker interface (contains no methods or fields). UsesObjectOutputStreamandObjectInputStream.
1. Type mismatch
int x = "hello"; // ❌
double x = 5; // ✅2. Undeclared variable
System.out.println(score); // ❌ if score was never declared3. Invalid identifier
int 2score; // ❌ starts with a digit
int class; // ❌ reserved keyword4. Missing return
public int getNum() {
// ❌ no return statement
}5. Wrong method arguments
void print(int x) { }
print("5"); // ❌ wrong parameter type6. 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 overloading7. Constructor mistake
class Dog {
Dog(String name) { }
}
Dog d = new Dog(); // ❌ no no-argument constructor exists8. super() mistake
Child() {
int x = 5;
super(); // ❌ super() must be first
}9. Abstract class
Shape s = new Shape(); // ❌ cannot instantiate an abstract class10. Inheritance / interface mistake
class Dog extends Animal implements PetRemember:
extends→ class inheritanceimplements→ interface
A class can extend only one superclass.
A class can implement multiple interfaces.