Oopj Paper Solution 2
Oopj Paper Solution 2
Q.1
(a) List out basic concepts of OOP. Explain any one in detail.
The basic concepts of Object-Oriented Programming (OOP) in Java include:
1. **Classes and Objects**
2. **Inheritance**
3. **Polymorphism**
4. **Encapsulation**
5. **Abstraction**
Polymorphism
Polymorphism is the ability of an object to take on many forms. It allows one
interface to be used for a general class of actions. The specific action is
determined by the exact nature of the situation. In Java, polymorphism is
primarily achieved through method overloading and method overriding.
Method Overloading
Method overloading allows a class to have more than one method with the
same name, provided their parameter lists are different. This can make the
code more readable and intuitive.
Method Overriding
Method overriding allows a subclass to provide a specific implementation of a
method that is already defined in its superclass. This is used to achieve runtime
polymorphism.
Example:
// Base class
class Animal {
void makeSound() {
System.out.println("Some generic animal sound");
}
}
// Derived class
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Woof");
}
}
// Derived class
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow");
}
}
(c) Write a program in java to find out minimum from any ten
numbers using command line argument.
public class FindMinimum {
public static void main(String[] args) {
if (args.length != 10) {
System.out.println("Please provide exactly 10 numbers as command line
arguments.");
return;
}
Q.2
(a) What is wrapper class? Explain with example
In Java, a wrapper class is a class that encapsulates a primitive data type within
an object. This allows primitive data types to be used as objects, providing the
benefits of object-oriented programming, such as the ability to use methods
and the compatibility with Java's collection framework which can only hold
objects.
Primitive Types and Their Corresponding Wrapper Classes:
- **int** -> **Integer**
- **char** -> **Character**
- **boolean** -> **Boolean**
- **byte** -> **Byte**
- **short** -> **Short**
- **long** -> **Long**
- **float** -> **Float**
- **double** -> **Double**
Example:
Here's a simple example demonstrating the use of a wrapper class:
public class WrapperClassExample {
public static void main(String[] args) {
// Creating wrapper class objects
Integer intObject = Integer.valueOf(10); // Boxing: Converting int to Integer
int primitiveInt = intObject.intValue(); // Unboxing: Converting Integer to
int
Java offers a wide range of features, but here are some key ones:
1. Simple: Java was designed to be easy to learn and use. It has a clean
syntax, automatic memory management, and clear documentation.
2. Object-Oriented: Java follows an object-oriented programming
paradigm, which promotes modularity, reusability, and extensibility.
Everything in Java is an object, allowing for better organization of code.
3. Platform Independence: Java programs are compiled into bytecode,
which can be executed on any platform with the help of the Java Virtual
Machine (JVM). This "write once, run anywhere" capability makes Java
platform-independent.
4. Secure: Java provides a robust security model with features like
bytecode verification, class loading, and runtime permissions to protect
systems from malicious code.
5. Multithreading: Java supports multithreading, allowing multiple threads
of execution to run concurrently within a single program. This feature is
essential for developing scalable and responsive applications.
6. Distributed: Java supports distributed computing by providing APIs for
network communication, remote method invocation (RMI), and web
services, enabling the development of distributed applications.
7. Dynamic: Java supports dynamic memory allocation and dynamic
linking, allowing for flexibility in memory management and runtime
loading of classes.
8. High Performance: Java's Just-In-Time (JIT) compiler optimizes bytecode
into native machine code at runtime, leading to high performance and
efficient execution.
Example:
return a + b;
}
// Method to add three integers
return a + b + c;
return a + b;
All three methods have the same name (`add`), but they differ in the number
or type of parameters they accept. This is method overloading. When you call
the `add` method with different parameter lists, Java determines which version
of the method to execute based on the arguments provided.
Q.2
(a) Explain Garbage collection in java.
Garbage collection in Java is the process by which the Java Virtual Machine
(JVM) automatically deallocates memory used by objects that are no longer
reachable or needed by the program. It's a mechanism for automatic memory
management, ensuring efficient memory usage and preventing memory leaks.
Key Points:
Benefits:
public Circle(int r) {
radius = r;
// }
// Class implementation
The `final` keyword ensures immutability, security, and design integrity in Java
programs.
// Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
Q. 3
(a) Explain super keyword with example.
In Java, the `super` keyword is used to refer to the superclass (parent class) of a
subclass (child class). It can be used to access superclass methods,
constructors, and variables.
Example:
// Parent class
class Vehicle {
String brand;
// Constructor
Vehicle(String brand) {
this.brand = brand;
}
// Method
void displayInfo() {
System.out.println("Brand: " + brand);
}
}
// Child class
class Car extends Vehicle {
int year;
// Constructor
Car(String brand, int year) {
super(brand); // Calls the constructor of the superclass
this.year = year;
}
// Method overriding
@Override
void displayInfo() {
super.displayInfo(); // Calls the method of the superclass
System.out.println("Year: " + year);
}
}
// Interface 2
interface Swimmable {
void swim();
}
@Override
public void swim() {
System.out.println("Bird is swimming");
}
}
Q. 3
(a) Explain static keyword with example.
In Java, the `static` keyword is used to declare members (variables and
methods) that belong to the class itself rather than to instances of the class.
These members are shared among all instances of the class and can be
accessed directly through the class name without creating an object of the
class.
Example:
public class Counter {
// Static variable
static int count = 0;
// Static method
static void increment() {
count++;
}
// Static method
static void displayCount() {
System.out.println("Count: " + count);
}
Q. 4
(a) Explain thread priorities with suitable example.
In Java, thread priorities are used to indicate the importance or urgency of a
thread's execution relative to other threads. Threads with higher priority are
scheduled to run before threads with lower priority. Java provides 10 priority
levels, ranging from 1 (lowest) to 10 (highest), with the default priority being 5.
Example:
public class PriorityExample {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable(), "Thread 1");
Thread t2 = new Thread(new MyRunnable(), "Thread 2");
// Start threads
t1.start();
t2.start();
}
1. New: A thread is in the new state when it's created but has not yet
started.
2. Runnable: A thread is in the runnable state when it's ready to run and
waiting for the processor to execute it.
3. Running: A thread is in the running state when the processor is actively
executing its task.
4. Blocked/Waiting: A thread is in the blocked or waiting state when it's
temporarily inactive, waiting for a resource or condition to become
available.
5. Timed Waiting: A thread is in the timed waiting state when it's
temporarily inactive for a specified amount of time.
6. Terminated: A thread is in the terminated state when it has completed
execution or terminated due to an exception.
MyThread(String name) {
threadName = name;
}
Q. 4
(a) List four different inbuilt exceptions. Explain any one inbuilt
exception.
Four different inbuilt exceptions in Java are:
1. **NullPointerException**: Occurs when you try to access or invoke methods
on an object reference that is `null`.
2. **ArithmeticException**: Occurs when an arithmetic operation is attempted
with inappropriate operands.
3. **ArrayIndexOutOfBoundsException**: Occurs when you try to access an
array element at an invalid index.
4. **FileNotFoundException**: Occurs when an attempt to open the file
specified by a filename has failed.
Explanation of NullPointerException:
The `NullPointerException` is one of the most common exceptions in Java, and
it occurs when you try to access or invoke methods on an object reference that
is `null`, meaning the object has not been instantiated.
Example:
public class NullPointerExceptionExample {
public static void main(String[] args) {
String str = null;
// This line will throw a NullPointerException
int length = str.length();
}
}
In this example, `str` is assigned `null`, and attempting to access its `length`
property (`str.length()`) results in a `NullPointerException` because you cannot
invoke methods on a `null` object reference.
Handling `NullPointerException` involves ensuring that object references are
properly initialized before accessing their properties or invoking their methods,
or using conditional checks to handle `null` values appropriately.
(c) Write a java program to create a text file and perform read
operation on the text file.
Below is a short Java program to create a text file and perform a read operation
on the text file:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class FileReadWriteExample {
public static void main(String[] args) {
String fileName = "example.txt";
Q.5
(a) Explain Divide by Zero Exception in Java with example.
In Java, a Divide by Zero Exception, formally known as ArithmeticException,
occurs when attempting to divide an integer or floating-point number by zero.
This operation is not mathematically defined and results in an error condition.
Example:
public class DivideByZeroExample {
public static void main(String[] args) {
try {
int result = divide(10, 0); // Attempting to divide by zero
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("ArithmeticException occurred: " + e.getMessage());
}
}
(c) Write a java program to display the content of a text file and
perform append operation on the text file.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;