0% found this document useful (0 votes)
8 views33 pages

Java OOP Complete CodeBook

The document is a comprehensive code book for a Java OOP course, covering various topics including JVM, data types, control statements, and methods. It includes detailed explanations and examples of Java concepts such as classes, objects, inheritance, polymorphism, and operators. Each unit is structured to provide practical coding exercises and outputs to reinforce learning.

Uploaded by

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

Java OOP Complete CodeBook

The document is a comprehensive code book for a Java OOP course, covering various topics including JVM, data types, control statements, and methods. It includes detailed explanations and examples of Java concepts such as classes, objects, inheritance, polymorphism, and operators. Each unit is structured to provide practical coding exercises and outputs to reinforce learning.

Uploaded by

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

JAVA OOP | 22AIE111

COMPLETE CODE BOOK


Every Topic — Every Program Type — All 32 Source Files Covered

UNIT 1: JVM Bytecode OOP Pillars Hello World Data Types Variables Operators
Control Statements Methods (Functions) Arrays Value vs Reference Types
UNIT 2: Classes & Objects Constructors this keyword Method Overloading
Object Class Garbage Collection Stack & Heap Memory
Inheritance (Single/Multilevel/Hierarchical) super Overriding
Runtime Polymorphism Encapsulation Abstract Classes Interfaces
Access Modifiers (private/protected/public/default) Packages
Array of Objects UML String Programs Exam-style Mixed Programs
UNIT 1 — JAVA BASICS, JVM, OPERATORS, CONTROL
STATEMENTS, ARRAYS & METHODS
1. Hello World — Basic Syntax, main() Method & Comments
▸ 1.1 — Hello World with all 3 comment types
/**
* Documentation Comment — used to generate Javadoc pages.
* @author Student
* @version 1.0
*/
public class HelloWorld {
public static void main(String[] args) {

/* Multi-line comment:
[Link] → prints and moves to next line
[Link] → prints WITHOUT moving to next line */

// Single-line comment: printing to console


[Link]("Hello, World!");
[Link]("Welcome to Java OOP - 22AIE111");
[Link]("Same ");
[Link]("line.");
[Link](); // blank line
[Link]("Done.");
}
// WHY public static void main(String[] args)?
// public → JVM calls it from outside the class
// static → JVM calls it WITHOUT creating an object
// void → returns nothing to JVM
// main → JVM looks for this exact name
// String[] args → accepts command-line arguments
}
OUTPUT: Hello, World! | Welcome to Java OOP - 22AIE111 | Same line. | Done.

2. Data Types — Primitive, Non-Primitive, Value vs Reference Types


▸ 2.1 — All 8 Primitive Data Types (from JAVA_UNIT1-[Link] slides 50-51)
public class PrimitiveDataTypes {
public static void main(String[] args) {
// INTEGER TYPES
byte b = 127; // 8-bit : -128 to 127
short s = 32000; // 16-bit : -32,768 to 32,767
int i = 2147483647; // 32-bit : most common integer
long l = 9876543210L; // 64-bit : needs 'L' suffix

// DECIMAL TYPES
float f = 3.14f; // 32-bit : needs 'f' suffix
double d = 3.141592653589; // 64-bit : default decimal type

// OTHER
char c = 'A'; // 16-bit Unicode character
boolean flag = true; // only true or false

[Link]("byte : " + b);


[Link]("short : " + s);
[Link]("int : " + i);
[Link]("long : " + l);
[Link]("float : " + f);
[Link]("double : " + d);
[Link]("char : " + c);
[Link]("boolean : " + flag);
}
}
OUTPUT: byte:127 short:32000 int:2147483647 long:9876543210 float:3.14
double:3.1415... char:A boolean:true

▸ 2.2 — Value Types vs Reference Types (from JAVA_UNIT1-[Link] slide 48-49)


public class ValueVsReference {
public static void main(String[] args) {

// VALUE TYPE — primitive, stored directly in Stack


// Assigning copies the VALUE → two independent variables
int a = 10;
int b = a; // b gets a COPY of a's value
b = 99;
[Link]("a = " + a); // 10 — a is NOT affected
[Link]("b = " + b); // 99

// REFERENCE TYPE — object in Heap; Stack holds the ADDRESS


// Assigning copies the ADDRESS → both point to SAME object
int[] arr1 = {1, 2, 3};
int[] arr2 = arr1; // arr2 holds SAME address as arr1
arr2[0] = 999;
[Link]("arr1[0] = " + arr1[0]); // 999 — CHANGED!

// String — reference type but IMMUTABLE


String s1 = "Hello"; // stored in String Constant Pool
String s2 = "Hello"; // reuses SAME pool object
String s3 = new String("Hello");// forces NEW Heap object
[Link](s1 == s2); // true (same pool reference)
[Link](s1 == s3); // false (s3 is a new object)
[Link]([Link](s3)); // true (same content)
}
}
NOTE: Primitive → Value type → Stack → independent copy on assignment. Object/Array/String → Reference
type → Stack holds address → Heap holds actual object. String is immutable: methods like concat() return a
NEW string object.

▸ 2.3 — Type Casting: Widening (implicit) and Narrowing (explicit)


public class TypeCasting {
public static void main(String[] args) {
// WIDENING — smaller fits into larger, safe, automatic
int x = 150;
long y = x; // int → long (auto)
double z = y; // long → double (auto)
[Link]("Widening int→long→double: " + z); // 150.0

// NARROWING — larger to smaller, must cast, may lose data


double pi = 3.99999;
int piInt = (int) pi; // truncates decimal (does NOT round)
[Link]("Narrowing double→int: " + piInt); // 3

// char and int


char ch = 'A';
int code = ch; // 'A' = 65 (widening)
char next = (char)(code + 1);// 66 = 'B' (narrowing)
[Link]("'A' as int: " + code); // 65
[Link]("Next char : " + next); // B
}
}
3. Variables — Local, Instance, Static + Concept of References
▸ 3.1 — All three variable types
public class VariableTypes {
// INSTANCE VARIABLE — one per object, stored in Heap with the object
int instanceVar = 10;

// STATIC VARIABLE — ONE shared copy for ALL objects (Method Area)
static int staticVar = 100;

void show() {
// LOCAL VARIABLE — inside method only, Stack, MUST be initialized
int localVar = 50;
[Link]("Local = " + localVar);
[Link]("Instance = " + instanceVar);
[Link]("Static = " + staticVar);
}

public static void main(String[] args) {


VariableTypes obj1 = new VariableTypes();
VariableTypes obj2 = new VariableTypes();

[Link] = 999; // changes obj1's copy ONLY


staticVar = 777; // changes the ONE shared copy — all objects see this

[Link]();
[Link]("obj2 instance = " + [Link]); // 10 (own copy)
[Link]("obj2 static = " + [Link]); // 777 (shared)
}
}
NOTE: Reference: 'obj1' is a variable stored in Stack holding the Heap ADDRESS of the VariableTypes object.
Two reference variables can point to the same object — any change through either affects the same object.

4. Operators — All 8 Types (from OOPS_W1_Extra_Operators_Notes.docx)


▸ 4.1 — Arithmetic Operators (exact from course file)
public class ArithmeticOperators {
public static void main(String args[]) {
int a = 50;
int b = 20;
[Link]("Addition : " + (a + b)); // 70
[Link]("Subtraction : " + (a - b)); // 30
[Link]("Multiplication : " + (a * b)); // 1000
[Link]("Division : " + (a / b)); // 2 (integer division)
[Link]("Modulus : " + (a % b)); // 10
// Double division to get decimal result:
[Link]("Double div : " + ((double) a / b)); // 2.5
}
}

▸ 4.2 — Unary Operators (pre/post increment & decrement)


public class UnaryOperators {
public static void main(String[] args) {
int x = 10;
[Link]("Unary minus : " + (-x)); // -10
[Link]("Logical NOT : " + (!true)); // false
[Link]("Bitwise NOT : " + (~x)); // -11

// Pre-increment: increment FIRST, then use


[Link]("++x (pre) : " + (++x)); // 11
// Post-increment: use FIRST, then increment
[Link]("x++ (post) : " + (x++)); // 11 (x becomes 12 after)
[Link]("x after : " + x); // 12

// Classic tricky question


int y = 5;
int result = y++ * 2; // uses y=5, then y becomes 6
[Link]("result=" + result + " y=" + y); // 10 6
}
}

▸ 4.3 — Relational, Logical, Assignment, Bitwise, Ternary, instanceof


public class AllOperators {
public static void main(String[] args) {
int a = 10, b = 20;

// RELATIONAL — always return boolean


[Link](a > b); // false
[Link](a < b); // true
[Link](a == b); // false
[Link](a != b); // true
[Link](a >= 10); // true
[Link](b <= 20); // true

// LOGICAL
[Link]((a < b) && (b < 50)); // true (both true)
[Link]((a > b) || (b < 50)); // true (one true)
[Link](!(a > b)); // true (negation)

// ASSIGNMENT SHORTHAND
int x = 10;
x += 5; [Link]("x+=5 : " + x); // 15
x -= 3; [Link]("x-=3 : " + x); // 12
x *= 2; [Link]("x*=2 : " + x); // 24
x /= 4; [Link]("x/=4 : " + x); // 6
x %= 4; [Link]("x%=4 : " + x); // 2

// BITWISE (on binary representations)


[Link]("5 & 3 = " + (5 & 3)); // 1 (0101 & 0011 = 0001)
[Link]("5 | 3 = " + (5 | 3)); // 7 (0101 | 0011 = 0111)
[Link]("5 ^ 3 = " + (5 ^ 3)); // 6 (XOR)
[Link]("~5 = " + (~5)); // -6 (bitwise NOT)
[Link]("5 << 1 = " + (5 << 1)); // 10 (left shift = x2)
[Link]("20>> 2 = " + (20 >> 2));// 5 (right shift = /4)

// TERNARY — one-line if-else


int max = (a > b) ? a : b;
[Link]("Max = " + max); // 20

// instanceof — check object type


String s = "Java";
[Link](s instanceof String); // true
[Link](s instanceof Object); // true (all inherit Object)
}
}

5. Control Statements — if/else, switch, loops, break, continue (from


OOPS_W2_ControlStmts.docx)
▸ 5.1 — if / if-else / if-else-if ladder / nested-if
import [Link];
public class IfStatements {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter marks (0-100): ");
int marks = [Link]();

// if-else-if ladder (grade calculator from Assignment)


if (marks >= 90) [Link]("Grade: S (Outstanding)");
else if (marks >= 80) [Link]("Grade: A (Excellent)");
else if (marks >= 70) [Link]("Grade: B (Good)");
else if (marks >= 60) [Link]("Grade: C (Average)");
else if (marks >= 50) [Link]("Grade: D (Pass)");
else [Link]("Grade: F (Fail)");

// Nested if
if (marks >= 50) {
if (marks >= 75) [Link]("Distinction!");
else [Link]("Pass — keep improving");
}

// Positive / Negative / Zero check (Assignment 2 Q6)


[Link]("Enter any number: ");
int n = [Link]();
if (n > 0) [Link](n + " is Positive");
else if (n < 0) [Link](n + " is Negative");
else [Link]("Zero");
}
}

▸ 5.2 — switch statement: int and String (from OOPS_W2_ControlStmts.docx)


import [Link];
public class SwitchDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// switch with int (Assignment 2 Q5: days in month)


[Link]("Enter month number (1-12): ");
int month = [Link]();
switch (month) {
case 1: [Link]("January - 31 days"); break;
case 2: [Link]("February - 28/29 days"); break;
case 3: [Link]("March - 31 days"); break;
case 4: [Link]("April - 30 days"); break;
case 5: [Link]("May - 31 days"); break;
case 6: [Link]("June - 30 days"); break;
case 7: [Link]("July - 31 days"); break;
case 8: [Link]("August - 31 days"); break;
case 9: [Link]("September- 30 days"); break;
case 10: [Link]("October - 31 days"); break;
case 11: [Link]("November - 30 days"); break;
case 12: [Link]("December - 31 days"); break;
default: [Link]("Invalid month!");
}

// switch with String


[Link]("Enter day name: ");
String day = [Link]().toLowerCase();
switch (day) {
case "saturday": case "sunday":
[Link]("Weekend!"); break;
default:
[Link]("Weekday");
}
}
}

▸ 5.3 — for, while, do-while, for-each, break, continue, patterns


public class LoopsDemo {
public static void main(String[] args) {

// for loop — sum of even numbers 1-20 (Assignment 2 Q1)


int sum = 0;
for (int i = 2; i <= 20; i += 2) sum += i;
[Link]("Sum of evens 1-20 : " + sum); // 110

// while loop — sum of even digits separately (Assignment 2 Q1)


int num = 123456, evenSum = 0, oddSum = 0, temp = num;
while (temp > 0) {
int digit = temp % 10;
if (digit % 2 == 0) evenSum += digit;
else oddSum += digit;
temp /= 10;
}
[Link]("Even digit sum: " + evenSum + " Odd digit sum: " + oddSum);

// do-while — runs at least once


int count = 1;
do { [Link](count + " "); count++; } while (count <= 5);
[Link]();

// break — stop at first multiple of 7 above 30


for (int i = 31; i <= 100; i++) {
if (i % 7 == 0) { [Link]("First multiple of 7>30: "+i); break; }
}

// continue — skip 4 and 7


[Link]("Skip 4 and 7: ");
for (int i = 1; i <= 10; i++) {
if (i == 4 || i == 7) continue;
[Link](i + " ");
}
[Link]();

// for-each loop
int[] arr = {10, 20, 30, 40, 50};
[Link]("for-each: ");
for (int val : arr) [Link](val + " ");
[Link]();

// Nested loops — star pattern


[Link]("Star pattern:");
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) [Link]("* ");
[Link]();
}
}
}

6. Methods (Functions) — Declaration, Calling, Return Values, Recursion (from


U1_Methodss.docx)
▸ 6.1 — Methods: void, return value, recursive; BMI from Teaching_example_1.docx
public class MethodsDemo {

// void method — does task, returns nothing


static void greet(String name) {
[Link]("Hello, " + name + "!");
}

// method with return value (from U1_Methodss.docx)


static int max(int x, int y) {
if (x > y) return x;
else return y;
}

// method returning double (from Teaching_example_1.docx)


static double calculateBMI(double weight, double height) {
return weight / (height * height);
}

// RECURSIVE — calls itself (factorial)


static long factorial(int n) {
if (n <= 1) return 1; // base case — STOPS recursion
return n * factorial(n - 1); // recursive call
}

// RECURSIVE — Fibonacci
static int fib(int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}

// method with multiple parameters


static void printInfo(String name, int age) {
[Link]("Name:" + name + " Age:" + age);
}

public static void main(String[] args) {


greet("Alice");
[Link]("max(45,78) = " + max(45, 78)); // 78
[Link]("BMI = %.2f%n", calculateBMI(70, 1.75)); // 22.86
[Link]("5! = " + factorial(5)); // 120
[Link]("fib(7) = " + fib(7)); // 13
printInfo("Bob", 20);
}
}

▸ 6.2 — Pass by Value vs Pass by Reference


public class PassByDemo {

// Primitive: only the VALUE is copied — original unchanged


static void tryChangeInt(int x) {
x = 9999; // only local copy changes
}

// Array: the ADDRESS is copied — same Heap object modified


static void changeFirstElement(int[] arr) {
arr[0] = 9999; // changes original array in Heap
}

public static void main(String[] args) {


int num = 10;
tryChangeInt(num);
[Link]("After tryChangeInt: " + num); // 10 — UNCHANGED

int[] data = {1, 2, 3};


changeFirstElement(data);
[Link]("After changeFirstElement: " + data[0]); // 9999 — CHANGED
}
}
NOTE: Java is ALWAYS pass-by-value. For primitives, a copy of the value is passed. For objects/arrays, a copy
of the REFERENCE (address) is passed — so the object contents can be changed but the caller's reference
cannot be redirected.
7. Arrays — 1D, 2D, Assignment Programs (from U1_Arrays.docx + [Link])
▸ 7.1 — 1D Array: declare, input, reverse, max/min, count even/odd (Assignment 2 Q8-Q10)
import [Link];
import [Link];
public class Array1D {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Direct initialization (from U1_Arrays.docx)


int a[] = {33, 3, 4, 5};
for (int i = 0; i < [Link]; i++)
[Link](a[i]);

// Q8: Read and display 5 integers using array and for loop
int[] arr = new int[5];
[Link]("Enter 5 numbers:");
for (int i = 0; i < [Link]; i++) arr[i] = [Link]();
[Link]("Array: ");
for (int i = 0; i < [Link]; i++) [Link](arr[i] + " ");
[Link]();

// Q9: Print array elements in reverse order


[Link]("Reverse: ");
for (int i = [Link] - 1; i >= 0; i--) [Link](arr[i] + " ");
[Link]();

// Q10: Count even and odd numbers


int even = 0, odd = 0, max = arr[0], min = arr[0], sum = 0;
for (int v : arr) {
if (v % 2 == 0) even++; else odd++;
if (v > max) max = v;
if (v < min) min = v;
sum += v;
}
[Link]("Even=" + even + " Odd=" + odd);
[Link]("Max=" + max + " Min=" + min + " Sum=" + sum + " Avg="+(sum/5.0));

// Sort
[Link](arr);
[Link]("Sorted: " + [Link](arr));
}
}

▸ 7.2 — 2D Array: Matrix 4x3 input and display (from sample exam question)
import [Link];
public class Matrix4x3 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int rows = 4, cols = 3;
int[][] mat = new int[rows][cols];

[Link]("Enter " + rows + "x" + cols + " matrix elements:");


for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
mat[i][j] = [Link]();

[Link]("Matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++)
[Link]("%5d", mat[i][j]);
[Link]();
}
// Sum of all elements
int total = 0;
for (int[] row : mat) for (int v : row) total += v;
[Link]("Sum of all elements: " + total);
}
}

▸ 7.3 — Assignment 2 programs: power(x^n), largest of 3, days in month, grade


import [Link];
public class AssignmentPrograms {

// Q2: x to the power n (without [Link])


static long power(int x, int n) {
if (n == 0) return 1;
long result = 1;
for (int i = 0; i < n; i++) result *= x;
return result;
}

// Q7: grade based on score


static String grade(int score) {
if (score >= 90) return "S"; if (score >= 80) return "A";
if (score >= 70) return "B"; if (score >= 60) return "C";
if (score >= 50) return "D"; return "F";
}

// Q5: days in a month with leap year


static int daysInMonth(int m, int y) {
if (m == 2) {
boolean leap = (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
return leap ? 29 : 28;
}
int[] days30 = {4, 6, 9, 11};
for (int d : days30) if (d == m) return 30;
return 31;
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

// Q2
[Link]("x n: "); int x=[Link](), n=[Link]();
[Link](x + "^" + n + " = " + power(x, n));

// Q3: even or odd


[Link]("Number: "); int num = [Link]();
[Link](num + " is " + (num % 2 == 0 ? "Even" : "Odd"));

// Q4: largest of three


[Link]("3 numbers: ");
int a=[Link](), b=[Link](), c=[Link]();
int largest = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
[Link]("Largest: " + largest);

// Q5
[Link]("Month Year: "); int m=[Link](), y=[Link]();
[Link]("Days in month " + m + "/" + y + " = " + daysInMonth(m, y));

// Q6
[Link]("Number: "); int k=[Link]();
if (k > 0) [Link]("Positive");
else if (k < 0) [Link]("Negative");
else [Link]("Zero");

// Q7
[Link]("Score: "); [Link]("Grade: " + grade([Link]()));
}
}
UNIT 2 — CLASSES, OBJECTS, CONSTRUCTORS, INHERITANCE,
ENCAPSULATION, INTERFACES, PACKAGES
8. Classes & Objects — Fields, Methods, Instantiation (from
U2_OOPs_1_Class_and_Objects.docx + Teaching_example_1.docx)
▸ 8.1 — Class with all 5 components: fields, methods, constructor, static block, instance block
public class StudentClass {

// 1. FIELDS (Instance Variables) — one per object, stored in Heap


int rollNo;
String name;
int marks;
static int totalStudents = 0; // Static field — shared by all

// 2. STATIC BLOCK — runs ONCE when class is first loaded into JVM
static {
[Link]("StudentClass loaded into JVM memory");
}

// 3. INSTANCE BLOCK — runs every time a new object is created (before constructor)
{
totalStudents++;
[Link]("New student object #" + totalStudents + " being created");
}

// 4. CONSTRUCTOR — initializes object


StudentClass(int rollNo, String name, int marks) {
[Link] = rollNo;
[Link] = name;
[Link] = marks;
}

// 5. METHODS — define behavior


void display() {
[Link]("Roll:" + rollNo + " Name:" + name + " Marks:" + marks);
}

char getGrade() {
if (marks >= 90) return 'S';
if (marks >= 75) return 'A';
if (marks >= 60) return 'B';
if (marks >= 50) return 'C';
return 'F';
}

public static void main(String[] args) {


StudentClass s1 = new StudentClass(101, "Alice", 88);
StudentClass s2 = new StudentClass(102, "Bob", 72);
[Link](); [Link]("Grade: " + [Link]());
[Link](); [Link]("Grade: " + [Link]());
[Link]("Total students: " + totalStudents);
}
}

▸ 8.2 — BMI Calculator class (exact from Teaching_example_1.docx)


package helloworld;
import [Link];

public class Person {


// Member variables of Person class
public String myName;
public double height; // in metres
public int weight; // in kg

// Method with no parameters, no return value


public void printPersonName() {
[Link]("The name of this person is " + myName);
}

// Method with no parameters, returns double


public double calculateBMI() {
double bmi = weight / (height * height);
return bmi;
}

public static void main(String[] args) {


[Link]("Hello World");

// Create instance (object) of Person class


Person bob = new Person();
[Link] = "Bob";
[Link] = 1.544;
[Link] = 60;
[Link]();
[Link]("BMI of Bob : %.2f%n", [Link]());

Person harry = new Person();


[Link] = "Harry";
[Link] = 1.85;
[Link] = 70;
[Link]();
[Link]("BMI of Harry : %.2f%n", [Link]());
}
}

9. Constructors — Default, Parameterized, Overloaded, this() (from


U2_Constructor_overloading.docx)
▸ 9.1 — Default vs Parameterized constructor
class Box {
double width, height, depth;

// DEFAULT CONSTRUCTOR — compiler provides if none defined


Box() {
width = height = depth = 0;
[Link]("Default Box created (0,0,0)");
}

// PARAMETERIZED CONSTRUCTOR
Box(double w, double h, double d) {
width = w; height = h; depth = d;
[Link]("Box(" + w + "," + h + "," + d + ") created");
}

double volume() { return width * height * depth; }


}
public class ConstructorBasic {
public static void main(String[] args) {
Box b1 = new Box(); // default
Box b2 = new Box(3.0, 4.0, 5.0); // parameterized
[Link]("b1 volume = " + [Link]()); // 0.0
[Link]("b2 volume = " + [Link]()); // 60.0
}
}
▸ 9.2 — Constructor Overloading (from U2_Constructor_overloading.docx)
class Rectangle {
double length, breadth;

Rectangle() { length = breadth = 1.0; } // 1x1


Rectangle(double side) { length = breadth = side; } // square
Rectangle(double l, double b) { length = l; breadth = b; } // full

double area() { return length * breadth; }


double perimeter() { return 2 * (length + breadth); }

void display() {
[Link]("L=%.1f B=%.1f Area=%.2f Perimeter=%.2f%n",
length, breadth, area(), perimeter());
}
}
public class ConstructorOverload {
public static void main(String[] args) {
Rectangle r1 = new Rectangle(); // 1x1
Rectangle r2 = new Rectangle(5); // 5x5 square
Rectangle r3 = new Rectangle(4, 7); // 4x7
[Link](); [Link](); [Link]();
// Constructor that gets called is decided at COMPILE TIME
// based on number/type of arguments — compile-time polymorphism
}
}

▸ 9.3 — 'this' keyword: 3 uses — name conflict, this(), pass current object
class Employee {
int empId;
String name;
double salary;

// (i) '[Link]' resolves parameter vs instance variable name conflict


Employee(int empId, String name, double salary) {
[Link] = empId; // '[Link]' = instance var
[Link] = name; // 'name' = parameter
[Link] = salary;
}

// (ii) this() — calls another constructor. MUST be first statement.


Employee(int empId, String name) {
this(empId, name, 30000.0); // chains to 3-arg constructor
}

Employee() {
this(0, "Unknown"); // chains to 2-arg constructor
}

// (iii) pass 'this' (the current object) as an argument


void printDetails(Employee e) {
[Link]("ID:" + [Link] + " Name:" + [Link] + " Salary:" + [Link]);
}
void showSelf() {
printDetails(this); // passes current object
}
}
public class ThisDemo {
public static void main(String[] args) {
Employee e1 = new Employee(101, "Alice", 55000);
Employee e2 = new Employee(102, "Bob");
Employee e3 = new Employee();
[Link](); [Link](); [Link]();
}
}
10. Method Overloading — Compile-time Polymorphism (from
U2_Method_overloading.docx)
▸ 10.1 — Calculator and StringUtils overloads (from U2_Method_overloading.docx)
class Calculator {
int add(int a, int b) { return a + b; } // two ints
int add(int a, int b, int c) { return a + b + c; } // three ints
double add(double a, double b) { return a + b; } // two doubles
double add(int a, double b) { return a + b; } // mixed types
String add(String s1, String s2){ return s1 + s2; } // String concat
}

// From U2_Method_overloading.docx StringUtils example


class StringUtils {
public String concatenate(String s1, String s2) { return s1 + s2; }
public String concatenate(String s1, String s2, String s3) { return s1+s2+s3; }
}

public class OverloadDemo {


public static void main(String[] args) {
Calculator c = new Calculator();
[Link]([Link](5, 3)); // 8 — int+int
[Link]([Link](5, 3, 2)); // 10 — 3 ints
[Link]([Link](5.5, 3.2)); // 8.7 — double+double
[Link]([Link](5, 3.0)); // 8.0 — int+double
[Link]([Link]("Hi", " Java")); // Hi Java

StringUtils su = new StringUtils();


[Link]([Link]("Java", " is", " fun!")); // Java is fun!

// CANNOT overload by return type alone — compile error:


// int foo() { return 1; }
// double foo() { return 1.0; } // ambiguous!
}
}
NOTE: Overloading = same name, DIFFERENT parameter list (number/type/order). Resolved at COMPILE TIME
(early binding). This is compile-time polymorphism. Return type ALONE does not distinguish overloaded
methods.

11. The Object Class — All 11 Methods (from U2_Object_class_Java.docx)


▸ 11.1 — Override toString(), equals(), hashCode(), finalize(), use getClass()
class Student {
String name;
int rollNo;
Student(String name, int rollNo) { [Link]=name; [Link]=rollNo; }

// (1) toString() — called automatically when object is printed


@Override
public String toString() {
return "Student{name='" + name + "', roll=" + rollNo + "}";
}

// (2) equals() — compare by CONTENT, not reference (address)


// Default equals() in Object just does '==' (reference compare)
@Override
public boolean equals(Object obj) {
if (this == obj) return true; // same reference
if (!(obj instanceof Student)) return false; // type check
Student s = (Student) obj;
return [Link] == [Link] && [Link]([Link]);
}

// (3) hashCode() — MUST override when equals() is overridden


// Contract: if [Link](b)==true → [Link]()==[Link]()
@Override
public int hashCode() { return rollNo * 31 + [Link](); }

// (4) finalize() — JVM calls this BEFORE garbage collecting object


@Override
protected void finalize() throws Throwable {
[Link]("[GC] About to collect: " + name);
}
}
public class ObjectClassDemo {
public static void main(String[] args) {
Student s1 = new Student("Alice", 101);
Student s2 = new Student("Alice", 101);
Student s3 = new Student("Bob", 102);

[Link](s1); // Student{name='Alice', roll=101}


[Link]("equals : " + [Link](s2)); // true (same content)
[Link]("== : " + (s1 == s2)); // false (diff objects)
[Link]("hashCode: " + [Link]()); // same as s2
[Link]("getClass: " + [Link]().getName()); // Student

// All Object class methods (from U2_Object_class_Java.docx table):


// getClass() → returns runtime class
// hashCode() → unique integer for object
// equals(obj) → compare (default: reference)
// clone() → create exact copy (needs Cloneable)
// toString() → string representation
// notify() → wake one waiting thread
// notifyAll() → wake all waiting threads
// wait() → pause current thread
// wait(long ms) → pause for ms milliseconds
// wait(long,int) → pause for ms + nanoseconds
// finalize() → called before GC destroys object
}
}

12. Garbage Collection & Stack/Heap Memory (from


U2_MemoryAllocation_Garbage.docx)
▸ 12.1 — Stack vs Heap demo + 3 ways to make objects GC-eligible
class Demo {
String tag;
Demo(String tag) { [Link] = tag; }
@Override
protected void finalize() {
[Link]("[GC] Collecting: " + tag);
}
}
public class GarbageDemo {
public static void main(String[] args) {

// MEMORY LAYOUT:
// int x = 10; → x VALUE stored in Stack
// Demo d = new Demo("X"); → 'd' REFERENCE in Stack
// → Demo object ("X") in HEAP

// WAY 1: Nullify reference → object has 0 references → eligible


Demo d1 = new Demo("Object-1");
d1 = null; // Object-1 → eligible for GC

// WAY 2: Reassign reference → original object abandoned


Demo d2 = new Demo("Object-2");
Demo d3 = new Demo("Object-3");
d2 = d3; // Object-2 has no reference now → eligible

// WAY 3: Object goes out of scope


{ Demo temp = new Demo("Object-4"); } // temp scope ends → eligible

// WAY 4: Anonymous object (from U2_MemoryAllocation_Garbage.docx)


new Demo("Object-5"); // never had a reference → immediately eligible

// Request GC — JVM MAY or MAY NOT run immediately (hint, not command)
[Link]();
[Link]().gc(); // alternative

[Link]("Main continues...");

// Stack characteristics (from U2_MemoryAllocation_Garbage.docx):


// - LIFO order | Thread-safe | Faster | throws StackOverflowError
// Heap characteristics:
// - Young Gen: new objects | Old Gen: long-lived | Perm Gen: JVM metadata
// - Shared | GC managed | Slower | throws OutOfMemoryError
}
}
NOTE: [Link]() is a REQUEST to JVM to run garbage collector — JVM may ignore it. The finalize() method
is called by GC BEFORE destroying the object, allowing cleanup. Do not rely on finalize() for critical cleanup.
13. Inheritance — Single, Multilevel, Hierarchical, super, final, Overriding (from
U2_Inheritance.docx + [Link])
▸ 13.1 — Single Inheritance: Vehicle → Car
class Vehicle {
String brand = "Toyota";
int speed;
Vehicle(int speed) { [Link] = speed; }
void display() { [Link]("Brand:" + brand + " Speed:" + speed); }
}

// Car IS-A Vehicle — inherits all non-private members


class Car extends Vehicle {
int doors;
Car(int speed, int doors) {
super(speed); // call parent constructor
[Link] = doors;
}
void showCar() {
[Link]("Doors: " + doors);
display(); // inherited from Vehicle
}
}
public class SingleInheritance {
public static void main(String[] args) {
Car c = new Car(120, 4);
[Link]();
[Link]("Brand (inherited): " + [Link]);

// Upcasting: parent reference → child object


Vehicle v = new Car(100, 2); // valid — Car IS-A Vehicle
[Link]();
// [Link](); // COMPILE ERROR — Vehicle ref can't see Car methods
}
}

▸ 13.2 — Multilevel Inheritance: Animal → Mammal → Dog → GoldenRetriever


class Animal {
void breathe() { [Link]("Breathing oxygen..."); }
}
class Mammal extends Animal {
void feedMilk() { [Link]("Feeds milk to young"); }
}
class Dog extends Mammal {
void bark() { [Link]("Woof! Woof!"); }
}
class GoldenRetriever extends Dog {
void fetch() { [Link]("Fetching the ball!"); }
}
public class MultilevelDemo {
public static void main(String[] args) {
GoldenRetriever g = new GoldenRetriever();
[Link](); // Level 1 — from Animal
[Link](); // Level 2 — from Mammal
[Link](); // Level 3 — from Dog
[Link](); // Level 4 — own method
}
}

▸ 13.3 — Hierarchical Inheritance: Shape → Circle, Rectangle, Triangle


class Shape {
String color;
Shape(String color) { [Link] = color; }
void describe() { [Link]("Shape, color: " + color); }
}
class Circle extends Shape {
double radius;
Circle(String c, double r) { super(c); radius = r; }
@Override void describe() {
[Link]();
[Link]("Circle r=%.1f area=%.2f%n", radius, [Link]*radius*radius);
}
}
class Rectangle extends Shape {
double l, b;
Rectangle(String c, double l, double b) { super(c); this.l=l; this.b=b; }
@Override void describe() {
[Link]();
[Link]("Rectangle %.1fx%.1f area=%.2f%n", l, b, l*b);
}
}
class Triangle extends Shape {
double base, height;
Triangle(String c, double bs, double h) { super(c); base=bs; height=h; }
@Override void describe() {
[Link]();
[Link]("Triangle base=%.1f h=%.1f area=%.2f%n", base, height,
0.5*base*height);
}
}
public class HierarchicalDemo {
public static void main(String[] args) {
Shape[] shapes = { new Circle("red",5), new Rectangle("blue",4,6), new
Triangle("green",3,8) };
for (Shape s : shapes) { [Link](); [Link](); }
}
}

▸ 13.4 — super keyword: all 3 uses (from Garbage_collector_access_modifier_encapsulation file)


class Superclass {
int num = 100;
Superclass() { [Link]("Superclass default constructor"); }
Superclass(String s){ [Link]("Superclass param: " + s); }
void display() { [Link]("Superclass display, num=" + num); }
}

class Subclass extends Superclass {


int num = 200; // hides parent's num

Subclass() {
super("from Subclass"); // (iii) call parent constructor — MUST be FIRST statement
}

void show() {
[Link]([Link]); // (i) parent variable = 100
[Link](num); // child variable = 200
[Link](); // (ii) call parent method
}

@Override
void display() { [Link]("Subclass display, num=" + num); }
}

public class SuperDemo {


public static void main(String[] args) {
Subclass obj = new Subclass();
[Link]();
[Link](); // calls child's version
}
}

▸ 13.5 — Method Overriding + @Override + final method + final class


class Animal {
public void sound() { [Link]("Generic animal sound"); }

// final method — CANNOT be overridden in subclass


public final void breathe() { [Link]("All animals breathe O2"); }
}

class Dog extends Animal {


@Override // ensures correct signature — compile error if wrong
public void sound() { [Link]("Dog barks: Woof!"); }
// Cannot reduce access modifier: public → private would be COMPILE ERROR
// Cannot override breathe() — it is final
}

class Cat extends Animal {


@Override
public void sound() { [Link]("Cat meows: Meow!"); }
}

final class Immutable { // cannot be extended


void show() { [Link]("Immutable class — cannot be subclassed"); }
}
// class TryExtend extends Immutable { } // COMPILE ERROR

class FinalVarDemo {
final int MAX = 100; // final variable — constant, cannot change
void show() {
// MAX = 200; // COMPILE ERROR
[Link]("MAX = " + MAX);
}
}

public class OverridingDemo {


public static void main(String[] args) {
Animal a;
a = new Dog(); [Link](); [Link](); // Dog's sound, Animal's breathe
a = new Cat(); [Link]();
new Immutable().show();
new FinalVarDemo().show();
}
}

14. Runtime Polymorphism — Dynamic Method Dispatch (from


U2_DynamicMethodDispatch file)
▸ 14.1 — A, B, C hierarchy — exact program from course notes
// From U2_DynamicMethodDispatch_orRuntimePolymorphism_in_Java.docx
class A { void m1() { [Link]("Inside A's m1 method"); } }
class B extends A { @Override void m1() { [Link]("Inside B's m1 method"); } }
class C extends A { @Override void m1() { [Link]("Inside C's m1 method"); } }

public class DynamicDispatch {


public static void main(String[] args) {
A ref; // superclass reference

ref = new A(); ref.m1(); // A's m1 — object type is A


ref = new B(); ref.m1(); // B's m1 — object type is B (JVM decides at RUNTIME)
ref = new C(); ref.m1(); // C's m1 — object type is C
// KEY RULE: JVM looks at the ACTUAL TYPE of the object in Heap,
// NOT the type of the reference variable 'ref'
// This is called LATE BINDING or DYNAMIC BINDING

// Instance VARIABLES are NOT polymorphic:


// they use the reference type at COMPILE TIME
// Only METHODS exhibit runtime polymorphism
}
}
NOTE: Runtime Polymorphism = Method Overriding + Superclass reference pointing to subclass object. JVM
resolves the method at RUNTIME based on actual object type. Compile-time polymorphism = Method
Overloading (resolved at compile time).
15. Encapsulation — Private Fields, Getters, Setters, Validation (from [Link]
+ Garbage_collector file)
▸ 15.1 — BankAccount with full encapsulation (from [Link])
// From [Link] — BankAccount example
class BankAccount {
private String accountHolder;
private double balance;
private String password; // private — cannot be accessed directly outside

BankAccount(String holder, double amount, String pwd) {


accountHolder = holder;
balance = (amount >= 0) ? amount : 0;
password = pwd;
}

// SETTER with VALIDATION (from [Link])


public void setPassword(String pwd) {
if ([Link]() >= 8) { // basic security check
password = pwd;
[Link]("Password updated.");
} else {
[Link]("Password must be at least 8 characters long.");
}
}

// Controlled GETTER — never exposes actual password (from [Link])


public String getPassword() { return "Access Denied"; }

public String getAccountHolder() { return accountHolder; }


public double getBalance() { return balance; }

public void deposit(double amount) {


if (amount > 0) { balance += amount; [Link]("Deposited: " + amount); }
else [Link]("Invalid deposit amount!");
}

public void withdraw(double amount, String pwd) {


if (![Link](password)) { [Link]("Wrong password!"); return; }
if (amount > balance) { [Link]("Insufficient funds!"); return; }
balance -= amount;
[Link]("Withdrawn: " + amount);
}
}
public class EncapsulationDemo {
public static void main(String[] args) {
BankAccount acc = new BankAccount("Alice", 5000, "secure123");
[Link]("short"); // rejected
[Link]("newSecure99"); // accepted
[Link]([Link]()); // Access Denied
[Link](2000);
[Link](1000, "newSecure99"); // success
[Link](500, "wrongPass"); // fails
// [Link] = 99999; // COMPILE ERROR — private!
}
}

16. Abstraction — Abstract Classes (from [Link] +


U1_Java_OOP_Concepts.docx)
▸ 16.1 — Abstract Shape class (from [Link] exact example + extended)
// From [Link]
abstract class Shape {
abstract void draw(); // abstract — no body, subclass MUST override
abstract double area();

// Concrete method — inherited without needing to override


void describe() {
[Link]("I am a " + getClass().getSimpleName()
+ " with area = " + [Link]("%.2f", area()));
}
}

// From [Link] — Rectangle


class Rect extends Shape {
double l, b;
Rect(double l, double b) { this.l=l; this.b=b; }
@Override void draw() { [Link]("drawing rectangle"); }
@Override double area() { return l * b; }
}

// From [Link] — Circle1


class Circle1 extends Shape {
double radius;
Circle1(double r) { [Link] = r; }
@Override void draw() { [Link]("drawing circle"); }
@Override double area() { return [Link] * radius * radius; }
}

// From [Link] TestAbstraction1


class TestAbstraction1 {
public static void main(String args[]) {
// Shape s = new Shape(); // ERROR — cannot instantiate abstract class
Shape s = new Circle1(5); // object is Circle1; reference is Shape
[Link]();
[Link]();

s = new Rect(4, 6);


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

17. Interfaces — Declaration, Implementation, Multiple, extends interface (from


U2_INTERFACE.docx)
▸ 17.1 — Device, TV, AC (exact from U2_INTERFACE.docx)
// From U2_INTERFACE.docx — exact Device/TV/AC program
interface Device {
void powerOn(); // public + abstract by default
void powerOff();
int MAX_VOLTAGE = 240; // public + static + final by default
}

class TV implements Device {


public void powerOn() { [Link]("TV is ON"); }
public void powerOff() { [Link]("TV is OFF"); }
}

class AC implements Device {


public void powerOn() { [Link]("AC is ON"); }
public void powerOff() { [Link]("AC is OFF"); }
}

public class InterfaceBasic {


public static void main(String[] args) {
Device myTV = new TV(); // interface reference
[Link]();
[Link]();
Device myAC = new AC();
[Link]();
[Link]();
[Link]("Max Voltage: " + Device.MAX_VOLTAGE);
}
}

▸ 17.2 — Multiple interface implementation + interface extends interface


interface Animal { void eat(); void breathe(); }
interface Pet { void play(); String getName(); }
interface Trainable { boolean train(String command); }

// Dog implements THREE interfaces — multiple inheritance (safe in Java)


class Dog implements Animal, Pet, Trainable {
private String name;
Dog(String name) { [Link] = name; }
@Override public void eat() { [Link](name + " eats kibble"); }
@Override public void breathe() { [Link](name + " breathes"); }
@Override public void play() { [Link](name + " plays fetch"); }
@Override public String getName() { return name; }
@Override public boolean train(String cmd) {
[Link](name + " learned: " + cmd); return true;
}
}

// Interface can extend multiple interfaces


interface Swimmable { void swim(); }
interface Duck extends Animal, Swimmable {
void quack();
}
class MallardDuck implements Duck {
public void eat() { [Link]("Duck eats seeds"); }
public void breathe(){ [Link]("Duck breathes"); }
public void swim() { [Link]("Duck swims"); }
public void quack() { [Link]("Quack!"); }
}

public class MultiInterfaceDemo {


public static void main(String[] args) {
Dog d = new Dog("Buddy");
[Link](); [Link](); [Link]("Sit");
Animal a = d; [Link](); // interface reference
Pet p = d; [Link]([Link]());
MallardDuck duck = new MallardDuck();
[Link](); [Link](); [Link]();
}
}

18. Access Specifiers — private, default, protected, public (from


U2_private/protected/public/Package files)
▸ 18.1 — All 4 access modifiers + access table
// ACCESS TABLE (from U2_Package_Protected.docx):
// Modifier | Same Class | Same Package | Subclass diff pkg | Other pkg
// private | YES | NO | NO | NO
// default | YES | YES | NO | NO
// protected | YES | YES | YES | NO
// public | YES | YES | YES | YES

class AccessParent {
private int pri = 1; // same class only
int def = 2; // same package
protected int pro = 3; // package + subclasses
public int pub = 4; // everywhere

void testInsideClass() {
[Link](pri + " " + def + " " + pro + " " + pub); // all OK
}
}

class AccessChild extends AccessParent {


void testSubclass() {
// [Link](pri); // COMPILE ERROR — private
[Link](def); // OK — same package
[Link](pro); // OK — subclass
[Link](pub); // OK — always
}
}

public class AccessDemo {


public static void main(String[] args) {
AccessParent obj = new AccessParent();
[Link]();
// [Link] → COMPILE ERROR in any other class
[Link]([Link]); // OK — same package
[Link]([Link]); // OK — same package
[Link]([Link]); // OK — everywhere

new AccessChild().testSubclass();
}
}

▸ 18.2 — Singleton pattern using private constructor (from U2_private_keyword.docx)


// Best use of private: fully encapsulated class (from U2_private_keyword.docx)
class Singleton {
private static Singleton instance = null;

private Singleton() { // private constructor — no external instantiation


[Link]("Singleton object created");
}

public static Singleton getInstance() {


if (instance == null)
instance = new Singleton(); // creates only ONCE
return instance;
}
public void show() { [Link]("I am the Singleton instance"); }
}
public class SingletonDemo {
public static void main(String[] args) {
// Singleton s = new Singleton(); // COMPILE ERROR — private constructor
Singleton s1 = [Link]();
Singleton s2 = [Link]();
[Link](s1 == s2); // true — same object!
[Link]();
}
}

▸ 18.3 — protected across packages (from U2_protected_keyword.docx)


// File: com/java/[Link]
package [Link];
public class A {
protected String msg = "Protected variable — accessible via inheritance";
protected void show() { [Link]("Protected method in A"); }
}
// File: com/javatpoint/[Link] (DIFFERENT package)
package [Link];
import [Link].A;

public class B extends A { // subclass in DIFFERENT package


public void display() {
[Link](msg); // OK — inherited protected member
show(); // OK — inherited protected method
}
public static void main(String[] args) {
B obj = new B();
[Link]();
// NOTE: new A().msg → COMPILE ERROR in different package
// (protected accessible only via inheritance, not object ref)
}
}

19. Packages — User-defined, import, fully qualified names (from


U2_Package_Protected.docx)
▸ 19.1 — vehicles/Vehicle and cars/Car (exact from U2_Package_Protected.docx)
// File: vehicles/[Link] (inside package vehicles)
package vehicles;
public class Vehicle {
public void display() {
[Link]("This is a vehicle.");
}
}

// File: cars/[Link] (inside package cars)


package cars;
import [Link]; // importing from another package

public class Car extends Vehicle {


public void show() {
[Link]("This is a car.");
}
}

// File: cars/[Link]
package cars;
public class TestCar {
public static void main(String[] args) {
Car c = new Car();
[Link](); // inherited from Vehicle (parent class)
[Link](); // Car's own method
}
}
// OUTPUT:
// This is a vehicle.
// This is a car.

▸ 19.2 — student/calculate package (exact exam Q5 program)


// File 1: student/[Link]
package student;
import [Link];

public class calculate {


private int m1, m2, m3;

public calculate(int m1, int m2, int m3) {


this.m1 = m1; this.m2 = m2; this.m3 = m3;
}

// Returns total; called from main()


public int calculate_marks() { return m1 + m2 + m3; }

public double getAverage() { return calculate_marks() / 3.0; }

public static void main(String[] args) {


calculate c = new calculate(85, 90, 78);
[Link]("Total : " + c.calculate_marks());
[Link] ("Average : %.2f%n", [Link]());
}
}

// File 2: [Link] (uses student package — another program)


import [Link];
import [Link];

public class calculate1 {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter 3 subject marks:");
int a = [Link](), b = [Link](), c = [Link]();
calculate obj = new calculate(a, b, c);
[Link]("Total : " + obj.calculate_marks());
[Link] ("Average : %.2f%n", [Link]());
[Link]();
}
}

▸ 19.3 — Fully qualified name to resolve [Link] vs [Link] conflict


import [Link]; // import [Link] — use as 'Date'
// Cannot also import [Link] — NAME CONFLICT

public class FullyQualifiedDemo {


public static void main(String[] args) {
// Using imported short name
Date utilDate = new Date();
[Link]("[Link] : " + utilDate);

// Using FULLY QUALIFIED NAME to avoid conflict (advantage!)


[Link] sqlDate = new [Link]([Link]());
[Link]("[Link] : " + sqlDate);

// Advantage: no ambiguity even when two packages share same class name
[Link]("FQN avoids conflict when 2 packages have same class name.");
}
}
20. Array of Objects — UML Concept, Create, Input, Sort (from
ARRAY_OF_OBJECTS.docx + UML_Class_diagram_.pptx)
▸ 20.1 — Array of Student objects with Scanner (from ARRAY_OF_OBJECTS.docx)
import [Link];

class Student {
String name;
int rollNo;
double marks;

// Default constructor (from ARRAY_OF_OBJECTS.docx)


Student() { [Link]("This is the default constructor"); }

// Parameterized constructor (from ARRAY_OF_OBJECTS.docx)


Student(String n, int r, double m) { name=n; rollNo=r; marks=m; }

void display() {
[Link]("Roll:%-4d Name:%-15s Marks:%.1f Grade:%s%n",
rollNo, name, marks, getGrade());
}

String getGrade() {
if (marks>=90) return "S"; if (marks>=75) return "A";
if (marks>=60) return "B"; if (marks>=50) return "C";
return "F";
}
}

public class ArrayOfStudents {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("How many students? ");
int n = [Link]();

// STEP 1: Create array — n REFERENCE SLOTS (all null initially)


Student[] students = new Student[n];

// STEP 2: Create ACTUAL OBJECT for each slot


for (int i = 0; i < n; i++) {
[Link]("-- Student " + (i+1) + " --");
[Link]("Name: "); String name = [Link]();
[Link]("Roll: "); int roll = [Link]();
[Link]("Marks: "); double marks = [Link]();
students[i] = new Student(name, roll, marks); // actual object in Heap
}

[Link]("
===== STUDENT REPORT =====");
for (Student s : students) [Link]();

// Find topper
Student topper = students[0];
for (Student s : students) if ([Link] > [Link]) topper = s;
[Link]("
Topper: " + [Link] + " (" + [Link] + ")");
}
}
// UML representation of Student class:
// +---------------------------+
// | Student | (class name)
// +---------------------------+
// | - rollNo : int | (private fields)
// | - name : String |
// | - marks : double |
// +---------------------------+
// | + display() : void | (public methods)
// | + getGrade() : String |
// +---------------------------+

21. String Programs — Methods, Immutability, Common Problems (from


String_in_Java_Complete_Notes.docx)
▸ 21.1 — All important String methods + immutability demo
public class StringMethods {
public static void main(String[] args) {
String s = "Hello World";

[Link]("length() : " + [Link]()); // 11


[Link]("toUpperCase() : " + [Link]()); // HELLO WORLD
[Link]("toLowerCase() : " + [Link]()); // hello world
[Link]("charAt(4) : " + [Link](4)); // o
[Link]("indexOf('o') : " + [Link]('o')); // 4
[Link]("substring(6) : " + [Link](6)); // World
[Link]("substring(0,5) : " + [Link](0, 5)); // Hello
[Link]("equals : " + [Link]("Hello World")); // true
[Link]("equalsIgnCase : " + [Link]("hello world")); // true
[Link]("replace : " + [Link]('l','r')); // Herro Worrd
[Link]("replace(str) : " + [Link]("World","Java")); // Hello Java
[Link]("contains : " + [Link]("World")); // true
[Link]("startsWith : " + [Link]("Hello")); // true
[Link]("trim : " + " spaces ".trim()); // spaces
[Link]("compareTo : " + "apple".compareTo("banana")); // negative

// String is IMMUTABLE — methods return NEW string objects


String orig = "Java";
String upper = [Link](); // new object
[Link]("orig =" + orig); // Java (unchanged)
[Link]("upper=" + upper); // JAVA (new object)

// String constant pool


String s1 = "Hello"; // pool
String s2 = "Hello"; // reuses pool object
String s3 = new String("Hello"); // new Heap object
[Link](s1 == s2); // true
[Link](s1 == s3); // false
[Link]([Link](s3)); // true
}
}

▸ 21.2 — Reverse string (from String_in_Java_Complete_Notes.docx) + palindrome + vowel count


public class StringPrograms {

// Reverse (from String_in_Java_Complete_Notes.docx)


static String reverse(String s) {
String rev = "";
for (int i = [Link]() - 1; i >= 0; i--)
rev += [Link](i);
return rev;
}

// Palindrome check
static boolean isPalindrome(String s) {
String clean = [Link]().replaceAll("[^a-z0-9]","");
return [Link](reverse(clean));
}

// Count vowels
static int countVowels(String s) {
int count = 0;
for (char c : [Link]().toCharArray())
if ("aeiou".indexOf(c) >= 0) count++;
return count;
}

public static void main(String[] args) {


[Link]("reverse('Java') = " + reverse("Java")); // avaJ
[Link]("reverse('racecar') = " + reverse("racecar")); // racecar
[Link]("palindrome('level') : " + isPalindrome("level")); // true
[Link]("palindrome('hello') : " + isPalindrome("hello")); // false
[Link]("palindrome('A man a plan a canal Panama'): "
+ isPalindrome("A man a plan a canal Panama")); // true
[Link]("vowels in 'Hello World': " + countVowels("Hello World")); // 3

// StringBuilder — MUTABLE, efficient for repeated concatenation


StringBuilder sb = new StringBuilder("Hello");
[Link](" World");
[Link](5, ",");
[Link]("StringBuilder: " + sb); // Hello, World
[Link]();
[Link]("Reversed: " + sb); // dlroW ,olleH
}
}
22. Exam-Style Programs — NUMBER+GENERATOR, Full OOP Design, Lab &
Assignment Programs
▸ 22.1 — NUMBER class + GENERATOR interface (Exam Q4 exact type)
import [Link];

class NUMBER {
int n;
NUMBER() { n = 0; }
NUMBER(int n) { this.n = n; }
void inputN() { Scanner sc = new Scanner([Link]); [Link]("n: ");
n=[Link](); }
}

interface GENERATOR {
void Number_generator();
void displayMI();
}

class MINumber_Generator extends NUMBER implements GENERATOR {


int MINumber;

MINumber_Generator(int n) { super(n); }

@Override
public void Number_generator() {
Scanner sc = new Scanner([Link]);
[Link]("Enter x: "); int x = [Link]();
// n odd → MINumber = n * 100 + x
// n even → MINumber = n * 200 + x
if (n % 2 != 0) MINumber = n * 100 + x;
else MINumber = n * 200 + x;
}

@Override
public void displayMI() {
[Link]("n = " + n + " (" + (n%2==0?"even":"odd") + ")");
[Link]("MINumber = " + MINumber);
// Example: n=7(odd), x=5 → MINumber = 700+5 = 705
// Example: n=4(even), x=3 → MINumber = 800+3 = 803
}
}

public class MIDemo {


public static void main(String[] args) {
MINumber_Generator obj1 = new MINumber_Generator(7); // odd
obj1.Number_generator();
[Link]();
[Link]();
MINumber_Generator obj2 = new MINumber_Generator(4); // even
obj2.Number_generator();
[Link]();
}
}

▸ 22.2 — Full OOP: abstract Person + FullTime/PartTime Employee + Payable interface


interface Payable {
double calculatePay();
void printPaySlip();
}

abstract class Person {


private String name; private int id;
Person(int id, String name) { [Link]=id; [Link]=name; }
public String getName() { return name; }
public int getId() { return id; }
abstract String getRole();
void printBasicInfo() {
[Link]("ID:"+id+" | Name:"+name+" | Role:"+getRole());
}
}

class FullTimeEmployee extends Person implements Payable {


private double monthlySalary;
FullTimeEmployee(int id, String name, double s) { super(id,name); monthlySalary=s; }
@Override public String getRole() { return "Full-Time"; }
@Override public double calculatePay() { return monthlySalary; }
@Override public void printPaySlip() {
printBasicInfo();
[Link](" Monthly:Rs.%.0f Annual:Rs.%.0f%n", calculatePay(),
calculatePay()*12);
}
}

class PartTimeEmployee extends Person implements Payable {


private int hoursWorked; private double hourlyRate;
PartTimeEmployee(int id, String name, int h, double r) {
super(id,name); hoursWorked=h; hourlyRate=r;
}
@Override public String getRole() { return "Part-Time"; }
@Override public double calculatePay() { return hoursWorked * hourlyRate; }
@Override public void printPaySlip() {
printBasicInfo();
[Link](" %dhrs x Rs.%.0f = Rs.%.0f%n", hoursWorked, hourlyRate,
calculatePay());
}
}

public class CompanyPayroll {


public static void main(String[] args) {
Payable[] staff = {
new FullTimeEmployee(101, "Alice", 50000),
new PartTimeEmployee(102, "Bob", 80, 200),
new FullTimeEmployee(103, "Charlie", 65000)
};
double total = 0;
[Link]("===== PAYROLL REPORT =====");
for (Payable p : staff) { [Link](); total += [Link]();
[Link]("---"); }
[Link]("Total Monthly Payroll: Rs.%.0f%n", total);
}
}

▸ 22.3 — Lab 1 programs (from OOPs_Lab_1.docx): Hello World, Add/Multiply, Average, Celsius to
Fahrenheit
import [Link];

// Lab Program 1: Hello World


public class DemoClass {
public static void main(String args[]) {
[Link]("Welcome to OOPs programming");
}
}

// Lab Program 2: Add and Multiply two numbers


class AddMul {
public static void main(String args[]) {
int a1 = 12, a2 = 14;
int add = a1 + a2; // addition
int prod = a1 * a2; // multiplication
[Link]("Sum = " + add);
[Link]("Product = " + prod);
}
}

// Lab Program 3: Compute average of two numbers from user


class ComputeAv {
public static void main(String args[]) {
Scanner scnr = new Scanner([Link]);
[Link]("Input the First Number: ");
double a1 = [Link]();
[Link]("Input the Second Number: ");
double b1 = [Link]();
double sum1 = a1 + b1;
double avg1 = sum1 / 2;
[Link]("Average = " + avg1);
}
}

// Lab Program 4: Celsius to Fahrenheit — F = ((C/5)*9)+32


class FahrenheitCelsius {
public static void main(String args[]) {
Scanner scnr = new Scanner([Link]);
[Link]("Input the temperature in Celsius: ");
double cel = [Link]();
double far = ((cel / 5.0) * 9.0) + 32;
[Link]("Temperature in Fahrenheit is: " + far);
}
}

END OF CODE BOOK | 22AIE111 JAVA OOP | ALL UNIT 1 & UNIT 2 TOPICS COVERED

You might also like