COURSE NAME: Object Oriented Programming Through Java
COURSE CODE: 231CS3T02
MID-II
1. a) Define an array. How can we initialize arrays? Explain with an example program
An array in Java is a collection of elements of the same data type stored in
contiguous memory locations..
An array is a sequence of objects of the same data type.
If the array elements have values in whole numbers, that is, of type int, the type of
array is also int.
If it is a sequence of characters, the type of array is char;
An array can hold objects of a class but cannot be a mixture of different data types.
Initialization of Arrays
You can initialize arrays in different ways:
1. Declaration and creation:
int[] numbers = new int[5]; // creates an array of 5 integers
2. Declaration, creation, and initialization together:
int[] numbers = {10, 20, 30, 40, 50};
3. Using the 'new' keyword with values:
int[] numbers = new int[] {10, 20, 30, 40, 50};
Initialization of Arrays
An array may be initialized by mentioning the values in braces and separated by
commas.
For example, the array pencils may be initialized as below:
int pencils [] = {4, 6, 8, 3};
Example program
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
[Link]("First element: " + numbers[0]);
[Link]("Second element: " + numbers[1]);
[Link]("Third element: " + numbers[2]);
}}
Output
First element: 10
Second element: 20
Third element: 30
b) Explain the concept of arrays of varying lengths and arrays as vectors.
Arrays of Varying Lengths
A two-dimensional array is treated as an array whose elements are one-dimensional
arrays, which may have different sizes.
A two-dimensional array may be declared as
int a2D [][] = new int [3 ][];
The arrays may as well be declared as int array [][] = {{5, 7, 8 },{10, 11 }, {4, 3, 2, 7,5 }};
Program
public class VaryingArray {
public static void main(String[] args) {
int[][] arr = new int[3][]; // 3 rows, columns not fixed
arr[0] = new int[2]; // 1st row has 2 columns
arr[1] = new int[4]; // 2nd row has 4 columns
arr[2] = new int[3]; // 3rd row has 3 columns
int num = 1;
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = num++;
[Link](arr[i][j] + " "); }
[Link]();
} }}
Output:
12
3456
789
Arrays as vectors
Similar to Arrays, vectors are another kind of data structure that is used for storing
information.
Using vector, we can implement a dynamic array.
The following are the vector constructors:
Vector() creates a default vector having an initial size of 10.
Vector(int size) creates a vector whose initial capacity is specified by size.
Example is
Vector vec = new Vector(5); // declaring with initial size of 5
Vector(int size, int incr)
Vectors have a number of advantages over arrays.
[Link] are dynamically allocated, and therefore, they provide efficient memory
allocation.
2. Size of the vector can be changed as and when required.
3. They can store dynamic list of objects.
4. The objects can be added or deleted from the list as per the requirement.
public class VectorArray {
public static void main(String[] args) {
int[] A = {2, 4, 6};
int[] B = {1, 3, 5};
int[] C = new int[3];
// Vector addition
for (int i = 0; i < [Link]; i++) {
C[i] = A[i] + B[i];
}
[Link]("Resultant Vector: ");
for (int x : C) {
[Link](x + " ");
} }}
Output:
Resultant Vector: 3 7 11
2. a) What is Method Overriding. Explain with an example program.
Overriding Method: If subclass has the same method as declared in the parent class, it is
known as method overriding.
Uses: runtime polymorphism
// Parent class
class Animal {
void sound() {
[Link]("Animal makes a sound");
}}
// Child class
class Dog extends Animal {
// Overriding sound() method
void sound() {
[Link]("Dog barks"); }}
public class TestOverride {
public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog();
[Link](); // Output: Animal makes a sound
[Link](); // Output: Dog barks
}}
b) What is interface in java? How do you implement Multiple Inheritance using Interfaces?
An interface in java is a blueprint of a class.
It has static constants and abstract methods. The interface in java is a mechanism to
achieve abstraction.
There can be only abstract methods in the java interface not method body.
It is used to achieve abstraction and multiple inheritance in Java.
• Using the keyword interface, you can fully abstract a class’ interface from its
implementation.
• That is, using interface, you can specify what a class must do, but not how it does it.
• Interfaces are syntactically similar to classes, but they lack instance variables, and their
methods are declared without any body
• Variables can be declared inside of interface declarations.
• They are implicitly final and static, meaning they cannot be changed by the implementing
class.
• They must also be initialized. All methods and variables are implicitly public.
Multiple inheritance using interfaces
// Interface 1
interface Printable {
void print();
}
// Interface 2
interface Showable {
void show();
}
// Class implementing multiple interfaces
class Display implements Printable, Showable {
// Providing implementation for both interface methods
public void print() {
[Link]("Printing from Printable interface");
}
public void show() {
[Link]("Showing from Showable interface");
}}
// Main class
public class MultipleInheritanceDemo {
public static void main(String[] args) {
Display obj = new Display();
[Link]();
[Link]();
}}
3. a) What is super keyword? Write a program to illustrate Multilevel Inheritance?
The keyword super is used for two purposes:
First, to distinguish between the variables having the same name in super class and
subclass.
When the member is called with an object of subclass, the subclass value will be
presented and super class value will get hidden.
For getting super class value, the keyword super is used.
Second, it is used in defining the constructor of subclass.
Instead of repeating the assignment of variables of super class, we simply qualify the
variable with super.
Multilevel inheritance
Class X {
public void methodX() {
[Link]("Class X method");
}
}
Class Y extends X {
public void methodY() {
[Link]("class Y method");
}
}
Class Z extends Y {
public void methodZ() {
[Link]("class Z method");
}
public static void main(String args[]) {
Z obj = new Z();
[Link](); //calling grand parent class method
[Link](); //calling parent class method
[Link](); //calling local method
}
}
b) What do you mean by Abstract classes and Interfaces? Explain the need of Interface
mechanism in programming.
Abstract classes
The abstract methods are not fully defined in super class.
An abstract class is a class declared with the abstract keyword that cannot be
instantiated directly
It can contain abstract methods—methods without a body or implementation (just a
declaration)
abstract class A {
abstract void callme();
void callmetoo() {
[Link]("This is a concrete method.");
}}
class B extends A {
void callme() {
[Link]("B's implementation of callme.");
}}
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
[Link]();
[Link](); }}
INTERFACES
An interface in java is a blueprint of a class.
It has static constants and abstract methods. The interface in java is a mechanism
to achieve abstraction.
There can be only abstract methods in the java interface not method body.
It is used to achieve abstraction and multiple inheritance in Java.
• Using the keyword interface, you can fully abstract a class’ interface from its
implementation.
• That is, using interface, you can specify what a class must do, but not how it does
it.
• Interfaces are syntactically similar to classes, but they lack instance variables, and
their methods are declared without any body
• Variables can be declared inside of interface declarations.
• They are implicitly final and static, meaning they cannot be changed by the
implementing class.
• They must also be initialized. All methods and variables are implicitly public
Need of Interface Mechanism in Programming
The interface mechanism in Java is introduced to achieve abstraction, multiple
inheritance, and loose coupling between classes.
It defines a contract that classes must follow, without specifying how the methods
are implemented.
4. a) What is Dynamic Binding? Explain with an example program?
Dynamic binding It is also called late binding. Here, the compiler is not able to
resolve the call (or binding) at compile time.
Method overriding is one such example where dynamic binding is involved.
method overriding: Dynamic binding primarily occurs in Scenarios involving method
overrinding, where a subclass provides its own Implementation for a me thod
already defined in it's Superclass
Polymorphism: When you have a reference variable of a Super class type that
points to an object of a class, and you Call an Override method on that reference,
Jvm determinus at Guntime which version of the method
Runtime object Type: The decision is made based on the actual type of the object .
class Animal {
void sound() {
[Link]("Animal makes a sound"); }}
class Dog extends Animal {
void sound() {
[Link]("Dog barks"); }}
class Cat extends Animal {
void sound() {
[Link]("Cat meows"); }}
public class DynamicBindingExample
public static void main(String[] args) {
Animal a; // Reference variable of parent clas
a = new Dog(); // Object of Dog class
[Link](); // Calls Dog’s version of sound()
a = new Cat(); // Object of Cat class
[Link](); // Calls Cat’s version of sound()
}}
b) Write a java program to demonstrate Single Inheritance.
5. a) Give brief description about the role of wrapper classes in java.
Primitive data types can be converted into object types by using the wrapper
classes contained in [Link] package.
A sample data type can also be converted into an object using Wrapper classes
As the name suggests, a Wrapper class wraps (le encloses) a primitive data type
and provides its object representation
Many data structures in Java are designed to operate on objects.
In such situations, we cannot use primitive data types with these data structures
For this, classes that encapsulate a primitive data type within an object are
provided in Java
The eight primitive data types, namely boolean, byte, short, int, long, float, double,
and char, are not objects of classes,
They cannot be passed on by references and they are passed on by value only
In order to provide object representation, eight Wrapper classes are defined in
[Link] package
The other two Wrapper classes are Boolean for boolean-type variables and
Character for chartype variables
public class WrapperExample {
public static void main(String[] args) {
int a = 10; // primitive type
Integer obj = a; // autoboxing
int b = obj; // unboxing
[Link]("a = " + a);
[Link]("Object = " + obj);
[Link]("b = " + b);
}}
Output:
a = 10
Object = 10
b = 10.
b) What is Exception Handling? Explain the advantages of Exception Handling.
Exception Handling:
• An exception is an abnormal condition that arises in a code sequence at run time.
Exception is a run time error.
• Java and other programming languages have mechanisms for handling exceptions that
you can use to keep your program from crashing. In Java, this is known as catching an
exception/exception handling.
• When java interpreter encounters an error, it creates an exception object and throws
it( informs us that an error occurred).
• If the exception object is not caught and handled properly, the interpreter will display a
message and stops the program execution.
• If we want the program to continue with the execution of the remaining code, then we
should try to catch the exception object thrown by the error condition and then display an
appropriate message for taking corrective actions.
Errors are broadly classified into two categories.
1. Compile time exception(error)
2. Run Time exception(error)
There are two types of exceptions in Java:
• Unchecked Exceptions
• Checked Exceptions
Java Exception handling is managed by 5 keywords:
1. try
2. catch
3. throw
4. throws
5. finally
advantages of Exception Handling.
Maintains Normal Program Flow
Separates Error Handling Code from Main Logic
Provides Meaningful Error Messages
Improves Program Reliability
6 a) Illustrate on how Packages can be created, defined and accessed.
a package is a mechanism to group related classes, interfaces, and sub-packages together.
It helps in organizing code, avoiding name conflicts, and providing access protection.
Packages are similar to folders on a computer, which store related files together.
Java provides two types of packages:
1. Built-in Packages (predefined)
2. User-defined Packages (created by the programmer)
Creating a Package:
A package is created using the package keyword at the top of the Java source file, before
any class or import statement.
Syntax:
package package_name;
Example:
package MyPackage;
public class Example {
public void display() {
[Link]("This is a user-defined package"); }}
Compiling the program:
> javac –d . [Link]
• -d tells java compiler to create a separate sub directory and place the .class file there.
• Dot (.) indicates that the package should be created in the current directory.
Accessing a Package:
Once a package is created, its classes can be accessed in another program in three ways:
1. Using Fully Qualified Name
[Link] obj = new [Link]();
[Link]();
2. Using import statement for a single class
import [Link];
class Test {
public static void main(String[] args) {
Example obj = new Example();
[Link](); }}
3. Using import statement for all classes
import MyPackage.*;
class Test {
public static void main(String[] args) {
Example obj = new Example();
[Link](); }}
Advantages of Using Packages:
1. Code Reusability
2. Avoids Name Conflicts
3. Access Protection
4. Easy Maintenance
5. Improves Readability and Structure
b) What do you mean by Auto-boxing and Auto-Unboxing? Explain with a suitable example.
Auto-boxing and Auto-unboxing:
The automatic conversion of primitive data types into its equivalent Wrapper type is
known as boxing and opposite operation is known as unboxing. This is the new feature of
Java5. So java programmer doesn't need to write the conversion code.
Advantage of Autoboxing and Unboxing:
No need of conversion between primitives and Wrappers manually so less coding is
required.
AutoBoxing Example:
class BoxingExample1 {
public static void main(String args[]) {
int a=50;
Integer a2=new Integer(a);//Boxing
Integer a3=5;//Boxing
[Link](a2+" "+a3); } }
UnBoxing Example
class UnboxingExample1 {
public static void main(String args[]) {
Integer i=new Integer(50);
int a=i;
[Link](a); } }
7. a) Elaborate on [Link] package and its classes.
The [Link] package is automatically imported in every Java program.
It provides fundamental classes and interfaces that are essential for Java programming.
Classes in this package are widely used for basic operations, type conversion, math
operations, string handling, thread management, and system-related tasks
1. Automatically imported in all Java programs; no need for explicit import.
2. Contains core classes for Java programming.
3. Provides classes for object handling, string manipulation, wrappers for primitive types,
math functions, and system operations.
4. Supports exception handling and multithreading.
Java. lang Package and its Classes:
The most important classes are of lang are
• Object, which is the root of the class hierarchy, and Class, instances of which .
represent classes at runtime.
protected Object clone()
boolean equals(Object obj)
protected void finalize()
Class getClass()
int hashCode()
void notify()
void notifyAll()
void wait()
String toString()
• The wrapper classes
BooleanCharacter
Integer
Short
Byte
Long
Float
Double
• The classes String, StringBuffer, and StringBuilder similarly provide commonly used
operations on character strings.
• Class Throwable encompasses objects that may be thrown by the throw statement.
Subclasses of Throwable represent errors and exceptions.
b) Define a Package. Explain the usage of a Package in a program.
A package in Java is a collection of related classes, interfaces, and sub-packages grouped
together under a common name.
It is similar to a folder or directory in a computer that organizes related files for easy
management.
Syntax to define a package:
package package_name;
Java provides two types of packages:
1. Built-in Packages (predefined)
2. User-defined Packages (created by the programmer)
Usage of a Package in a Program:
1. Organizing Classes
Packages help organize classes logically into groups, making large programs easier to
manage and maintain.
Example:
package MyPackage;
public class Demo {
public void show() {
[Link]("Welcome to MyPackage!"); } }
2. Avoiding Name Conflicts
Two classes with the same name can exist in different packages without conflict.
This ensures unique identification of classes using the package name.
3. Code Reusability
Classes inside a package can be reused in multiple programs by importing the package.
Example:
import [Link];
public class Test {
public static void main(String[] args) {
Demo obj = new Demo();
[Link](); } }
[Link] Packages
To access classes of a package, Java provides the import statement:
Ways to import:
1. Specific class: import package_name.ClassName;
2. Entire package: import package_name.*;
8. a) Briefly explain Checked Exceptions and Unchecked Exceptions.
Checked Exceptions:
• A checked exception is any subclass of Exception (or Exceptionclass itself), excluding
class RuntimeException and its subclasses.
• Checked exceptions must be handled by the programmer to avoid a compile-time error.
• There are two ways to handle checked exceptions.
o Declare the exception using a throws clause.
o catch the exception.
The compiler requires a throws clause or a try-catch statement for any call to a method
that may cause a checked exception to occur.
• Checked Exceptions are checked at compile time, where as unchecked exceptions are at
runtime.
Unchecked Exceptions:
• Unchecked exceptions are RuntimeExceptions and any of its
subclasses.
• Error class and its subclasses are also called unchecked exceptions.
• Compiler does not force the program to catch the exception or declare in a throws clause.
o Ex: ArithMeticException
• Unchecked exceptions can occur anywhere in a program and in a typical program can be
very numerous
b) Demonstrate the class Throwable with the help of a java program.
The class is declared as
public class Throwable extends Object
The class Throwable is super class to all the error and exception classes.
The program code can throw only objects of this class or objects of its subclasses.
Only the object of Throwable class or its subclasses can be the arguments of catch clause.
It would be a bad programming practice to throw Throwable or make Throwable as
argument of catch blocks because it will hide desirable information.
9. a) Explain the various states in the lifecycle of a Thread? Explain it with a neat diagram.
A) Lifecycle of a Thread in Java
A thread in Java passes through different states in its lifetime. These states are managed
by the Thread Scheduler and JVM. The various states are:
1. New State:When a thread is created using the Thread class, but the start() method has
not yet been called.
Example:
Thread t = new Thread();
[Link] State:After calling the start() method, the thread becomes runnable. It is ready
to run but the CPU decides when it will actually execute.
3. Running State:When the thread is picked by the scheduler, it starts executing its run()
method and enters the running state.
4. Blocked State:A thread enters the blocked state when it is waiting to acquire a lock on a
synchronized method or block that is held by another thread.
5. Waiting / Timed Waiting State:
Waiting: Thread waits indefinitely for another thread to perform a task (like using wait() or
join()).
Timed Waiting: Thread waits for a specific period using methods like sleep(time) or
wait(time).
6. Terminated State:
When the thread finishes execution (either normally or due to an error), it enters the
terminated state.
b) Write and explain the String buffer class.
A) StringBuffer Class in Java
The StringBuffer class in Java is used to create mutable strings, meaning the content of the
string can be changed after creation.
Unlike the String class (which is immutable), changes made to a StringBuffer object are
reflected in the same object without creating a new one.
It belongs to the package [Link].
Important Features:
1. Mutable: You can modify the contents (add, delete, insert, or replace).
2. Thread-safe: All methods are synchronized, so it is safe to use in multithreading.
3. Dynamic Capacity: It automatically expands when more characters are added.
Common Constructors:
StringBuffer() – creates an empty buffer with default capacity (16 characters).
StringBuffer(String str) – creates a buffer with the specified string.
StringBuffer(int capacity) – creates a buffer with given capacity.
Common Methods:
append(String s) – adds text at the end.
insert(int pos, String s) – inserts text at a position.
replace(int start, int end, String s) – replaces part of the text.
delete(int start, int end) – deletes characters.
reverse() – reverses the contents.
length() – returns current string length.
capacity() – returns total storage capacity.
Example:
class StringBufferExample {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
[Link](" World");
[Link](5, ",");
[Link]();
[Link](sb);
}
}
Output:
dlroW,olleH
10. a) Differentiate between the Thread class and Runnable Interface for creating a Thread
A) In java thread can be created in two ways:
1) By extending the thread class
2) By implementing the runnable interface
Both achieve the same goal,but they differ in structure and usage
EXAMPLE:
class MyThread extends Thread {
public void run() {
[Link]("Thread using Thread class");
}
}
class MyRunnable implements Runnable {
public void run() {
[Link]("Thread using Runnable interface");
}}
b) Develop a JDBC program to establish a link between MySQL and Java to access a table.
A) import [Link].*;
class JdbcExample {
public static void main(String[] args) )
String url = "jdbc:mysql:
String user = "root";
String password = "1234";
try {
[Link]("[Link]");
Connection con = [Link](url, user, password);
[Link](" Connection established successfully!");
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM students");
[Link]("\nStudent Table Data:");
while ([Link]()) {
[Link]([Link]("id") + " " + [Link]("name") + " " +
[Link]("age"));
}
[Link]();
[Link]("\nConnection closed.");
}
catch (Exception e) {
[Link]("Error: " + [Link]());
}
}
}
🔹 Steps Explained:
Load the JDBC driver:
[Link]("[Link]");
Establish connection:
[Link](url, user, password);
Create a statement:
Statement stmt = [Link]();
Execute SQL query:
ResultSet rs = [Link]("SELECT * FROM students");
Process results:
Read data using [Link](), [Link](), etc.
Close connection:
[Link]();