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

JAVA_sem ans

The document outlines various concepts in Java, including the usage of the 'static' keyword, constructors, classes and objects, access control, jagged arrays, abstract classes, packages, exception handling, threading, JDBC, and annotations. It also discusses command-line arguments, type casting, and the final keyword, along with Object-Oriented Programming principles. Each section provides definitions, examples, and explanations relevant to Java programming.

Uploaded by

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

JAVA_sem ans

The document outlines various concepts in Java, including the usage of the 'static' keyword, constructors, classes and objects, access control, jagged arrays, abstract classes, packages, exception handling, threading, JDBC, and annotations. It also discusses command-line arguments, type casting, and the final keyword, along with Object-Oriented Programming principles. Each section provides definitions, examples, and explanations relevant to Java programming.

Uploaded by

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

MODEL PAPER – 1 :- 2 MARKS

1a) List the various ways of 'static' keyword usage:


The static keyword in Java is versatile and can be used in several ways:
o Static Variables: These are shared among all instances of a class.
A static variable is initialized only once and retains its value
across instances.

class Example {
static int counter = 0;
}
o Static Methods: These methods belong to the class, not to any
specific instance, so they can be called directly on the class itself.
Static methods cannot access non-static (instance) variables
directly.

class Example {
static void display() {
System.out.println("Static method");
}
}
o Static Blocks: Static blocks execute when the class is first loaded.
They are typically used for static initialization of variables.

class Example {
static int count;
static {
count = 10;
}

1
}
o Static Nested Classes: A static class within a class can access only
static members of the outer class. It helps in logically grouping
classes and controlling the visibility of inner classes.

class Outer {
static class Inner {
void display() {
System.out.println("Static Nested Class");
}
}
}

1b) Define a constructor? When does the compiler supply a default


constructor for a class?

A constructor is a special method in Java that is called when an instance of a


class is created. Its main purpose is to initialize the object with default or
user-defined values. A default constructor is supplied by the compiler if no
constructors are defined in the class. It initializes instance variables to default
values (e.g., 0 for integers, null for objects).

1c) Define class and object in Java.


o Class: A class is a blueprint or template that defines the
attributes (fields) and behaviors (methods) common to all objects
of that type. It serves as the foundation for creating objects and
represents a real-world entity.
o Object: An object is an instance of a class. It represents a real-
world entity with specific characteristics and behaviors as

2
defined by the class. Each object has its own set of values for the
fields defined in the class.

1d) Explain why access control is important for methods in a class.

Access control is essential for encapsulation and security within a Java


program. It allows developers to control which parts of the code can access
certain methods and variables. By restricting access to sensitive data and only
exposing necessary methods, classes can protect their internal state, enforce
proper usage, and prevent unintended modifications. This is achieved through
the use of access modifiers: public, protected, default (package-private), and
private.

1e) Define arrays of varying lengths (jagged arrays) in Java.

Jagged arrays, also known as arrays of varying lengths, are arrays where
each row can have a different number of elements. In Java, a jagged array
is created by defining an array of arrays, where each sub-array can be of
different length. This structure is useful for representing data that
naturally fits an irregular grid.

int[][] jaggedArray = new int[3][];


jaggedArray[0] = new int[4]; // First row has 4 elements
jaggedArray[1] = new int[2]; // Second row has 2 elements
jaggedArray[2] = new int[5]; // Third row has 5 elements

3
1f) Explain why abstract classes are used in Java.

Abstract classes are used in Java to provide a base for other classes to extend
and to enforce a particular structure for subclasses. They are especially useful
when creating a hierarchy of classes with shared behavior, but where some
methods may not have a meaningful default implementation. Abstract classes
can contain both abstract methods (which subclasses must implement) and
concrete methods (which provide a default implementation).

abstract class Animal {


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

1g) Explain the process of defining a package in a Java program.

Packages are used to organize classes and interfaces in a structured way, often
reflecting the project’s structure or functionality. To define a package, the
package keyword is used at the top of the Java file, followed by the package
name. This not only helps in organizing code but also prevents naming
conflicts by creating unique namespaces.

package com.example.project;
public class MyClass {
// Class implementation
}
4
After defining a package, the class can be accessed in other parts of the
project by importing the package or using the full package name.

1h) Explain the use of try, catch, and finally blocks in Java.

o try block: This block contains code that may throw an exception.
o catch block: When an exception occurs in the try block, it is
caught by the appropriate catch block. Each catch block can
handle a specific type of exception.
o finally block: This block executes regardless of whether an
exception occurred. It’s useful for cleanup operations, like closing
resources.

try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("An error occurred: " + e.getMessage());
} finally {
System.out.println("Execution completed.");
}

1i) Describe the role of the Thread class in thread creation.

The Thread class is the primary way to create and manage threads in Java. A
thread represents a separate path of execution in a program. You can create a
thread by:
o Extending the Thread class and overriding its run method.

5
o Implementing the Runnable interface and passing it to a Thread
instance.

class MyThread extends Thread {


public void run() {
System.out.println("Thread running...");
}
}

1j) Explain the primary purpose of JDBC in Java applications.

JDBC (Java Database Connectivity) is an API that enables Java applications to


interact with databases. It allows Java programs to execute SQL statements,
retrieve data, and perform updates in a database-independent manner.
Through JDBC, developers can connect to any relational database and handle
database operations like queries, inserts, updates, and deletions.

import java.sql.*;
Connection connection = DriverManager.getConnection(url, username,
password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM myTable");

MODEL PAPER – 2 :- 2 MARKS


1a) List the main components of a simple Java program.

The main components of a simple Java program include:

6
Class Definition: The blueprint or structure for the program,
encapsulating data and behaviors.
Main Method: The entry point of the program (public static void
main(String[] args)).
Variables and Data Types: Used to store data and perform
operations.
Statements and Expressions: Instructions that control the flow of
the program, perform calculations, etc.
Comments: For documentation and readability, using // for single-
line comments and /* ... */ for multi-line comments.

1b) Write a Java program to take an integer and a string as input from the
console using the Scanner class.
Here’s a simple program that uses Scanner to take an integer and a string
as input.

import java.util.Scanner;

public class InputExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter an integer: ");


int number = scanner.nextInt();
scanner.nextLine(); // Consume the newline

System.out.print("Enter a string: ");


String text = scanner.nextLine();

7
System.out.println("You entered: " + number + " and \"" + text +
"\"");
scanner.close();
}
}

1c) Describe the components that can be part of a Java class, such as
fields, methods, and constructors.

Components of a Java class include:


Fields: Variables that hold the state or properties of an object. Fields
can be of any data type.
Methods: Functions within a class that define behaviors. Methods
can take parameters, perform actions, and return values.
Constructors: Special methods that initialize an object when it’s
created. Constructors have the same name as the class and do not
have a return type.
Inner Classes: Classes defined within a class. Useful for logical
grouping and encapsulation.

1d) Explain how method overriding works in Java.

Method overriding occurs when a subclass provides its own


implementation of a method that is already defined in its superclass. The
overridden method in the subclass must have the same name, return type,
and parameters as the method in the superclass. This allows for
polymorphism, where a subclass can be treated as an instance of its
superclass, but exhibit specific behavior.

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

class Dog extends Animal {


@Override
void sound() {
System.out.println("Bark");
}
}

1e) Define the purpose of the super keyword in inheritance.

The super keyword is used in Java to refer to the superclass of the current
class. It has several uses:
Accessing Superclass Methods: super.methodName() can call a
method from the superclass that has been overridden in the
subclass.
Calling Superclass Constructor: super() is used to invoke the
superclass constructor from the subclass constructor.
Accessing Superclass Fields: It allows access to fields in the
superclass when there’s a naming conflict.

class Animal {
String color = "brown";
}

9
class Dog extends Animal {
String color = "black";

void printColor() {
System.out.println(super.color); // Access superclass color
}
}

1f) Define the term "annotation" and list examples of commonly used
annotations in Java.

An annotation in Java is a form of metadata that provides information to


the compiler and JVM. Annotations do not change the program’s behavior
directly but are used to give instructions or indicate special properties.
Examples of Commonly Used Annotations:
@Override: Indicates that a method overrides a method in
its superclass.
@Deprecated: Marks a method or class as obsolete and
discouraged for use.
@SuppressWarnings: Suppresses specific warnings during
compilation.
@FunctionalInterface: Indicates an interface is a functional
interface with a single abstract method.

1g) Explain the purpose of the Math class in Java.

The Math class in Java provides a collection of methods for performing


mathematical operations, such as trigonometric, logarithmic, and
exponential functions. It also includes constants like Math.PI and Math.E.

10
The methods in the Math class are static, allowing for quick access without
creating an instance of the class.
Example Usage:

double result = Math.sqrt(25); // Square root of 25


double sine = Math.sin(Math.PI / 2); // Sine of 90 degrees

1h) Difference between throws and throw in Java?


throws: Used in a method signature to declare that a method might
throw one or more exceptions. It indicates that the calling code
should handle or declare these exceptions.

public void readFile() throws IOException {


// Code that might throw IOException
}
throw: Used within a method to explicitly throw an exception. It
allows the program to throw a specific exception, either predefined
or custom.

if (value < 0) {
throw new IllegalArgumentException("Value cannot be negative");
}

1i) Define JDBC.

JDBC (Java Database Connectivity) is an API that enables Java applications


to interact with relational databases. It allows Java programs to execute
SQL queries, retrieve results, and update data in a consistent and platform-

11
independent manner. JDBC is widely used for database operations in Java
applications.

1j) Describe the structure of a JavaFX application window.


A JavaFX application window typically consists of the following
components:
Stage: The main window or container where the GUI is displayed.
Scene: Holds all visual elements (nodes) within the stage. A stage can only
display one scene at a time.
Nodes: Individual components like buttons, labels, and text fields arranged
in a hierarchy to form the GUI.
Layouts: Containers that arrange nodes in specific patterns, such as VBox,
HBox, and GridPand

MODEL PAPER – 1 :- 5 MARKS


UNIT I
2. a) How can command-line arguments be passed to a Java program?
Provide an example of how they can be accessed within a program. (5
Marks)
Command-line arguments in Java are passed to the main method through
an array of String objects (String[] args). This array captures any text typed
after the program name when it is run from the command line, enabling
input without using a graphical user interface.
Detailed Example:

public class CommandLineExample {


public static void main(String[] args) {
// Check if arguments are passed
12
if (args.length > 0) {
System.out.println("Command-line arguments:");
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + i + ": " + args[i]);
}
} else {
System.out.println("No command-line arguments provided.");
}
}
}
How to Run:
1. Compile the program using:

javac CommandLineExample.java
2. Run it with command-line arguments:

java CommandLineExample Hello World 123


Output:

Command-line arguments:
Argument 0: Hello
Argument 1: World
Argument 2: 123
Explanation:
 In this example, args holds the command-line arguments, which are
accessed by their index in the array (args[i]).

13
 Using command-line arguments allows flexible input during runtime
without modifying the code.

2. b) Describe the difference between implicit and explicit type casting


with simple examples. (5 Marks)
In Java, type casting allows variables to be converted from one type to
another, and there are two main types: implicit and explicit casting.

 Implicit Type Casting (Automatic Conversion):


o Occurs when converting a smaller or less precise data type to a
larger or more precise data type.
o Handled automatically by Java when there’s no risk of data loss.
o Example: Converting an int to a double.

int num = 100;


double result = num; // Implicit casting from int to double
System.out.println("Result: " + result); // Output: 100.0

Explanation: Here, num (an int) is converted to double without explicit


casting because double can hold larger values than int.

 Explicit Type Casting (Manual Conversion):

14
o Needed when converting a larger or more precise data type to a
smaller or less precise one.
o Must be done manually by the programmer to avoid potential
data loss.
o Example: Converting a double to an int.

double value = 99.99;


int convertedValue = (int) value; // Explicit casting from double to int
System.out.println("Converted Value: " + convertedValue); // Output: 99
Explanation: Since casting from double to int may result in a loss of
information (e.g., decimal precision), an explicit cast ((int) value) is
required to perform the conversion.

OR
3. a) Explain the use of the final keyword in Java. What are its implications
when applied to variables, methods, and classes? (5 Marks)
In Java, the final keyword is used to enforce immutability and prevent
modifications to variables, methods, or classes.
1. Final Variable:
o A final variable can only be assigned once; after that, it becomes
a constant.
o Trying to modify a final variable will result in a compilation error.

final int MAX_SIZE = 100;


// MAX_SIZE = 200; // Compilation error
Implication: This feature is useful when defining constants or values that
should remain unchanged throughout the program’s execution.

15
2. Final Method:
o A final method cannot be overridden by subclasses.
o This is often used to prevent altering essential behavior in
subclasses.

class Animal {
public final void makeSound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {


// public void makeSound() {} // Error: cannot override final method
}
Implication: Using final methods helps maintain consistency in behavior
across all instances.
3. Final Class:
o A final class cannot be subclassed.
o This is helpful for creating immutable classes, such as String, and
ensuring that specific classes cannot be extended or modified.

public final class Constants {


public static final String APP_NAME = "MyApp";
}

// class SubClass extends Constants {} // Error: cannot inherit from final


class

16
Implication: Final classes provide security and prevent undesired
modifications in large applications.

3. b) Explain the concepts of Object-Oriented Programming. (5 Marks)


Object-Oriented Programming (OOP) is a programming paradigm centered
around the concept of objects and the four key principles: Encapsulation,
Inheritance, Polymorphism, and Abstraction.
1. Encapsulation:
o Bundles data (variables) and methods (functions) that operate on
the data into a single unit called a class.

o It restricts access to some components using access modifiers


(like private), promoting information hiding.

Example:

class Car {
private String color;
public String getColor() { return color; }
public void setColor(String color) { this.color = color; }
}
Explanation: The color attribute is private, accessed only through getter
and setter methods.
2. Inheritance:
o Allows one class (subclass) to inherit properties and behaviors
(methods) from another class (superclass).
o Supports code reusability and a logical hierarchy of classes.
Example:
17
class Animal {
void eat() { System.out.println("Eating"); }
}

class Dog extends Animal {


void bark() { System.out.println("Barking"); }
}
Explanation: Dog inherits the eat() method from Animal, reusing
functionality.
3. Polymorphism:
o Allows objects of different classes to be treated as objects of a
common superclass.
o Enables methods to perform differently based on the object
invoking them, supporting flexibility and scalability.
Example:
class Animal {
void sound() { System.out.println("Animal sound"); }
}

class Dog extends Animal {


void sound() { System.out.println("Bark"); }
}
Explanation: Method sound() behaves differently for Dog objects.
4. Abstraction:
o Focuses on hiding the complexity of implementation, showing
only essential features.
o Achieved through abstract classes and interfaces.
18
Example:

abstract class Shape {


abstract void draw();
}

class Circle extends Shape {


void draw() { System.out.println("Drawing Circle"); }
}
Explanation: Shape provides an abstract view; Circle provides specific
implementation.
OOP helps create modular, flexible, and maintainable code that reflects
real-world entities and relationships.

UNIT-2

4. (a) Explain the usage of constructor and types of constructors in Java. (5


Marks)
Constructors in Java are special methods used to initialize objects. They are
called when an object is created and set initial values for object attributes.
Constructors have the same name as the class and do not have a return type.

19
Types of Constructors:
1. Default Constructor: This constructor has no parameters. If no
constructor is defined in a class, Java provides a default constructor
that initializes objects with default values.

class Example {
int value;
// Default Constructor
Example() {
value = 10;
}
}
2. Parameterized Constructor: This constructor takes parameters to
initialize an object with specific values. It provides flexibility to initialize
objects in different ways.

class Example {
int value;
// Parameterized Constructor
Example(int val) {
value = val;
}
}
3. Copy Constructor: This constructor creates an object by copying values
from another object of the same class. Java does not provide an in-built
copy constructor, so it must be defined explicitly.

class Example {

20
int value;
// Copy Constructor
Example(Example e) {
this.value = e.value;
}
}

4. (b) Describe the scenarios in which this keyword is used. (5 Marks)


The this keyword in Java refers to the current instance of a class and is used in
various scenarios:
1. To refer to instance variables: It is used to differentiate between
instance variables and parameters with the same name.

class Example {
int value;
Example(int value) {
this.value = value; // Refers to instance variable
}
}
2. To call another constructor in the same class: It’s used to invoke a
different constructor within the same class, helping avoid code
duplication.

class Example {
int value;
Example() {
this(10); // Calls the parameterized constructor
}
21
Example(int value) {
this.value = value;
}
}
3. To pass the current object as a parameter: this can be used to pass the
current object as an argument to another method or constructor.

void display(Example e) {
// method body
}
void callDisplay() {
display(this); // Passes the current object
}
4. To return the current instance: It can be used to return the current
instance of a class, often used in method chaining.

Example getInstance() {
return this;
}

OR

5. (a) What is a recursive method? Provide an example of a recursive method


in Java. (5 Marks)
A recursive method in Java is a method that calls itself directly or indirectly to
solve a problem. Recursion is useful for problems that can be broken down
into smaller, similar problems. The recursive method must have a base case to
avoid infinite recursion.

22
Key Components of Recursion:
1. Base Case: This is the condition under which the recursive method stops
calling itself, preventing infinite recursion. Without a base case,
recursion would continue indefinitely, leading to a stack overflow error.

2. Recursive Call: In each recursive step, the method calls itself with a
modified parameter, bringing the problem closer to the base case with
each call.

3. Stack Mechanism: When a recursive method calls itself, Java places each
call on the call stack. The stack keeps track of each method call until it
reaches the base case, then it begins to unwind the calls, completing
each one in reverse order.

Example:
A recursive method to calculate the factorial of a number:

class FactorialExample {
// Recursive method to calculate factorial
int factorial(int n) {
if (n == 0) {
return 1; // Base case
} else {
return n * factorial(n - 1); // Recursive call
}

23
}
}

//For Example Let The n Value Be 5 Then The Output Would Be

Output:-

Factorial of 5 is: 120

5(b) Discuss the difference between passing arguments by value and by


reference. How does Java handle argument passing? (5 Marks)

Passing by Value means that a copy of the variable is passed, so any changes
made within the method do not affect the original variable.

Passing by Reference means that the reference (or memory address) is


passed, so changes to the parameter affect the original variable.

In Java, all arguments are passed by value. However:

 For primitive data types (like int, float), the value of the variable is
passed, and modifications inside the method do not affect the original
variable.

 For objects, the reference (or address) of the object is passed by value.
While the reference itself cannot be changed to point to a different

24
object, the fields within the object can be modified, affecting the
original object.

Example:

class Example {
int data;

void modifyPrimitive(int x) {
x = 20; // Change does not affect the original
}

void modifyObject(Example obj) {


obj.data = 20; // Change affects the original object
}
}

UNIT-3

6a) How can the size of an array be dynamically


changed in Java? Discuss the limitations of this
approach.

In Java, the size of an array cannot be changed once it


is created because arrays have a fixed size. However,
you can work around this limitation by creating a new
array with the desired size and copying the elements
from the original array to the new one. This can be
done using:

25
 Using Arrays.copyOf() method:

int[] original = {1, 2, 3};


int[] newArray = Arrays.copyOf(original, original.length
+ 1); // New array with size increased
newArray[3] = 4; // Adding new element to the array

 Using System.arraycopy():

int[] original = {1, 2, 3};


int[] newArray = new int[original.length + 1];
System.arraycopy(original, 0, newArray, 0,
original.length);
newArray[3] = 4; // Adding new element to the array

Limitations of this approach:

1. Memory Overhead: Creating a new array each time


to increase the size can lead to increased memory
usage, especially if the array grows repeatedly.

2. Performance: Copying elements from the old array


to the new one each time the size changes can be
inefficient for large arrays.

3. Fixed Size Limitation: Even though you can create a


new array, it still has a fixed size, and resizing it
again requires repeating the copying process.

26
6 b) Write different types of inheritance in Java and
give an example for each.

In Java, inheritance is a mechanism where one class


can inherit the properties and methods of another.
There are several types of inheritance:

1. Single Inheritance: A class inherits from a single


parent class.

Example:

class Animal {
void eat() {
System.out.println("Eating...");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Barking...");
}
}
2. Multilevel Inheritance: A class inherits from a class
that is already a subclass of another class.

o Example:

27
class Animal {
void eat() {
System.out.println("Eating...");
}
}

class Dog extends Animal {


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

class Puppy extends Dog {


void play() {
System.out.println("Playing...");
}
}

3. Hierarchical Inheritance: Multiple classes inherit


from a single parent class.
o Example:

class Animal {
void eat() {
System.out.println("Eating...");
}

28
}

class Dog extends Animal {


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

class Cat extends Animal {


void meow() {
System.out.println("Meowing...");
}
}
4. Multiple Inheritance (through interfaces): A class
can implement more than one interface (Note: Java
does not support multiple inheritance of classes).

o Example:

interface Animal {
void eat();
}

interface Mammal {
void giveBirth();
}

class Dog implements Animal, Mammal {

29
public void eat() {
System.out.println("Eating...");
}
public void giveBirth() {
System.out.println("Giving birth...");
}
}

OR

7. a) Describe how abstract classes differ from regular


(concrete) classes in Java.

An abstract class in Java is a class that cannot be


instantiated directly and is meant to be subclassed by
other classes. It may contain abstract methods (methods
without a body) that must be implemented by
subclasses.

Differences between abstract and concrete classes:

1. Instantiation:

o Abstract classes cannot be instantiated


directly.
o Concrete classes can be instantiated directly.

2. Abstract Methods:

30
o Abstract classes can have abstract methods
(without implementation).
o Concrete classes cannot have abstract methods
(all methods must have implementation).

3. Purpose:

o Abstract classes are used to provide a blueprint


for subclasses, defining common behavior that
must be shared or overridden.
o Concrete classes implement all methods and
can be used to create objects directly.

Example:

abstract class Animal {


abstract void sound(); // Abstract method
}

class Dog extends Animal {


void sound() {
System.out.println("Bark");
}
}

7b) Write a Java code snippet that includes a nested


interface and shows how it can be implemented.

31
In Java, an interface can be defined within a class
(nested interface). To implement it, a subclass of the
outer class must implement the nested interface.
Example:

class OuterClass {
interface NestedInterface {
void greet();
}

class InnerClass implements NestedInterface {


public void greet() {
System.out.println("Hello from the nested
interface!");
}
}
}

Public class Main {


public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new
InnerClass();
inner.greet();
}
}

32
UNIT – 4

8. a) Discuss the Math Class in Java. provide Examples of


common Mathematical operations performed using this
class.
The Math class in Java provides a collection of methods
to perform operations that are commonly used in
mathematical calculations. Some key features include:
 Static Methods: All methods in the Math class are
static, meaning they can be called directly without
creating an instance of the Math class.
 Precision: The class is optimized for precision and
performance, using algorithms designed to return
accurate results for most scientific and engineering
purposes.
Examples of Mathematical Operations with Detailed
Explanation:
1. Basic Arithmetic Operations – Although addition,
subtraction, multiplication, and division are done
with operators, Math provides methods for more
complex operations:
2. Square Root and Cubic Root:
Math.sqrt(double a)– Returns the square root
of a
Math.cbrt(double a) – Returns the cubic root of
a.
3. Trigonometric Functions – Methods for sine, cosine,
tangent, and their inverses:
4. Rounding and Ceiling Functions:
Math.ceil(double a) – Rounds a up to the nearest
integer.
Math.floor(double a) – Rounds a down to the
nearest integer.
5. Random Number Generation:

33
Math.random() – Generates a double value between
0.0 (inclusive) and 1.0 (exclusive).

public class MathExamples {


public static void main(String[] args) {
// Absolute value
System.out.println("Absolute of -5: " + Math.abs(-
5));

// Power
System.out.println("2 to the power of 3: " +
Math.pow(2, 3));

// Square root
System.out.println("Square root of 25: " +
Math.sqrt(25));

// Maximum and minimum


System.out.println("Maximum of 10 and 20: " +
Math.max(10, 20));
System.out.println("Minimum of 10 and 20: " +
Math.min(10, 20));

// Rounding operations
System.out.println("Ceiling of 5.3: " +
Math.ceil(5.3));
System.out.println("Floor of 5.7: " +
Math.floor(5.7));
System.out.println("Round of 5.5: " +
Math.round(5.5));

34
// Trigonometric functions
System.out.println("Sine of 45 degrees: " +
Math.sin(Math.toRadians(45)));
}
}

8. b) Exception Handling in Java


Exception handling in Java enables programs to manage
and respond to runtime errors gracefully without
abruptly stopping. Java provides built-in exceptions
(such as ArithmeticException, NullPointerException,
etc.) and allows users to create custom exceptions.
Key Components of Exception Handling:
1. try – Block that contains code which may throw an
exception.
2. catch – Block that handles specific exceptions
thrown in the try block.
3. finally – Optional block that executes code
regardless of whether an exception was thrown.
4. throw – Used to explicitly throw an exception.
5. throws – Declares exceptions that a method might
throw.

EXAMPLE:

public class ExceptionExample {


public static void main(String[] args) {
try {

35
int data = 100 / 0; // This will cause an
ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught an exception: " +
e.getMessage());
} finally {
System.out.println("This is always executed,
regardless of an exception.");
}
}
}

Benefits of Exception Handling:


1. Improves Program Reliability – By catching and
handling errors gracefully.
2. Separates Error Handling Code – Isolates error-
handling logic, making main logic more readable.
3. Allows Error Recovery – Provides an opportunity to
recover from errors and attempt alternative
actions.
OR

9(a) Creating a Custom Exception in Java


In Java, custom exceptions are used when the standard
exceptions don’t adequately describe the error you want
to handle. By creating your own exceptions, you can
provide more specific error messages and make your
code easier to understand and maintain.
Why Create a Custom Exception?
Custom exceptions help make the code self-explanatory
and improve readability. They are especially useful in

36
applications with specific requirements, where built-in
exceptions might not be descriptive enough.
Steps to Create and Use a Custom Exception:
1. Define a Custom Exception Class – Extend the
Exception class if it should be a checked exception
(requiring handling) or extend RuntimeException for
an unchecked exception.
2. Use the Custom Exception – Throw the custom
exception when a specific error condition occurs.
Example: Custom Exception for Bank Withdrawal
Imagine a banking application where an exception needs
to be thrown if someone tries to withdraw more money
than is available in their account.
Step 1: Define the custom exception class.
Step 2: Use the custom exception in a method that
performs the withdrawal.

EXAMPLE:
// Define and use a custom exception
class UnderageException extends Exception {
public UnderageException(String message) {
super(message);
}
}

public class VotingEligibility {


// Method to check eligibility
public static void checkEligibility(int age) throws
UnderageException {

37
if (age < 18) {
throw new UnderageException("You must be at
least 18 to vote.");
}
System.out.println("You are eligible to vote.");
}

public static void main(String[] args) {


try {
checkEligibility(16); // This will throw
UnderageException
} catch (UnderageException e) {
System.out.println("Exception caught: " +
e.getMessage());
}
}
}

Explanation:
1. Custom Exception (InsufficientFundsException) – A
specific exception that represents an insufficient
balance.
2. Withdrawal Method – Checks if the withdrawal
amount exceeds the balance; if it does, throws
InsufficientFundsException.
3. Usage in main Method – Calls withdraw with an
amount exceeding the balance, triggering the
exception and displaying an error message.

38
9. b) Packages in Java
Packages in Java are a way to group related classes and
interfaces, providing a modular structure to Java
applications. They also help in resolving naming
conflicts and controlling access through encapsulation.
Benefits of Using Packages:
1. Organized Codebase – Packages group classes
logically, making it easier to locate and maintain
code.
2. Avoid Naming Conflicts – Different packages can
have classes with the same name without collision.
3. Access Control – By organizing classes into
packages, you can control which classes are
accessible to other parts of the application.
Creating and Using Packages:
1. Defining a Package – Use the package keyword at
the beginning of a Java file.
EXAMPLE:
// File: utilities/MathUtilities.java
package utilities;

public class MathUtilities {


public static int square(int x) {
return x * x;
}
}

2.Using the Package – Import the package and access its


classes.

39
EXAMPLE:

import utilities.MathUtilities;

public class PackageExample {


public static void main(String[] args) {
System.out.println("Square of 5: " +
MathUtilities.square(5));
}
}

3.Compile and Run: Save the package files in folders


matching the package structure,compile with javac, and
run the program that imports it.

10. a) Comparison of StringBuilder, StringBuffer, and


String in Java
In Java, String, StringBuffer, and StringBuilder are used
to handle and manipulate strings, but they differ in
terms of mutability, synchronization, and performance.
1. String
 Immutable: Once a String object is created, it
cannot be changed. Any modification creates a new
String object.
 Performance: Slower when frequently modified, as
each change creates a new object.
 Use Case: Best for scenarios where the string
content doesn’t change, such as constant values or
simple concatenations.

40
Example:

String str = "Hello";


str = str + " World"; // Creates a new String object
2. StringBuffer
 Mutable: StringBuffer can be modified after creation
without creating new objects.
 Thread-Safe: Synchronized for thread safety,
making it slower than StringBuilder in single-
threaded applications.
 Use Case: Suitable for multi-threaded environments
where thread safety is required while modifying
strings.
Example:

StringBuffer sb = new StringBuffer("Hello");


sb.append(" World"); // Modifies the same StringBuffer
object
3. StringBuilder
 Mutable: StringBuilder is mutable and allows
modifications without creating new objects.
 Not Thread-Safe: Faster than StringBuffer because
it’s not synchronized.
 Use Case: Ideal for single-threaded scenarios where
performance is a priority, such as constructing
complex strings within a single thread.
Example:

StringBuilder sb = new StringBuilder("Hello");


sb.append(" World"); // Modifies the same StringBuilder
object
41
Summary:
 String: Immutable, slower for frequent
modifications.
 StringBuffer: Mutable, thread-safe, slower than
StringBuilder.
 StringBuilder: Mutable, non-thread-safe, best for
performance in single-threaded contexts.

10. b) suspend(), resume(), and stop() Methods in Java


Thread Management
The methods suspend(), resume(), and stop() were
originally used in Java for managing threads. However,
they are now deprecated due to potential deadlock
issues and unsafe thread management.
1. suspend()
 Purpose: Temporarily pauses the execution of a
thread, allowing it to resume later.
 Issues: Can cause deadlock if the thread holds
resources, as other threads may be indefinitely
blocked.
 Alternative: Use flags or wait() and notify() methods
for better control.
2. resume()
 Purpose: Resumes a thread that has been
suspended by suspend().
 Issues: When used with suspend(), it can cause
synchronization issues.
 Alternative: Use custom mechanisms to control
thread states safely.
3. stop()
 Purpose: Terminates a thread immediately.

42
 Issues: Unsafe as it stops a thread without
releasing resources, potentially causing memory
leaks.
 Alternative: Use a flag to signal the thread to
terminate gracefully.
Example of Safe Thread Management Using Flags:
Instead of suspend() and resume(), we can use a
boolean flag to control thread execution.

class SafeThread extends Thread {


private volatile boolean running = true;

public void stopThread() {


running = false;
}

public void run() {


while (running) {
System.out.println("Thread is running...");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println("Thread stopped safely.");
}
}

43
public class ThreadExample {
public static void main(String[] args) {
SafeThread thread = new SafeThread();
thread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.stopThread(); // Stops the thread safely
}
}
In this example, stopThread() changes the running flag,
allowing the thread to exit its loop safely.

OR

11. a) Components in JDBC Connection Process


The Java Database Connectivity (JDBC) API provides a
standard method for accessing relational databases. The
key components are:
1. DriverManager:
o Role: Manages a list of database drivers and
establishes a connection to the database.
o Example:

44
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:33
06/mydb", "user", "password");
2. Connection:
o Role: Represents the connection session with
the database. It allows creating statements and
managing transactions.
o Example:

Statement stmt = conn.createStatement();


ResultSet rs = stmt.executeQuery("SELECT * FROM
my_table");
3. SQLException:
o Role: An exception that handles database
access errors and other issues related to SQL.
o Example:

try {
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:33
06/mydb", "user", "password");
} catch (SQLException e) {
System.out.println("Database connection failed: " +
e.getMessage());
}
These components work together to open a connection,
perform SQL operations, and handle any potential
database-related exceptions.

11. b) Displaying Text and Images in a JavaFX


Application

45
JavaFX provides a modern GUI toolkit with controls for
displaying text and images, such as Label, Text, and
ImageView.
1. Label:
 Purpose: Displays a single line of read-only text.
 Example:

Label label = new Label("Hello, JavaFX!");

2. Text:
 Purpose: Displays text with more formatting options
and can support multi-line text.
 Example:

Text text = new Text("Welcome to JavaFX!");


text.setFont(new Font(20));
3. ImageView:
 Purpose: Displays images in the JavaFX scene.
 Example:

Image image = new Image("file:path/to/image.jpg");


ImageView imageView = new ImageView(image);
imageView.setFitWidth(200);
imageView.setPreserveRatio(true);
Complete Example:

46
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class JavaFXExample extends Application {


@Override
public void start(Stage stage) {
Label label = new Label("Hello, JavaFX!");
Text text = new Text("This is a text node
example.");
Image image = new
Image("file:path/to/image.jpg");
ImageView imageView = new ImageView(image);

VBox vbox = new VBox(label, text, imageView);


Scene scene = new Scene(vbox, 300, 300);
stage.setTitle("JavaFX Example");
stage.setScene(scene);
stage.show();
}

public static void main(String[] args) {


launch(args);

47
}
}

MODEL PAPER-2

UNIT-1

2. a) Explain the difference between primitive and


reference data types in Java. (5M)
Primitive Data Types:
 Java has eight primitive data types: int, byte, short,
long, float, double, char, and boolean.
 These types store actual values directly.
 They are defined by the language and are not
objects.
 They have fixed sizes and do not have methods
associated with them.
 Example: int a = 10; stores the integer value 10
directly in memory.
Reference Data Types:
 Reference data types store references (addresses)
to objects in memory rather than the actual data.
 They include arrays, classes, interfaces, and
strings.
 Reference types are created using constructors and
can be null.

48
 They do not have a fixed size and are stored in the
heap memory.
 Example: String str = "Hello"; stores a reference to
the String object.

 Example
 public class DataTypesExample {
 public static void main(String[] args) {
 // Primitive data type
 int primitiveInt = 50;

 // Reference data type
 Integer referenceInt =
Integer.valueOf(50);

 // Use primitive data type
 System.out.println("Primitive value: " +
primitiveInt);

 // Use reference data type
 System.out.println("Reference value: " +
referenceInt.toString());
 }
 }

Output:
Primitive value: 50
Reference value: 50

2. b) For-Each Loop in Java and Its Differences from a


Traditional For Loop
For-each is another array traversing technique like for
loop, while loop, do-while loop introduced in Java5.

 It starts with the keyword for like a normal for-loop.

49
 Instead of declaring and initializing a loop counter
variable, you declare a variable that is the same
type as the base type of the array, followed by a
colon, which is then followed by the array name.
 In the loop body, you can use the loop variable you
created rather than using an indexed array
element.

 It’s commonly used to iterate over an array or a


Collections class (eg, ArrayList)

Syntax:
for (type var : array)
{
statements using var;
}

Differences from Traditional For Loop:


 Read-Only Access: For-each loop provides read-only
access to elements and cannot modify the collection
directly.
 Simplified Syntax: Automatically iterates over all
elements without needing an index variable.
 Safety: Reduces the chance of errors related to
array boundaries.
 Use Case: Ideal for scenarios where each element
needs to be processed in sequence, such as printing
or summing values.

EXAMPLE USING FOR-EACH LOOP:

50
String[] names = {"Alice", "Bob", "Charlie"};
for (String name : names) {
System.out.println(name);
}

SAME EXAMPLE USING TRADITIONAL FOR LOOP

for (int i = 0; i < names.length; i++) {


System.out.println(names[i]);
}

OR
3a) Role of Each Type of Token in Java:

Tokens in Java represent the smallest units of code that


are meaningful to the compiler. Key token types include:

Keywords:
Keywords are pre-defined or reserved words in a
programming language. Each keyword is meant to
perform a specific function in a program. Since keywords
are referred names for a compiler, they can’t be used as
variable names

EXAMPLES: Boolean, Byte , Char , Double , Float , Int ,


Long , Short , Void , Class

Identifiers:

51
Identifiers are used as the general terminology for
naming of variables, functions and arrays. These are
user-defined names consisting of an arbitrarily long
sequence of letters and digits with either a letter or the
underscore (_) as a first character. Identifier names must
differ in spelling and case from any keywords.

EXAMPLE: MyVariable , MYVARIABLE , myvariable ,


_myvariable , $myvariable , sum_of_array , geeks123.

3. Constants/Literals:
Constants are also like normal variables. But the only
difference is, their values cannot be modified by the
program once they are defined. Constants refer to fixed
values. They are also called as literals.

Syntax:
final data_type variable_name;

4. Comments:
In Java, Comments are the part of the program which are
ignored by the compiler while compiling the Program.
They are useful as they can be used to describe the
operation or methods in the program. The Comments
are classified as follows:
 Single Line Comments
 Multiline Comments

SYNTAX
// This is a Single Line Comment
/*

52
This is a Multiline Comment
*/
5.Separators:
Separators are used to separate different parts of the
codes. It tells the compiler about completion of a
statement in the program. The most commonly and
frequently used separator in java is semicolon (;).

SYNTAX:
int variable; //here the semicolon (;) ends the
declaration of the variable

3b) Types of Control Statements in Java

In Java, control statements are used to control the flow


of execution of the program. They are broadly classified
into the following types:
1. Decision-Making Statements:
These are used to make decisions based on certain
conditions.
 if statement: Executes a block of code if the
specified condition is true.

SYNTAX:
if (condition) {
// code block
}
 if-else statement: Executes one block of code if the
condition is true, and another if the condition is
false.
SYNTAX:
53
if (condition) {
// code block
} else {
// code block
}

 if-else if-else statement: Checks multiple conditions


in a sequence.

SYNTAX:

if (condition1) {
// code block
} else if (condition2) {
// code block
} else {
// code block
}
 switch statement: Selects one of many code blocks
to execute based on the value of a variable.

SYNTAX:

switch (variable) {
case value1:
// code block

54
break;
case value2:
// code block
break;
default:
// code block
}
2. Looping (Repetition) Statements:
These are used to repeat a block of code multiple times
based on certain conditions.
 for loop: Repeats a block of code a specific number
of times.

SYNTAX:

for (int i = 0; i < 10; i++) {


// code block
}
 while loop: Repeats a block of code as long as the
condition is true.

SYNTAX:

while (condition) {
// code block
}
 do-while loop: Executes a block of code once before
checking the condition, and then repeats as long as
the condition is true.

55
SYNTAX:

do {
// code block
} while (condition);

3. Jump Statements:
These are used to transfer control to another part of the
program.
 break statement: Exits from a loop or a switch
statement.

SYNTAX:

break;
 continue statement: Skips the current iteration of a
loop and continues with the next iteration.

SYNTAX:

continue;

 return statement: Exits from the current method


and optionally returns a value.

SYNTAX:

56
return;

UNIT-2
4a.) Distinguish Between Method Overloading and
Method Overriding

Method Overloading and Method Overriding are both


key concepts in object-oriented programming, but they
serve different purposes:
1. Method Overloading:
 Definition: Method overloading occurs when
multiple methods with the same name exist in the
same class but with different parameters (either in
number or type).
 Purpose: It allows a class to have more than one
method with the same name, each performing
similar tasks but with different input arguments.
 Parameters: Overloaded methods must differ in the
number or type of parameters, but they cannot
differ by return type alone.
 Binding Type: It is resolved at compile time, also
known as compile-time polymorphism.
 Example:

class MathOperations {
// Overloaded methods
int add(int a, int b) {
return a + b;
}
57
double add(double a, double b) {
return a + b;
}
}

2. Method Overriding:
 Definition: Method overriding occurs when a
subclass provides a specific implementation for a
method that is already defined in its superclass,
with the same method signature (name, return
type, and parameters).
 Purpose: It allows a subclass to modify or extend
the behavior of an inherited method from the
superclass.
 Parameters: The method in the subclass must have
the same parameter list as in the superclass.
 Binding Type: It is resolved at runtime, also known
as runtime polymorphism.
 Example:

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

class Dog extends Animal {


// Overriding method
@Override

58
void sound() {
System.out.println("Bark");
}
}

4. b) Design a Java Class that Demonstrates the Use of


Both Final and Static Methods
59
class Example {
// Static method
static void staticMethod() {
System.out.println("This is a static method.");
}

// Final method
final void finalMethod() {
System.out.println("This is a final method.");
}

public static void main(String[] args) {


// Calling the static method
Example.staticMethod();

// Creating an object to call the final method


Example obj = new Example();
obj.finalMethod();
}
}

OUTPUT:

This is a static method.


This is a final method.

60
 Static method: Can be called without creating an
instance of the class (i.e., Example.staticMethod()).
 Final method: Cannot be overridden in any subclass,
but can be called like any other method from the
instance of the class (i.e., obj.finalMethod()).

Explanation of Execution Flow:


1. Define static and final methods in the Example
class.
2. Call the static method using the class name
(Example.staticMethod()).
3. Create an object of the class (Example obj = new
Example();).
4. Call the final method using the created object
(obj.finalMethod();).
5. Output: Print statements from both method calls.

OR
5. a) Discuss the Concept of Access Control in Methods.
How do Access Modifiers Affect Method Visibility?
In Java, access modifiers control the visibility and
accessibility of methods to other classes or packages.
The main access modifiers are:

61
1. Public (public): The method is accessible from
anywhere, both within the same package and from
other packages.

2. Private (private): The method is accessible only


within the same class. It cannot be accessed
outside the class.

3. Protected (protected): The method is accessible


within the same package and by subclasses (even if
they are in different packages).

4. Default (no modifier): If no access modifier is


specified, the method is accessible only within the
same package.

EXAMPLE:

class AccessControlExample {

// Public method - accessible from anywhere


public void publicMethod() {
System.out.println("Public method can be accessed
from anywhere.");
}

// Private method - accessible only within the same


class
private void privateMethod() {

62
System.out.println("Private method can only be
accessed within the same class.");
}

// Protected method - accessible within the same


package and subclasses
protected void protectedMethod() {
System.out.println("Protected method can be
accessed within the same package or subclasses.");
}

// Default (package-private) method - accessible only


within the same package
void defaultMethod() {
System.out.println("Default method can be
accessed only within the same package.");
}

public static void main(String[] args) {


AccessControlExample obj = new
AccessControlExample();

// Accessing methods
obj.publicMethod(); // Accessible
// obj.privateMethod(); // Error: privateMethod()
has private access in AccessControlExample
obj.protectedMethod(); // Accessible
obj.defaultMethod(); // Accessible within the
same package
}

63
}

Effect on Method Visibility:


 Public methods can be accessed from anywhere in
the program.

 Private methods are only accessible within the class


where they are defined, ensuring encapsulation.

 Protected methods are accessible by subclasses and


classes in the same package, allowing for extended
functionality.

 Default methods are restricted to the package,


limiting the visibility to classes within the same
package.

5. b) What are Nested Classes in Java? Discuss the


Difference Between Static Nested Classes and Inner
Classes with Examples.

Nested Classes in Java are classes defined within other


classes. These can be categorized into two types:

1. Static Nested Class:

64
o A static nested class is associated with its
enclosing class, but it does not have access to
the instance variables and methods of the
outer class.
o It can be instantiated without an instance of
the enclosing class.

Example:
class Outer {
static int outerVar = 10;

static class StaticNested {


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

public class Main {


public static void main(String[] args) {
Outer.StaticNested nested = new
Outer.StaticNested();
nested.display();
}
}

65
2. Inner Class:
o An inner class is associated with an instance of
its enclosing class. It has access to the instance
variables and methods of the outer class.
o It must be instantiated through an instance of
the enclosing class.
Example:

class Outer {
int outerVar = 10;

class Inner {
void display() {
System.out.println("Inner Class: " + outerVar);
}
}
}

public class Main {


public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display();
}
}
Key Differences:

66
Aspect Static Nested Class Inner Class
Belongs to the
Requires an instance
enclosing class, but
of the enclosing
Association does not need an
class to be
instance of the
instantiated.
enclosing class.
Cannot access non- Can access both
Access to static members of the static and non-static
Outer Class enclosing class members of the
directly. enclosing class.
Can be instantiated Must be instantiated
Instantiatio
without an object of through an instance
n
the outer class. of the outer class.

UNIT III

6. a) What is a Two-Dimensional Array? Provide an


Example of Declaring, Initializing, and Accessing a Two-
Dimensional Array
A two-dimensional array in Java can be visualized as a
grid or matrix with rows and columns. It allows you to
store data in a structured form where each element can
be accessed via two indices: one for the row and one for
the column.
 Declaration: A two-dimensional array is declared by
specifying two sets of square brackets.
 Initialization: The array can be initialized at the
time of declaration or later by using nested curly
braces {}.

67
 Accessing: You access elements using the row and
column index. Arrays in Java are zero-indexed,
meaning the first element of the array is at index 0.
Types of Two-Dimensional Arrays:
1. Rectangular Arrays: All rows have the same number
of columns.
2. Jagged Arrays: Each row can have a different
number of columns.
Detailed Example:

public class TwoDimensionalArrayExample {


public static void main(String[] args) {
// Declare and initialize a 2D array (3 rows, 3
columns)
int[][] matrix = new int[3][3];

// Assigning values to the 2D array


matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[1][0] = 4;
matrix[1][1] = 5;
matrix[1][2] = 6;
matrix[2][0] = 7;
matrix[2][1] = 8;
matrix[2][2] = 9;

// Accessing a specific element (row 1, column 2)

68
System.out.println("Element at [1][2]: " + matrix[1]
[2]);

// Loop to display all elements


System.out.println("All elements in the 2D array:");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
Explanation:
 The array matrix[3][3] represents a 3x3 grid.
 Each element is accessed using two indices: [row]
[column].
 The loop prints all elements row by row.

6. b) What is Dynamic Method Dispatch? Provide an


Example Demonstrating Its Use in Java
Dynamic method dispatch (or runtime polymorphism)
occurs when Java decides at runtime which method to
call. This is important in object-oriented programming as
it allows for method overriding, where a subclass

69
provides a specific implementation of a method declared
in its superclass.
When a method in a subclass overrides a method in the
superclass, the decision about which method to invoke
is made dynamically based on the actual object type, not
the reference type.
Example:

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

class Dog extends Animal {


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

class Cat extends Animal {


void sound() {
System.out.println("Cat meows");
}
}

public class DynamicDispatchExample {

70
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Animal
reference and object
Animal myDog = new Dog(); // Animal reference
but Dog object
Animal myCat = new Cat(); // Animal reference
but Cat object

myAnimal.sound(); // Output: Animal makes a


sound
myDog.sound(); // Output: Dog barks
myCat.sound(); // Output: Cat meows
}
}

Explanation:
 The sound() method is dynamically dispatched to
the correct subclass method based on the actual
object type.
 At runtime, Java decides which version of sound() to
invoke, even though the reference type is Animal.
OR

7. a) How is an Interface Implemented in a Class?


Provide an Example of a Class That Implements an
Interface
An interface in Java is a blueprint for classes, containing
abstract methods (without a body) that must be
implemented by any class that declares it implements
the interface.
Steps to implement an interface:

71
1. Declare the interface using the interface keyword.
2. Use the implements keyword in the class to
implement the interface.
3. The class must provide concrete implementations
for all abstract methods of the interface.

Example:

interface Animal {
void sound(); // Abstract method
}

class Dog implements Animal {


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

class Cat implements Animal {


public void sound() {
System.out.println("Cat meows");
}
}

public class InterfaceImplementation {


public static void main(String[] args) {

72
Animal myDog = new Dog(); // Reference of type
Animal, object of type Dog
Animal myCat = new Cat(); // Reference of type
Animal, object of type Cat

myDog.sound(); // Output: Dog barks


myCat.sound(); // Output: Cat meows
}
}

Explanation:
 The Animal interface defines a method sound(),
which both Dog and Cat classes implement.
 The classes provide their own implementations of
the sound() method.
 The classes are able to be referenced as Animal,
demonstrating polymorphism.

7b) What is Multilevel Inheritance? Provide an


Example Demonstrating the Concept

Multilevel inheritance occurs when a class inherits from


another class, which itself is derived from a third class.
This creates a chain of inheritance where a class can
inherit properties and methods from multiple classes in
the hierarchy.
Example:

class Animal {
void eat() {
73
System.out.println("Animal eats");
}
}

class Dog extends Animal {


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

class Puppy extends Dog {


void play() {
System.out.println("Puppy plays");
}
}

public class MultilevelInheritance {


public static void main(String[] args) {
Puppy myPuppy = new Puppy();
myPuppy.eat(); // Inherited from Animal
myPuppy.bark(); // Inherited from Dog
myPuppy.play(); // Defined in Puppy
}
}
Explanation:

74
 The Puppy class extends Dog, which itself extends
Animal.
 The Puppy class inherits methods from both Dog
and Animal.
 This demonstrates multilevel inheritance as the
Puppy class forms the third level of the inheritance
chain.

UNIT-4

8. a) List and Describe the Standard Packages Available


in Java SE. How Do They Contribute to the Java Standard
Library?
Java SE provides a wide variety of built-in standard
packages that help developers by offering ready-to-use
functionality. These packages save time by providing
commonly used features, such as mathematical
operations, file handling, collections, networking, and
graphical interfaces.
Some key packages include:

1. java.lang:
o Contains fundamental classes like String, Math,
System, and Thread.
o Automatically imported into every Java
program.
o Contribution: Provides essential classes for
basic programming tasks (e.g., string
manipulation, system operations, and
threading).
2. java.util:

75
o Contains utility classes like ArrayList, HashMap,
Date, Calendar, and Random.
o Contribution: Provides tools for working with
collections, data structures, and dates. It is
crucial for managing data efficiently in Java.
3. java.io:
o Includes classes for input and output
operations like File, BufferedReader,
PrintWriter, and FileReader.
o Contribution: Provides classes for reading from
and writing to files, handling streams, and
serializing objects.
4. javax.swing:
o Used for building graphical user interfaces
(GUIs) with components like JFrame, JButton,
and JLabel.
o Contribution: Enables the development of
desktop applications with rich user interfaces.
Example: Here’s a small example using the java.util
package to demonstrate the use of ArrayList:

import java.util.ArrayList;

public class Example {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>(); //
Create an ArrayList
list.add("Apple"); // Add elements
list.add("Banana");
list.add("Orange");

76
System.out.println("Fruits List: " + list); // Output
the list
}
}

OUTPUT:

Fruits List: [Apple, Banana, Orange]

Explanation:
 The ArrayList class from the java.util package is
used to store a dynamic list of strings.
 The program demonstrates adding items to the list
and printing them. The ArrayList class helps
manage collections of data more efficiently than
arrays in Java.

8. b) What is the Purpose of Multiple Catch Clauses in


Java? Provide an Example Demonstrating Their Use.
In Java, multiple catch clauses allow handling different
types of exceptions that may arise from a single try
block. By using multiple catch clauses, you can catch
and handle various specific exceptions separately and
apply different recovery mechanisms for each one.
Purpose:
 Specific Handling: Each catch block can handle
different types of exceptions (e.g.,
FileNotFoundException, IOException).
 Order of Exceptions: The more specific exceptions
should come before general ones. For instance,
catch a FileNotFoundException before catching a

77
general Exception because the latter can catch any
exception, including specific ones.
 Improved Readability and Maintainability: Multiple
catch clauses allow for cleaner, more maintainable
code by clearly defining the response to different
exceptions.
Example:

import java.io.*;
public class MultipleCatchExample {
public static void main(String[] args) {
try {
// Attempting to open a file
FileReader file = new
FileReader("nonexistentfile.txt");
BufferedReader reader = new
BufferedReader(file);

// Attempting to read the first line of the file


String firstLine = reader.readLine();
System.out.println("First Line: " + firstLine);

} catch (FileNotFoundException e) {
// This block will execute if the file does not exist
System.out.println("Error: File not found.");
} catch (IOException e) {
// This block will execute for other I/O issues
System.out.println("Error: An I/O error
occurred.");

78
} catch (Exception e) {
// This block will catch any other exceptions
System.out.println("Error: Something went
wrong.");
}
}
}
Explanation:
 In this example, the program tries to open a file and
read a line from it.
 Three catch clauses are provided:
o The first catch block handles a
FileNotFoundException, which is thrown if the
specified file does not exist.
o The second catch block handles any
IOException that may occur during the file
reading process (e.g., problems with file
access).
o The third catch block catches any other
exceptions that are not specifically handled by
the previous blocks.
Output (when the file doesn't exist):
Error: File not found.

OR

9. a) Explain the Hierarchy of Standard Exception


Classes in Java. What is the Difference Between
Exception and RuntimeException?
Hierarchy of Standard Exception Classes in Java:

79
In Java, exceptions are objects that are instances of the
Throwable class. The hierarchy of exception classes is as
follows:
 Throwable (Base class for all errors and exceptions)
o Error (Represents serious errors that a program
should not catch)
 Examples: OutOfMemoryError,
StackOverflowError
o Exception (Represents conditions that a
program can catch and handle)
 Checked Exceptions (Exceptions that are
checked at compile-time and must be
handled explicitly)
 Examples: IOException, SQLException,
ClassNotFoundException
 Unchecked Exceptions (Also called runtime
exceptions, they do not need to be caught
or declared in a method signature)
 Examples: NullPointerException,
ArrayIndexOutOfBoundsException,
IllegalArgumentException
Difference Between Exception and RuntimeException:
 Exception:
o Represents checked exceptions that must be
either caught using a try-catch block or
declared in the method signature using throws.
o These exceptions occur due to conditions that
are outside the program’s control, such as IO
errors, database errors, etc.
o Example: IOException, SQLException.
 RuntimeException:

80
o Represents unchecked exceptions that are
typically caused by programming bugs.
o These exceptions do not require explicit
handling (no need for a try-catch block or
throws declaration).
o They occur during the program's execution due
to errors like invalid array access, null
references, etc.
o Example: NullPointerException,
ArithmeticException.
Example:

public class ExceptionExample {


public static void main(String[] args) {
try {
int[] arr = new int[2];
System.out.println(arr[3]); // This will throw
ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught an exception: " +
e.getMessage());
}
}
}

9. b) Explain How to Read and Write Data to a Text File


in Java Using Character Streams. Provide Code
Examples.
In Java, character streams are used to handle input and
output of 16-bit Unicode characters. Character streams
are more efficient when dealing with text files because

81
they handle the conversion between characters and
bytes automatically.
Reading and Writing Using Character Streams:
 FileReader and FileWriter are the primary classes
for reading and writing character data in Java.
Example of Writing Data to a Text File:

import java.io.FileWriter;
import java.io.IOException;

public class WriteToFile {


public static void main(String[] args) {
try {
// Create a FileWriter object to write to a file
FileWriter writer = new
FileWriter("example.txt");
writer.write("Hello, this is a test file!\n");
writer.write("Java Character Streams are
great!");
writer.close(); // Always close the writer
System.out.println("Data written to the file.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
 Explanation:

82
o The FileWriter object is used to write text to a
file. The text is written in the form of
characters, so no encoding/decoding is needed.
o Always ensure that you close the stream using
the close() method to prevent resource leaks.
Example of Reading Data from a Text File:

import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;

public class ReadFromFile {


public static void main(String[] args) {
try {
// Create a FileReader object to read from the file
FileReader reader = new
FileReader("example.txt");
BufferedReader br = new
BufferedReader(reader); // For efficient reading
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close(); // Always close the reader
} catch (IOException e) {
e.printStackTrace();
}
}
}

83
 Explanation:
o FileReader is used to read characters from a
file.
o The BufferedReader is often used to wrap
around FileReader for efficient reading
(buffering).
o The readLine() method reads a line of text, and
it returns null when the end of the file is
reached.

UNIT 5

10a.)In Java, String and StringBuffer are both used to


handle text, but they differ significantly in terms of
mutability, performance, and use cases.
String:
 Immutability: A String object is immutable, meaning
once a String object is created, its value cannot be
changed. Any operation that modifies a string
actually creates a new String object.
 Performance: Operations that modify strings (like
concatenation or replacement) are slow because a
new String object is created every time a
modification is made. This involves a lot of memory
allocation and deallocation.
 Use Case: Suitable for scenarios where the string is
not going to change often, as it is more memory-
efficient when not modified.
StringBuffer:

84
 Mutability: StringBuffer objects are mutable,
meaning their values can be changed after creation
without creating new objects. This is more efficient
when performing many modifications to the text.
 Performance: More efficient than String when
performing repeated modifications, as it does not
create new objects each time.
 Use Case: Suitable for scenarios where the string
content needs to be modified multiple times (e.g.,
in loops).

Example:

public class StringAndStringBufferExample {


public static void main(String[] args) {
// Using String (Immutable)
String str = "Java";
str = str + " Programming"; // A new String is
created here
System.out.println("String: " + str);

// Using StringBuffer (Mutable)


StringBuffer sb = new StringBuffer("Java");
sb.append(" Programming"); // The existing
StringBuffer is modified here
System.out.println("StringBuffer: " + sb);
}
}

85
Output:

String: Java Programming


StringBuffer: Java Programming

10. b) What is Multithreaded Programming in Java, and


Why is it Important for Modern Software Development?
Multithreaded Programming:
Multithreaded programming in Java is a technique that
allows a program to perform multiple tasks concurrently.
In a multithreaded environment, multiple threads run
within the same application, and they share the same
resources like memory, but execute independently.
A thread is a lightweight process, and each thread has
its own program counter, stack, and local variables. In
Java, multithreading is achieved by using the Thread
class or implementing the Runnable interface.
Why is Multithreading Important?
1. Improved Performance: Multithreading allows tasks
to be executed in parallel, making full use of
multicore processors, improving performance for
CPU-bound tasks.
2. Better Resource Utilization: Threads share
resources, reducing memory overhead compared to

86
multiple processes. This helps in improving system
efficiency.
3. Increased Responsiveness: Multithreading is
essential for creating responsive applications, such
as GUI applications, where the main thread can
remain responsive to user actions while other tasks
(e.g., downloading files, processing data) continue
in the background.
4. Concurrency: Multiple threads can handle
independent tasks concurrently, such as handling
multiple user requests in a web server or
performing multiple computations in parallel.
Example of Multithreading:
Here is a simple example demonstrating multithreading
in Java by extending the Thread class:

class MyThread extends Thread {


public void run() {
for (int i = 1; i <= 5; i++) {

System.out.println(Thread.currentThread().getId() + "
Value: " + i);
try {
Thread.sleep(1000); // Pause for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

87
public class ThreadExample {
public static void main(String[] args) {
// Creating two threads
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();

// Starting the threads


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

1 Value: 1
2 Value: 1
1 Value: 2
2 Value: 2
1 Value: 3
2 Value: 3
...
In this example, two threads (t1 and t2) run
concurrently. Each thread prints numbers from 1 to 5
with a delay of 1 second. The exact order of output
might vary because the threads execute independently,
demonstrating multithreading.

Key Concepts:

88
 Thread: The basic unit of execution in a program.
 Thread.sleep(): A static method used to pause the
current thread for a specified amount of time.
 Thread Scheduling: The operating system’s thread
scheduler manages the execution of threads. Java
provides mechanisms to control thread behavior
(like priority).
Importance in Modern Software Development:

 Concurrency is essential in modern applications,


especially in web servers, real-time systems, and
GUI-based applications where tasks need to run
simultaneously without blocking the main program.
 Parallelism using multiple threads can significantly
reduce computation time, especially for resource-
intensive operations.

OR

11. a) Explain the Architecture of JDBC. What Are the


Main Components and How Do They Interact with
Databases?
JDBC (Java Database Connectivity) is an API that allows
Java programs to connect to relational databases. The
architecture of JDBC defines how Java applications
interact with databases.

Main Components of JDBC Architecture:

1. JDBC Drivers:

o Types of JDBC Drivers:

89
 Type 1 (JDBC-ODBC Bridge Driver): Uses
ODBC driver to connect with the database.
 Type 2 (Native-API Driver): Uses database-
specific API to connect directly.
 Type 3 (Network Protocol Driver): Uses a
middleware server to communicate with
the database.
 Type 4 (Thin Driver): Directly
communicates with the database using
database's native protocol.
2. DriverManager:

o A class that manages a list of database drivers


and handles the connection between Java
applications and databases.
o DriverManager selects an appropriate driver
based on the database URL.
3. Connection:

o Represents an open connection to a database.


It is used to create Statement,
PreparedStatement, and CallableStatement
objects.
o Methods like getConnection() are used to
establish the connection.
4. Statement:

o Used to send SQL queries to the database and


retrieve results.

90
o There are different types of Statement objects:
Statement, PreparedStatement, and
CallableStatement.
5. ResultSet:

o Represents the result of a query executed


against a database.
o It is used to retrieve data from the database.
6. SQLException:

o Exception thrown if there is an issue in


database connectivity or query execution.
JDBC Interaction Flow:

1. Load the JDBC driver.

2. Establish a connection to the database using


DriverManager.

3. Create a Statement to execute SQL queries.

4. Execute the query and store the result in a


ResultSet.

5. Close the connection and statement.

91
Example of JDBC Code:

import java.sql.*;

public class JDBCExample {


public static void main(String[] args) {
try {
// Step 1: Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// Step 2: Establish a connection to the database


Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:33
06/mydb", "root", "password");

// Step 3: Create a Statement


Statement stmt = conn.createStatement();

// Step 4: Execute a query and retrieve the result


ResultSet rs = stmt.executeQuery("SELECT *
FROM users");

// Step 5: Process the result


while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") + ",
Name: " + rs.getString("name"));
}

92
// Step 6: Close the resources
rs.close();
stmt.close();
conn.close();

} catch (ClassNotFoundException | SQLException e)


{
e.printStackTrace();
}
}
}
Explanation:
 This example connects to a MySQL database
(mydb), retrieves all users from the users table, and
displays the id and name of each user.
 JDBC uses Connection, Statement, and ResultSet to
interact with the database.

11. b) How Are Nodes Laid Out in a JavaFX Scene Graph?


Discuss the Different Layout Panes Like VBox, HBox,
GridPane, and BorderPane.

In JavaFX, the layout of the GUI is controlled using the


Scene Graph, which is a hierarchical tree structure of
visual nodes. Each node represents a UI component such
as buttons, text fields, and containers.
Layout Panes in JavaFX:
1. VBox (Vertical Box Layout):

93
o Lays out children in a single vertical column.
o All children are stacked on top of each other,
and you can set the spacing between them.
Example:

VBox vbox = new VBox(10); // 10px spacing between


children
vbox.getChildren().addAll(new Button("Button 1"), new
Button("Button 2"));

2. HBox (Horizontal Box Layout):


o Lays out children in a single horizontal row.
o You can control the horizontal spacing between
the children.
Example:

HBox hbox = new HBox(10); // 10px spacing between


children
hbox.getChildren().addAll(new Button("Button 1"), new
Button("Button 2"));

3. GridPane:
o Lays out children in a flexible grid of rows and
columns.
o Each child can be placed in a specific cell in the
grid.
Example:

GridPane grid = new GridPane();

94
grid.add(new Button("Button 1"), 0, 0); // Row 0,
Column 0
grid.add(new Button("Button 2"), 1, 0); // Row 0,
Column 1
4. BorderPane:
o Divides the layout into five regions: top,
bottom, left, right, and center.
o Each region can contain one child.
Example:

BorderPane borderPane = new BorderPane();


borderPane.setTop(new Button("Top"));
borderPane.setLeft(new Button("Left"));
borderPane.setCenter(new Button("Center"));

Conclusion:
These layout panes help organize the GUI in a flexible
and structured manner. They automatically manage the
positioning and resizing of the UI components.

95

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy