0% found this document useful (0 votes)
6 views9 pages

Java OOP & Advanced Concepts Guide

Uploaded by

akanshi281282
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views9 pages

Java OOP & Advanced Concepts Guide

Uploaded by

akanshi281282
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java OOP & Advanced Concepts — Exam + Placement Bible (IIT Prof + Google Recruiter Edition)

Java OOP & Advanced Concepts


Exam + Placement Bible — IIT Professor x Google Recruiter Edition

• Detailed theory with Hinglish explanations for tough topics


• Clean runnable code samples
• Exam highlights, interview traps, and practice sets

Authoring assistant: GPT-5 Thinking — Compiled for personalized exam prep

Page 1
Java OOP & Advanced Concepts — Exam + Placement Bible (IIT Prof + Google Recruiter Edition)

Table of Contents

Placeholder for table of contents 0

Page 2
Java OOP & Advanced Concepts — Exam + Placement Bible (IIT Prof + Google Recruiter Edition)

1. Java Basics & Environment Setup


Why first? JVM, JRE, JDK concepts form the base. In interviews, incorrect basics kill the round
early.

1.1 JVM, JRE, JDK — Foundations


• JVM (Java Virtual Machine): Bytecode run-time. Handles memory (heap/stack), GC, JIT.
• JRE (Java Runtime Environment): JVM + core libraries (to run Java apps).
• JDK (Java Development Kit): JRE + compiler/tools (to develop apps).
Hinglish: JDK = development ka dabba (compiler javac + tools). JRE = run karne ki cheez. JVM =
actual engine jo bytecode chalata hai.

1.2 Compile & Run Flow


// File: [Link]
class Hello {
public static void main(String[] args) {
[Link]("Hello Java");
}
}
// Compile: javac [Link] -> [Link] (bytecode)
// Run: java Hello

Exam Q: Why java Hello (no .class/.java)? Kyunki launcher class naam se bytecode lookup karta hai.

1.3 Command-line Args & Parsing


public class SumArgs {
public static void main(String[] args) {
if ([Link] < 3) {
[Link]("Usage: java SumArgs <a> <b> <c>");
return;
}
int a = [Link](args[0]);
int b = [Link](args[1]);
int c = [Link](args[2]);
int sum = a + b + c;
[Link]("Sum: " + sum);
}
}

Gotcha: [Link]() throws NumberFormatException if arg is not numeric — handle in


Exceptions chapter.

1.4 Looping Constructs


for (int i = 0; i < 5; i++) { [Link](i + " "); }
int j = 5;
while (j > 0) { [Link](j-- + " "); }
int k = 0;
do { [Link](k + " "); } while (++k < 3);

Recruiter Tip: Prefer for-each when index not required — reads better and is safer.

1.5 Methods — params & returns


public class Methods {
public static void isPrime(int n) {

Page 3
Java OOP & Advanced Concepts — Exam + Placement Bible (IIT Prof + Google Recruiter Edition)

if (n <= 1) { [Link]("Not Prime"); return; }


boolean prime = true;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) { prime = false; break; }
}
[Link](prime ? "Prime" : "Not Prime");
}
public static int factorial(int n) {
int fact = 1;
for (int i = 2; i <= n; i++) fact *= i;
return fact;
}
public static void main(String[] args) {
isPrime(13);
[Link](factorial(5));
}
}

2. OOPs Concepts
2.1 Class, Object, Instance State/Behavior
class Person {
String name, gender;
int id, age;
void eat() { [Link]("[Link]()"); }
void print() { [Link]("Name: " + name + ", Gender: " + gender + ", Age: " + age +
}

2.2 Constructors — default & parameterized; overloading


class Person {
private String name, gender; private int id, age;
Person() { [Link]("[Link]()"); }
Person(String name, String gender, int id, int age) {
[Link] = name; [Link] = gender; [Link] = id; [Link] = age;
}
void print() { [Link](name + " / " + gender + " / " + id + " / " + age); }
}
class CtorOL {
private String name, gender; private int empId;
CtorOL() { [Link]("0-arg"); }
CtorOL(String name) { this(); [Link] = name; [Link]("1-arg"); }
CtorOL(String name, int empId) { this(name); [Link] = empId; [Link]("2-arg");
CtorOL(String name, String gender, int empId) { this(name, empId); [Link] = gender; Syste
}

2.3 Encapsulation — private + getters/setters


class Account {
private double balance;
public double getBalance() { return balance; }
public void deposit(double amt) { if (amt>0) balance += amt; }
public void withdraw(double amt) { if (amt>0 && amt<=balance) balance -= amt; }
}

2.4 this / super / final


class M { int n = 900; }
class Q extends M { int n = 100; }
class T extends Q {

Page 4
Java OOP & Advanced Concepts — Exam + Placement Bible (IIT Prof + Google Recruiter Edition)

int n = 200;
void m1() {
int n = 300;
[Link]("n: " + n);
[Link]("this.n: " + this.n);
[Link]("super.n: " + super.n);
}
}
final class TCar {
final String brandName;
TCar(String brandName) { [Link] = brandName; }
}

2.5 Inheritance & Polymorphism (Overloading vs Overriding)


class M2 { public void m1(){ [Link]("M.m1()"); } public void m2(){ [Link](
class T2 extends M2 { public void t1(){ [Link]("T.t1()"); } }
class OverLoadingEx {
public void sum() { [Link](100); }
public void sum(int n) { [Link](n + 100); }
public void sum(int n, int m) { [Link](n + m); }
public void sum(double n, int m) { [Link](n + m); }
public void sum(int n, double m) { [Link](n + m); }
}
class Dog extends Animal { @Override void sound(){ [Link]("bark"); } }
abstract class Animal { abstract void sound(); }

2.6 Abstraction — abstract classes & interfaces


public abstract class Animal2 {
public abstract void eat();
public abstract Animal2 run();
public abstract void sleep();
}
public class Tiger extends Animal2 {
@Override public void eat(){ [Link]("Tiger can eat veg and non-veg both"); }
@Override public Tiger run(){ [Link]("[Link]()"); return this; }
@Override public void sleep(){ [Link]("[Link]()"); }
}

2.7 Association (HAS-A) — Car → Engine, Driver


class Engine { int hp, torque; Engine(int hp, int torque){ [Link] = hp; [Link] = torque; } }
class Driver { String name; int age; Driver(String name, int age){ [Link]=name; [Link]=age; }
class Car { private final Engine engine = new Engine(1120, 440); Driver driver; void setDriver(Dri

3. Arrays
3.1 1D Arrays — traversal, input, sum
public static int sum(int[] arr){ int s=0; for(int n:arr) s+=n; return s; }

3.2 Insertion / Deletion / Searching / Sorting


// See full implementations earlier (insertAt, deleteAt, linearSearch, binarySearch, bubble)

3.3 2D Arrays — traversal & sum


public static int sum(int[][] arr){ int s=0; for(int[] row:arr) for(int x:row) s+=x; return s; }

3.4 Varargs (int... nums)

Page 5
Java OOP & Advanced Concepts — Exam + Placement Bible (IIT Prof + Google Recruiter Edition)

public static void sumAll(int... nums){ int s=0; for(int n:nums) s+=n; [Link]("Sum: "+

4. Strings
4.1 Equality & Pool — '==' vs equals()
String s1="Hi"; String s2="Hi"; [Link](s1==s2); [Link]([Link](s2));

4.2 Common Methods


" Hey ".trim().toUpperCase().endsWith("EY");

4.3 Custom methods — toMyUpperCase / toMyLowerCase


// toMyUpperCase / toMyLowerCase implementations shown earlier

4.4 Counting Problems


// countLetters / countWords / countVowels / countUpper / countLower shown earlier

5. Exception Handling
5.1 try-catch flow + NullPointer
try { String s=null; [Link](); } catch(NullPointerException e){ [Link](); }

6. Wrapper Classes & Autoboxing


Integer i=33; int n=i; Integer j=n;

7. Multithreading & Concurrency


7.1 Extending Thread & Implementing Runnable
class MyThread extends Thread { public void run(){ [Link](getName()); } }

7.2 Thread Pool — ExecutorService


ExecutorService pool=[Link](2); [Link](()->[Link]("task"))

7.3 Synchronization — Seat Booking


synchronized(this){ /* critical section */ }

7.4 Join & Thread Lifecycle


[Link](); [Link](); [Link]();

8. Collections Framework (as covered in class)


8.1 ArrayList basics
ArrayList<String> list=new ArrayList<>();

8.2 LinkedList ops + Iterator removal


Iterator<Integer> it=[Link](); while([Link]()){ int x=[Link](); if(x%2!=0) [Link]();

8.3 Enumeration on Vector


Enumeration<Integer> en=[Link](); while([Link]()) [Link]([Link]

Page 6
Java OOP & Advanced Concepts — Exam + Placement Bible (IIT Prof + Google Recruiter Edition)

8.4 Sets — HashSet/TreeSet + [Link]()


TreeSet<Integer> ts=new TreeSet<>([Link]());

9. Singleton Patterns (from class)


9.1 Eager & Lazy
class Eager{ private static final Eager I=new Eager(); private Eager(){} public static Eager get()
class Lazy{ private static Lazy I; private Lazy(){} public static Lazy get(){ if(I==null) I=new La

9.2 Double-Checked Locking (multithread safe)


class Safe{ private static volatile Safe I; private Safe(){} public static Safe get(){ if(I==null)

10. Practice Sets — Exam + Placement


10.1 Basics & Methods
• Print all factors of n.
• Prime check optimized (i*i<=n).
• Reverse integer; check palindrome.
• Implement fast exponentiation.
10.2 OOPs
• Student with encapsulation & validation.
• Constructor chaining with this().
• Shape hierarchy with area().
• Upcasting + dynamic dispatch demo.
10.3 Arrays
• Insert at index k (new array).
• Delete first occurrence of key.
• Binary search; return index or -1.
• Bubble + Selection sort.
10.4 Strings
• Robust word count (multiple spaces).
• Replace vowels with next char.
• Check anagram (ignore spaces & case).
• Custom toUpper/toLower (no built-ins).
10.5 Exceptions
• Handle NumberFormatException for CLI args.
• Multiple catch + finally.
• Custom InvalidAgeException.
10.6 Wrappers & Autoboxing

Page 7
Java OOP & Advanced Concepts — Exam + Placement Bible (IIT Prof + Google Recruiter Edition)

• Integer caching demo.


• List to List via autobox.
10.7 Multithreading
• 3 threads print names with sleep.
• ExecutorService: 10 tasks on pool size 3.
• Race condition + fix with synchronized.
10.8 Collections
• Roster via ArrayList; sort; dedupe with Set.
• Queue via LinkedList offer/poll.
• TreeSet top-3 scores (desc).

Page 8
Java OOP & Advanced Concepts — Exam + Placement Bible (IIT Prof + Google Recruiter Edition)

End of Book — Practice hard, read code, and dry-run! ■

Page 9

Common questions

Powered by AI

OOP in Java is exemplified through classes, which serve as blueprints for creating objects, including their state (attributes) and behavior (methods). An example is the Person class containing attributes such as name and age, as well as behaviors like eat() and print(). Encapsulation, a core principle of OOP, involves restricting access to certain components of an object and providing controlled ways to modify them through methods, enhancing security and modularity. Encapsulation is demonstrated through private fields and public getter/setter methods, as seen in the Account class with its balance field .

Inheritance in Java allows a new class (subclass) to inherit properties and behaviors from an existing class (superclass), promoting code reusability and efficiency by reducing redundancy. This facilitates extending a class's functionality without modifying it directly. An example of method overriding is demonstrated in the Dog class extending Animal, where the sound() method in Dog overrides the abstract sound() method of Animal. This enables polymorphism, allowing a reference variable to call overridden methods dynamically at runtime, enhancing flexibility and maintainability .

Multithreading in Java allows concurrent execution of two or more threads for optimal resource utilization and performance. It is implemented through extending the Thread class or implementing the Runnable interface, as seen with MyThread class and Runnable tasks executed by ExecutorService. Synchronization is vital in a multithreaded environment because it prevents race conditions by ensuring that only one thread accesses a critical section at a time. Java provides synchronized blocks or methods to achieve this, ensuring thread-safe access to shared resources, as demonstrated in seat booking context .

Collections like ArrayList and HashSet in Java offer dynamic data handling capabilities, enhancing application efficiency. ArrayList is a resizable array implementation that allows indexed access and manipulation of elements, making it suitable for scenarios requiring frequent retrieval or insertion operations. HashSet, part of the Set interface, provides a collection that prevents duplicate elements, efficiently managing uniqueness through hashing. These collections simplify data management tasks, like sorting and filtering, improving performance and reducing boilerplate code .

In Java, string handling involves understanding memory allocation and comparison methods. The '==' operator checks for reference equality, meaning if two string variables point to the same object. The equals() method checks for value equality, meaning if two string objects contain the same sequence of characters. This distinction has implications: using '==' may cause unexpected results due to multiple string objects with the same content stored at different memory locations, while equals() ensures logical equivalence, crucial for tasks like string comparison, data deduplication, and conditional checks .

Command-line arguments in Java allow programs to accept input values at runtime, enhancing flexibility and usability for varied operation scenarios. The practical application is illustrated in the SumArgs class, where the program parses integer inputs provided as command-line arguments, computes, and prints their sum. This enables the program's versatility by allowing users to specify different input parameters on execution, which can be applied in scenarios like batch processing or configuration settings, while also demonstrating input validation with exceptions for robustness .

Exception handling in Java is crucial for building robust applications that can manage runtime errors gracefully, preventing crashes and maintaining control flow. The try-catch-finally construct allows developers to handle exceptions by specifying a block of code to execute in case of an error (try), a block to run if an exception is caught (catch), and a block that executes regardless of exceptions (finally). For instance, handling a NullPointerException involves placing potential null dereference code in a try block and catching the exception to print the stack trace, ensuring the program does not terminate unexpectedly .

Singleton patterns in Java ensure that a class has only one instance throughout the application lifecycle, promoting resource optimization by permitting controlled access and reducing unnecessary instantiations. Strategies include eager initialization, where the instance is created at load time, as shown in the Eager class, and lazy initialization, where the instance is created only when needed using double-checked locking for thread safety, as seen in the Safe class. These approaches manage memory efficiently and provide global access points for the instance .

Abstract classes and interfaces support abstraction in Java by allowing the definition of a common framework for derived classes to implement, promoting code generalization and flexibility. An abstract class like Animal2, containing abstract methods without implementations, mandates subclasses such as Tiger to provide specific implementations for eat(), run(), and sleep() methods. This approach enforces a contract for subclass behaviors while facilitating polymorphism, enabling references to use the common interface while executing subclass-specific methods .

The key differences are foundational for understanding Java development. JVM (Java Virtual Machine) is responsible for running Java bytecode and managing the runtime environment including memory (heap/stack), garbage collection, and just-in-time compilation. JRE (Java Runtime Environment) includes the JVM and core libraries, providing the resources to run Java applications. JDK (Java Development Kit) encompasses the JRE and additional development tools such as the compiler (javac) and other utilities, crucial for developing Java applications. Understanding these differences helps developers in selecting the right package for their needs—whether running or developing Java applications .

You might also like