Appearance
Quick Revision
Key Terms
- Class: Blueprint or template (reference type); groups fields/methods; no data until instantiated.
- Object: Runtime instance with its own state; variables hold references to objects.
- Method: Named behavior tied to a class/object; can read/write fields.
- Constructor: Special method that runs on
new; no return type; sets initial state. - Overloading: Same method name, different parameters; compile-time resolution.
- Overriding: Subclass replaces superclass implementation; runtime dispatch.
- Constructor Overloading: Multiple constructors with varied parameters.
- Encapsulation: Keep fields private; expose getters/setters to protect invariants.
- Inheritance: Subclass reuses/extends parent members using
extends. - Polymorphism: Supertype reference to subtype; overridden methods chosen at runtime.
Threads basics
- Q1 – Java thread: Lightweight unit of execution inside a process; multiple threads share the same process memory and run concurrently.
- Q2 – Creating a thread: Extend
Threadand overriderun(), then callstart(); or implementRunnableand pass an instance tonew Thread(r).start(). - Q3 – Life cycle:
NEW → RUNNABLE → RUNNING → (WAITING / TIMED_WAITING / BLOCKED) → RUNNABLE → TERMINATEDviastart(), scheduler,wait()/sleep()/join(), monitor lock,notify()/notifyAll(), timeout, andrun()completion.
3x3 matrix operations
- Q4 – Addition: Read two
3×3arrays; triple nested loops;C[i][j] = A[i][j] + B[i][j]. - Q5 – Multiplication: Triple nested loops; inner loop accumulates
sum += A[i][k] * B[k][j], thenC[i][j] = sum. - Q6 – Subtraction: Same structure as addition;
C[i][j] = A[i][j] - B[i][j].
Exception handling programs
- Q7 – SafeDivide: Wrap input and division in
try–catch–finally; handleArithmeticException(divide by zero) andInputMismatchException(non‑int), always closingScanner. - Q7 – ArrayAccessTest: Catch
ArrayIndexOutOfBoundsException(index 0–4 only) andInputMismatchException; show friendly messages. - Q7 – FileReadTest: Use
File,Scanner, handleFileNotFoundExceptionand genericException, closeScannerinfinally.
Small multithreading tasks
- Q8 – 7 strings: Store in
ArrayList<String>; twoRunnabletasks with start indices0and1, step byi += 2, sleep200 msbetween prints for interleaving. - Q9 – 12 chars: Shared
ArrayList<Character>; helperisVowel; one thread prints vowels, another consonants; skip non‑letters usingCharacter.isLetter. - Q10 – 10 ints (foreach):
ArrayList<Integer>filled with1..10;Runnableuses foreach and an index counter; threads distinguished byidx % 2.
SQL + JSP + threads
- Q11 – Exam table:
ExamIDPK,DurationMinutes CHECK (DurationMinutes > 0); JSP usesPreparedStatementtoINSERTand handlesSQLExceptionintry–catch–finally; three threads print multiples of2,3, and5up toX. - Q12 – Teacher table:
TeacherIDPK,Email UNIQUE; JSP selects withPreparedStatementand parameterDepartment; three threads print all odd numbers from1toX. - Q13 – Employee table:
Salary NOT NULL; JSP updates salary byEmpIDusingPreparedStatement; three threads print primes from1toX, splitting work byi % 3.
OOP design questions
- Q14 – Course + AssessmentPolicy: Base
Course(id, name, instructor,isAvailable,enrollStudent());AssessmentPolicywithcalculateScore;VideoCoursereturns normal percentage;TextCourseadds5%bonus. - Q15 – Bank system: Base
Account(no, holder, balance,deposit, protectedwithdraw); customInsufficientFundsException;SavingsAccountandCheckingAccountimplementTransaction.performTransactionwithtry–catcharoundwithdraw, and overridedisplayInfo. - Q16 – Course Enrollment: Base
Course(id, name,maxSeats,enrolledStudents,safeEnroll()that throwsIllegalStateExceptionif full);OnlineCourseandOfflineCourseimplementEnrollmentPolicy.register()withtry–catchto show messages instead of crashing.
Simple threading patterns
- Q17 – Fib + primes: Two
Threadsubclasses; one prints first10Fibonacci numbers; the other prints first10primes. - Q18 – Evens & odds (Runnable): Two
Runnableimplementations; one prints even numbers2–20, the other prints odd numbers1–19. - Q19 – Numbers & letters: Two
Runnabletasks; one prints numbers1–5, the other prints lettersA–E.
Important Concepts
Constructor Best Practices
- Parameter names should match field names for clarity.
- Use
this.fieldName = fieldNameto assign constructor parameters to fields. - Call
super()in subclass constructors to initialize parent class fields. - Initialize subclass-specific fields after calling
super().
Encapsulation
- Make fields
privateto prevent direct access. - Provide
publicgetter methods to read values. - Provide
publicsetter methods to modify values safely. - Use
this.fieldNamein setters when parameter name matches field name.
Inheritance
- Use
extendskeyword to create subclass. - Subclass inherits all public and protected members from parent.
- Subclass can add new fields and methods.
- Subclass can override parent methods.
- Use
super.methodName()to call parent class methods. - Use
super()to call parent constructor.
Polymorphism
- A supertype reference can point to a subtype object.
- Method calls are resolved at runtime based on actual object type.
- Use
instanceofto check object type before downcasting. - Downcast only when necessary:
SubClass obj = (SubClass) superRef.
Key Comparisons
Class vs Object
- Class: Blueprint/template; logical structure; no memory allocated.
- Object: Instance; physical entity; memory allocated when created.
- Summary: Class = Design, Object = Product
Encapsulation vs Abstraction
- Encapsulation: Data protection; hides variables; uses access modifiers.
- Abstraction: Complexity reduction; hides implementation; shows only essentials.
- Summary: Encapsulation = Security | Abstraction = Simplicity
Method Overloading vs Method Overriding
- Overloading: Same class; different parameters; compile-time resolution.
- Overriding: Parent-child classes; same signature; runtime resolution.
- Summary: Overloading → Same class | Overriding → Parent–Child classes
Inheritance vs Composition
- Inheritance: IS-A relationship; strongly coupled; uses
extends. - Composition: HAS-A relationship; loosely coupled; uses object references.
- Summary: Inheritance = Reuse by extension | Composition = Reuse by inclusion
Compile-time vs Run-time Polymorphism
- Compile-time: Method overloading; resolved at compile time; faster.
- Run-time: Method overriding; resolved at execution time; based on object type.
- Summary: Compile-time = Overloading | Runtime = Overriding
Common Patterns
Base Class Pattern
- Create base class with common attributes.
- Use private fields with getters/setters.
- Initialize all fields in constructor using
this.fieldName = fieldName.
Subclass Pattern
- Extend base class using
extends. - Call
super()with parent constructor parameters. - Initialize subclass-specific fields after
super(). - Override parent methods when needed.
Service Class Pattern (Polymorphism)
- Create base service class with generic method.
- Create subclass that extends service class.
- Override method to handle specific types.
- Use
instanceofto check type before downcasting. - Call specific methods after downcasting.
Important Points to Remember
- Always use
this.when parameter names match field names. - Private fields require getters/setters for access.
- Constructor parameters should match field names.
- Use
super()to call parent constructor (must be first line). - Method overriding requires same signature as parent method.
- Use
@Overrideannotation for clarity (optional but recommended). instanceofchecks object type before downcasting.- Downcasting:
SubClass obj = (SubClass) superRef. - Polymorphism allows supertype reference to subtype object.
- Runtime polymorphism uses actual object type, not reference type.
Common Scenarios
Student Management
- Base class: Person (name, ID)
- Subclass: Student (adds courses, attendance)
- Service: ReportService → StudentReportService
Library System
- Base class: LibraryItem (title, year, ID)
- Subclass: Book (adds borrowCount, availability)
- Service: LibraryService → BookService
Membership Tracking
- Base class: Member (name, joinYear, ID)
- Subclass: GymMember (adds workoutHours, membershipType)
- Service: MembershipService → GymMembershipService
Course Progress
- Base class: Course (name, modules, code)
- Subclass: ProgrammingCourse (adds completedModules, difficulty)
- Service: CourseService → ProgrammingCourseService
Error Prevention Checklist
- Use
String(capital S), notstring. - Match parameter names with field names in constructors.
- Use
this.fieldNamewhen assigning in constructors/setters. - Include closing parentheses in constructors.
- Match variable names consistently (no typos like
tittlevstitle). - Don't compare different types (int vs String).
- Return correct type (boolean, not String).
- Include semicolons at end of statements.
- Use proper access modifiers (private for fields, public for getters/setters).
IUS Preps - Your Academic Success Partner