15 mark
What is method overloading? Write a Java public int add(int a, int b, int c) { Explain jLabel and JButton with the help // Create a frame
program to implement the method return a + b + c; of a real-world example. JFrame frame = new JFrame("JLabel and
overloading mechanism. } In Java Swing, JLabel and JButton are used JButton Example");
Method Overloading in Java refers to the for building Graphical User Interface (GUI) text!");
ability to define multiple methods with the // Overloaded method to add two double [Link]: It is used to display a // Create a JLabel
same name but different parameter lists within values public double add(double a, double b) short string or an image. It doesn't interact JLabel label = new JLabel("Click the button
the same class. The methods can differ by the { with the user but simply provides information to change the
number of parameters or the type of return a + b; or displays content. It is a non-editable // Create a JButton
parameters. Overloading allows the same } [Link]: It is a push button that JButton button = new JButton("Click Me");
method to be used in different contexts, } can be clicked to perform an action. When the // Add an ActionListener to the button
reducing the need for distinct method names. public class Main { user clicks on it, an event is triggered, and an [Link](new
Java determines which method to call based public static void main(String[] args) { action listener can respond to this event. ActionListener() {
on the number and types of arguments passed Calculator calc = new Calculator(); These components are often used together to public void actionPerformed(ActionEvent e) {
during method invocation. This is resolved at ); create interactive applications. For example, a [Link]("Text has been changed!");
compile time, making method overloading an // Calling different overloaded methods JLabel can be used to display instructions or }});
example of compile-time polymorphism. [Link]("Sum of two integers: " + messages, and a JButton can be used to trigger // Set layout manager [Link](new
ava [Link](5, actions when clicked, such as submitting a FlowLayout());
Copy code [Link]("Sum of three integers: " + form or closing a window. // Add components to the frame
class Calculator { [Link](5, Ex Program:java [Link](label); [Link](button);
// Method to add two integers public int 10, 15)); Copy code // Set frame size and visibility
add(int a, int b) { [Link]("Sum of two doubles: " + import [Link].; import [Link].; [Link](300, 200);
return a + b; [Link](5.5, import [Link].*; [Link](true);
} 10.5)); public class ButtonLabelExample { [Link]([Link]
// Overloaded method to add three integers }} public static void main(String[] args) { T_ON_CLOSE); }}
explain [Link] examples, class Cat implements Animal { public void Differentiate final methods and final classes / Trying to override the final method will
An interface in Java is a reference type, sound() { with examples. cause an error
similar to a class, that can contain only [Link]("Meow"); In Java, final is a keyword that can be applied // void display() { // Error: cannot override
constants, method signatures, default methods, } to methods, classes, and variables to restrict final method
static methods, and nested types. Interfaces } certain behavior. //[Link]("I am a dog.");
cannot contain instance fields or constructors. public class InterfaceExample { Final Methods: // }}
A class implements an interface by providing public static void main(String[] args) { a. A final method cannot be overridden by public class FinalMethodExample {
implementations for all its methods. Interfaces Animal dog = new Dog(); subclasses. This is useful when you want to public static void main(String[] args) {
are used to define a contract for what a class prevent a method from being modified in a Animal animal = new Animal();
can do, without specifying how it does it. A Animal cat = new Cat(); [Link] Classes:b.A final class cannot [Link]();
class that implements an interface must be extended by other classes. This means no }}
provide concrete implementations for the [Link](); // Calls Dog's implementation of subclass can be created from a final class. Ex:
methods declared in the interface. sound [Link](); // Calls Cat's Example for Final Method: java
Example Program: implementation of sound java Copy code
java } Copy code final class FinalClass { void showMessage() {
Copy code interface Animal { } [Link]("This is a final class.");
void sound(); // Abstract method The Animal interface defines an abstract class Animal { }}{ // Error: cannot subclass the final class
} method sound(). Both Dog and Cat classes final void display() { [Link]("I am // }public class FinalClassExample {
class Dog implements Animal { public void implement this interface and provide their an animal."); public static void main(String[] args) {
sound() { own implementation of the sound() method. } FinalClass obj = new FinalClass();
[Link]("Bark"); } [Link]();
}} class Dog extends Animal { }}
What is constructor overloading? Write a // Overloaded constructor with two What is multithreading? Describe the 2 java
Java program to implement the constructor parameters public Vehicle(String name, int ways in which a thread can be created in Copy code
overloading mechanism. wheels) { Java. class MyRunnable implements Runnable {
Constructor Overloading is a concept in Java [Link] = name; [Link] = wheels; Multithreading is a feature in Java that allows public void run() {
where multiple constructors with the same } the execution of two or more parts of a [Link]("Thread running using
name but different parameter lists are defined public void displayDetails() { program simultaneously. Each part of the Runnable");
within the same class. Like method [Link]("Vehicle Name: " + name); program is called a thread, and it runs }
overloading, constructor overloading allows [Link]("Number of Wheels: " + independently of the others. Multithreading }
the creation of objects in different ways, wheels); improves the efficiency of CPU usage by public class ThreadExample {
giving flexibility in object initialization. }} allowing tasks to be executed concurrently. public static void main(String[] args) {
Constructor overloading is useful when you public class Main { There are two main ways to create a thread in MyRunnable runnable = new MyRunnable();
want to initialize objects with different sets of public static void main(String[] args) { Java:By implementing the Runnable interface: Thread thread = new Thread(runnable);
data, allowing you to provide default values or Vehicle v1 = new Vehicle(); // Calls default a. A class can implement the Runnable [Link](); // Start the thread
other initialization based on the parameters constructor Vehicle v2 = new Vehicle("Car"); interface and override the run() method. The }
provided .Ex // Calls constructor with thread is then created by passing the Runnable }
java one parameter object to a Thread object. Ex of creating a thread by extending the
Copy code Vehicle v3 = new Vehicle("Bike", 2); // Calls By extending the Thread class: Thread class:
class Vehicle { constructor with two parameters a. A class can extend the Thread class and java
private String name; private int wheels; [Link](); [Link](); override its run() method. The thread is Copy code
// Default constructor public Vehicle() { [Link](); created by calling the start() method on the class MyThread extends Thread { public void
name = "Unknown"; wheels = 4; }} Thread object. run() {
}// Overloaded constructor with one parameter Example of creating a thread using Runnable: [Link]("Thread running by
public Vehicle(String name) {
[Link] = name; [Link] = 4; }
extending Thread Explain different types of literals with diverse data types directly in the code,
class"); examples. improving readability and reducing the need
} In Java, literals represent fixed values that are for complex calculations or conversions.
} assigned directly in the code. Literals can be
of different types, matching Java’s data types:
public class ThreadExample { integer, floating-point, character, string, and
public static void main(String[] args) { boolean literals. Integer literals, such as 100,
MyThread thread = new MyThread(); are numbers without a fractional part, and
[Link](); // Start the thread they can be written in decimal, octal (prefix
} 0), or hexadecimal (prefix 0x) format. For
} example, int num = 42; is an integer literal.
Floating-point literals represent decimal
values, like 3.14 or 2.71, and they can be
written with or without an exponent (e.g.,
1.5e2 for 1.5 * 10^2). Character literals,
enclosed in single quotes ('A'), represent
single characters, while string literals,
enclosed in double quotes ("Hello"), represent
sequences of characters.
Boolean literals, true and false, represent
logical values and are commonly used in
control statements like if or while. These
literals give Java flexibility in representing
5 mark
Describe the use of jump statements with public class JumpStatementsExample { Explain primitive data types. encoding to support characters from various
examples. public static void main(String[] args) { for Java provides eight primitive data types, languages. The boolean type is used for
(int i = 1; i <= 10; i++) { which are the building blocks for all other logical values (true or false), commonly used
In Java, jump statements are used to control if (i == 5) break; // Stops the loop when i is 5 data handling in the language. These types are in control structures like if statements to make
the flow of execution by allowing the categorized based on the kind of values they decisions based on conditions. Together, these
program to “jump” to specific points within if (i % 2 == 0) continue; // Skips even hold: byte, short, int, and long for integer primitive data types give Java the versatility
the code. The main jump statements are break, numbers [Link](i); // Prints only values, float and double for decimal values, to handle both simple and complex
continue, and return. The break statement is odd numbers up to char for single characters, and boolean for calculations efficiently.
commonly used in loops or switch statements 5 true/false values. Primitive data types are not
to exit the loop or case block prematurely. For } objects and are directly stored in memory,
instance, when a certain condition is met, } making them faster and more efficient in
break allows the program to stop further } operations.
iterations and move out of the loop. The integer types (byte, short, int, and long)
The continue statement is used within loops to differ in their size and range. For instance, int
skip the current iteration and proceed to the is a 32-bit signed integer, suitable for most
next one. For example, if a loop is iterating integer calculations, while long is a 64-bit
through numbers and we want to skip the even integer, used when higher values are required.
ones, we can use continue to bypass them. The For floating-point numbers, float is a 32-bit
return statement is used in methods to exit and single-precision type, while double is a 64-bit
optionally return a value to the calling code. double- precision type, providing higher
Here's a simple example illustrating break and accuracy.
continue in a for loop: Characters in Java are represented by the char
data type, which uses 16-bit Unicode
Explain looping statements with examples. public class LoopingStatementsExample { Explain different types of built-in Explain about user-defined packages.
Java provides several looping statements to public static void main(String[] args) { exceptions. In Java, a package is a namespace that groups
repeat blocks of code based on conditions. // For loop Java provides several built-in exceptions that related classes and interfaces. While Java
The main looping statements are for, while, for (int i = 1; i <= 5; i++) { are part of the [Link] package. Exceptions provides several built-in packages, such as
and do-while. The for loop is commonly used [Link]("For loop iteration: " + i); in Java are classified into two main [Link] and [Link], you can also create your
when the number of iterations is known } categories: checked exceptions and unchecked own user-defined packages to organize classes
beforehand, while while and do-while loops [Link] exceptions are exceptions and avoid naming conflicts. Creating
are used when the condition needs to be // While loop int j = 1; that the compiler forces you to handle. These packages helps in modularizing the code,
evaluated before each iteration or after each while (j <= 5) { exceptions are checked at compile-time, and improving code readability, and maintaining it
iteration, respectively. [Link]("While loop iteration: " + you must either catch them using a try- catch easily.A user-defined package is declared
In a for loop, the syntax includes initialization, j); j++; block or declare them in the method signature using the package keyword at the beginning
condition, and update steps, all in one line. For } using the throws [Link]:of checked of a Java file. The package name should
example, for (int i = 0; i < 5; i++) will iterate exceptions include IOException, follow Java's naming conventions, typically
five times. The while loop, however, // Do-while loop int k = 1; SQLException, and FileNotFoundException. lowercase letters, and can be hierarchical
continues to iterate as long as its condition do { Unchecked exceptions (also known as runtime (e.g., [Link]).
remains true. If the condition is false from the [Link]("Do-while loop iteration: " exceptions) are exceptions that occur during
start, it won’t execute at all. Conversely, the + k); the program’s execution. These exceptions are
do-while loop guarantees at least one iteration not checked at compile time, and the program
because the condition is checked at the end. k++; may terminate if they are not handled.
Here’s a sample program using each loop } while (k <= 5); Examples of unchecked exceptions include
type: } NullPointerException,
} ArrayIndexOutOfBoundsException, and
ArithmeticException.
Write a Java program to demonstrate priority What are JDBC statements? necessary resources when the object is
thread [Link] Java, each thread has a priority JDBC (Java Database Connectivity) [Link] are two main types of
priority that determines its importance in [Link](Thread.MIN_PRIORITY); statements are used to interact with databases constructors in Java — default constructor
relation to other threads. The thread priority is // Setting minimum from Java applications. The and parameterized constructor. A default
an integer value, where the default priority is [Link](Thread.NORM_PRIORITY); // [Link] interface is used to execute constructor is automatically provided by Java
5, and the valid range is from Default priority SQL queries against a database, retrieve data, if no constructor is defined in the class, and it
Thread.MIN_PRIORITY (1) to [Link](Thread.MAX_PRIORITY); and update records. There are three types of initializes all variables with default values. A
Thread.MAX_PRIORITY (10). // Setting maximum JDBC statements:Statement: Used for parameterized constructor, on the other hand,
Thread priority influences the thread [Link](); executing simple SQL queries without allows values to be passed as arguments
scheduling in a multi-threaded environment, [Link](); parameters. PreparedStatement: Used to during object creation, giving more control
but note that it doesn’t guarantee that a thread [Link](); execute precompiled SQL statements with or over how objects are initialized. Constructors
with a higher priority will always be executed } without parameters, providing better can also be overloaded, meaning a class can
before one with a lower priority. } performance and preventing SQL injection. have multiple constructors with different
Here’s a Java program demonstrating thread In this program, three threads are created with CallableStatement: Used to call stored parameter lists. In short, constructors play a
priorities:class MyThread extends Thread { different priorities. The setPriority() method procedures in the database. vital role in object-oriented programming by
public void run() { is used to assign priorities to each thread. Write a note on constructors ensuring that every object starts in a valid,
[Link]([Link]().get When executed, the thread scheduler decides In Java, a constructor is a special method that predictable state when it is created.
Name() + " is running"); the order of thread execution based on their is used to initialize objects. It has the same
} priorities. name as the class and is automatically called
}public class ThreadPriorityExample { when an object of that class is created. Unlike
public static void main(String[] args) { normal methods, constructors do not have a
MyThread t1 = new MyThread(); MyThread return type, not even void. The main purpose
t2 = new MyThread(); MyThread t3 = new of a constructor is to assign initial values to
MyThread(); the object’s data members and set up
Explain throw, throws s finally with an ArithmeticException { Define a class. State the uses of the super keyword in Java.
example. divideByZero(); A class is a blueprint or template in Java that The super keyword in Java refers to the
In Java, exception handling is a mechanism to } defines the properties (fields) and behaviors immediate parent class of a subclass. It can be
handle runtime errors, allowing the program to public static void divideByZero() throws (methods) of objects. A class is used to create used to access:
continue execution. Three important keywords ArithmeticException { int result = 10 / 0; // instances (objects) and is fundamental to Parent class methods.
related to exception handling are throw, This will throw ArithmeticException object-oriented programming. Parent class constructors.
throws, and finally. }} Define a Package. Parent class variables that are hidden by the
throw: Used to explicitly throw an exception. finally: A block that is always executed after A package in Java is a namespace that subclass.
It is followed by an instance of the the try-catch block, regardless of whether an organizes a set of related classes and Write any four methods of the Thread class.
Throwable class (e.g., Exception or Error). exception was thrown or not. It is often used interfaces. It helps in avoiding name conflicts start(): Starts the thread's execution.
Example: to release resources. and makes the program easier to maintain. run(): Contains the code to be executed when
public class ThrowExample { Example: Java has both built-in packages and the thread runs.
public static void main(String[] args) { public class FinallyExample { user-defined packages. sleep(long millis): Pauses the thread for a
throw new ArithmeticException("Division by public static void main(String[] args) { try { Define Swing. specified time.
zero is not allowed"); int result = 10 / 0; Swing is a GUI toolkit for Java that provides a join(): Ensures that the calling thread waits for
}} } catch (ArithmeticException e) { richer set of components than AWT (Abstract the thread to finish execution.
throws: Used in method signatures to declare [Link]("Exception: " + e); Window Toolkit). Swing components are List out the different branching statements
that a method may throw one or more } finally { lightweight, meaning they are not dependent used in Java.
exceptions. It helps the caller of the method [Link]("Finally block is always on the platform's native windowing system, if - Used for conditional execution.
handle the exception. executed."); making them platform- independent. if-else - Executes one block if the condition is
Ex:public class ThrowsExample { } true, and another block if false.
public static void main(String[] args) throws } switch - Used for selecting one of many code
blocks to execute based on a variable.