0% found this document useful (0 votes)
14 views

java 2024 (1)

The document is a Java exam paper for April 2024, containing questions and answers on various Java concepts such as JVM, JRE, access specifiers, exception handling, applets, and Java features. It includes both multiple-choice questions and brief explanations of topics like method overriding, data types, and the differences between character and byte streams. The paper serves as a comprehensive review of fundamental Java programming principles and practices.

Uploaded by

asharafmakani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

java 2024 (1)

The document is a Java exam paper for April 2024, containing questions and answers on various Java concepts such as JVM, JRE, access specifiers, exception handling, applets, and Java features. It includes both multiple-choice questions and brief explanations of topics like method overriding, data types, and the differences between character and byte streams. The paper serves as a comprehensive review of fundamental Java programming principles and practices.

Uploaded by

asharafmakani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

JAVA PAPER

APRIL-2024

Q-1(A) Attempt the following:

1. JVM stands for


Java Virtual Machine.
2. Who created Java programming language?
James Gosling.
3. JRE stands for
Java Runtime Environment.
4. Keywords cannot be used as a name of a variable, class, or method.

Q-1(B) Answer in brief (Any One)

1. Explain IIB block and vargs.

:- IIB (Instance Initialization Block): It is a block of code inside a class that runs
whenever an object of the class is created, before the constructor execution.

Vargs (Variable Arguments): It allows a method to accept multiple arguments of the


same type using the … notation, e.g., void sum(int… numbers).

2. Explain JDK components.

:- JDK (Java Development Kit) consists of three main components:

1. JVM (Java Virtual Machine): Executes Java bytecode


2. JRE (Java Runtime Environment): Provides runtime libraries and environment for
Java applications
3. Development Tools: Includes compilers, debuggers, and other utilities.

Q-2(A) Attempt the following:

1. Which package is used when we use StringBuffer class?


: java.lang
2. List out types of access specifiers in Java:
:- public

Private

Protected

Default (no modifier)

3. Is Gregorian Calendar comes under java.util package?


:- True

4. API stands for


:-Application Programming Interface

Q-2(B) Answer in brief (Any One)

1. Differentiate normal import and static import:

Normal Import: Imports an entire class, and methods must be


accessed using the class name.

import java.util.Scanner;

Scanner sc = new Scanner(System.in);

Static Import: Allows accessing static members directly without using the
class name.

import static java.lang.Math.*;

System.out.println(sqrt(25)); // No need to write Math.sqrt()

2. Explain abstract class:


An abstract class in Java is a class that cannot create objects on its own. It is used as a
base for other classes and contains abstract methods (without a body) that must be
completed by subclasses. It helps in reusing code and defining common behavior for
multiple classes.

Example:
abstract class Animal {
abstract void makeSound();
}
class Dog extends Animal {
void makeSound() {
System.out.println("Bark!");
}
}
Here are the answers to the given questions:

Q-3(A)Attempt the following:

1.Exception is a runtime error to handle.

2.Which method is used to start thread execution.


:- Start()

3.If an array index is out of range which exception generated.


:- ArrayIndexOutofBounds Exception

4.Which keyword is used to manually throw an exception.


:- Throw keyword

Q-3(B) Answer in brief (Any One)

1.Difference between Character Stream and Byte Stream:

Character Stream handles character data (text) and uses classes like FileReader and
FileWriter.
Byte Stream handles binary data (images, audio, etc.) and uses classes like
FileInputStream and FileOutputStream.

2.Difference between Daemonand Non-Daemon Thread:

Daemon Thread: Runs in the background, supporting other threads (e.g., Garbage
Collector).

Non-Daemon Thread: Executesindependently and does not terminate unless execution


completes.
Here are the answers to the questions from the image:

Q-4(A)Attempt the following:

1.Which function is used to display output of applet?

The paint(Graphics g) function is used to display output in an applet.

2.Which is the default layout manager for applet?

The default layout manager for an applet is FlowLayout.

3.Which method uses Graphics class object as argument?

The paint(Graphics g) method uses the Graphics class object as an argument.

4.Which method is called first by applet?

The init() method is called first when an applet starts execution.

Q-4(B)Answer in brief (Any One)


1.What is no layout manager?

When no layout manager is used, components must be placed manually using absolute
positioning with setBounds(x, y, width, height). This approach is known as null layout.

2.What is applet tag?

The <applet> tag in HTML is used to embed Java applets in a web page. It specifies
parameters like code, width, and height for loading an applet.

Example:
<applet code=”MyApplet.class” width=”300” height=”200”></applet>

Q-5 (A) Attempt the following

1. JFC stands for

:- Java Foundation Classes

2. Which package is needed to use swing components?

:-javax.swing

3. Swing components that do not rely on OS or GUI are known as

:-Lightweight components

4. AWT stands for:

:-Abstract Window Toolkit

(B) Answer in brief (Any One)

1 JTextField with Example:

JTextField is a class in Swing used to create a single-line text input field.


Example:

import javax.swing.*;
public class TextFieldExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JTextField Example");
JTextFieldtextField = new JTextField("Enter text here", 20);
frame.add(textField);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}

1. JComboBox:
JComboBox is a drop-down menu in Swing that allows users to select one item
from a list.
Example:

import javax.swing.*;
public class ComboBoxExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JComboBox Example");
String[] options = {"Apple", "Banana", "Cherry"};
JComboBox<String>comboBox = new JComboBox<>(options);
frame.add(comboBox);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}

(1)1.Explain features of java


Java is a widely used, versatile, and powerful programming language with several key
features that make it a popular choice for building various types of applications. Here
are the main features of Java:
1. Object-Oriented:
o Java follows the Object-Oriented Programming (OOP) paradigm. It allows
you to create reusable code by organizing software design around objects
and classes. Key principles of OOP in Java include encapsulation,
inheritance, abstraction, and polymorphism.
2. Platform Independence (Write Once, Run Anywhere):
o Java is platform-independent because of the Java Virtual Machine (JVM).
When you write a Java program, it is compiled into bytecode, which can
be run on any system with a compatible JVM. This makes Java code
portable across different operating systems and platforms.
3. Simple and Easy to Learn:
o Java syntax is based on C, but it eliminates some of the more complex
features like pointers and memory management, which makes it easier to
learn and use.
4. Secure:
o Java offers a secure environment for developing and running applications.
It includes several security features like bytecode verification, secure class
loading, and a security manager, which helps protect against viruses and
unauthorized access.
5. Multithreading:
o Java has built-in support for multithreading, which allows multiple tasks to
be executed simultaneously. This makes it suitable for applications that
require concurrency, like real-time applications, games, or web servers.
6. Robust:
o Java is known for its reliability due to features like automatic memory
management (garbage collection) and strong exception handling
mechanisms. It also provides tools for checking errors at compile-time and
runtime.
7. Portable:
o Since Java programs are compiled into bytecode, they can be run on any
device with a JVM, regardless of the underlying hardware or operating
system. This is a key benefit for distributed applications.
8. High Performance:
o Java provides performance optimizations such as Just-In-Time (JIT)
compilation and the use of the JVM for efficient execution. It may not be as
fast as languages like C++ but provides a good balance between
performance and portability.
9. Distributed Computing:
o Java has built-in APIs for developing distributed applications. These
include tools for networking, file handling, and accessing remote
resources, which makes Java ideal for creating web services, cloud
applications, and enterprise systems.
10. Dynamic:
o Java is dynamic in nature, meaning it can adapt to changes at runtime.
This includes dynamic class loading, which enables Java to load classes
dynamically as needed without having to recompile the program.
11. Rich API:
o Java comes with a vast set of libraries and APIs that support everything
from networking, file I/O, data structures, graphical user interfaces (GUIs),
databases, and more. This enables rapid application development (RAD).
12. Garbage Collection:
o Java has an automatic garbage collection mechanism, which helps
manage memory efficiently by automatically reclaiming memory used by
objects that are no longer needed, thus preventing memory leaks.
13. High-Level Language:
o Java is a high-level language that abstracts away low-level details, making
it easier for developers to focus on building applications without worrying
about managing hardware or memory manually.
14. Network-Centric:
o Java has built-in support for TCP/IP protocols and facilitates the creation
of network applications like web servers, clients, and chat applications.
15. Multiplatform Support:
o Java can be run on a variety of platforms, including Windows, Linux,
macOS, and mobile platforms (like Android), without modification to the
source code.

(1)2. Explain datatype


In Java, a data type defines the type of data that can be stored in a variable or passed
as an argument to a method. It specifies the size, range, and operations that can be
performed on the data. Java has two main categories of data types: Primitive data
types and Reference data types.
1. Primitive Data Types

Primitive data types are the most basic type of data in Java. They are predefined by the
language and represent simple values like numbers, characters, or booleans. There are
8 primitive data types in Java:
 byte:
o Size: 1 byte (8 bits)
o Range: -128 to 127
o Example: byte a = 100;
 short:
o Size: 2 bytes (16 bits)
o Range: -32,768 to 32,767
o Example: short b = 5000;
 int:
o Size: 4 bytes (32 bits)
o Range: -2^31 to 2^31-1 (approximately -2 billion to +2 billion)
o Example: int c = 100000;
 long:
o Size: 8 bytes (64 bits)
o Range: -2^63 to 2^63-1 (very large range)
o Example: long d = 10000000000L; (Note the "L" at the end)
 float:
o Size: 4 bytes (32 bits)
o Range: ±3.40282347E+38F (7 decimal digits)
o Used for representing decimal numbers (single precision)
o Example: float e = 10.5f; (Note the "f" at the end)
 double:
o Size: 8 bytes (64 bits)
o Range: ±1.7976931348623157E+308 (15 decimal digits)
o Used for representing decimal numbers (double precision)
o Example: double f = 3.14159;
 char:
o Size: 2 bytes (16 bits)
o Range: 0 to 65,535 (Unicode characters)
o Used for storing single characters or symbols
o Example: char g = 'A';
 boolean:
o Size: 1 bit (though JVM may use a byte for it)
o Values: true or false
o Example: boolean h = true;
2. Reference Data Types

Reference data types are more complex than primitive data types. They store
references (or memory addresses) to the actual data. These include objects, arrays,
and interfaces.
 Objects: An object is an instance of a class. In Java, a class defines the
structure and behavior of an object. Reference types store the memory address
of the object.
o Example:
String str = "Hello, World!";
 Arrays: An array is a collection of elements of the same type. The array itself is a
reference data type, which points to the memory location of the array elements.
o Example:
int[] numbers = {1, 2, 3, 4, 5};
Key Differences Between Primitive and Reference Data Types:

Feature Primitive Data Types Reference Data Types

Stores memory reference


Storage Stores actual values
(address)

Each primitive type has a default value, e.g.,


Default Value Default value is null
0 for int

Varies depending on the


Size Fixed size
object

Operations involve calling


Operations Can be operated directly
methods

int a =
Example String str = "Hello";
10;
(2)1.Explain method overriding with example

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


implementation of a method that is already defined in its superclass. The overriding
method in the subclass must have the same name, return type, and parameters as the
method in the superclass.
The purpose of method overriding is to modify or extend the behavior of an existing
method in the superclass, while keeping the method signature the same.
Key Points of Method Overriding:
1. Same Method Signature: The method in the subclass must have the same
name, return type, and parameters as the method in the superclass.
2. Runtime Polymorphism: Method overriding is a way of achieving runtime
polymorphism (or dynamic method dispatch), where the method that gets called
is determined at runtime based on the object type.
3. Access Modifier: The access modifier in the subclass method should be the
same or more permissive than the one in the superclass.
4. @Override Annotation: While not required, it is a good practice to use the
@Override annotation in the subclass to indicate that you are intentionally
overriding a method. This helps to avoid errors like incorrect method signature.
Example of Method Overriding

Let's say we have a superclass called Animal, and a subclass called Dog. Both classes
have a method sound(), but we want the Dog class to implement its own version of
sound().

// Superclass (Parent class)


class Animal {

// Method in superclass

void sound() {

System.out.println("Some generic animal sound");

}
// Subclass (Child class)

class Dog extends Animal {

// Overriding the sound() method in the subclass

@Override

void sound() {

System.out.println("Bark");

public class Main {

public static void main(String[] args) {

// Create an object of Animal

Animal animal = new Animal();

animal.sound(); // Calls the method in Animal class

// Create an object of Dog

Dog dog = new Dog();

dog.sound(); // Calls the overridden method in Dog class

// Using reference of Animal but creating an object of Dog

Animal animalDog = new Dog();

animalDog.sound(); // Calls the overridden method in Dog class

}
}
Output:

rust

Copy
Some generic animal sound

Bark

Bark
Explanation:
1. Superclass Method: In the Animal class, we define a method sound() that prints
"Some generic animal sound."
2. Subclass Method: In the Dog class, we override the sound() method. When
sound() is called on a Dog object, it prints "Bark" instead of the generic message
from Animal.
3. Using Reference of Superclass: In the Main class, when we use a reference of
type Animal but create an object of Dog, the overridden method in the Dog class
is called. This is an example of runtime polymorphism where the method call is
resolved at runtime based on the actual object type (Dog), not the reference type
(Animal).
Important Points:
 Method Overloading vs. Method Overriding:
o Method overloading occurs when two or more methods have the same
name but different parameters (different number or type of parameters).
o Method overriding occurs when a method in the subclass has the same
signature as a method in the superclass and provides a new
implementation.
 Super Keyword: If you want to call the overridden method in the superclass from
the subclass, you can use the super keyword.
o Example:
@Override

void sound() {

super.sound(); // Calls the method in the superclass

System.out.println("Bark");

}
Benefits of Method Overriding:
 Dynamic Polymorphism: It allows different behaviors for the same method
depending on the type of object.
 Code Reusability: You can reuse code from the superclass and modify its
behavior in the subclass as needed.
 Flexibility: It provides flexibility to extend or modify behavior without altering the
existing superclass code.
Method overriding is fundamental for building flexible and maintainable object-oriented
programs where subclasses can provide specific behavior for inherited methods.

Get smarter responses, upload files and images, and more.

(2)2. Explain with example math class and its methods


Math.abs(double a): Returns the absolute value of the argument.
Math.pow(double a, double b): Returns the value of a raised to the power of b (i.e.,
a^b).
Math.sqrt(double a): Returns the square root of the argument.

Math.max(double a, double b): Returns the larger of two values.

Math.min(double a, double b): Returns the smaller of two values.

Math.random(): Returns a random number between 0.0 (inclusive) and 1.0


(exclusive).
Math.round(double a): Returns the closest long to the argument, rounding up or
down as necessary.
Math.sin(double a): Returns the sine of the argument (in radians).

Math.cos(double a): Returns the cosine of the argument (in radians).


Math.log(double a): Returns the natural logarithm (base e) of the argument.

Example:
public class MathExample {

public static void main(String[] args) {

// Absolute Value

int a = -10;
double absValue = Math.abs(a);

System.out.println("Absolute value of " + a + " is: " + absValue);


// Power

double base = 2;

double exponent = 3;

double power = Math.pow(base, exponent);

System.out.println(base + " raised to the power of " + exponent + " is: " + power);

// Square Root
double number = 16;

double sqrtValue = Math.sqrt(number);

System.out.println("Square root of " + number + " is: " + sqrtValue);

// Maximum and Minimum

double x = 5.5;

double y = 7.2;

double maxValue = Math.max(x, y);

double minValue = Math.min(x, y);

System.out.println("Maximum of " + x + " and " + y + " is: " + maxValue);

System.out.println("Minimum of " + x + " and " + y + " is: " + minValue);

// Random Number (0.0 <= random < 1.0)

double randomValue = Math.random();

System.out.println("Random number between 0.0 and 1.0: " + randomValue);

// Round

double numberToRound = 7.8;

long roundedValue = Math.round(numberToRound);


System.out.println("Rounded value of " + numberToRound + " is: " + roundedValue);

// Trigonometric Functions (Sine and Cosine)

double radians = Math.PI / 2; // 90 degrees in radians

double sineValue = Math.sin(radians);

double cosineValue = Math.cos(radians);

System.out.println("Sine of 90 degrees (PI/2 radians) is: " + sineValue);

System.out.println("Cosine of 90 degrees (PI/2 radians) is: " + cosineValue);

// Logarithm (Natural log)

double logValue = Math.log(10);

System.out.println("Natural logarithm of 10 is: " + logValue);

Absolute value of -10 is: 10.0

2.0 raised to the power of 3.0 is: 8.0

Square root of 16.0 is: 4.0

Maximum of 5.5 and 7.2 is: 7.2

Minimum of 5.5 and 7.2 is: 5.5


Random number between 0.0 and 1.0: 0.6729738969897844

Rounded value of 7.8 is: 8

Sine of 90 degrees (PI/2 radians) is: 1.0

Cosine of 90 degrees (PI/2 radians) is: 6.123233995736766E-17


Natural logarithm of 10.0 is: 2.302585092994046

(3)1.Explain thread life cycle


In Java, the Thread Life Cycle refers to the various states a thread goes through from
its creation to its termination. The Java Thread API, part of the java.lang package,
helps manage this lifecycle. Here’s a breakdown of the key stages:

1. New (Created) State

 When it occurs: A thread is in this state immediately after it is created using the
Thread class or implementing the Runnable interface.
 How it happens: You create a thread instance but it hasn’t started running yet.
 Example:

Thread t = new Thread();

 Key Point: The thread is just an object here, not yet executing any code.

2. Runnable State

 When it occurs: After calling the start() method, the thread moves to the
runnable state. The thread is now ready to run but may not start immediately
because of thread scheduling by the OS.
 How it happens: The thread is waiting for CPU time to execute.
 Example:

t.start();

 Key Point: The thread scheduler decides when the thread actually runs, based
on priority, CPU availability, etc.

3. Running State

 When it occurs: The thread is actively executing its task. This is a subset of the
runnable state where the thread is actually running.
 How it happens: The CPU assigns time to the thread, and the thread's run()
method executes.
 Key Point: A thread may not run continuously—it can be preempted by other
threads.
4. Blocked State

 When it occurs: A thread is waiting to acquire a lock (monitor) that another


thread currently holds.
 How it happens: When a thread tries to enter a synchronized block or method
that another thread is using.
 Example:

synchronized (lock) {
// Critical section
}

 Key Point: The thread cannot proceed until the lock is released.

5. Waiting State

 When it occurs: A thread is waiting indefinitely for another thread to perform a


specific action.
 How it happens: Using methods like wait(), join(), or park().
 Example:

t.join(); // Waits for thread 't' to die

 Key Point: The thread remains in this state until another thread explicitly wakes
it up.

6. Timed Waiting State

 When it occurs: A thread is waiting for another thread to perform an action


within a stipulated amount of time.
 How it happens: Using methods like sleep(), wait(time), join(time),
parkNanos(), etc.
 Example:

Thread.sleep(2000); // Waits for 2 seconds

 Key Point: After the specified time, the thread automatically moves back to the
runnable state.
7. Terminated (Dead) State

 When it occurs: A thread has completed its execution or has been terminated
due to an exception.
 How it happens: The run() method has finished executing, or an unhandled
error caused the thread to stop.
 Key Point: The thread cannot be restarted once it has terminated.

1. Write a program to copy data one file to aother file

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

public class FileCopyExample {

public static void main(String[] args) {

// Specify the source and destination file paths

String sourceFile = "source.txt"; // Replace with your source file path

String destinationFile = "destination.txt"; // Replace with your destination file path

// Buffer size for reading and writing data

byte[] buffer = new byte[1024];

int bytesRead;

try (

FileInputStream fis = new FileInputStream(sourceFile);

FileOutputStream fos = new FileOutputStream(destinationFile)

){

// Reading from source and writing to destination

while ((bytesRead = fis.read(buffer)) != -1) {


fos.write(buffer, 0, bytesRead);

System.out.println("File copied successfully!");

} catch (IOException e) {

System.err.println("An error occurred during file copy: " + e.getMessage());

}
}

(4)2.Write a program to draw smiley face in javafx


public class Main {
int i,n;
int no[5];
int max,min;
int minp,maxp;
int s=0,avg=0;

printf("enter %d number:")
scanf("%d",n)

for(i=0; i<n; i++)


{
printf("enter %d element:",i+1)
scanf("%d",&no[i])
}
printf("\n")

for(i=0; i<n; i++)


{
printf("%d",no[i])
}
min[0]=0;
max[0]=0;
minp=0;
maxp=0;
for(i=0; i<n; i++)
{
if(no[i]>max)
{
i=max;
maxp=i;
}
if(no[i]<min)
{
i=min;
minp=i;
}
s=s+no[i]
avg=s\n
printf("sum=%d",s)
printf("avg=%d",avg)
printf("[%d]->max=%d",maxp+1,max)
printf("[%d]->min=%d",minp+1,min)

getch();
}
}

(5)2.Write a program to display message in textbox


when button is clicked
import javax.swing.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class MessageDisplayApp {

public static void main(String[] args) {

// Create a new JFrame


JFrame frame = new JFrame("Message Display Example");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(400, 150);

frame.setLayout(null);

// Create a text field

JTextField messageBox = new JTextField();


messageBox.setBounds(50, 30, 300, 30);

messageBox.setEditable(false); // Make it read-only

// Create a button

JButton displayButton = new JButton("Click Me!");

displayButton.setBounds(150, 70, 100, 30);

// Add action listener to the button


displayButton.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

// Set the message to be displayed in the text field

messageBox.setText("Hello, this is your message!");

});

// Add components to the frame

frame.add(messageBox);

frame.add(displayButton);

// Set the frame visibility

frame.setVisible(true);

}
}

JAVA APRIL-2024 5-Marker


1(1).What Is Inheritance? List Out types of inheritance and
explain any one with example in detail.

 In Java, Inheritance means creating new classes based on


existing ones. A class that inherits from another class can
reuse the methods and fields of that class.
 In addition, you can add new fields and methods to your
current class as well.

 Code Reusability: The code written in the Superclass is


common to all subclasses. Child classes can directly use the
parent class code.

 Method Overriding: Method Overriding is achievable only


through Inheritance. It is one of the ways by which Java
achieves Run Time Polymorphism.

 Abstraction: The concept of abstract where we do not have to


provide all details, is achieved through inheritance. Abstraction
only shows the functionality to the user.
 How to Use Inheritance in Java?

The extends keyword is used for inheritance in Java. Using


the extends keyword indicates you are derived from an existing
class. In other words, “extends” refers to increased
functionality.

Syntax :
class DerivedClass extends BaseClass
{
//methods and fields
}

 Example

class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

class Dog extends Animal {


void bark() {
System.out.println("The dog barks.");
}
}
public class InheritanceExample {

public static void main(String[] args) {


Dog myDog = new Dog();
myDog.eat();
myDog.bark();
}
}

 Output :
This animal eats food.
The dog barks.

Explanation:
 Animal is the base class with a method eat().
 Dog is the derived class that extends Animal and has its own
method bark().
 In the main method, we create an instance of Dog and call
both the inherited method eat() and the bark() method
defined in the Dog class.

 Java InheritanceTypes:

1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance

1. Single Inheritance
 In single inheritance, a sub-class is derived from only one
super class.
 It inherits the properties and behavior of a single-parent
class. Sometimes, it is also known as simple inheritance.

2. Multilevel Inheritance

 In Multilevel Inheritance, a derived class will be inheriting a


base class, and as well as the derived class also acts as the
base class for other classes.
 In Java, a class cannot directly access the grandparent’s
members.

3. Hierarchical Inheritance

 In Hierarchical Inheritance, one class serves as a superclass


(base class) for more than one subclass.

 Example:

class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}

class Cat extends Animal {


void meow() {
System.out.println("The cat meows.");
}
}

public class HierarchicalInheritanceExample {


public static void main(String[] args) {
Dog myDog = new Dog();
Cat myCat = new Cat();

myDog.eat();
myDog.bark();
myCat.eat();
myCat.meow();
}
}

Output:
 This animal eats food.
 The dog barks.
 This animal eats food.
 The cat meows.

4. Multiple Inheritance
 In Multiple inheritances, one class can have more than one
superclass and inherit features from all parent classes.
 Java does not support multiple inheritances with classes.
 In Java, we can achieve multiple inheritances only through
Interfaces.

5. Hybrid Inheritance
 It is a mix of two or more of the above types of inheritance.
 Since Java doesn’t support multiple inheritances with
classes, hybrid inheritance involving multiple inheritance is
also not possible with classes.
 In Java, we can achieve hybrid inheritance only through
Interface if we want to involve multiple inheritance to
implement Hybrid inheritance.
 inheritance does not necessarily require the use of Multiple
Inheritance exclusively.
 It can be achieved through a combination of Multilevel
Inheritance and Hierarchical Inheritance with classes,
Hierarchical and Single Inheritance with classes.
 Therefore, it is indeed possible to implement Hybrid
inheritance using classes alone, without relying on multiple
inheritance type.

Advantages Of Inheritance in Java:

 Code Reusability
 Abstraction
 Class Hierarchy
 Polymorphism

Disadvantages of Inheritance in Java:

 Complexity
 Overriding Issues

1(2). Write Short Note On Method Overloading.

 Definition: Method overloading is a feature in object-


oriented programming that allows a class to have more than
one method with the same name, but with different
parameters (different type, number, or both).

 This enables methods to perform similar functions while


accepting different types or numbers of inputs.
Key Points:

1. Same Method Name:

 All overloaded methods share the same name but differ in


their parameter lists.

2. Different Parameters:

a. Number of Parameters: For example, one method can


take two parameters while another takes three.
b. Type of Parameters: Methods can accept different
data types, such as integers, doubles, or strings.
c. Order of Parameters: The order of parameters can
also be different, allowing for further distinction.

3. Compile-Time Polymorphism:

 Method overloading is a form of compile-time


polymorphism, meaning the method to be executed is
determined at compile time based on the method signature.
4. Improved Readability:

 It enhances code readability and usability, allowing to use


the same method name for similar actions.

Example:

class MathOperations {
int add(int a, int b) {
return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}

double add(double a, double b) {


return a + b;
}
}

Advantages of Method Overloading:

 Code Clarity:
By using the same method name for similar operations, the
code becomes easier to read and understand.

 Reduced Complexity:
It reduces the need for multiple method names, which can
clutter the codebase.

 Flexibility:
We can create methods that handle various data types and
numbers of parameters, making the code more versatile.
Limitations of Method Overloading:

 Ambiguity:
If not designed carefully, overloaded methods can lead to
ambiguity, especially if the parameters are of similar types.

 Increased Complexity in Maintenance: While it can reduce


the number of method names, it may complicate
maintenance if the overloaded methods
havesignificantlydifferent implementations.
2(1). Write a short note on nested class and inner class and
differentiate them.

Nested Class and Inner Class in Java

 a nested class is a class defined within another class.


Nested classes are useful for logically grouping classes that
will only be used in one place, thereby making the code
more readable and maintainable.
 There are two main categories of nested classes:
 static nested classes and inner classes.

1. Nested Class:

 A nested class is simply any class that is defined inside


another class, but it can either be static or non-static.
 Static Nested Class:
A static nested class is declared with the static keyword and
can be instantiated without creating an instance of the outer
class.
It can access only static members (fields and methods) of
the outer class, but it cannot directly access instance
variables or methods of the outer class.

Example:

class Outer {
static int outerStaticVar = 100;

static class StaticNested {


void display() {
System.out.println("Static Nested Class accessing
outerStaticVar: " + outerStaticVar);
}
}
}

In this example, the StaticNested class can access the static


variable outerStaticVar, but it cannot access instance variables of
the outer class.

2. Inner Class:

 An inner class is a non-static nested class. It is


associated with an instance of the outer class, and it
has access to both static and non-static members of
the outer class. The inner class needs an instance of
the outer class to be created because it is bound to
the outer class's instance.

Key Differences Between Nested Class and Inner Class:


Advantages of Nested and Inner Classes:

1. Encapsulation: By nesting a class inside another, you can


encapsulate the inner class within the outer class, thus
promoting data hiding.

2. Readability: When a class is used only within a specific


context (i.e., inside another class), nesting it can make the
code more readable and logically grouped.

3. Increased functionality: Inner classes allow for more


specific behavior and interactions with the outer class,
especially when inner classes need to access instance
members of the outer class.
Conclusion:
 Nested classes are classes defined within another
class. They can either be static or non-static.

 Inner classes are always non-static nested classes


that can access both static and non-static members
of the outer class.

 The main difference between nested and inner


classes lies in their ability to access instance
variables and whether they require an instance of the
outer class to be instantiated.

2(2). How multiple inheritance is achieved using interface?


Explain with example.

 multiple inheritance (the ability of a class to inherit from


more than one class) is not directly supported through
classes.

 This is primarily done to avoid the complexity and ambiguity


that can arise, such as the diamond problem. However,
Java provides a mechanism to achieve multiple inheritance
through interfaces.

 An interface in Java is a reference type, similar to a class,


that can contain only abstract methods (methods without a
body) and constants (fields that are static and final).
 A class can implement multiple interfaces.

 Java allows a class to implement multiple interfaces,


meaning a class can inherit the behaviors (abstract
methods) from more than one interface.

 This way, a class can achieve multiple inheritance without


the ambiguity issues associated with class inheritance.

Key Points:

1. A class can implement multiple interfaces.

2. An interface can extend multiple interfaces (but not


classes).

3. Interfaces provide a way for different types of classes to


share common functionality, promoting flexibility in Java
programming.

Example:
interface Animal {
void eat();
void sleep();
}

interface Swim {
void swim();
}

class Dolphin implements Animal, Swim {


public void eat() {
System.out.println("Dolphin eats fish.");
}

public void sleep() {


System.out.println("Dolphin sleeps.");
}

public void swim() {


System.out.println("Dolphin swims in the ocean.");
}
}

public class Main {


public static void main(String[] args) {
Dolphin dolphin = new Dolphin();

dolphin.eat();
dolphin.sleep();
dolphin.swim();
}
}

Explanation:
 Animal Interface: This interface defines two methods
eat() and sleep(). These are the behaviors common to
all animals.
 Swim Interface: This interface defines the swim()
method, which specifies the swimming behavior

 Dolphin Class: The Dolphin class implements both the


Animal and Swim interfaces. It provides the
implementation for all the methods declared in both
interfaces.

 The Dolphin class achieves multiple inheritance by


implementing both the Animal and Swim interfaces.

 Even though Java doesn’t support multiple inheritance


through classes, the Dolphin class can still exhibit
multiple behaviors from different interfaces.

Advantages of Using Interfaces for Multiple Inheritance:

1. No Diamond Problem: Since interfaces don’t have


implementation, the diamond problem (where a class inherits
from two classes that have conflicting methods) does not
occur.

2. Code Reusability: Interfaces allow a class to inherit


behavior from multiple sources without creating unnecessary
dependencies.

3. Flexibility: Interfaces provide a flexible way to define a


contract that can be implemented by any class, allowing for
easy polymorphism.

Conclusion:
 Multiple inheritance is not supported directly via classes
in Java to avoid ambiguity.

 However, Java allows multiple inheritance using


interfaces, where a class can implement multiple
interfaces and inherit behaviours from them.

 By implementing multiple interfaces, a class can have


methods from different interfaces, enabling a form of
multiple inheritance without the complexity and potential
issues of class inheritance.
3.(1) Explain thread life cycle.

 In Java, the thread life cycle refers to the various states a


thread goes through during its existence.
 Threads in Java are represented by the Thread class and
go through several states, from creation to termination.
Below are the key states in the thread life cycle:
1. New (Born) State

 When a thread is first created using the Thread class


constructor (e.g., Thread t = new Thread();), it is in the
New state.

 At this point, the thread is not yet started, and the start()
method has not been called.
2. Runnable (Ready to run) State

 A thread moves to the Runnable state when the start()


method is called.

 It doesn't mean the thread is actually running; it simply


means that the thread is ready to be executed by the JVM
and is waiting for CPU time.

 In this state, the thread is either running or waiting to be


assigned CPU resources. Multiple threads can be in the
Runnable state at once, but only one thread is actually
executing at a time (depending on the operating system
and CPU scheduling).

3. Blocked (Waiting for a resource) State


 A thread enters the Blocked state when it wants to
access a synchronized resource but is blocked by another
thread holding the resource.
 This state occurs when a thread tries to acquire a lock on
a resource that is already locked by another thread.
 It remains in this state until the lock becomes available.
4. Waiting (Indefinitely waiting) State
 A thread enters the Waiting state when it calls methods
like wait(), join(), or sleep() that cause it to wait indefinitely
for another thread to perform a specific action.

 In the Waiting state, a thread does not consume any CPU


resources.
 For example, when a thread calls join() on another thread,
it enters the Waiting state until the other thread finishes
execution.

5. Timed Waiting (Waiting for a specific time) State

 A thread can enter the Timed Waiting state when it calls


methods like:
o sleep(millis) — makes the thread sleep for the specified
time.
o join(millis) — makes the thread wait for a specific time
for the other thread to finish.
o wait(millis) — makes the thread wait for a specific time
before waking up automatically.

 In this state, the thread will wake up either after the specified
time has passed or when notified (depending on the method
used).

6. Terminated (Dead) State

 A thread enters the Terminated state when it has


completed its execution or has been forcefully terminated.
 Once a thread reaches this state, it cannot be restarted. If
you want the thread to run again, you must create a new
thread object and start it again.

Key Notes:

 Threads are managed by the Java Virtual Machine


(JVM) and the underlying operating system.
 The state transitions are typically controlled by the
thread scheduler and the actions or methods invoked
within the program (e.g., wait(), sleep(), etc.).

3(2). Write a program to copy data of one file into another file.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileCopy {

public static void main(String[] args) throws IOException {

String sourceFile = "source.txt";


String destinationFile = "destination.txt";
FileInputStream fis = new FileInputStream(sourceFile);
FileOutputStream fos = new
FileOutputStream(destinationFile);

int byteData;

while ((byteData = fis.read()) != -1) {


fos.write(byteData);
}

fis.close();
fos.close();

System.out.println("File copied successfully!");


}

4. What is Layout? Explain Grid layoutwith example.

 In Java, Layout refers to the way components (like


buttons, text fields, labels, etc.) are arranged or
positioned within a container (like a JFrame, JPanel,
etc.).
 Layout managers in Java control the arrangement of
these components based on certain rules and
algorithms.
 They help in making applications look consistent and
adaptive to different screen sizes.

 Java provides several layout managers, including:


 FlowLayout – arranges components in a left-to-right
flow.
 BorderLayout – divides the container into five regions:
North, South, East, West, and Center.
 GridLayout – arranges components in a grid of rows
and columns.
 BoxLayout – arranges components either vertically or
horizontally.

GridLayout in Java

 The GridLayout arranges components in a rectangular grid


with a specified number of rows and columns. The
components are placed in the grid from left to right and top
to bottom. All components are given the same size.

Key Points about GridLayout:


 All components in the grid are of the same size (unless
manually set).

 It requires you to specify the number of rows and columns


when creating the GridLayout object.

 If there are more components than available grid cells, it will


span across additional rows or columns.

Syntax to create a GridLayout:


GridLayout grid = new GridLayout(rows, columns);

You can also specify the gap between components using the
constructor:

GridLayout grid = new GridLayout(rows, columns, hgap, vgap);

Example:

public class LoginForm extends Application {

public void start(Stage primaryStage) {


GridPane grid = new GridPane();

grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);

LabeluserLabel = new Label("Username:");


TextField userTextField = new TextField();
Label passLabel = new Label("Password:");
PasswordField passField = new PasswordField();

Button submitButton = new Button("Submit");


Button clearButton = new Button("Clear");

grid.add(userLabel, 0, 0); // Row 0, Column 0


grid.add(userTextField, 1, 0); // Row 0, Column 1
grid.add(passLabel, 0, 1); // Row 1, Column 0
grid.add(passField, 1, 1); // Row 1, Column 1
grid.add(submitButton, 0, 2); // Row 2, Column 0
grid.add(clearButton, 1, 2); // Row 2, Column 1

submitButton.setOnAction(e -> {
String username = userTextField.getText();
String password = passField.getText();
System.out.println("Username: " + username);
System.out.println("Password: " + password);
});

clearButton.setOnAction(e -> {
userTextField.clear();
passField.clear();
});

Scene scene = new Scene(grid, 300, 200);


primaryStage.setTitle("Login Form");
primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {


launch(args);
}
}

Output:

The result is a simple login form with:

 A label "Username:" followed by a text field to enter the


username.

 A label "Password:" followed by a password field to enter the


password.
 Two buttons: "Submit" to print the entered username and
password to the console, and "Clear" to clear both input
fields.

You might also like