0% found this document useful (0 votes)
3 views8 pages

Java Exam Notes-V2

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)
3 views8 pages

Java Exam Notes-V2

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 COMPREHENSIVE EXAM NOTES

1. Introduction to Packages in Java

A package in Java is a namespace that organizes a set of related classes and interfaces.
Conceptually, you can think of packages as folders in a file directory. They are primarily used to
prevent naming conflicts, provide controlled access (encapsulation), and make searching/locating
classes easier.

Conceptual Architecture & Built-in Packages

STRUCTURE HIERARCHY: COMMON BUILT-IN JAVA PACKAGES:


[ PACKAGE ] [ JAVA ]
| |
+-- [ CLASS ] +-- [Link] (Core classes)
| +-- [Link] (Utility & Collections)
+-- [ METHOD 1 ] +-- [Link] (Input/Output)
+-- [ METHOD 2 ] +-- [Link] (Abstract Window Toolkit)
+-- [ METHOD 3 ] +-- [Link] (Networking)
+-- [Link](Applet creation)

Steps to Create and Use a Custom Package

To successfully build a custom package and execute it via a main program, follow these 6 precise
steps from creation to execution:

1. Declare the Package: In your source code file, use the package keyword at the very top (e.g.,
package mypack;) to define the package namespace.

2. Create a Public Class & Method: Write your class and method, ensuring both are declared
as public so they are visible and accessible outside the package directory.

3. Save in a Matching Folder: Save this `.java` file inside a sub-folder that exactly matches the
package name (e.g., save inside a folder named mypack). Compile the file using javac.

4. Import into Main File: Create a separate [Link] file outside the package folder. Use the
import statement (e.g., import mypack.*;) at the top of this file to link your custom
package.
5. Instantiate the Object: Inside the public static void main method of your Main class,
allocate memory by creating an object of your imported class using the new keyword (e.g.,
MyClass obj = new MyClass();).

6. Call the Method: Finally, use the object reference variable alongside the dot (.) operator to
execute the specific method (e.g., [Link]();) and run your program.

2. Custom Package Programs

Program 1: The Calculator Program

// calculator/[Link] // calculator/ // calculator/


package calculator; // [Link] [Link]
Step 1 package calculator; package calculator;
public class Adder { // public class Subtractor { public class Multiplier {
Step 2 public int sub(int a, public int mul(int a,
public int add(int a, int b) { int b) {
int b) { return a - b; return a * b;
return a + b; } }
} } }
}

Main Execution

// File: [Link]
import calculator.*; // Step 4

public class CalculatorMain {


public static void main(String[] args) {
Adder a = new Adder(); // Step 5
[Link]("Add: " + [Link](20, 10)); // Step 6

Subtractor s = new Subtractor();


[Link]("Sub: " + [Link](20, 10));
}
}
Program 2: The Geometry Program

// geometry/[Link] // geometry/ // geometry/[Link]


package geometry; [Link] package geometry;
public class Circle { package geometry; public class Square {
public double public class Rectangle { public double
area(double r) { public double area(double s) {
return [Link] * r * area(double l, double w) return s * s;
r; { }
} return l * w; }
} }
}

Main Execution

// File: [Link]
import geometry.*;

public class GeometryMain {


public static void main(String[] args) {
Circle c = new Circle();
[Link]("Circle Area: " + [Link](5.0));

Rectangle r = new Rectangle();


[Link]("Rectangle Area: " + [Link](4.0, 5.0));
}
}
Program 3: The Student Info Program

// student/[Link] // student/[Link] // student/


package student; package student; [Link]
public class Semester { public class Email { package student;
public void show(int public void show(String public class RollNumber {
sem) { mail) { public void show(String
roll) {
[Link]("Sem: [Link]("Email:
" + sem); " + mail); [Link]("Roll:
} } " + roll);
} } }
}

Main Execution

// File: [Link]
import student.*;

public class StudentMain {


public static void main(String[] args) {
Semester sem = new Semester();
[Link](2);

RollNumber roll = new RollNumber();


[Link]("CS-2024-001");
}
}

3. Inheritance in Java

Inheritance is a core Object-Oriented Programming feature where a new class (subclass/child)


acquires the properties and methods of an existing class (superclass/parent). This promotes code
reusability and runtime polymorphism.
Diagram: All Types of Inheritance

1. SINGLE 2. MULTILEVEL 3. HIERARCHICAL 4. MULTIPLE 5. HYBRID


[A] [A] [A] [A] [B] [A]
| | / \ \ / / \
[B] [B] [B] [C] [C] [B] [C]
| \ /
[C] [D]
(Supported) (Supported) (Supported) (Unsupported) (Unsupported)

3.1 Single Inheritance (Supported)

Definition: When a single subclass inherits from exactly one superclass. It is a straightforward,
one-to-one parent-child relationship.

class Animal { void eat() { [Link]("Eating..."); } }


class Dog extends Animal { void bark() { [Link]("Barking..."); } }

public class SingleTest {


public static void main(String[] args) {
Dog d = new Dog(); [Link](); [Link]();
}
}

3.2 Multilevel Inheritance (Supported)

Definition: When a derived class becomes the base class for another derived class, forming a
chain of inheritance.

class Animal { void eat() { [Link]("Eating..."); } }


class Dog extends Animal { void bark() { [Link]("Barking..."); } }
class BabyDog extends Dog { void weep() { [Link]("Weeping..."); } }

public class MultiTest {


public static void main(String[] args) {
BabyDog d = new BabyDog(); [Link](); [Link](); [Link]();
}
}

3.3 Hierarchical Inheritance (Supported)

Definition: When two or more subclasses inherit from the exact same single superclass.
class Animal { void eat() { [Link]("Eating..."); } }
class Dog extends Animal { void bark() { [Link]("Barking..."); } }
class Cat extends Animal { void meow() { [Link]("Meowing..."); } }

public class HierarchicalTest {


public static void main(String[] args) {
Cat c = new Cat(); [Link](); [Link]();
}
}

⚠️ Unsupported Inheritance in Java Classes

Java absolutely does not support Multiple and Hybrid inheritance using classes. This design
choice prevents catastrophic ambiguity known as the Diamond Problem. Note: You can
achieve multiple inheritance safely by using Interfaces.

3.4 Multiple Inheritance (Unsupported)

Definition: When one subclass tries to extend more than one superclass simultaneously.

Why it is not used: If Class C inherits from Class A and Class B, and both parents contain a
method with the exact same name, the Java compiler gets confused about which parent's method
to execute. To avoid this chaos, it throws a compile-time error.

3.5 Hybrid Inheritance (Unsupported)

Definition: A combination of two or more types of inheritance (for example, combining


Hierarchical and Multiple inheritance).

Why it is not used: Since Hybrid inheritance relies on Multiple inheritance to form its structure,
it inherently brings back the exact same ambiguity (the Diamond Problem). Therefore, it is also
blocked by the compiler.

4. Exception Handling in Java

What is Exception Handling? Exception Handling is a mechanism used to manage runtime


errors, ensuring that the normal flow of the application is maintained. It prevents the program
from crashing abruptly when unexpected events occur.
4.1 How We Handle Exceptions

We handle exceptions locally using three primary blocks of code:

• try: The block of code where you place statements that might potentially throw an error.

• catch: The block that intercepts and handles the specific exception thrown by the try block.

• finally: A block that will execute unconditionally, regardless of whether an exception


occurred or not. Primarily used to safely close resources.

public class ExceptionDemo {


public static void main(String[] args) {
try {
int data = 100 / 0; // Might throw ArithmeticException
} catch (ArithmeticException e) {
[Link]("Caught an error: Cannot divide by zero.");
} finally {
[Link]("Finally block always executes.");
}
}
}

4.2 Types of Common Exceptions

1. ArithmeticException

When to use / Why it occurs: Thrown when an exceptional arithmetic condition occurs in your
logic, such as attempting to divide a number by zero.

try { int result = 50 / 0; }


catch (ArithmeticException e) { [Link]("Error: " + [Link]()); }

2. NullPointerException (NPE)

When to use / Why it occurs: Occurs when your application attempts to use or access an object
reference that has not been initialized (i.e., it points to null).

try { String text = null; [Link]([Link]()); }


catch (NullPointerException e) { [Link]("Error: Object is null."); }

3. ArrayIndexOutOfBoundsException

When to use / Why it occurs: Triggered when a program attempts to access an array using an
index that is either negative or greater than/equal to the array's size.
try { int[] numbers = {1, 2, 3}; [Link](numbers[5]); }
catch (ArrayIndexOutOfBoundsException e) { [Link]("Error: Invalid index."); }

5. Method Overloading in Java

Method Overloading is a compile-time polymorphism feature where a single class can have
multiple methods sharing the exact same name, provided their parameter lists are distinctly
different. This enhances program readability by allowing conceptually identical operations to be
grouped under a unified method name.

Main Features and Rules of Overloading:

1. Number of Parameters: Overloaded if they accept a different number of arguments.

2. Data Type of Parameters: Overloaded if the types of their arguments differ.

3. Sequence of Parameters: Overloaded if the order of different data types is rearranged.

public class MathOperations {

// Feature 1: Changing number of parameters


public int multiply(int a, int b) { return a * b; }
public int multiply(int a, int b, int c) { return a * b * c; }

// Feature 2: Changing data types of parameters


public double multiply(double a, double b) { return a * b; }

public static void main(String[] args) {


MathOperations op = new MathOperations();
[Link]("2 params (int): " + [Link](5, 4));
[Link]("3 params (int): " + [Link](5, 4, 2));
[Link]("2 params (double): " + [Link](2.5, 3.0));
}
}

You might also like