KEMBAR78
Java Unit 1 15marks | PDF | Inheritance (Object Oriented Programming) | Class (Computer Programming)
0% found this document useful (0 votes)
9 views31 pages

Java Unit 1 15marks

The document explains Java packages, their benefits, and the Java API package, highlighting that packages organize related classes and avoid name conflicts. It also covers threads in Java, including how to create them and a sample program that prints even and odd numbers. Additionally, it discusses inheritance, object-oriented programming features, exception handling, and thread priority with relevant examples.
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)
9 views31 pages

Java Unit 1 15marks

The document explains Java packages, their benefits, and the Java API package, highlighting that packages organize related classes and avoid name conflicts. It also covers threads in Java, including how to create them and a sample program that prints even and odd numbers. Additionally, it discusses inheritance, object-oriented programming features, exception handling, and thread priority with relevant examples.
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
You are on page 1/ 31

15 MARKS QUESTIONS

1 What are packages? What are the benefits of packages? Explain Java API package. List out of any five
methods of string class by giving an example.

Sure! Here's an easy and clear explanation for your exam:

What are Packages in Java?


In Java, a package is like a folder that groups related classes and interfaces together.
It helps organize the code neatly and avoid name conflicts.
There are two types of packages:
1. Built-in Packages (like java.util, java.io)
2. User-defined Packages (created by the programmer)

Benefits of Packages:
1. ✅ Organizes Code: Makes the code easy to manage.
2. ✅ Avoids Name Conflicts: Same class names can be used in different packages.
3. ✅ Reusability: Classes in packages can be reused in other programs.
4. ✅ Access Control: Packages help to protect classes using access modifiers.
5. ✅ Easy Maintenance: Code is easier to maintain and debug.

Java API Package:


Java API (Application Programming Interface) is a large collection of predefined classes and methods that come
with Java.
They are organized in packages like:
 java.lang – basic classes (like String, Math, Object)
 java.util – utility classes (like ArrayList, Scanner)
 java.io – input/output classes
 java.net – networking classes
Example:
To use Scanner class from java.util package:
import java.util.Scanner;

5 Methods of String Class with Examples:


1. length() – returns the number of characters in the string
2. String name = "Java";
3. System.out.println(name.length()); // Output: 4
4. toUpperCase() – converts all characters to uppercase
5. String word = "hello";
6. System.out.println(word.toUpperCase()); // Output: HELLO
7. toLowerCase() – converts all characters to lowercase
8. String word = "HELLO";
9. System.out.println(word.toLowerCase()); // Output: hello
10. charAt(int index) – returns the character at the given index
11. String name = "Java";
12. System.out.println(name.charAt(1)); // Output: a
13. substring(int start, int end) – returns a part (substring) of the string
14. String name = "Programming";
15. System.out.println(name.substring(0, 4)); // Output: Prog

2 Define thread. How to create a thread in Java? Write a program that execute two threads. One thread
will print the even numbers and another thread will print odd numbers from 1 to 5.

Sure! Here's a simple and easy-to-understand explanation and example for your exam:
What is a Thread in Java?
A thread is a lightweight process.
It is used to perform multiple tasks at the same time (called multithreading).
In Java, a thread allows a program to do two or more things at once, like printing even and odd numbers
together.

How to Create a Thread in Java?


There are two main ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface

✅ Simple Program Using Threads to Print Even and Odd Numbers (1 to 5):
// Thread to print even numbers
class EvenThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
if (i % 2 == 0) {
System.out.println("Even: " + i);
}
}
}
}

// Thread to print odd numbers


class OddThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
if (i % 2 != 0) {
System.out.println("Odd: " + i);
}
}
}
}

// Main class
public class NumberThreads {
public static void main(String[] args) {
EvenThread even = new EvenThread(); // create even thread
OddThread odd = new OddThread(); // create odd thread

even.start(); // start even thread


odd.start(); // start odd thread
}
}

🔎 Explanation:
 We created two classes: EvenThread and OddThread, both extend the Thread class.
 Each class overrides the run() method to print either even or odd numbers from 1 to 5.
 In main(), we created objects of both threads and started them using .start().
This program may print numbers in different order each time (because threads run independently).

3 What are packages in Java? How a user defined package is created in Java, explain with example.

Sure! Here's a simple and exam-friendly explanation of packages in Java and how to create a user-defined
package, with example.
✅ What are Packages in Java?
In Java, a package is like a folder that stores related classes and interfaces together.
It helps to:
 Organize code better
 Avoid class name conflicts
 Reuse code easily

📦 Types of Packages:
1. Built-in Packages – Already available in Java (Example: java.util, java.io, java.lang)
2. User-defined Packages – Created by the programmer

✅ How to Create a User-Defined Package in Java?


💡 Steps:
1. Create a package using the package keyword.
2. Save the file in a folder with the same name as the package.
3. Use the package in another class using import.

🔧 Example: User-defined Package


📁 Step 1: Create the package and class
// File: MyPackage/Message.java
package MyPackage;

public class Message {


public void show() {
System.out.println("Hello from user-defined package!");
}
}
📌 Save this file inside a folder named MyPackage.

📁 Step 2: Use the package in another class


// File: TestPackage.java
import MyPackage.Message;

public class TestPackage {


public static void main(String[] args) {
Message msg = new Message();
msg.show();
}
}

▶️How to Compile and Run:


1. Compile Message.java (inside MyPackage folder):
2. javac MyPackage/Message.java
3. Compile TestPackage.java:
4. javac TestPackage.java
5. Run TestPackage:
6. java TestPackage
✅ Output:
Hello from user-defined package!

✍️In Short (For Exam Writing):


 A package is a group of related classes.
 User-defined packages are created using the package keyword.
 We can use import to use the package in other classes.
4. (a) Explain the concept of inheritance with its types.
(b) Discuss the key features supported by Object-Oriented programming

Sure! Here's a simple and clear explanation of both parts of your question, written in easy language so you can
understand and write it well in your exam.

✅ (a) Inheritance in Java


🔹 What is Inheritance?
Inheritance means one class (child) can use the properties and methods of another class (parent).
It helps in reusing code and building a relationship between classes.
👉 In Java, we use the keyword extends for inheritance.

🔸 Example:
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Dog barks");
}
}
In this example:
 Dog inherits from Animal
 Dog can use both bark() and sound() methods

🧩 Types of Inheritance in Java:


1. Single Inheritance – One child class inherits from one parent class
(Java supports this)
2. Multilevel Inheritance – Child → Parent → Grandparent
(Java supports this)
3. Hierarchical Inheritance – Multiple child classes inherit from the same parent
(Java supports this)
4. Multiple Inheritance (by Interface only) – A class implements multiple interfaces
(Java does NOT support multiple inheritance using classes, only using interfaces)

✅ (b) Key Features of Object-Oriented Programming (OOP)


OOP is a way of programming where everything is grouped around objects. Java is an object-oriented language.
🌟 Main Features:
1. Class and Object
o Class is a blueprint; object is the real thing.
o Example: Class = Car, Object = MyCar
2. Encapsulation
o Wrapping data and methods together in one unit (class)
o Keeps data safe from outside access
3. Inheritance
o One class can use features of another class (code reuse)
4. Polymorphism
o One task can be done in many ways (like method overloading and overriding)
5. Abstraction
o Hides complex code and shows only necessary details to the user
6. Reusability
oCode can be reused in other programs using inheritance
7. Modularity
o Program is divided into small parts (classes/objects) for easy management

✍️In Short (For Exam Writing):


(a) Inheritance is the process where one class can use the methods and properties of another class.
Java supports single, multilevel, and hierarchical inheritance.
(b) OOP Features include class and object, inheritance, encapsulation, polymorphism, abstraction, and reusability.

Let me know if you want diagrams or a printable version of this!

5 What is an exception? How is exception handled in JAVA. Difference between Throw and Throws.
Sure! Here's a simple and easy-to-remember explanation of exceptions, how to handle them, and the difference
between throw and throws, perfect for exam writing.

✅ What is an Exception in Java?


An exception is an error that happens while the program is running.
🔸 It stops the normal flow of the program.
🔸 Examples: dividing by zero, accessing a file that doesn't exist.

🔹 Example of Exception:
int a = 10;
int b = 0;
int c = a / b; // This will cause an exception (Divide by zero)

✅ How is Exception Handled in Java?


Java provides a way to handle exceptions using:
 try
 catch
 finally
 throw
 throws

🔸 Simple Syntax:
try {
// risky code
} catch (Exception e) {
// code to handle exception
} finally {
// (optional) code that always runs
}

🔹 Example:
public class Example {
public static void main(String[] args) {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} finally {
System.out.println("This will always run.");
}
}
}
✅ Output:
Cannot divide by zero.
This will always run.

✅ Difference between throw and throws:


throw throws
Used to throw an exception manually Used to declare an exception
Followed by an object (like new) Followed by exception class name
Used inside method Used with method signature
Only one exception at a time Can declare multiple exceptions
Example: Example:
throw new ArithmeticException(); void myMethod() throws IOException

✍️In Short (for exam writing):


 Exception is a runtime error.
 It is handled using try, catch, and finally.
 throw is used to throw an exception manually.
 throws is used to declare exceptions in the method signature.

6 What is package? what are the benefits of package? explain java API packages. list out any five
methods of string class by giving an example.
Sure! Here's a simple and easy-to-remember explanation of packages, their benefits, Java API packages, and
String class methods, written for easy learning and exam writing.

✅ What is a Package in Java?


A package in Java is like a folder that contains related classes, interfaces, and sub-packages.
👉 It helps in organizing the code properly.

✅ Benefits of Packages:
1. Organizes code in a better way.
2. Avoids name conflicts (two classes with the same name can be in different packages).
3. Reusability – We can use the same package in different programs.
4. Access control – Helps to protect classes using access modifiers.
5. Easy to manage and maintain code.

✅ What are Java API Packages?


 Java provides many predefined packages called Java API packages.
 These packages contain ready-made classes and methods we can use in our programs.

🔸 Common Java API Packages:


Package Description
java.lang Basic classes (String, Math, Object)
java.util Utility classes (Scanner, ArrayList)
java.io Input/Output (File, FileReader)
java.net For networking (Socket, URL)
java.sql For database programming

✅ 5 String Class Methods with Examples:


The String class is part of the java.lang package.
1. length() – returns the number of characters
String name = "Java";
System.out.println(name.length()); // Output: 4
2. toUpperCase() – converts to uppercase
String name = "hello";
System.out.println(name.toUpperCase()); // Output: HELLO
3. toLowerCase() – converts to lowercase
String name = "HELLO";
System.out.println(name.toLowerCase()); // Output: hello
4. charAt(int index) – returns character at given position
String name = "Java";
System.out.println(name.charAt(2)); // Output: v
5. substring(int start, int end) – returns part of the string
String name = "Programming";
System.out.println(name.substring(0, 4)); // Output: Prog

📝 Short Notes for Exam:


 Package is a group of related classes.
 Benefits: Organized code, avoids conflicts, reusability.
 Java API packages are built-in packages like java.util, java.io.
 String methods: length(), toUpperCase(), toLowerCase(), charAt(), substring().

7.What is thread priority? write the default values. write a program to define two threads. one thread
will print 1 to 10 no. whereas other will print 10 to 1 no.
Sure! Here's a simple explanation and example about thread priority and how to write a Java program using two
threads — perfect for learning and writing in your exam.

✅ What is Thread Priority in Java?


Thread Priority in Java is used to set the importance of a thread.
The thread with higher priority gets more chances to run.
Java gives each thread a priority between:
 🔴 1 (Lowest)
 🟡 5 (Normal – Default)
 🟢 10 (Highest)

✅ Default Thread Priority


 The default priority of a thread is 5.
You can change a thread’s priority using:
threadName.setPriority(number);

✅ Java Program with Two Threads


👉 One thread prints 1 to 10
👉 Other thread prints 10 to 1
class AscendingThread extends Thread {
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("Ascending: " + i);
}
}
}

class DescendingThread extends Thread {


public void run() {
for (int i = 10; i >= 1; i--) {
System.out.println("Descending: " + i);
}
}
}

public class ThreadExample {


public static void main(String[] args) {
AscendingThread t1 = new AscendingThread();
DescendingThread t2 = new DescendingThread();

// Set priorities (optional)


t1.setPriority(Thread.MIN_PRIORITY); // 1
t2.setPriority(Thread.MAX_PRIORITY); // 10

// Start both threads


t1.start();
t2.start();
}
}

🔎 Explanation:
 AscendingThread prints numbers from 1 to 10.
 DescendingThread prints numbers from 10 to 1.
 start() method is used to run the threads.
 We also set different priorities using:
o Thread.MIN_PRIORITY = 1
o Thread.MAX_PRIORITY = 10
Note: Thread execution order may vary, because threads run independently.

📝 Short Notes for Exam:


 Thread Priority decides which thread is more important.
 Range: 1 (Low) to 10 (High)
 Default value: 5
 Use .setPriority() to change priority.

Let me know if you’d like a one-page revision sheet or a test to check your understanding!
8. What is exception? Give different types of exception that could occur during run time. Why
to handle exceptions.

Sure! Here's a simple and easy-to-remember explanation of exceptions, types, and why we handle them, written in
exam-friendly language:

✅ What is an Exception in Java?


An exception is an error that happens while the program is running (at runtime).
It stops the normal flow of the program.

🔹 Example:
int a = 10;
int b = 0;
int c = a / b; // This will cause an exception (divide by zero)
👉 This will crash the program if not handled.

✅ Types of Exceptions (at Runtime):


Here are some common runtime exceptions:
Exception Name When it Happens
ArithmeticException Dividing by zero
NullPointerException Using a null object
ArrayIndexOutOfBoundsException Accessing invalid array index
NumberFormatException Converting wrong string to number
InputMismatchException Wrong input type (in Scanner, etc.)
✅ Why Should We Handle Exceptions?
1. ✅ To avoid program crash
Without handling, the program stops when an error happens.
2. ✅ To show user-friendly messages
We can show a message like "Please enter a valid number" instead of showing error codes.
3. ✅ To continue program execution
Program can continue even after error if handled properly.
4. ✅ For better debugging and maintenance
Helps to find and fix bugs easily.

✅ How to Handle Exceptions in Java:


We use:
 try → block to write risky code
 catch → block to handle exception
 finally → (optional) block that always runs

🔹 Example:
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("You cannot divide by zero.");
}
✅ Output:
You cannot divide by zero.

📝 Short Notes for Exam:


 Exception is a runtime error.
 Types: ArithmeticException, NullPointerException, etc.
 Why handle? To avoid crash, show messages, and run smoothly.
 Use try and catch to handle exceptions.

Let me know if you want this in a printable format or with a diagram!

9 What is Inheritance in Java? If we need to extend more than one class then how it is possible? Write code
for the same

Sure! Here's a simple and clear explanation of Inheritance in Java, and how to extend more than one class
using interfaces, written in easy language for exam preparation.

✅ What is Inheritance in Java?


Inheritance means one class (child) can use the properties and methods of another class (parent).
It helps in code reusability and making programs more organized.
👉 In Java, we use the keyword extends for inheritance.

🔹 Example of Single Inheritance:


class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Dog barks");
}
}

public class Test {


public static void main(String[] args) {
Dog d = new Dog();
d.sound(); // from Animal
d.bark(); // from Dog
}
}

❓ Can We Extend More Than One Class?


🚫 Java does NOT support multiple inheritance with classes (to avoid confusion if both parents have same
method names).

✅ How to Inherit from More Than One Class?


We can use interfaces to achieve multiple inheritance in Java.
🔸 Use implements keyword for interfaces.

✅ Example: Multiple Inheritance using Interface


interface A {
void showA();
}

interface B {
void showB();
}

class C implements A, B {
public void showA() {
System.out.println("This is from Interface A");
}

public void showB() {


System.out.println("This is from Interface B");
}
}

public class Test {


public static void main(String[] args) {
C obj = new C();
obj.showA();
obj.showB();
}
}

📝 Short Notes for Exam:


 Inheritance lets a class use code from another class.
 Java supports single, multilevel, and hierarchical inheritance.
 Java does not support multiple inheritance with classes.
 We can use interfaces to achieve multiple inheritance.

Let me know if you’d like this in a printable format or revision flashcards!

10 .What is inheritance? If we need to extend more than one class then how it will work.
Perfect 👍 Let’s write this in detailed, exam-ready notes with examples and diagram so you can write
confidently.

Inheritance in OOP
Definition
Inheritance is a feature of Object-Oriented Programming (OOP) where one class (called the child class or
subclass) can acquire the properties (variables) and behaviors (methods) of another class (called the parent
class or superclass).
It is mainly used for:
1. Code reusability – No need to write the same code again.
2. Method overriding – Child class can provide its own implementation.
3. Creating hierarchy – Helps in modeling real-world relationships.

Example of Simple Inheritance (C++/Java style)


// Parent class
class Vehicle {
public:
void start() {
cout << "Vehicle starting..." << endl;
}
};

// Child class
class Car : public Vehicle {
public:
void drive() {
cout << "Car is driving..." << endl;
}
};

int main() {
Car obj;
obj.start(); // Inherited from Vehicle
obj.drive(); // Own method
}
👉 Here, Car automatically got the start() method from Vehicle.

Types of Inheritance
1. Single Inheritance → One child inherits from one parent.
2. Multilevel Inheritance → A class inherits from another class, which itself is inherited from another.
(Grandparent → Parent → Child)
3. Hierarchical Inheritance → Multiple classes inherit from one parent.
4. Multiple Inheritance → One class inherits from more than one parent.
5. Hybrid Inheritance → Combination of above types.

Multiple Inheritance (Important for exam)


 C++: Supports multiple inheritance directly.
class A {
public: void showA() { cout << "Class A" << endl; }
};
class B {
public: void showB() { cout << "Class B" << endl; }
};
class C : public A, public B { // Multiple inheritance
};
 Java: Does not support multiple inheritance with classes (to avoid Diamond Problem: when two
parents have the same method, compiler won’t know which one to use).
👉 Instead, Java supports multiple inheritance through interfaces.
interface A {
void showA();
}
interface B {
void showB();
}
class C implements A, B {
public void showA() { System.out.println("From A"); }
public void showB() { System.out.println("From B"); }
}

Diagram of Inheritance
Vehicle (Parent)
/ \
/ \
Car Bike
👉 Car and Bike inherit from Vehicle.
For multiple inheritance in C++:
Class A Class B
\ /
\ /
\ /
Class C

Final Exam-Ready Answer


“Inheritance is an object-oriented programming feature where a child class acquires the properties and methods
of a parent class. It improves code reusability, allows overriding, and helps in modeling real-world hierarchies.
If we want to extend more than one class, it is called multiple inheritance. In C++, multiple inheritance is
allowed directly. However, in Java, multiple inheritance with classes is not supported to avoid ambiguity
(Diamond problem). Instead, Java provides multiple inheritance through interfaces.”

7 MARKS QUESTIONS

1 Explain the concepts of inheritance in java. Also explain the types of Inheritance.
Got it 👍 Let me give you a clear, exam-ready explanation of inheritance in Java in easy language.

Inheritance in Java
Definition
Inheritance in Java is a mechanism where one class (child class) can get the fields (variables) and methods
(functions) of another class (parent class) using the keyword extends.
👉 It helps in reusing code, reducing redundancy, and achieving method overriding (runtime polymorphism).

Simple Example
class Vehicle {
void start() {
System.out.println("Vehicle starts");
}
}

class Car extends Vehicle { // Car inherits from Vehicle


void drive() {
System.out.println("Car is driving");
}
}

public class Main {


public static void main(String[] args) {
Car c = new Car();
c.start(); // Inherited method
c.drive(); // Own method
}
}
👉 Here, Car got the start() method from Vehicle without writing it again.

Types of Inheritance in Java


Java mainly supports single inheritance (through classes) and multiple inheritance (through interfaces). The
common types are:
1. Single Inheritance
o One child class inherits from one parent class.
Example: Car extends Vehicle
2. Multilevel Inheritance
o A class inherits from another class, and then another class inherits from it.
Example: SportsCar extends Car and Car extends Vehicle
(Grandparent → Parent → Child)
3. Hierarchical Inheritance
o Multiple child classes inherit from the same parent.
Example: Car extends Vehicle, Bike extends Vehicle
4. Multiple Inheritance (Not supported with classes in Java)
o Java does not allow multiple inheritance with classes (to avoid confusion, called the Diamond
Problem).
o But Java allows multiple inheritance using interfaces.
5. interface A { void show(); }
6. interface B { void display(); }
7.
8. class C implements A, B {
9. public void show() { System.out.println("Show from A"); }
10. public void display() { System.out.println("Display from B"); }
11. }

Final Exam-Friendly Answer


“Inheritance in Java is a process where one class acquires the properties and methods of another class using the
extends keyword. It improves code reusability and supports method overriding.
The main types of inheritance in Java are:
1. Single Inheritance – one class inherits from another.
2. Multilevel Inheritance – chain of inheritance (grandparent → parent → child).
3. Hierarchical Inheritance – many classes inherit from one parent.
4. Multiple Inheritance – not supported with classes, but can be achieved using interfaces.”

👉 Do you want me to also make a diagram for all types of inheritance in Java (easy tree-like format) so you can
quickly draw in exam?

2 Illustrate the features of Java Programming Language.

Perfect 👍 I’ll give you an easy, exam-friendly explanation of the features of Java programming language.

Features of Java Programming Language


Java is a widely used object-oriented, platform-independent, and secure programming language. Its main
features are:

1. Simple
 Java is easy to learn and understand.
 It removes complex features of C++ like pointers and multiple inheritance.

2. Object-Oriented
 Everything in Java is treated as an object.
 Concepts like class, object, inheritance, polymorphism, encapsulation, abstraction are supported.

3. Platform Independent (Write Once, Run Anywhere)


 Java code is compiled into bytecode which runs on the Java Virtual Machine (JVM).
 Same program can run on Windows, Linux, or Mac without change.

4. Secure
 Java does not use pointers directly, so memory access is safe.
 Programs run inside JVM, reducing chances of virus or hacking.

5. Robust
 Java is strong and reliable.
 It has exception handling and automatic memory management (Garbage Collection).

6. Portable
 Java programs can be easily moved from one system to another.
 Bytecode makes it independent of system architecture.

7. Multithreaded
 Java allows multiple tasks to run at the same time (like downloading and playing music together).

8. High Performance
 Though slower than C++, Java uses JIT (Just-In-Time) compiler to make execution faster.

9. Distributed
 Java supports RMI (Remote Method Invocation) and networking APIs which help in creating
distributed (internet-based) applications.

10. Dynamic
 Java can load classes at runtime, making it more flexible.

Final Exam-Friendly Answer


“The main features of Java programming language are:
1. Simple – easy to learn and removes complex features of C++.
2. Object-Oriented – supports classes, objects, inheritance, polymorphism, etc.
3. Platform Independent – write once, run anywhere using JVM.
4. Secure – no pointers, runs inside JVM.
5. Robust – exception handling and garbage collection.
6. Portable – can run on any system.
7. Multithreaded – supports multitasking.
8. High Performance – JIT compiler improves speed.
9. Distributed – supports internet-based applications.
10. Dynamic – loads classes at runtime.
Hence, Java is a secure, portable, and powerful language widely used for application development.”

👉 Do you want me to also make a short bullet version (only 5–6 key points) for last-minute revision before
exam?

3 Discuss the key features supported by object-oriented programming languages.


Got it 👍 Let’s make this easy, exam-style explanation for the features of Object-Oriented Programming
(OOP) languages.

Key Features of OOP Languages


Object-Oriented Programming (OOP) is a way of programming where everything is organized around objects
(real-world entities). OOP makes programs easier to understand, reuse, and maintain.
The main features are:

1. Class
 A class is like a blueprint or template.
 It defines variables (data) and methods (functions).
 Example: class Car { int speed; void drive(){} }

2. Object
 An object is an instance of a class.
 It represents a real-world entity.
 Example: Car c1 = new Car();

3. Encapsulation
 Wrapping data (variables) and methods (functions) together inside a class.
 Provides data hiding using access modifiers (private, public).

4. Abstraction
 Hiding unnecessary details and showing only important features.
 Example: When we drive a car, we just use steering and brakes, without knowing the internal engine
details.

5. Inheritance
 One class can acquire properties and methods of another class.
 Supports code reusability and hierarchical relationships.

6. Polymorphism
 Means many forms.
 Same function name can have different forms.
o Compile-time polymorphism → method overloading.
o Runtime polymorphism → method overriding.

7. Message Passing
 Objects communicate with each other by calling methods.
 Example: obj1.sendMessage(obj2);

Final Exam-Friendly Answer


“The key features of Object-Oriented Programming (OOP) languages are:
1. Class – blueprint for creating objects.
2. Object – instance of a class representing real-world entities.
3. Encapsulation – wrapping data and methods together, with data hiding.
4. Abstraction – showing essential features and hiding details.
5. Inheritance – one class can acquire properties of another.
6. Polymorphism – same operation can behave differently (overloading/overriding).
7. Message Passing – objects interact by sending messages (method calls).
Thus, OOP makes programming more modular, reusable, and easier to maintain.”

👉 Do you want me to also create a diagram showing OOP features (like a box with all 7 features inside) so you
can draw it in your exam answer sheet?

4 What is exception?. How the exception is handled in java. Difference between


throw and throws.
Okay 👍 Let’s break this into easy exam-friendly notes with examples.

What is Exception?
 An exception in Java is an unexpected event or error that happens during
program execution.
 Example: dividing a number by zero, accessing an array out of range, or opening a
file that doesn’t exist.
 If not handled, exceptions can make the program crash.

How Exception is Handled in Java?


Java provides a mechanism called exception handling to deal with errors.
It uses try-catch-finally blocks.
Syntax:
try {
// risky code
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero!");
} finally {
System.out.println("This block always runs.");
}
Explanation:
1. try block → contains risky code.
2. catch block → handles the exception.
3. finally block → always runs (used for closing files, connections, etc.).
👉 This way, the program does not crash.

Difference between throw and throws


throw throws
Used in method
Used to explicitly throw an exception declaration to indicate that
from a method or block. the method may throw
exceptions.
Multiple exceptions can be
Only one exception can be thrown at
declared separated by
a time.
commas.
Example: void myMethod()
Example: throw new
throws IOException,
ArithmeticException("Error!");
SQLException { ... }

Final Exam-Friendly Answer


“An exception is an unexpected error that occurs at runtime, such as dividing by zero or
invalid input. Exception handling in Java is done using try-catch-finally blocks. The try
block has risky code, the catch block handles the error, and the finally block always runs.
The difference between throw and throws is:
 throw is used inside a method to actually throw an exception.
 throws is used in the method declaration to specify which exceptions might occur.”

5 Write a program to count number of objects created in the program.


Nice one 👍 This is a common exam-style Java program. Let’s write it in easy language with explanation.

Program to Count Number of Objects in Java


class Counter {
// static variable shared by all objects
static int count = 0;

// Constructor (runs whenever object is created)


Counter() {
count++; // increase count whenever new object is made
}

// Method to show number of objects


void showCount() {
System.out.println("Number of objects created: " + count);
}
}

public class Main {


public static void main(String[] args) {
// Creating objects
Counter obj1 = new Counter();
Counter obj2 = new Counter();
Counter obj3 = new Counter();
// Displaying object count
obj3.showCount();
}
}

Output
Number of objects created: 3

Explanation (in easy words)


1. We use a static variable count so that its value is shared by all objects.
2. Each time the constructor runs, count increases by 1.
3. Finally, we print the count → gives the number of objects created.

✅ Exam-Ready Short Answer


“We can count objects in Java using a static variable inside the class. Each time the constructor is called, we increase
the counter. At the end, the counter shows how many objects are created.”

👉 Do you also want me to give you a slightly shorter version of the program (5–6 lines) for quick writing in exams?

6. Differentiate between
a. Constructor and finalize
b. Method overloading and Method overriding
c. Super and final keyword

Got it 👍 You want the differences of (a), (b), (c) only, in easy and clear exam style.
Here’s the neat version 👇

a) Constructor vs finalize()
 Constructor is used to initialize an object when it is created.
 finalize() is called before the object is destroyed by Garbage Collector.
Constructor finalize()
Called at object creation. Called before object destruction.
Used for initialization. Used for cleanup (closing files, connections).
Can have parameters. Cannot have parameters.

b) Method Overloading vs Method Overriding


 Overloading → same method name, but different parameters.
 Overriding → same method name and parameters, but in parent-child classes.
Method Overloading Method Overriding
Same name, different parameters. Same name, same parameters.
Happens in the same class. Happens in subclass (inheritance).
Compile-time polymorphism. Runtime polymorphism.

c) super vs final keyword


 super → used to access parent class members.
 final → used to restrict inheritance, overriding, or variable modification.
super final
Refers to parent class constructor, method, or variable. Prevents inheritance, overriding, or modification.
super final
Example: super.show(); Example: final class A { }
Used for accessing parent features. Used for restricting features.

✅ This version is short, clear, and exam-ready.


👉 Do you want me to also add a one-line mnemonic (shortcut memory trick) for each difference so you can
recall quickly in exam?

7 Java Support Single inheritance, if we need to extend more than one class, how it can be
achieved? Explain with sample code
Perfect 👍 Let’s answer this in easy exam style with clear explanation + code.

Java and Inheritance


 Java supports single inheritance with classes (one class can extend only one parent class).
 Java does not allow multiple inheritance with classes because it may create confusion (called the
Diamond Problem).
👉 Example of problem: If two parent classes have the same method, child class will get confused which
one to use.

How to Achieve Multiple Inheritance in Java?


✅ In Java, multiple inheritance is achieved using interfaces.
 A class can implement multiple interfaces at the same time.
 This way, Java allows multiple inheritance safely.

Example Code
// First interface
interface A {
void show();
}

// Second interface
interface B {
void display();
}

// Child class implements both interfaces


class C implements A, B {
public void show() {
System.out.println("Show from interface A");
}
public void display() {
System.out.println("Display from interface B");
}
}

// Main class
public class Main {
public static void main(String[] args) {
C obj = new C();
obj.show();
obj.display();
}
}

Output
Show from interface A
Display from interface B

Final Exam-Friendly Answer


“Java supports single inheritance with classes. If we need to extend more than one class, Java does not
allow it directly (to avoid ambiguity). Instead, multiple inheritance is achieved using interfaces. A class
can implement multiple interfaces at the same time, thus behaving like it is inheriting from more than one
parent.”

👉 Do you want me to also give you a small diagram (two parents → one child using interfaces) so you
can draw it in your exam answer sheet?

8. Explain Multithreading in Java? Write code also.


Great 👍 Let’s write this in easy exam language with a simple code example.

Multithreading in Java
Definition
 Multithreading means running multiple tasks (threads) at the same time in a program.
 Each thread runs independently, so CPU can do multitasking (like downloading a file and playing music
together).
 Threads in Java can be created in two ways:
1. By extending Thread class.
2. By implementing Runnable interface.

Advantages of Multithreading
1. Efficient use of CPU.
2. Saves time (tasks run parallel).
3. Useful for animations, games, servers, etc.

Example Code (using Thread class)


// Thread by extending Thread class
class MyThread extends Thread {
public void run() {
// code that will run in thread
for(int i = 1; i <= 5; i++) {
System.out.println("Thread running: " + i);
try {
Thread.sleep(500); // pause for 0.5 sec
} catch(Exception e) {
System.out.println(e);
}
}
}
}

public class Main {


public static void main(String[] args) {
// create objects of thread class
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();

// start threads
t1.start();
t2.start();
}
}

Output (example)
Thread running: 1
Thread running: 1
Thread running: 2
Thread running: 2
...
👉 Both threads run at the same time.

Final Exam-Friendly Answer


“Multithreading in Java is the process of executing multiple threads (small parts of a program) simultaneously.
It helps in multitasking and efficient CPU usage.
Java provides two ways to create threads – by extending Thread class or by implementing Runnable interface.
The run() method contains the code of the thread, and the start() method is used to begin execution.”

👉 Do you also want me to show you the Runnable interface version (shorter code) so you can pick whichever is
easier for exam?

9 What do you mean by constructor in java? Differentiate between default constructor and copy
constructor?
Got it 👍 Let’s explain constructor in Java and the difference between default and copy
constructor in easy exam-friendly language.

What is Constructor in Java?


 A constructor is a special method in Java that is used to initialize objects.
 It has the same name as the class.
 It is automatically called when an object is created.
 It does not have a return type (not even void).
👉 Example:
class Student {
int id;
String name;

// Constructor
Student(int i, String n) {
id = i;
name = n;
}
}

Types of Constructors
1. Default Constructor
 A constructor with no parameters.
 If we don’t write any constructor, Java provides a default constructor automatically.
 Example:
class Student {
Student() {
System.out.println("Default constructor called");
}
}

2. Copy Constructor
 A constructor which copies the values of one object into another.
 Java doesn’t provide copy constructor by default (like C++), but we can create it manually.
 Example:
class Student {
int id;
String name;

// Normal constructor
Student(int i, String n) {
id = i;
name = n;
}

// Copy constructor
Student(Student s) {
id = s.id;
name = s.name;
}
}

Difference between Default Constructor and Copy Constructor


Default Constructor Copy Constructor
Has no parameters. Takes another object as a parameter.
Used to initialize object with default Used to initialize object by copying values from
values. another object.
Provided by compiler if not defined. Must be written by programmer in Java.
Example: Student() { } Example: Student(Student s) { }

Final Exam-Friendly Answer


“A constructor in Java is a special method used to initialize objects, called automatically when an
object is created.
 A default constructor has no parameters and initializes objects with default values.
 A copy constructor takes another object as a parameter and copies its values into the new object.
Thus, default constructor provides default initialization, while copy constructor provides initialization
by copying existing object values.”

👉 Do you want me to also make a small diagram (Object1 → Object2 using copy constructor) so
it’s easy to draw in your exam?

10 What is exception? Explain methods of handling exception in Java?


Perfect 👍 Let’s write this in easy, exam-style language with simple explanation and examples.

What is Exception?
 An exception in Java is an unexpected error that happens when a program is running.
 Example: dividing by zero, accessing an invalid array index, or opening a file that doesn’t exist.
 If not handled, exceptions can make the program crash.

Methods of Handling Exceptions in Java


Java provides different ways to handle exceptions so that the program does not crash:

1. try–catch block
 We put risky code inside try block.
 If an error happens, it is caught in catch block.
try {
int x = 10 / 0; // risky code
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero!");
}

2. finally block
 finally block always runs (whether there is an exception or not).
 Mostly used to close files, databases, or free resources.
try {
int arr[] = {1, 2, 3};
System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid array index!");
} finally {
System.out.println("This will always execute.");
}

3. throw keyword
 Used to manually throw an exception.
throw new ArithmeticException("Division not allowed");

4. throws keyword
 Used in method declaration to say that this method might throw an exception.
void myMethod() throws IOException {
// code that may cause IOException
}

Final Exam-Friendly Answer


“An exception in Java is an error that occurs during program execution, like division by zero or invalid input. If
not handled, the program will stop abnormally.
The main methods of handling exceptions are:
1. try–catch block – risky code in try, error handled in catch.
2. finally block – runs always, used to release resources.
3. throw – used to manually throw an exception.
4. throws – used in method declaration to indicate possible exceptions.
Thus, exception handling makes programs more reliable and prevents crashes.”

👉 Do you want me to also add a small real-life example (like ATM transaction error) so your exam answer
looks more practical?
11 What is exception handling in Java? What is method of handling exception in Java?
Okay 👍 Let’s make this easy exam-style answer for you.

What is Exception Handling in Java?


 An exception is an unexpected error that happens while a program is running (like division by zero,
invalid input, file not found).
 Exception handling in Java is a process of detecting and handling such errors so that the program does
not crash and continues smoothly.
 It improves reliability and user experience.

Methods of Handling Exception in Java


Java provides some ways to handle exceptions:

1. try–catch block
 Risky code is written inside try.
 Errors are handled inside catch.
try {
int x = 10 / 0; // risky code
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero!");
}

2. finally block
 Code inside finally always executes (whether error happens or not).
 Used for cleanup (closing files, database connection).
try {
int arr[] = {1,2,3};
System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid index!");
} finally {
System.out.println("This will always run.");
}

3. throw keyword
 Used to manually throw an exception.
throw new ArithmeticException("Not allowed");

4. throws keyword
 Used in method declaration to say that a method might throw an exception.
void myMethod() throws IOException {
// code that may cause exception
}
Final Exam-Friendly Answer
“Exception handling in Java is the process of handling runtime errors so that the normal flow of the program is
not disturbed.
The methods of handling exceptions are:
1. try–catch block – catch and handle errors.
2. finally block – runs always, used to close resources.
3. throw – to manually throw an exception.
4. throws – to declare exceptions in method definition.
Thus, exception handling makes Java programs safe and reliable.”

12 What is inheritance in java? Explain all its type.


Perfect 👍 Let’s write this in easy, exam-friendly language.

What is Inheritance in Java?


 Inheritance means one class can use the properties and methods of another class.
 It allows code reusability (we don’t need to write the same code again).
 In Java, inheritance is achieved using the extends keyword.
👉 Example:
class Animal {
void eat() {
System.out.println("Animals eat food");
}
}

class Dog extends Animal { // Dog inherits Animal


void bark() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String args[]) {
Dog d = new Dog();
d.eat(); // from Animal class
d.bark(); // from Dog class
}
}

Types of Inheritance in Java


Java supports different types of inheritance (except multiple inheritance with classes).

1. Single Inheritance
 One class inherits another class.
class A { }
class B extends A { }
2. Multilevel Inheritance
 A class is inherited by another class, and that class is again inherited by another.
class A { }
class B extends A { }
class C extends B { }

3. Hierarchical Inheritance
 One parent class is inherited by many child classes.
class A { }
class B extends A { }
class C extends A { }

4. Multiple Inheritance (through Interface only)


 A class can implement multiple interfaces (since Java does not allow multiple inheritance with classes).
interface A { void show(); }
interface B { void display(); }

class C implements A, B {
public void show() { System.out.println("Show"); }
public void display() { System.out.println("Display"); }
}

Final Exam-Friendly Answer


“Inheritance in Java is the process where one class can acquire the properties and methods of another class using
the extends keyword. It improves code reusability and makes the program easier to manage.
Types of inheritance in Java are:
1. Single Inheritance – one class inherits another.
2. Multilevel Inheritance – chain of inheritance.
3. Hierarchical Inheritance – one parent, many child classes.
4. Multiple Inheritance (using interfaces) – one class implements multiple interfaces.
Java does not support multiple inheritance with classes to avoid confusion, but it allows it with interfaces.”

👉 Do you want me to also make a simple diagram for each type so you can quickly draw it in your exam answer
sheet?
13 What are the packages in Java? Illustrate the appropriate example.

Great 👍 Let’s write this in easy exam-style language.

What are Packages in Java?


 A package in Java is a collection of classes and interfaces grouped together.
 It is like a folder in a computer that contains related files.
 Packages are used to organize code and avoid name conflicts.
 Java has two types of packages:
1. Built-in Packages (already available in Java, like java.util, java.io, etc.)
2. User-defined Packages (created by programmers).

Example 1: Using Built-in Package


import java.util.*; // importing util package

public class Main {


public static void main(String args[]) {
Scanner sc = new Scanner(System.in); // Scanner is in util package
System.out.println("Enter your name:");
String name = sc.nextLine();
System.out.println("Hello, " + name);
}
}

Example 2: Creating User-defined Package


👉 Step 1: Create a package
package mypack; // defining package

public class MyClass {


public void display() {
System.out.println("Hello from mypack!");
}
}
👉 Step 2: Save this file as MyClass.java, then compile:
javac -d . MyClass.java
👉 Step 3: Use the package in another program
import mypack.MyClass; // importing user-defined package

public class Test {


public static void main(String args[]) {
MyClass obj = new MyClass();
obj.display();
}
}

Final Exam-Friendly Answer


“A package in Java is a way of grouping related classes and interfaces. It helps organize code, avoid name conflicts,
and provide reusability.
There are two types of packages:
1. Built-in packages like java.util, java.io.
2. User-defined packages, created by the programmer using the package keyword.
Example:
 import java.util.Scanner; (built-in package).
 Creating package mypack and using class MyClass (user-defined package).”
👉 Do you want me to also make a small diagram (Packages → Classes) so it’s easy to draw in exam?

14 Explain features of java?


Got it 👍 Let’s write the features of Java in easy exam-style language.

Features of Java Programming Language


Java is a popular programming language because it has many useful features:

1. Simple
 Java is easy to learn and understand.
 It removes complex features like pointers, multiple inheritance (with classes).

2. Object-Oriented
 Everything in Java is based on objects and classes.
 Supports OOP concepts like inheritance, polymorphism, abstraction, encapsulation.

3. Platform Independent
 Java code is compiled into bytecode, which can run on any machine using the JVM (Java Virtual
Machine).
 “Write Once, Run Anywhere”.

4. Secure
 Java does not use pointers directly.
 Provides security features like bytecode verification, exception handling, and access modifiers.

5. Robust
 Java has strong memory management, exception handling, and automatic garbage collection, which
makes programs reliable.

6. Multithreaded
 Java allows multiple tasks to run at the same time using multithreading (example: playing music while
typing).

7. Distributed
 Java supports distributed applications (programs that run on multiple computers) using technologies like
RMI and EJB.

8. High Performance
 Java is not as fast as C/C++ but faster than other interpreted languages because of Just-In-Time (JIT)
compiler.

9. Portable
 Java programs can run on any system (Windows, Linux, Mac) without changes.

10. Dynamic
 Java can load classes dynamically at runtime and adapt to evolving environments.
Final Exam-Friendly Answer
“The main features of Java are:
1. Simple – easy to learn.
2. Object-Oriented – based on objects.
3. Platform Independent – WORA (Write Once, Run Anywhere).
4. Secure – no pointers, strong security.
5. Robust – exception handling, garbage collection.
6. Multithreaded – supports multitasking.
7. Distributed – used for network-based apps.
8. High Performance – uses JIT compiler.
9. Portable – runs on any system.
10. Dynamic – supports runtime changes.
These features make Java a powerful and widely used programming language.”

15 What is type casting? give an example to explain it.


Alright 👍 Let’s make this easy and exam-style.

What is Type Casting in Java?


 Type casting in Java means converting one data type into another.
 It is useful when we want to store a value of one type into another type.
 Example: converting int to double or double to int.

Types of Type Casting in Java


1. Widening (Implicit Casting)
 Smaller type is automatically converted into bigger type.
 Done by Java automatically.
 Example: int → long → float → double
public class Main {
public static void main(String[] args) {
int num = 10; // int
double d = num; // automatic conversion (int → double)
System.out.println(d); // Output: 10.0
}
}

2. Narrowing (Explicit Casting)


 Bigger type is converted into smaller type.
 Done manually using (type).
 Example: double → int
public class Main {
public static void main(String[] args) {
double d = 9.8;
int num = (int) d; // manual conversion (double → int)
System.out.println(num); // Output: 9
}
}
Final Exam-Friendly Answer
“Type casting in Java is the process of converting one data type into another.
It is of two types:
1. Widening (implicit) – smaller type to bigger type (done automatically). Example: int → double.
2. Narrowing (explicit) – bigger type to smaller type (done manually). Example: double → int.
Example:
int x = 10;
double y = x; // widening
double a = 9.8;
int b = (int) a; // narrowing

👉 Do you want me to also add a simple diagram of type conversion order (byte → short → int → long → float
→ double) so you can draw it in exam?

16 What do you mean by package in java?


Okay 👍 Let’s keep it simple and exam-ready.

What is Package in Java?


 A package in Java is like a folder that contains related classes and interfaces.
 It is used to group classes so that programs are easy to manage and use.
 Packages help in:
1. Organizing code
2. Avoiding name conflicts
3. Reusing classes

Types of Packages
1. Built-in Packages – already available in Java (example: java.util, java.io).
2. User-defined Packages – created by programmers.

Example (Built-in Package)


import java.util.Scanner; // using built-in package

public class Main {


public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name:");
String name = sc.nextLine();
System.out.println("Hello, " + name);
}
}

Example (User-defined Package)


👉 Step 1: Create a package
package mypack; // creating package

public class MyClass {


public void display() {
System.out.println("Hello from mypack!");
}
}
👉 Step 2: Compile it
javac -d . MyClass.java
👉 Step 3: Use it in another program
import mypack.MyClass;

public class Test {


public static void main(String args[]) {
MyClass obj = new MyClass();
obj.display();
}
}

Final Exam-Friendly Answer


“A package in Java is a way of grouping related classes and interfaces together. It makes programs easy to
manage, avoids name conflicts, and allows reusability.
There are two types of packages:
1. Built-in packages (like java.util, java.io).
2. User-defined packages (created by the programmer using package keyword).”

👉 Do you want me to also give you a 1–2 line super short version (only definition + types) for quick writing in
exams?

You might also like