0% found this document useful (0 votes)
14 views18 pages

Java Mid2

The document provides an overview of various Java programming concepts including arrays, method overriding, interfaces, multilevel inheritance, abstract classes, exception handling, and threading. It explains key features, syntax, and provides example programs for each concept. Additionally, it discusses the role of wrapper classes, the lifecycle of threads, and the differences between using the Thread class and Runnable interface for creating threads.

Uploaded by

govindaharish724
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)
14 views18 pages

Java Mid2

The document provides an overview of various Java programming concepts including arrays, method overriding, interfaces, multilevel inheritance, abstract classes, exception handling, and threading. It explains key features, syntax, and provides example programs for each concept. Additionally, it discusses the role of wrapper classes, the lifecycle of threads, and the differences between using the Thread class and Runnable interface for creating threads.

Uploaded by

govindaharish724
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

1a)Define an array. How can we initialize arrays?

Explain with an example


program

🔹 Definition of Array in Java

An array in Java is a collection of elements of the same data type stored in


contiguous memory locations.

It is a fixed-size data structure — once the size is declared, it cannot be


changed.

🔹 Array Declaration

dataType[] arrayName;

or

dataType arrayName[];

Example:

int[] numbers;

🔹 Array Initialization

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};

🔹 Example Program

class ArrayExample {

public static void main(String[] args) {

// Array declaration and initialization

int[] marks = {90, 80, 70, 60, 50};

// Displaying array elements

[Link]("Student Marks:");

for (int i = 0; i < [Link]; i++) {

[Link]("marks[" + i + "] = " + marks[i]);


}

🔹 Output

Student Marks:

marks[0] = 90

marks[1] = 80

marks[2] = 70

marks[3] = 60

marks[4] = 50

2. a) What is Method Overriding. Explain with an example program.

A)Method Overriding in Java is a feature that allows a subclass to provide


its own implementation of a method that is already defined in its
superclass.

1. The method name, parameters, and return type must be exactly same
as in the parent class.

2. It is used to achieve runtime polymorphism.

3. The @Override annotation is used to indicate overriding.

4. The child class method overrides the parent class method when both
are defined with the same signature.

5. The method that gets executed is decided at runtime, based on the


object type, not the reference type.

✅ Example:

class Animal {

void sound() {

[Link]("Animal makes sound");

class Dog extends Animal {

@Override

void sound() {
[Link]("Dog barks");

public class Main {

public static void main(String[] args) {

Animal a = new Dog();

[Link](); // Output: Dog barks

Output:

Dog barks

b) What is interface in java? How do you implement Multiple Inheritance


using Interfaces?

A)An interface in Java is a blueprint of a class.

It defines a set of abstract methods (methods without implementation)


that any class implementing the interface must provide an
implementation for.

It is used to achieve abstraction and multiple inheritance in Java.

✳ Key Features of Interfaces:

All methods in an interface are abstract (until Java 8).

Variables declared in an interface are public, static, and final by default.

A class uses the implements keyword to use an interface.

A class can implement multiple interfaces — this is how Java achieves


multiple inheritance.

🧱 Syntax Example:

interface Animal {

void eat();

interface Pet {

void play();
}

class Dog implements Animal, Pet {

public void eat() {

[Link]("Dog is eating.");

public void play() {

[Link]("Dog is playing.");

public class Main {

public static void main(String[] args) {

Dog d = new Dog();

[Link]();

[Link]();

3. a) What is super keyword? Write a program to illustrate Multilevel


Inheritance?

A) In Java, the super keyword is used to refer to the immediate parent


class (superclass) of the current class.

It is mainly used for three purposes:

1. To access parent class variables (when they are hidden by subclass


variables).

2. To call parent class methods (when overridden in subclass).

3. To call parent class constructor (to initialize parent class members)

Multilevel inheritance

Multilevel inheritance means a class is derived from another derived class.

class GrandParent {

GrandParent() {

[Link]("GrandParent constructor called");


}

void showMessage() {

[Link]("Message from GrandParent");

}}

class Parent extends GrandParent {

Parent() {

super(); // calls GrandParent constructor

[Link]("Parent constructor called");

void showMessage() {

[Link](); // calls GrandParent method

[Link]("Message from Parent");

class Child extends Parent {

Child() {

super(); // calls Parent constructor

[Link]("Child constructor called");

void showMessage() {

[Link](); // calls Parent method

[Link]("Message from Child");

public class MultilevelInheritanceExample {

public static void main(String[] args) {

Child obj = new Child(); // constructor chaining

[Link]();

[Link](); // method overriding with super calls


}

Output:

GrandParent constructor called

Parent constructor called

Child constructor called

Message from GrandParent

Message from Parent

Message from Child

b) What do you mean by Abstract classes and Interfaces? Explain the


need of Interface mechanism in programming.

A) Abstract Class:

An abstract class is a class that cannot be instantiated.

It can contain abstract methods (without body) and concrete methods


(with body).

It is used to provide a common base for subclasses and achieve partial


abstraction.

abstract class Animal {

abstract void sound(); // abstract method (no implementation)

void eat() { // concrete method

[Link]("All animals eat food.");

class Dog extends Animal {

void sound() {

[Link]("Dog barks.");

public class AbstractExample {


public static void main(String[] args) {

Animal obj = new Dog();

[Link]();

[Link]();

output:

All animals eat food.

Dog barks.

Interface:

An interface is a fully abstract class that defines only method declarations.

A class implements an interface and provides method definitions.

It is used to achieve multiple inheritance and loose coupling in Java.

// interface:

interface Vehicle {

void start();

void stop();

class Car implements Vehicle {

public void start() {

[Link]("Car started.");

public void stop() {

[Link]("Car stopped.");

public class InterfaceExample {

public static void main(String[] args) {

Vehicle v = new Car();


[Link]();

[Link](); }}

output:

Car started.

Car stopped.

Need for Interface Mechanism:

To achieve multiple inheritance.

To define a common contract for different classes.

To make programs more flexible, reusable, and maintainable.

4. a) What is Dynamic Binding? Explain with an example program?

A) Dynamic Binding (Runtime Polymorphism):

𝚛𝚞𝚗𝚝𝚒𝚖𝚎, not at compile time.


Dynamic Binding means that the method to be called is decided at

It occurs when a method is overridden in a subclass and is accessed


through a parent class reference.

It is also called Runtime Polymorphism.

💻 Example Program:

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 class

a = new Dog(); // Dog object

[Link](); // calls Dog's sound() -> runtime decision

a = new Cat(); // Cat object

[Link](); // calls Cat's sound()

🧾 Output:

Dog barks

Cat meows

5. a) Give brief description about the role of wrapper classes in java.

A) Role of Wrapper Classes in Java

Wrapper classes in Java are used to convert primitive data types (like int,
char, float, etc.) into objects.

Each primitive type has a corresponding wrapper class:

int → Integer, char → Character, float → Float, boolean → Boolean, etc.

They are mainly used in:

1. Collections Framework (like ArrayList, HashMap) — which store only


objects.

2. Data conversion between primitives and objects (autoboxing and


unboxing).

3. Utility methods (e.g., [Link](), [Link]()).

Example:

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.

A) Exception Handling in Java is a mechanism to detect and handle


runtime errors so that the normal flow of the program is not disrupted.

It allows the program to catch errors and take appropriate action instead
of abruptly terminating.

It uses keywords like try, catch, throw, throws, and finally.

Example:

public class ExceptionExample {

public static void main(String[] args) {

try {

int a = 10 / 0; // causes ArithmeticException

} catch (ArithmeticException e) {

[Link]("Error: Division by zero is not allowed.");

[Link]("Program continues...");

🧾 Output:

Error: Division by zero is not allowed.


Program continues...

Advantages of Exception Handling:

1. ✅ Maintains normal program flow — prevents program termination due


to errors.

2. ✅ Separates error-handling code from regular code — makes code


cleaner.

3. ✅ Identifies and handles specific errors easily using multiple catch


blocks.

4. ✅ Improves program reliability and robustness.

6 b) What do you mean by Auto-boxing and Auto-Unboxing? Explain with a


suitable example

A) A Wrapper class in Java is one whose object wraps or contains primitive


data types. This leads to two key features: Autoboxing and Unboxing.

1. Autoboxing

The automatic conversion of primitive types to the object of their


corresponding wrapper classes is known as autoboxing. For example:
conversion of int to Integer, long to Long, double to Double, etc.

class AutoBoxingExample {

public static void main(String[] args) {

// Primitive data type

int num = 10;

// Autoboxing: primitive → wrapper object

Integer obj = num; // automatically converts int to Integer

[Link]("Primitive value: " + num);

[Link]("Wrapper object value: " + obj)

}}

Auto Unboxing

It is just the reverse process of autoboxing. Automatically converting an


object of a wrapper class to its corresponding primitive type is known as
unboxing. For example, conversion of Integer to int, Long to long, Double
to double, etc.
class AutoUnboxingExample {

public static void main(String[] args) {

Integer obj = new Integer(200);

int num = obj;

[Link]("Wrapper object value: " + obj);

[Link]("Primitive value after auto-unboxing: " + num);

7b) Define a Package. Explain the usage of a Package in a program.

A) 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

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)

8. a) Briefly explain Checked Exceptions and Unchecked Exceptions.

A) 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.

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
S.N
Thread Class Runnable Interface
o

Runnable is an interface in
1 Thread is a class in Java.
Java.

To create a thread, we
To create a thread, we extend the
2 implement the Runnable
Thread class.
interface.

We implement the run()


We override the run() method directly
3 method of the Runnable
in the subclass.
interface.

We pass the Runnable object


We create a thread object using new
4 to a Thread object → new
MyThread().start();
Thread(obj).start();

Not suitable when your class already


Suitable because a class can
5 extends another class (Java doesn’t
implement multiple interfaces.
support multiple inheritance).

More flexible and commonly


6 Less flexible.
used

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:

1. Load the JDBC driver:


[Link]("[Link]");

2. Establish connection:
[Link](url, user, password);
3. Create a statement:
Statement stmt = [Link]();

4. Execute SQL query:


ResultSet rs = [Link]("SELECT * FROM students");

5. Process results:
Read data using [Link](), [Link](), etc.

6. Close connection:
[Link]();

You might also like