Java Winter 23

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 23

Java Winter 23

1. Attempt any FIVE of the following : 10

a) Enlist any two logical operators and two bitwise operators.


Ans.
&& : Logical AND
|| : Logical OR
! : Logical NOT

Bitwise AND (&):


Bitwise OR (|):
Bitwise XOR (^):

b) Define constructor.
Ans.Constructor: A constructor is a special member which initializes an object immediately
upon creation. It has the same name as class name in which it resides and it is syntactically
similar to any method. When a constructor is not defined, java executes a default constructor
which initializes all numeric members to zero and other types to null or spaces. Once defined,
constructor is
automatically called immediately after the object is created before new operator completes.
Types of constructors:
1. Default constructor
2. Parameterized constructor
3. Copy constructor

c) Write down the syntax of array declaration, initialization.


Ans.
Array Declaration
dataType[] arrayName; // Preferred way
// or
dataType arrayName[]; // Less preferred way

Array Initialization
dataType[] arrayName = {value1, value2, value3, ...};

d) List out different ways to access package from another package.


Ans.
1. Import Statement
The most common way to access classes from another package is by using the import statement.
You can import specific classes or all classes in a package.
2. Fully Qualified Class Name
If you do not want to use the import statement, you can access a class from another package by
using its fully qualified name. This includes the package name followed by the class name.
3. Using the Class from Another Package in Your Code
Once you have imported the class or used its fully qualified name, you can create instances and
call methods as you would with any other class.
4. Access Modifiers
When accessing classes from another package, keep in mind the following access modifiers:
 Public: Classes and members declared as public can be accessed from any other package.
 Protected: Members declared as protected can be accessed only within the same package
and by subclasses in other packages.
 Default (no modifier): Classes and members with default access can only be accessed
within the same package.
 Private: Members declared as private are accessible only within their own class.

e) Differentiate between starting thread with run ( ) method and start ( ) method.
Ans.
Aspect run() Method start() Method
Invoca Directly called like a normal method Initiates a new thread of execution
tion
Thread Does not create a new thread Creates a new thread
Creatio
n
Execut Code runs in the current thread Code runs in a new, separate thread
ion
Use Useful for testing the thread's run() Used to start the thread and execute run()
Case method directly in a new thread
Examp java Thread t = new Thread(new java Thread t = new Thread(new
le MyRunnable()); t.run(); // No new thread is MyRunnable()); t.start(); // New thread is
created created
f) State the classes that can an applet extend.
Ans.
1. java.applet.Applet:This is the original applet class provided in Java 1.0. When you extend
this class, you can create basic applets that include methods like init(), start(), stop(), and
destroy(), which are used for controlling the applet's lifecycle.
2. javax.swing.JApplet :This class extends Applet and provides a Swing-based applet. It allows
you to create GUI components using Swing, which is more flexible and powerful compared to
the AWT components that Applet supports.
g) Give syntax to open a file using Inputstream class.
Ans.InputStream inputStream = new FileInputStream("path/to/file");

2. Attempt any THREE of the following : 12

a) Write a program to display ASCII value of a number 9.


Ans.
public class AsciiValueExample {
public static void main(String[] args) {
char character = '9'; // The character whose ASCII value we want to find
int asciiValue = (int) character; // Cast the character to an int to get its ASCII value

// Display the ASCII value


System.out.println("The ASCII value of '" + character + "' is: " + asciiValue);
}
}
Example:
The ASCII value of '9' is: 57

b) Write a program to sort the elements of an array in ascending order.


Ans.
import java.util.Arrays;
public class ArraySortExample {
public static void main(String[] args) {
// Initialize an array of integers
int[] numbers = {64, 34, 25, 12, 22, 11, 90};

// Display the original array


System.out.println("Original array: " + Arrays.toString(numbers));

// Sort the array using Bubble Sort


bubbleSort(numbers);

// Display the sorted array


System.out.println("Sorted array in ascending order: " + Arrays.toString(numbers));
}

// Method to perform Bubble Sort


public static void bubbleSort(int[] arr) {
int n = arr.length;
boolean swapped; // Variable to check if a swap occurred

// Outer loop for number of passes


for (int i = 0; i < n - 1; i++) {
swapped = false; // Reset swapped for this pass

// Inner loop for comparing adjacent elements


for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true; // Set swapped to true if a swap occurred
}
}

// If no two elements were swapped, the array is already sorted


if (!swapped) {
break;
}
}
}
}

c) Define Thread. Draw life cycle of Thread.


Ans.A Thread is a lightweight process, representing a single path of execution within a
program. Java provides built-in support for multithreading, allowing concurrent execution of two
or more threads to maximize CPU utilization and improve application performance.

Thread Life Cycle Thread has five different states throughout its
life.
1. Newborn State
2. Runnable State
3. Running State
4. Blocked State
5. Dead State
Thread should be in any one state of above and it can be move from one state to another by
different methods and ways.
Newborn state: When a thread object is created it is said to be in a new born state. When the
thread is in a new born state it is not scheduled running from this state it can be scheduled for
running by start() or killed by stop(). If put in a queue it moves to runnable state.
Runnable State: It means that thread is ready for execution and is waiting for the availability of
the processor i.e. the thread has joined the queue and is waiting for execution. If all threads have
equal priority, then they are given time slots for execution in round robin fashion. The thread that
relinquishes control joins the queue at the end and again waits for its turn. A thread can
relinquish the control to another before its turn comes by yield().
Running State: It means that the processor has given its time to the thread for execution. The
thread runs until it relinquishes control on its own or it is pre-empted by a higher priority thread.
Blocked state: A thread can be temporarily suspended or blocked from entering into the
runnable and running state by using either of the following thread method.
1) suspend() : Thread can be suspended by this method. It can be rescheduled by resume().
2) wait(): If a thread requires to wait until some event occurs, it can be done using wait method
and can be scheduled to run again by notify().
3) sleep(): We can put a thread to sleep for a specified time period using sleep(time) where time
is in ms. It re-enters the runnable state as soon as period has elapsed /over
Dead State: Whenever we want to stop a thread form running further we can call its stop().The
statement causes the thread to move to a dead state. A thread will also move to dead state
automatically when it reaches to end of the method. The stop method may be used when the
premature death is required.

d) Write a program to read a file and then count number of words.


Ans.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordCountExample {
public static void main(String[] args) {
// Specify the path to the file
String filePath = "path/to/your/file.txt"; // Change this to your file path
// Initialize a word count variable
int wordCount = 0;
try {
// Create a File object
File file = new File(filePath);
// Create a Scanner object to read the file
Scanner scanner = new Scanner(file);
// Read the file word by word
while (scanner.hasNext()) {
String word = scanner.next(); // Read the next word
wordCount++; // Increment the word count
}
// Close the scanner
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
// Display the word count
System.out.println("Number of words in the file: " + wordCount);
}
}

3. Attempt any THREE of the following : 12

a) Write a program which displays functioning of ATM machine(Hint : Withdraw,


Deposit, Check Balance and Exit)
Ans.
import java.util.Scanner;
public class ATMMachine {
private double balance; // Variable to hold the account balance

public ATMMachine() {
this.balance = 0.0; // Initialize balance to zero
}
// Method to check balance
public void checkBalance() {
System.out.println("Your current balance is: $" + balance);
}
// Method to deposit money
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Successfully deposited: $" + amount);
} else {
System.out.println("Deposit amount must be positive.");
}
}
// Method to withdraw money
public void withdraw(double amount) {
if (amount <= balance && amount > 0) {
balance -= amount;
System.out.println("Successfully withdrawn: $" + amount);
} else if (amount > balance) {
System.out.println("Insufficient balance.");
} else {
System.out.println("Withdrawal amount must be positive.");
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ATMMachine atm = new ATMMachine(); // Create an instance of ATMMachine
while (true) {
System.out.println("\n--- ATM Menu ---");
System.out.println("1. Check Balance");
System.out.println("2. Deposit");
System.out.println("3. Withdraw");
System.out.println("4. Exit");
System.out.print("Choose an option (1-4): ");
int choice = scanner.nextInt(); // Read user choice
switch (choice) {
case 1:
atm.checkBalance(); // Check balance
break;
case 2:
System.out.print("Enter amount to deposit: $");
double depositAmount = scanner.nextDouble();
atm.deposit(depositAmount); // Deposit money
break;
case 3:
System.out.print("Enter amount to withdraw: $");
double withdrawAmount = scanner.nextDouble();
atm.withdraw(withdrawAmount); // Withdraw money
break;
case 4:
System.out.println("Thank you for using the ATM. Goodbye!");
scanner.close();
return; // Exit the program
default:
System.out.println("Invalid choice. Please choose a valid option.");
}
}
}
}

b) Differentiate between method overloading and method overriding.


Ans.
Method Overloading Method Overriding
Method overloading is a compile-time Method overriding is a run-time polymorphism.
polymorphism.
Method overloading helps to increase the Method overriding is used to grant the specific
readability of the program. implementation of the method which is already
provided by its parent class or superclass.
It occurs within the class. It is performed in two classes with inheritance
relationships.
Method overloading may or may not Method overriding always needs inheritance.
require inheritance.
In method overloading, methods must In method overriding, methods must have the same
have the same name and different name and same signature.
signatures.
In method overloading, the return type In method overriding, the return type must be the
can or can not be the same, but we just same or co-variant.
have to change the parameter.
Static binding is being used for Dynamic binding is being used for overriding
overloaded methods. methods.
Private and final methods can be Private and final methods can’t be overridden.
overloaded.
The argument list should be different The argument list should be the same in method
while doing method overloading. overriding.
c) Explain applet life cycle in detail.
Ans.When an applet begins, the AWT calls the following methods, in
this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method
calls takes place:
4. stop( )
5. destroy( )

init ( ):The init( ) method is the first method to be called. This is


where you should initialize Variables. This method is called only
once during the run time of your applet.
start( ):The start( ) method is called after init( ).It is also called
to restart an applet after it has Been stopped. Whereas init( ) is
called once- the first time an applet is loaded-start( )is called
each time an applets HTML document is displayed onscreen.
Paint ( ): The paint ( ) method is called each time your applets
output must be redrawn. Paint ( ) is also called when the applet
begins execution. Whatever the cause, whenever the applet must
redraw its output, paint( ) is called. The paint ( ) method has one
parameter of type Graphics.
Stop ( ): When stop ( ) is called, the applet is probably running.
You should use stop ( ) to suspend threads that dont need to run
when the applet is not visible.
destroy( ): The destroy ( ) method is called when the environment
determines that your applet needs to be removed completely from
memory.

d) Differentiate between Byte Stream Class and Character Stream Class. (Any four points)
Ans.
Aspect Character Streams Byte Streams
Data Handling Handle character-based data Handle raw binary data
Representation Classes end with "Reader" or Classes end with "InputStream" or
"Writer" "OutputStream"
Suitable for Textual data, strings, human- Non-textual data, binary files,
readable info multimedia
Character Encoding Automatic encoding and decoding No encoding or decoding
Text vs non-Text Text-based data, strings Binary data, images, audio, video
data
Performance Additional conversion may impact Efficient for handling large binary
performance data
Handle Large Text May impact performance due to Efficient, no encoding overhead
Files encoding
String Operations Convenient methods for string Not specifically designed for string
operations operations
Convenience Higher-level abstractions for text Low-level interface for byte data
Methods data
Reading Line by Line Convenient methods for reading Byte-oriented, no built-in line-reading
lines methods
File Handling Read/write text files Read/write binary files
Network Sending/receiving text data Sending/receiving binary data
Communication
Handling Not designed for handling binary Suitable for handling binary
Images/Audio/Video data directly multimedia data
Text Encoding Supports various character No specific text encoding support
encodings

4. Attempt any THREE of the following : 12

a) Explain implicit and explicit type conversion with example in detail.


Ans.Type conversion in programming refers to changing the data type of a value to another type.
In Java, type conversion can be classified into two categories: implicit type conversion (also
known as automatic type conversion or coercion) and explicit type conversion (also known as
type casting). Below, we'll explore both concepts in detail, including examples.
Implicit Type Conversion
Implicit Type Conversion occurs when a value of a smaller data type is automatically converted
to a larger data type. This conversion is done by the Java compiler without any explicit
instruction from the programmer. Implicit conversion is safe because it does not lead to data loss.

Explicit Type Conversion


Explicit Type Conversion, or type casting, is when a programmer manually converts a variable
from one type to another. This is done using casting operators. Explicit conversion can
potentially lead to data loss, especially when converting from a larger data type to a smaller one.
Example:
public class TypeConversionExample {
public static void main(String[] args) {
// Implicit Type Conversion (Widening Conversion)
int intValue = 100; // Integer value
double doubleValue = intValue; // Implicit conversion from int to double
System.out.println("Implicit Conversion:");
System.out.println("Integer value: " + intValue); // Output: 100
System.out.println("Double value (after implicit conversion): " + doubleValue); // Output:
100.0
// Explicit Type Conversion (Narrowing Conversion)
doubleValue = 9.78; // Assign a new double value
intValue = (int) doubleValue; // Explicit conversion from double to int
System.out.println("\nExplicit Conversion:");
System.out.println("Double value: " + doubleValue); // Output: 9.78
System.out.println("Integer value (after explicit conversion): " + intValue); // Output: 9
}
}

b) Write a program to show the use of copy constructor.


Ans.Copy Constructor : A copy constructor is a constructor that creates a new object using an
existing object of the same class and initializes each instance variable of newly created object
with corresponding instance variables of the existing object passed as argument. This constructor
takes a single argument whose type is that of the class containing the constructor.

class Rectangle
{
int length;
int breadth;
Rectangle(int l, int b)
{
length = l;
breadth= b;
}
//copy constructor
Rectangle(Rectangle obj)
{
length = obj.length;
breadth= obj.breadth;
}
public static void main(String[] args)
{
Rectangle r1= new Rectangle(5,6);
Rectangle r2= new Rectangle(r1);
System.out.println("Area of First Rectangle : "+
(r1.length*r1.breadth));
System .out.println("Area of First Second Rectangle : "+
(r1.length*r1.breadth));
}
}

c) Write a program to show the Hierarchical inheritance.


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

// Subclass 1
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}

// Subclass 2
class Cat extends Animal {
void meow() {
System.out.println("The cat meows.");
}
}

// Main class
public class HierarchicalInheritanceExample {
public static void main(String[] args) {
// Creating an object of Dog
Dog dog = new Dog();
dog.eat(); // Calling method from Animal class
dog.bark(); // Calling method from Dog class

System.out.println(); // Adding a blank line for readability

// Creating an object of Cat


Cat cat = new Cat();
cat.eat(); // Calling method from Animal class
cat.meow(); // Calling method from Cat class
}
}
Output:
This animal eats food.
The dog barks.
This animal eats food.
The cat meows.

d) Explain any four font methods with example.


Ans.The Font class in Java's AWT package provides various methods for working with fonts.
Here, I’ll explain six commonly used font methods with examples.

1.Font(String name, int style, int size)


This constructor creates a new Font object with the specified name, style, and size.
 Parameters:
o name: The name of the font (e.g., "Arial", "Times New Roman").
o style: The style of the font (e.g., Font.PLAIN, Font.BOLD, Font.ITALIC).
o size: The point size of the font.
2. getName()
This method returns the name of the font.
3. getStyle()
This method returns the style of the font (e.g., plain, bold, italic).
4. getSize()
This method returns the size of the font in points.
5. deriveFont(float size)
This method creates a new Font object that is derived from the original font but with a different
size.
6. isBold()
This method checks if the font is bold.

Example:
import javax.swing.*;
import java.awt.*;

public class FontMethodsExample extends JFrame {


public FontMethodsExample() {
setTitle("Font Methods Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create a Font object


Font font1 = new Font("Arial", Font.BOLD, 16);

// Display font information using various methods


String fontName = font1.getName();
int style = font1.getStyle();
int size = font1.getSize();
Font font2 = font1.deriveFont(20.0f);
boolean isBold = font1.isBold();

JTextArea textArea = new JTextArea();


textArea.setFont(font1);
textArea.setText("Font Name: " + fontName + "\n" +
"Font Style: " + (style == Font.BOLD ? "Bold" : "Plain") + "\n" +
"Font Size: " + size + "\n" +
"Derived Font Size: " + font2.getSize() + "\n" +
"Is Font Bold? " + (isBold ? "Yes" : "No"));

add(textArea);
setVisible(true);
}

public static void main(String[] args) {


SwingUtilities.invokeLater(FontMethodsExample::new);
}
}

e) Write a program to append content of one file into another file.


Ans.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileAppender {


public static void main(String[] args) {
String sourceFilePath = "source.txt"; // Path of the source file
String destinationFilePath = "destination.txt"; // Path of the destination file

appendFileContent(sourceFilePath, destinationFilePath);
}
public static void appendFileContent(String source, String destination) {
try (BufferedReader reader = new BufferedReader(new FileReader(source));
BufferedWriter writer = new BufferedWriter(new FileWriter(destination, true))) { //
'true' for append mode
String line;
while ((line = reader.readLine()) != null) { // Read until the end of the source file
writer.write(line); // Write the line to the destination file
writer.newLine(); // Add a new line after each line
}
System.out.println("Content appended successfully from " + source + " to " +
destination);
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}

5. Attempt any TWO of the following : 12

a) Explain vector with the help of example. Explain any 3 methods of vector class.
Ans.A Vector is a part of the Java Collection Framework and is used to store a dynamically sized
collection of objects. It implements the List interface and is similar to an array but provides more
flexible sizing and built-in synchronization.
Characteristics of Vector
1. Dynamic Size: Unlike arrays, which have a fixed size, a Vector can grow and shrink as
elements are added or removed.
2. Thread Safety: The methods in a Vector are synchronized, which means that it is thread-
safe and can be used safely in concurrent applications.
3. Element Access: Like arrays, Vectors allow for random access to their elements through
an index.
4. Growth Policy: When a Vector needs to grow, it typically doubles its size, which can lead
to wasted space if not managed properly.
Example:
import java.util.Vector;

public class VectorExample {


public static void main(String[] args) {
// Create a Vector
Vector<String> vector = new Vector<>();
// Adding elements to the Vector
vector.add("Apple");
vector.add("Banana");
vector.add("Cherry");
vector.add("Date");
// Displaying the contents of the Vector
System.out.println("Vector elements: " + vector);
// Inserting an element at a specific position
vector.add(2, "Mango");
System.out.println("After adding Mango at index 2: " + vector);
// Accessing an element
String fruit = vector.get(1);
System.out.println("Element at index 1: " + fruit);
// Removing an element
vector.remove("Banana");
System.out.println("After removing Banana: " + vector);
// Size of the Vector
int size = vector.size();
System.out.println("Size of the Vector: " + size);
// Clearing the Vector
vector.clear();
System.out.println("After clearing, the Vector is: " + vector);
}
}

The Vector class in Java is part of the java.util package and is a dynamic array that can grow as
needed to accommodate new elements. It implements the List interface and is synchronized,
making it thread-safe. Here, we'll explore three important methods of the Vector class in detail:
add(), get(), and remove().
1. add(E e)
Description: The add() method is used to append an element to the end of the vector. If the
vector's capacity is reached, it will automatically increase its size to accommodate the new
element.
Syntax:
public boolean add(E e)

2. get(int index)
Description: The get() method is used to retrieve an element at a specified index in the vector.
The index is zero-based, meaning the first element is at index 0.
Syntax:
public E get(int index)

3. remove(int index)
Description: The remove() method is used to remove an element from the vector at a specified
index. After removal, all subsequent elements are shifted to the left (decreased in index).
Syntax:
public E remove(int index)

b) Develop and Interest Interface which contains Simple Interest and Compound Interest
methods and static final field of rate 25%. Write a class to implement those methods.
Ans.
// Step 1: Define the Interest Interface
public interface Interest {
double RATE = 25.0; // Static final field for interest rate

double calculateSimpleInterest(double principal, double time);


double calculateCompoundInterest(double principal, double time, int
numberOfTimesCompounded);
}

// Step 2: Implement the Interest Interface


public class InterestCalculator implements Interest {

@Override
public double calculateSimpleInterest(double principal, double time) {
return (principal * RATE * time) / 100; // Simple Interest formula
}

@Override
public double calculateCompoundInterest(double principal, double time, int
numberOfTimesCompounded) {
return principal * Math.pow((1 + RATE / (100 * numberOfTimesCompounded)),
numberOfTimesCompounded * time) - principal; // Compound Interest
formula
}
}

// Step 3: Create a Main Class to Test the Implementation


public class Main {
public static void main(String[] args) {
InterestCalculator calculator = new InterestCalculator();

// Example values
double principal = 1000; // Principal amount
double time = 2; // Time in years
int numberOfTimesCompounded = 4; // Quarterly compounding

// Calculate Simple Interest


double simpleInterest = calculator.calculateSimpleInterest(principal, time);
System.out.println("Simple Interest: " + simpleInterest);

// Calculate Compound Interest


double compoundInterest = calculator.calculateCompoundInterest(principal, time,
numberOfTimesCompounded);
System.out.println("Compound Interest: " + compoundInterest);
}
}
c) Write a program that throws an exception called “NoMatchException” when a string is
not equal to “India”.
Ans.
// Step 1: Define the Custom Exception
public class NoMatchException extends Exception {
public NoMatchException(String message) {
super(message); // Call the superclass constructor
}
}

// Step 2: Create a Method to Check the String


public class StringChecker {
public void checkString(String input) throws NoMatchException {
if (!input.equals("India")) {
throw new NoMatchException("Input does not match 'India': " + input);
} else {
System.out.println("Input matches 'India'.");
}
}
}

// Step 3: Write a Main Class to Demonstrate Exception Handling


public class Main {
public static void main(String[] args) {
StringChecker checker = new StringChecker();

String testString = "USA"; // Change this value to test different inputs

try {
checker.checkString(testString);
} catch (NoMatchException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
Output:
Exception caught: Input does not match 'India': USA

If you change testString to "India" and run the program, the output will be:
Input matches 'India'.
6. Attempt any TWO of the following : 12
a) Write a program to print the sum, difference and product of two complex numbers by
creating a class named “Complex” with separate methods for each operation whose real
and imaginary parts are entered by user.
Ans.
import java.util.Scanner;

// Step 1: Define the Complex Class


class Complex {
private double real;
private double imaginary;

// Constructor to initialize complex number


public Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}

// Method to add two complex numbers


public Complex add(Complex other) {
return new Complex(this.real + other.real, this.imaginary + other.imaginary);
}

// Method to subtract two complex numbers


public Complex subtract(Complex other) {
return new Complex(this.real - other.real, this.imaginary - other.imaginary);
}

// Method to multiply two complex numbers


public Complex multiply(Complex other) {
double realPart = this.real * other.real - this.imaginary * other.imaginary;
double imaginaryPart = this.real * other.imaginary + this.imaginary * other.real;
return new Complex(realPart, imaginaryPart);
}

// Method to display the complex number


@Override
public String toString() {
return real + " + " + imaginary + "i";
}
}

// Step 2: Create a Main Class to Get Input and Perform Operations


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

// Get first complex number


System.out.print("Enter the real part of the first complex number: ");
double real1 = scanner.nextDouble();
System.out.print("Enter the imaginary part of the first complex number: ");
double imaginary1 = scanner.nextDouble();
Complex complex1 = new Complex(real1, imaginary1);

// Get second complex number


System.out.print("Enter the real part of the second complex number: ");
double real2 = scanner.nextDouble();
System.out.print("Enter the imaginary part of the second complex number: ");
double imaginary2 = scanner.nextDouble();
Complex complex2 = new Complex(real2, imaginary2);

// Perform operations
Complex sum = complex1.add(complex2);
Complex difference = complex1.subtract(complex2);
Complex product = complex1.multiply(complex2);

// Display results
System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
System.out.println("Product: " + product);

scanner.close();
}
}

b) i) Explain Errors and its types in detail.


ii) Explain thread methods to set and get priority.
Ans.An Error is a subclass of the Throwable class that indicates serious problems that a
reasonable application should not try to catch. Errors typically represent unrecoverable
conditions, such as hardware failures or resource exhaustion, and are generally outside the
control of the application. This contrasts with exceptions, which are conditions that applications
might want to catch and handle.
Types of Errors
Errors in Java are divided into two main categories: Linkage Errors and Runtime Errors. Below
are detailed explanations of various types of errors in Java:
1. Linkage Errors
Linkage errors occur when the Java Virtual Machine (JVM) is unable to link a class or resource that
is required by the application at runtime. These errors can occur due to various reasons, such as
missing classes or incompatible versions of libraries.
Example:
public class Example {
public static void main(String[] args) {
try {
Class.forName("NonExistentClass");
} catch (ClassNotFoundException e) {
System.out.println("Class not found: " + e);
}
}
}

2. Runtime Errors
Runtime errors are exceptions that occur during the execution of the program. These errors
indicate that the application has encountered a condition that it cannot handle, leading to a crash
or unintended behavior.
 Example:
public class MemoryErrorExample {
public static void main(String[] args) {
try {
int[] arr = new int[Integer.MAX_VALUE]; // Attempting to allocate huge array
} catch (OutOfMemoryError e) {
System.out.println("Caught OutOfMemoryError: " + e);
}
}
}

Threads are a fundamental part of concurrent programming. Each thread has a priority that helps
the thread scheduler determine the order in which threads should be executed. Java provides
methods in the Thread class to set and get the priority of a thread. Here’s a detailed explanation
of these methods:
Thread Priority in Java
Java threads have priorities that range from 1 (minimum priority) to 10 (maximum priority). The
default priority for a thread is 5. The priority of a thread can influence the order in which threads
are scheduled for execution, but it does not guarantee execution order.
Methods to Set and Get Thread Priority
1. setPriority(int newPriority)
a. Description: This method is used to set the priority of the thread. The priority
must be between Thread.MIN_PRIORITY (1) and Thread.MAX_PRIORITY (10).
b. Syntax:
public final void setPriority(int newPriority) throws IllegalArgumentException

2.getPriority()
 Description: This method returns the priority of the thread.
 Syntax:
public final int getPriority()

Example:
public class ThreadPriorityExample {
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
System.out.println("Thread 1 is running.");
});

Thread thread2 = new Thread(() -> {


System.out.println("Thread 2 is running.");
});

// Setting priorities
thread1.setPriority(Thread.MAX_PRIORITY); // Setting maximum priority
thread2.setPriority(Thread.MIN_PRIORITY); // Setting minimum priority

// Displaying thread priorities


System.out.println("Thread 1 priority: " + thread1.getPriority());
System.out.println("Thread 2 priority: " + thread2.getPriority());

// Starting threads
thread1.start();
thread2.start();
}
}

c) Write a program to draw a chessboard in Java Applet.


Ans.
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;

public class ChessboardApplet extends Applet {

// Method to draw the chessboard


@Override
public void paint(Graphics g) {
int squareSize = 50; // Size of each square
Color color1 = Color.BLACK; // Color for black squares
Color color2 = Color.WHITE; // Color for white squares

// Loop through rows and columns to draw squares


for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
// Determine the color of the square
if ((row + col) % 2 == 0) {
g.setColor(color1);
} else {
g.setColor(color2);
}
// Draw the square
g.fillRect(col * squareSize, row * squareSize, squareSize, squareSize);
}
}
}
}

You might also like