0% found this document useful (0 votes)
2 views13 pages

Java Complete Exam Notes

Uploaded by

Avik Chowdhury
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)
2 views13 pages

Java Complete Exam Notes

Uploaded by

Avik Chowdhury
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 COMPLETE

EXAM NOTES

Custom Packages · Inheritance · Exception Handling


Method Overloading · Java Features

PART 1: CUSTOM PACKAGES (Multiple Classes, One Method Each)


Package Structure: Each class has ONE method. [Link] uses wildcard import (import mypackage.*;) to access all classes.

PROGRAM 1: Calculator
// mypackage/[Link]
package mypackage;
public class Addition {
public double add(double a, double b) { return a + b; }
}

// mypackage/[Link]
package mypackage;
public class Subtraction {
public double subtract(double a, double b) { return a - b; }
}

// mypackage/[Link]
package mypackage;
public class Multiplication {
public double multiply(double a, double b) { return a * b; }
}

// mypackage/[Link]
package mypackage;
public class Division {
public double divide(double a, double b) {
if (b == 0) { [Link]("Error!"); return 0; }
return a / b;
}
}

// [Link] (outside mypackage folder)


import mypackage.*;
public class Main {
public static void main(String[] args) {
double a = 20, b = 4;
Addition add = new Addition();
Subtraction sub = new Subtraction();
Multiplication mul = new Multiplication();
Division div = new Division();
[Link]("Add: " + [Link](a,b));
[Link]("Sub: " + [Link](a,b));
[Link]("Mul: " + [Link](a,b));
[Link]("Div: " + [Link](a,b));
}
}

Compile & Run: javac mypackage/*.java && javac [Link] && java Main
PROGRAM 2: Geometry
// mypackage/[Link]
package mypackage;
public class CircleArea {
public double getArea(double r) { return [Link] * r * r; }
}

// mypackage/[Link]
package mypackage;
public class SquareArea {
public double getArea(double side) { return side * side; }
}

// mypackage/[Link]
package mypackage;
public class RectangleArea {
public double getArea(double l, double w) { return l * w; }
}

// [Link] (outside mypackage folder)


import mypackage.*;
public class Main {
public static void main(String[] args) {
CircleArea c = new CircleArea();
SquareArea s = new SquareArea();
RectangleArea r = new RectangleArea();
[Link]("Circle (r=7): " + [Link](7));
[Link]("Square (s=5): " + [Link](5));
[Link]("Rectangle (10x4): " + [Link](10, 4));
}
}

PROGRAM 3: Student Semester


// mypackage/[Link]
package mypackage;
public class Semester1 {
public double calc(double m, double e, double s, double c, double h) {
return (m + e + s + c + h) / 5.0;
}
}

// mypackage/[Link]
package mypackage;
public class Semester2 {
public double calc(double p, double c, double b, double pr, double m) {
return (p + c + b + pr + m) / 5.0;
}
}

// mypackage/[Link]
package mypackage;
public class GradeCalc {
public String getGrade(double avg) {
if(avg >= 90) return "A+";
if(avg >= 80) return "A";
if(avg >= 70) return "B+";
if(avg >= 60) return "B";
if(avg >= 50) return "C";
return "F";
}
}
// [Link]
import mypackage.*;
public class Main {
public static void main(String[] args) {
Semester1 s1 = new Semester1();
Semester2 s2 = new Semester2();
GradeCalc gc = new GradeCalc();
double avg1 = [Link](85, 78, 90, 88, 72);
double avg2 = [Link](76, 82, 79, 95, 88);
[Link]("Sem1 Avg: " + avg1 + " Grade: " + [Link](avg1));
[Link]("Sem2 Avg: " + avg2 + " Grade: " + [Link](avg2));
}
}
PART 2: INHERITANCE IN JAVA

What is Inheritance?
Inheritance is a mechanism in Java where a child class (subclass) inherits properties and methods from a parent
class (superclass). It allows code reuse and establishes a relationship between classes. The child class can
override parent methods or add new ones. Inheritance is achieved using the extends keyword.

Types of Inheritance
Type Description

Single One child class extends one parent class

Multilevel Child inherits from parent, which inherits from grandparent (A→B→C)

Hierarchical Multiple child classes extend one parent class

Multiple NOT SUPPORTED - one class extends 2+ classes (use interfaces instead)

Hybrid Combination of multiple types (NOT SUPPORTED in same way)

SINGLE INHERITANCE (Supported)


Single Inheritance: One child class extends only ONE parent class. This is the simplest form. Example: Animal
(parent) ← Dog (child). The child inherits all non-private members of parent.

Example Program:
// Parent class
class Animal {
void eat() {
[Link]("Animal is eating");
}
}

// Child class extends parent


class Dog extends Animal {
void bark() {
[Link]("Dog is barking");
}
}

// Main
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link](); // Inherited from Animal
[Link](); // Own method
}
}

Output: Animal is eating | Dog is barking

MULTILEVEL INHERITANCE (Supported)


Multilevel Inheritance: A chain of inheritance where Child extends Parent, and Parent extends GrandParent
(A→B→C). Each class inherits from the one above it. The bottom class gets properties from all classes above it.

Example Program:
class Animal { // Level 1
void eat() { [Link]("Eating"); }
}

class Mammal extends Animal { // Level 2


void sleep() { [Link]("Sleeping"); }
}

class Dog extends Mammal { // Level 3


void bark() { [Link]("Barking"); }
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
[Link](); // From Animal
[Link](); // From Mammal
[Link](); // Own method
}
}

Hierarchy: Animal → Mammal → Dog


Why MULTIPLE & HYBRID Inheritance NOT Supported

MULTIPLE INHERITANCE (NOT Supported in Java)


Multiple Inheritance: One class extends TWO or more parent classes. Java DOES NOT support this because of
the Diamond Problem. If ClassC extends both ClassA and ClassB, and both have same method, which one will
ClassC inherit? This ambiguity is avoided by not supporting it.

Why NOT Supported? – Diamond Problem:


// A
// / \
// B C
// \ /
// D

class A {
void display() { [Link]("A"); }
}

class B extends A {
void display() { [Link]("B"); }
}

class C extends A {
void display() { [Link]("C"); }
}

// ERROR: class D extends B, C { // NOT ALLOWED!


// Which display() to use - from B or C?
// }

Solution: Use INTERFACES instead. Java allows implementing multiple interfaces because interfaces don't have conflicting
implementations.

Solution Using Interfaces:


interface A { void display(); }
interface B { void show(); }

class C implements A, B { // ALLOWED!


public void display() { [Link]("A"); }
public void show() { [Link]("B"); }
}

public class Main {


public static void main(String[] args) {
C obj = new C();
[Link](); // A
[Link](); // B
}
}

HYBRID INHERITANCE (NOT Supported)


Hybrid Inheritance: A combination of multiple and multilevel inheritance. For example, if you have classes A, B, C
extending A, and D extending both B and C. Since multiple inheritance isn't supported, hybrid isn't either. Use
interfaces to achieve similar effects.

Example of Hybrid Problem:


// A
// / \
// B C
// | |
// E F
// \ /
// D <- Trying to extend both E and F

// class D extends E, F { } // NOT ALLOWED!

// Solution: Use interfaces


interface E { }
interface F { }
class D implements E, F { } // ALLOWED!
PART 3: EXCEPTION HANDLING IN JAVA

What is Exception?
Exception: An unexpected event or error that occurs during program execution. It disrupts the normal flow of the
program. Exceptions are objects that represent an error. Java provides mechanisms to catch and handle
exceptions gracefully using try-catch-finally blocks.

Try-Catch-Finally Syntax:
try {
// Code that may throw an exception
int result = 10 / 0; // ArithmeticException
}
catch (ArithmeticException e) {
// Handle the exception
[Link]("Cannot divide by zero: " + e);
}
catch (Exception e) { // Catch all other exceptions
[Link]("Error occurred: " + e);
}
finally {
// Executes always (even if exception or not)
[Link]("Finally block always runs");
}

Try-Catch-Finally Definition:
try: Contains code that might throw an exception. catch: Catches the exception if it occurs and handles it. Multiple
catches allowed. finally: Executes always, whether exception happens or not. Used for cleanup (close files, DB
connections).

Example Programs:
Example 1: ArithmeticException
public class Main {
public static void main(String[] args) {
try {
int a = 10, b = 0;
int c = a / b; // Exception here!
}
catch (ArithmeticException e) {
[Link]("Error: " + e);
}
finally {
[Link]("Calculation done");
}
}
}

Output: Error: / by zero | Calculation done

Example 2: ArrayIndexOutOfBoundsException
public class Main {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3};
[Link](arr[5]); // Index 5 doesn't exist!
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Error: Index out of bounds");
}
finally {
[Link]("Array access done");
}
}
}

Output: Error: Index out of bounds | Array access done

Common Exception Types:


1. ArithmeticException
Occurs when dividing by zero or invalid arithmetic operation. Example: int x = 10 / 0; throws ArithmeticException.
Can be caught and handled to prevent program crash.

try { int x = 10 / 0; }
catch (ArithmeticException e) { [Link]("Division by zero!"); }

2. ArrayIndexOutOfBoundsException
Thrown when accessing array element beyond its size. Array indices start from 0. If array has 5 elements, valid
indices are 0-4. Accessing index 5 or higher causes this exception.

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


try { [Link](arr[5]); }
catch (ArrayIndexOutOfBoundsException e) { [Link]("Invalid index!"); }

3. NullPointerException
Occurs when trying to access methods/properties of null object. If a variable is null (not initialized), calling methods
on it throws this error. Check if object is not null before using it.

String str = null;


try { [Link]([Link]()); }
catch (NullPointerException e) { [Link]("Object is null!"); }

4. NumberFormatException
Thrown when converting invalid string to number. Example: [Link]("abc") fails because "abc" is not a
valid integer. Always validate string before converting to numeric types.

try { int x = [Link]("abc"); }


catch (NumberFormatException e) { [Link]("Invalid number format!"); }

5. StringIndexOutOfBoundsException
Occurs when accessing character at invalid position in string. String indices start from 0 to length-1. Accessing
beyond this range throws this exception.

try { String s = "Java"; [Link]([Link](10)); }


catch (StringIndexOutOfBoundsException e) { [Link]("Invalid position!"); }

6. FileNotFoundException
Thrown when trying to open a file that doesn't exist. Check if file exists before opening it. Used in file I/O
operations.
import [Link].*;
try { FileInputStream f = new FileInputStream("[Link]"); }
catch (FileNotFoundException e) { [Link]("File not found!"); }
PART 4: METHOD OVERLOADING

What is Method Overloading?


Method Overloading: Creating multiple methods with SAME name but DIFFERENT parameters in the SAME
class. Methods must differ in: (1) Number of parameters, (2) Type of parameters, (3) Order of parameters. Return
type alone is NOT enough. Compiler decides which method to call based on arguments.

Method Overloading Example:


class Calculator {
// Overloading 1: Different number of parameters
public int add(int a, int b) {
return a + b;
}

public int add(int a, int b, int c) {


return a + b + c;
}

// Overloading 2: Different type of parameters


public double add(double a, double b) {
return a + b;
}

// Overloading 3: Different order of parameters


public void display(String s, int n) {
[Link](s + " " + n);
}

public void display(int n, String s) {


[Link](n + " " + s);
}
}

Using the Overloaded Methods:


public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
[Link]([Link](10, 20)); // Calls 1st add
[Link]([Link](10, 20, 30)); // Calls 2nd add
[Link]([Link](10.5, 20.5)); // Calls 3rd add
[Link]("Age", 25); // Calls 1st display
[Link](25, "Age"); // Calls 2nd display
}
}

Output: 30 | 60 | 31.0 | Age 25 | 25 Age

Overloading Rules:
Rule Details

Same Name All methods must have identical names

Different Parameters Must differ in number, type, or order of parameters

Return Type Return type is NOT considered (can be same or different)

Must Be in Same Class Overloading is class-specific

Compiler Resolution Compiler chooses method based on arguments AT COMPILE TIME


PART 5: MAIN FEATURES OF JAVA

1. SIMPLE & EASY TO LEARN


Java syntax is similar to C/C++ but simpler. No need for manual memory management (automatic garbage
collection). Code is easy to read, write, and maintain.

2. PLATFORM INDEPENDENT (Write Once, Run Anywhere)


Java code is compiled to bytecode (.class files). Bytecode runs on any JVM (Java Virtual Machine) without
recompilation. Same code works on Windows, Linux, Mac, etc.

3. OBJECT-ORIENTED
Everything in Java is an object except primitive data types. Supports encapsulation, inheritance, polymorphism,
and abstraction. Makes code reusable and organized.

4. ROBUST & SECURE


Strong memory management and exception handling prevent crashes. Bytecode verification ensures no unsafe
code runs. Built-in security features prevent unauthorized access.

5. MULTITHREADING
Supports concurrent execution of multiple threads. Allows multiple tasks to run simultaneously in one program.
Improves performance and responsiveness.

PARAMETERS IN JAVA
Parameter Type Description

Primitive Parameters Passed by value (int, double, boolean, etc.) - original not affected

Object Parameters Passed by reference - changes affect original object

Variable Length (...) int... arr allows passing any number of int values

Reference Type Objects passed as references, modifications reflected in original

Parameter Passing Examples:


// Primitive (Pass by Value)
void change(int x) { x = 100; }
int a = 5;
change(a);
[Link](a); // Still 5, not 100

// Object (Pass by Reference)


void change(StringBuilder sb) { [Link]("Java"); }
StringBuilder str = new StringBuilder("Hello");
change(str);
[Link](str); // HelloJava (changed!)

// Variable Length
void print(int... numbers) {
for(int n : numbers) [Link](n);
}
print(1, 2, 3, 4, 5); // Can pass any number of args

Quick Reference — Comparison


Feature Details

Bytecode Intermediate code between source & machine code

JVM Java Virtual Machine - executes bytecode

Garbage Collection Automatic memory cleanup

Access Modifiers public, private, protected, default

Packages Used for organizing classes (import package.*)

Exceptions Handled with try-catch-finally blocks

Inheritance Single, Multilevel, Hierarchical (NO Multiple/Hybrid)

You might also like