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

Java Lab Solutions (1)

Uploaded by

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

Java Lab Solutions (1)

Uploaded by

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

11/9/24, 1:38 PM java lab solutions.

java

1. Implementing Different Types of Operators


a. Comparison of Values, Simple Arithmetic, and Bit-wise Operations
Program:

java code:

public class OperatorsDemo {


public static void main(String[] args) {
int a = 10;
int b = 20;

// Comparison Operators
System.out.println("a == b: " + (a == b));
System.out.println("a != b: " + (a != b));
System.out.println("a > b: " + (a > b));
System.out.println("a < b: " + (a < b));

// Arithmetic Operators
System.out.println("a + b: " + (a + b));
System.out.println("a - b: " + (a - b));
System.out.println("a * b: " + (a * b));
System.out.println("a / b: " + (a / b));
System.out.println("a % b: " + (a % b));

// Bit-wise Operators
System.out.println("a & b: " + (a & b));
System.out.println("a | b: " + (a | b));
System.out.println("a ^ b: " + (a ^ b));
System.out.println("~a: " + (~a));
System.out.println("a << 2: " + (a << 2));
System.out.println("a >> 2: " + (a >> 2));
System.out.println("a >>> 2: " + (a >>> 2));
}
}

Explanation:

Comparison Operators: These are used to compare two values. The output is a boolean (true/false).

== checks if values are equal.


!= checks if values are not equal.
> checks if the left value is greater than the right value.
< checks if the left value is less than the right value.
Arithmetic Operators: These perform basic arithmetic operations.

+ adds two values.


- subtracts the second value from the first.
* multiplies two values.
/ divides the first value by the second.
% returns the remainder of the division.
Bit-wise Operators: These operate on bits and perform bit-by-bit operations.

& performs a bit-wise AND.


| performs a bit-wise OR.
^ performs a bit-wise XOR.
~ performs a bit-wise NOT.
<< performs a left shift.
>> performs a right shift.
>>> performs a zero fill right shift.

b. Checking and Printing the Grade of a Student Using Switch Statement and If-Else
Using Switch Statement:

java code:

public class GradeSwitch {


public static void main(String[] args) {
int score = 85;
char grade;
file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 1/23
11/9/24, 1:38 PM java lab solutions.java

switch (score / 10) {


case 10:
case 9:
grade = 'A';
break;
case 8:
grade = 'B';
break;
case 7:
grade = 'C';
break;
case 6:
grade = 'D';
break;
default:
grade = 'F';
}

System.out.println("The grade is: " + grade);


}
}
Using If-Else:

javacode:

public class GradeIfElse {


public static void main(String[] args) {
int score = 85;
char grade;

if (score >= 90) {


grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else if (score >= 60) {
grade = 'D';
} else {
grade = 'F';
}

System.out.println("The grade is: " + grade);


}
}
Explanation:

Switch Statement: Divides the score by 10 to map the range of scores to a single digit, then
assigns a grade based on the case.
If-Else Statement: Checks the score against grade thresholds in descending order and assigns a
grade accordingly.

c. Demonstrating Command-Line Arguments


Program:

java code:

public class CommandLineDemo {


public static void main(String[] args) {
if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + i + ": " + args[i]);
}
} else {
System.out.println("No command-line arguments found.");
}
}
}

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 2/23


11/9/24, 1:38 PM java lab solutions.java

Explanation:

args is an array of String that stores command-line arguments.


The program checks if there are any arguments and prints each one.

2. Overloading Constructors and Methods, Type Casting


a. Overloading Constructors and Methods
Program:

java code:

class OverloadingDemo {
int a, b;

// Constructor Overloading
OverloadingDemo() {
this.a = 0;
this.b = 0;
}

OverloadingDemo(int a) {
this.a = a;
this.b = 0;
}

OverloadingDemo(int a, int b) {
this.a = a;
this.b = b;
}

// Method Overloading
void display() {
System.out.println("a: " + a + ", b: " + b);
}

void display(String message) {


System.out.println(message + " a: " + a + ", b: " + b);
}

public static void main(String[] args) {


OverloadingDemo obj1 = new OverloadingDemo();
OverloadingDemo obj2 = new OverloadingDemo(10);
OverloadingDemo obj3 = new OverloadingDemo(10, 20);

obj1.display();
obj2.display();
obj3.display("Values are ");
}
}

Explanation:

Constructor Overloading: Multiple constructors with different parameters allow object


initialization in various ways.
Method Overloading: Multiple methods with the same name but different parameters provide different
implementations.

b. Type Casting
Program:

java code:

public class TypeCastingDemo {


public static void main(String[] args) {
// Implicit Casting (Widening)
int intValue = 100;
long longValue = intValue;
float floatValue = longValue;

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 3/23


11/9/24, 1:38 PM java lab solutions.java

System.out.println("int value: " + intValue);


System.out.println("long value: " + longValue);
System.out.println("float value: " + floatValue);

// Explicit Casting (Narrowing)


double doubleValue = 100.04;
long longValue2 = (long) doubleValue;
int intValue2 = (int) longValue2;

System.out.println("double value: " + doubleValue);


System.out.println("long value (after casting): " + longValue2);
System.out.println("int value (after casting): " + intValue2);
}
}

Explanation:

Implicit Casting: Automatically converts a smaller data type to a larger data type (e.g., int to
long).
Explicit Casting: Manually converts a larger data type to a smaller data type using the cast
operator (e.g., double to int).
These are the first two sets of problems solved step-by-step. Let me know if you need any
modifications or if you want me to continue with the next problems.

3. Arrays
a. Finding the Sum and Average of Elements in an Array
Program:

java code:

public class ArraySumAndAverage {


public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int sum = 0;

for (int num : numbers) {


sum += num;
}

double average = (double) sum / numbers.length;

System.out.println("Sum: " + sum);


System.out.println("Average: " + average);
}
}

Explanation:

Sum Calculation: Iterates through the array and accumulates the sum of the elements.
Average Calculation: Divides the sum by the number of elements in the array.

b. Further Programs on the Usage of Arrays


Program: Sorting an Array

java code:

import java.util.Arrays;

public class ArraySort {


public static void main(String[] args) {
int[] numbers = {50, 20, 30, 10, 40};

Arrays.sort(numbers);

System.out.println("Sorted Array: " + Arrays.toString(numbers));


}
}

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 4/23


11/9/24, 1:38 PM java lab solutions.java
Explanation:

Uses Arrays.sort() method to sort the array in ascending order.


Program: Searching an Element in an Array

java code:

import java.util.Arrays;

public class ArraySearch {


public static void main(String[] args) {
int[] numbers = {50, 20, 30, 10, 40};
int key = 30;

int result = Arrays.binarySearch(numbers, key);

if (result >= 0) {
System.out.println("Element found at index: " + result);
} else {
System.out.println("Element not found");
}
}
}
Explanation:

Uses Arrays.binarySearch() method to search for an element in the array.


Note: The array must be sorted before using binarySearch.

4. Packages and Access Modifiers


a. Utilizing Standard and Custom Packages
Program:

java code:

// Save this file as MyPackageDemo.java in a folder named mypackage


package mypackage;

public class MyPackageDemo {


public void display() {
System.out.println("Hello from MyPackageDemo!");
}
}

// Save this file as PackageTest.java in the same folder as mypackage folder


import mypackage.MyPackageDemo;

public class PackageTest {


public static void main(String[] args) {
MyPackageDemo demo = new MyPackageDemo();
demo.display();
}
}

Explanation:

Custom Package: Defined a package named mypackage and included a class MyPackageDemo in it.
Access Modifiers: The display() method is public, so it can be accessed from outside the package.

b. Using gc() Method of System and Runtime Classes


Program:

java code:

public class GcDemo {


public static void main(String[] args) {
// Using System.gc()
System.out.println("Calling System.gc()");
System.gc();

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 5/23


11/9/24, 1:38 PM java lab solutions.java
// Using Runtime.gc()
Runtime runtime = Runtime.getRuntime();
System.out.println("Calling Runtime.gc()");
runtime.gc();
}
}

Explanation:

System.gc() and Runtime.gc() are used to suggest the JVM to perform garbage collection.

5. Inheritance and Polymorphism


a. Employee Hierarchy in a University
Program:

java code:

class Employee {
String name;
int id;

Employee(String name, int id) {


this.name = name;
this.id = id;
}

void display() {
System.out.println("Name: " + name + ", ID: " + id);
}
}

class Professor extends Employee {


String department;

Professor(String name, int id, String department) {


super(name, id);
this.department = department;
}

@Override
void display() {
super.display();
System.out.println("Department: " + department);
}
}

class AdminStaff extends Employee {


String role;

AdminStaff(String name, int id, String role) {


super(name, id);
this.role = role;
}

@Override
void display() {
super.display();
System.out.println("Role: " + role);
}
}

public class UniversityEmployee {


public static void main(String[] args) {
Professor prof = new Professor("Dr. Smith", 101, "Computer Science");
AdminStaff admin = new AdminStaff("John Doe", 102, "Registrar");

prof.display();
admin.display();
}

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 6/23


11/9/24, 1:38 PM java lab solutions.java
}

Explanation:

Inheritance: Professor and AdminStaff classes inherit from the Employee class.

Method Overriding: Each subclass overrides the display() method to include additional information.

b. Polymorphic Invocation of Methods


Program:

java code:

class Employee {
String name;

Employee(String name) {
this.name = name;
}

double computeSalary() {
return 0.0;
}
}

class Manager extends Employee {


double bonus;

Manager(String name, double bonus) {


super(name);
this.bonus = bonus;
}

@Override
double computeSalary() {
return 50000 + bonus;
}
}

public class PolymorphismDemo {


public static void main(String[] args) {
Employee emp = new Manager("Alice", 5000);
System.out.println("Salary: " + emp.computeSalary());
}
}
Explanation:

Polymorphism: The computeSalary() method of the Manager class is invoked at runtime even though
the reference type is Employee.

c. Application Using Inheritance (Banking Operations)


Program:

java code:

class Account {
String accountNumber;
double balance;

Account(String accountNumber, double balance) {


this.accountNumber = accountNumber;
this.balance = balance;
}

void deposit(double amount) {


balance += amount;
}

void withdraw(double amount) {

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 7/23


11/9/24, 1:38 PM java lab solutions.java
if (balance >= amount) {
balance -= amount;
} else {
System.out.println("Insufficient balance");
}
}

void display() {
System.out.println("Account Number: " + accountNumber + ", Balance: " + balance);
}
}

class SavingsAccount extends Account {


double interestRate;

SavingsAccount(String accountNumber, double balance, double interestRate) {


super(accountNumber, balance);
this.interestRate = interestRate;
}

void addInterest() {
balance += balance * interestRate / 100;
}

@Override
void display() {
super.display();
System.out.println("Interest Rate: " + interestRate);
}
}

class Customer {
String name;
Account account;

Customer(String name, Account account) {


this.name = name;
this.account = account;
}

void display() {
System.out.println("Customer Name: " + name);
account.display();
}
}

class Employee {
String name;
String employeeId;

Employee(String name, String employeeId) {


this.name = name;
this.employeeId = employeeId;
}

void display() {
System.out.println("Employee Name: " + name + ", Employee ID: " + employeeId);
}
}

public class BankingApplication {


public static void main(String[] args) {
SavingsAccount savingsAccount = new SavingsAccount("12345", 1000, 5);
Customer customer = new Customer("John Doe", savingsAccount);
Employee employee = new Employee("Alice", "E001");

customer.display();
employee.display();

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 8/23


11/9/24, 1:38 PM java lab solutions.java
savingsAccount.addInterest();
customer.display();
}
}
Explanation:

Inheritance: SavingsAccount inherits from Account.


Banking Operations: Demonstrates account operations like deposit, withdrawal, and adding interest.
Customer and Employee Classes: Represent customer and employee entities in the banking
application.
These are the next three sets of problems solved step-by-step. Let me know if you need more
solutions or any modifications.

6. Abstract Classes and Interfaces


a. Demonstrating the Use of Abstract Classes

Program:

java code:

abstract class Person {


String name;
int age;

Person(String name, int age) {


this.name = name;
this.age = age;
}

abstract void display();


}

class Student extends Person {


String studentId;

Student(String name, int age, String studentId) {


super(name, age);
this.studentId = studentId;
}

@Override
void display() {
System.out.println("Student Name: " + name + ", Age: " + age + ", Student ID: " +
studentId);
}
}

class Faculty extends Person {


String facultyId;

Faculty(String name, int age, String facultyId) {


super(name, age);
this.facultyId = facultyId;
}

@Override
void display() {
System.out.println("Faculty Name: " + name + ", Age: " + age + ", Faculty ID: " +
facultyId);
}
}

public class AbstractClassDemo {


public static void main(String[] args) {
Student student = new Student("John Doe", 20, "S123");
Faculty faculty = new Faculty("Dr. Smith", 45, "F456");

student.display();
faculty.display();

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 9/23


11/9/24, 1:38 PM java lab solutions.java
}
}

Explanation:

Abstract Class: Person is an abstract class with an abstract method display().


Subclass: Student and Faculty classes extend Person and implement the display() method.

b. Demonstrating the Usage of Interfaces

Program:

java code:

interface Printable {
void print();
}

interface Showable {
void show();
}

class TestInterface implements Printable, Showable {


public void print() {
System.out.println("Hello");
}

public void show() {


System.out.println("Welcome");
}

public static void main(String[] args) {


TestInterface obj = new TestInterface();
obj.print();
obj.show();
}
}
Explanation:

Interfaces: Printable and Showable interfaces declare methods print() and show().
Implementation: TestInterface class implements both interfaces and defines the methods.

7. String Manipulations
a. Understanding the Full Capability of String Class
Program:

java code:

public class StringDemo {


public static void main(String[] args) {
String str = "Hello World";

// String length
System.out.println("Length: " + str.length());

// Character at specific index


System.out.println("Character at index 4: " + str.charAt(4));

// Substring
System.out.println("Substring (0, 5): " + str.substring(0, 5));

// Index of
System.out.println("Index of 'World': " + str.indexOf("World"));

// Replace
System.out.println("Replace 'World' with 'Java': " + str.replace("World", "Java"));

// Uppercase and Lowercase


System.out.println("Uppercase: " + str.toUpperCase());

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 10/23


11/9/24, 1:38 PM java lab solutions.java
System.out.println("Lowercase: " + str.toLowerCase());

// Trim
String strWithSpaces = " Hello World ";
System.out.println("Trimmed: '" + strWithSpaces.trim() + "'");

// Split
String[] words = str.split(" ");
for (String word : words) {
System.out.println("Word: " + word);
}

// Concatenation
String str2 = "!";
System.out.println("Concatenated String: " + str.concat(str2));
}
}

Explanation:

Demonstrates various String methods such as length(), charAt(), substring(), indexOf(), replace(),
toUpperCase(), toLowerCase(), trim(), split(), and concat().

b. StringBuffer and StringBuilder

Program: Using StringBuffer

java code:

public class StringBufferDemo {


public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");

// Append
sb.append(" World");
System.out.println("Appended String: " + sb);

// Insert
sb.insert(5, " Java");
System.out.println("Inserted String: " + sb);

// Replace
sb.replace(6, 10, "Language");
System.out.println("Replaced String: " + sb);

// Delete
sb.delete(6, 14);
System.out.println("Deleted String: " + sb);

// Reverse
sb.reverse();
System.out.println("Reversed String: " + sb);
}
}

Program: Using StringBuilder

java code:

public class StringBuilderDemo {


public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");

// Append
sb.append(" World");
System.out.println("Appended String: " + sb);

// Insert
sb.insert(5, " Java");

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 11/23


11/9/24, 1:38 PM java lab solutions.java
System.out.println("Inserted String: " + sb);

// Replace
sb.replace(6, 10, "Language");
System.out.println("Replaced String: " + sb);

// Delete
sb.delete(6, 14);
System.out.println("Deleted String: " + sb);

// Reverse
sb.reverse();
System.out.println("Reversed String: " + sb);
}
}

Explanation:

StringBuffer: Mutable sequence of characters, thread-safe.


StringBuilder: Mutable sequence of characters, not thread-safe but faster.

8. Exception Handling
a. Demonstrating the Usage of Try and Associated Keywords
Program:

java code:

public class ExceptionDemo {


public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of bounds!");
} finally {
System.out.println("This block is always executed.");
}
}
}

Explanation:

try: Block to wrap code that may throw an exception.


catch: Block to handle the exception.
finally: Block that always executes, regardless of whether an exception was thrown.

b. Creating and Using Custom Exceptions


Program:

java code:

class CustomException extends Exception {


public CustomException(String message) {
super(message);
}
}

public class CustomExceptionDemo {


public static void main(String[] args) {
try {
throw new CustomException("This is a custom exception");
} catch (CustomException e) {
System.out.println(e.getMessage());
}
}
}

Explanation:

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 12/23


11/9/24, 1:38 PM java lab solutions.java
Custom Exception: Extends Exception class and can be thrown using throw keyword.

c. Using Various Methods of Throwable, Exception Classes and Chaining Exceptions


Program:

java code:

public class ChainingExceptionDemo {


public static void main(String[] args) {
try {
method1();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void method1() throws Exception {


try {
method2();
} catch (Exception e) {
throw new Exception("Exception in method1", e);
}
}

public static void method2() throws Exception {


throw new Exception("Exception in method2");
}
}

Explanation:

Exception Chaining: method1 catches the exception from method2 and throws a new exception with the
original exception as the cause.
Throwable Methods: printStackTrace() is used to print the stack trace of the exception.
These are the next three sets of problems solved step-by-step. Let me know if you need more
solutions or any modifications.

9. File Operations

a. Using Byte Streams to Read from and Write to Files


Program:

java code:

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

public class ByteStreamDemo {


public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("input.txt");
FileOutputStream fos = new FileOutputStream("output.txt")) {

int data;
while ((data = fis.read()) != -1) {
fos.write(data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation:

FileInputStream: Reads bytes from a file.


FileOutputStream: Writes bytes to a file.
Try-with-Resources: Ensures that the streams are closed after the operation.

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 13/23


11/9/24, 1:38 PM java lab solutions.java

b. Using FileReader and FileWriter for File Copying


Program:

java code:

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

public class FileReaderWriterDemo {


public static void main(String[] args) {
try (FileReader fr = new FileReader("input.txt");
FileWriter fw = new FileWriter("output.txt")) {

int data;
while ((data = fr.read()) != -1) {
fw.write(data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation:

FileReader: Reads characters from a file.


FileWriter: Writes characters to a file.

c. Counting Characters, Lines, and Words in a Text File

Program:

java code:

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

public class FileStatistics {


public static void main(String[] args) {
int charCount = 0;
int wordCount = 0;
int lineCount = 0;

try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {


String line;
while ((line = br.readLine()) != null) {
lineCount++;
charCount += line.length();
String[] words = line.split("\\s+");
wordCount += words.length;
}
} catch (IOException e) {
e.printStackTrace();
}

System.out.println("Number of Characters: " + charCount);


System.out.println("Number of Words: " + wordCount);
System.out.println("Number of Lines: " + lineCount);
}
}

Explanation:

BufferedReader: Reads text from a character-input stream.


File Statistics: Counts the number of characters, words, and lines.

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 14/23


11/9/24, 1:38 PM java lab solutions.java
10. StringTokenizer, StringReader, StringWriter, and Assertions
a. Using StringTokenizer, StringReader, and StringWriter
Program:

java code:

import java.io.StringReader;
import java.io.StringWriter;
import java.util.StringTokenizer;

public class StringClassDemo {


public static void main(String[] args) {
// StringTokenizer
String str = "Hello World from StringTokenizer";
StringTokenizer st = new StringTokenizer(str);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}

// StringReader
StringReader sr = new StringReader("Hello World from StringReader");
int data;
try {
while ((data = sr.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println();

// StringWriter
StringWriter sw = new StringWriter();
sw.write("Hello World from StringWriter");
System.out.println(sw.toString());
}
}

Explanation:

StringTokenizer: Splits the string into tokens based on delimiters.


StringReader: Reads characters from a string as a source.
StringWriter: Writes characters to a string buffer.

b. Demonstrating Enumerations and Assertions


Program:

java code:

public class EnumDemo {


enum Days {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public static void main(String[] args) {


for (Days day : Days.values()) {
System.out.println(day);
}

// Assertion
int x = 1;
assert x > 0 : "x is not greater than 0";
System.out.println("x is greater than 0");
}
}

Explanation:

Enumerations: Days enum lists the days of the week.

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 15/23


11/9/24, 1:38 PM java lab solutions.java
Assertions: assert keyword checks the truth of an expression and throws an AssertionError if the
expression is false.

c. Demonstrating Assertions through Simple Programs


Program:

java code:

public class AssertionDemo {


public static void main(String[] args) {
int number = -1;
assert number >= 0 : "Number is negative";
System.out.println("Number is non-negative");
}
}

Explanation:

Assertions: Ensures that number is non-negative, and if not, throws an AssertionError with the
message "Number is negative".

11. Threads
a. Illustrating the Use of Thread Class and Runnable Interface
Program: Using Thread Class

java code:

class MyThread extends Thread {


public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread using Thread class: " + i);
}
}
}

public class ThreadDemo {


public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}

Program: Using Runnable Interface

java code:

class MyRunnable implements Runnable {


public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread using Runnable interface: " + i);
}
}
}

public class RunnableDemo {


public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
t1.start();
}
}

Explanation:

Thread Class: Extends Thread class and overrides run() method.


Runnable Interface: Implements Runnable interface and overrides run() method.

b. Showing the Assignment of Thread Priorities


Program:

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 16/23


11/9/24, 1:38 PM java lab solutions.java
java code:

class PriorityThread extends Thread {


public void run() {
System.out.println(Thread.currentThread().getName() + " - Priority: " +
Thread.currentThread().getPriority());
}
}

public class ThreadPriorityDemo {


public static void main(String[] args) {
PriorityThread t1 = new PriorityThread();
PriorityThread t2 = new PriorityThread();
PriorityThread t3 = new PriorityThread();

t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.NORM_PRIORITY);
t3.setPriority(Thread.MAX_PRIORITY);

t1.start();
t2.start();
t3.start();
}
}

Explanation:

Thread Priorities: MIN_PRIORITY, NORM_PRIORITY, and MAX_PRIORITY are used to set the priority of
threads.

c. Synchronizing Threads (Producer-Consumer Problem)


Program:

//java code:
class SharedResource {
private int data;
private boolean available = false;

public synchronized void produce(int value) {


while (available) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
data = value;
available = true;
System.out.println("Produced: " + data);
notify();
}

public synchronized void consume() {


while (!available) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Consumed: " + data);
available = false;
notify();
}
}

class Producer extends Thread {


private SharedResource resource;

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 17/23


11/9/24, 1:38 PM java lab solutions.java
Producer(SharedResource resource) {
this.resource = resource;
}

public void run() {


for (int i = 0; i < 5; i++) {
resource.produce(i);
}
}
}

class Consumer extends Thread {


private SharedResource resource;

Consumer(SharedResource resource) {
this.resource = resource;
}

public void run() {


for (int i = 0; i < 5; i++) {
resource.consume();
}
}
}

public class ProducerConsumerDemo {


public static void main(String[] args) {
SharedResource resource = new SharedResource();
Producer producer = new Producer(resource);
Consumer consumer = new Consumer(resource);

producer.start();
consumer.start();
}
}

Explanation:

Producer-Consumer Problem: Demonstrates thread synchronization using wait() and notify() methods.
SharedResource: Shared object used by both producer and consumer threads to store and retrieve
data.
These are the next three sets of problems solved step-by-step. Let me know if you need more
solutions or any modifications.

12. Advanced Calculator and Testing


a. Advanced Calculator with Modules

Program:

java code:

public class AdvancedCalculator {


public static void main(String[] args) {
// Checking if a number is prime
int number = 29;
if (isPrime(number)) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}

// Sum of N prime numbers


int N = 5;
System.out.println("Sum of first " + N + " prime numbers: " + sumOfNPrimes(N));

// Checking if a number is even


number = 8;
if (isEven(number)) {

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 18/23


11/9/24, 1:38 PM java lab solutions.java
System.out.println(number + " is an even number.");
} else {
System.out.println(number + " is an odd number.");
}

// Sum of N even and odd numbers


System.out.println("Sum of first " + N + " even numbers: " + sumOfNEvens(N));
System.out.println("Sum of first " + N + " odd numbers: " + sumOfNOdds(N));
}

public static boolean isPrime(int num) {


if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}

public static int sumOfNPrimes(int N) {


int count = 0, sum = 0, num = 2;
while (count < N) {
if (isPrime(num)) {
sum += num;
count++;
}
num++;
}
return sum;
}

public static boolean isEven(int num) {


return num % 2 == 0;
}

public static int sumOfNEvens(int N) {


int sum = 0;
for (int i = 1; i <= N; i++) {
sum += 2 * i;
}
return sum;
}

public static int sumOfNOdds(int N) {


int sum = 0;
for (int i = 0; i < N; i++) {
sum += 2 * i + 1;
}
return sum;
}
}

Explanation:

isPrime: Checks if a number is prime.


sumOfNPrimes: Calculates the sum of the first N prime numbers.
isEven: Checks if a number is even.
sumOfNEvens: Calculates the sum of the first N even numbers.
sumOfNOdds: Calculates the sum of the first N odd numbers.

b. Sorting and Searching with JUnit Tests


Program:

//java code:

import java.util.Arrays;

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 19/23


11/9/24, 1:38 PM java lab solutions.java

public class ArrayOperations {


public static void main(String[] args) {
int[] array = {5, 3, 8, 4, 2};

// Sorting
Arrays.sort(array);
System.out.println("Sorted array: " + Arrays.toString(array));

// Searching
int key = 4;
int index = Arrays.binarySearch(array, key);
if (index >= 0) {
System.out.println(key + " found at index " + index);
} else {
System.out.println(key + " not found in the array.");
}
}

public static int[] sortArray(int[] array) {


Arrays.sort(array);
return array;
}

public static int searchArray(int[] array, int key) {


return Arrays.binarySearch(array, key);
}
}

JUnit Tests:

java code:

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class ArrayOperationsTest {


@Test
public void testSortArray() {
int[] array = {5, 3, 8, 4, 2};
int[] sortedArray = {2, 3, 4, 5, 8};
assertArrayEquals(sortedArray, ArrayOperations.sortArray(array));
}

@Test
public void testSearchArray() {
int[] array = {2, 3, 4, 5, 8};
int key = 4;
int index = 2;
assertEquals(index, ArrayOperations.searchArray(array, key));
}

@Test
public void testSearchArrayNotFound() {
int[] array = {2, 3, 4, 5, 8};
int key = 7;
assertTrue(ArrayOperations.searchArray(array, key) < 0);
}
}

Explanation:

sortArray: Sorts the array using Arrays.sort().


searchArray: Searches for a key in the array using Arrays.binarySearch().
JUnit Tests: Tests the sortArray and searchArray methods.
/*
13. GUI Applications and Events
a. Designing a Frame and Controlling Display Properties
Program:

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 20/23


11/9/24, 1:38 PM java lab solutions.java
*/
//java code:
import javax.swing.JFrame;

public class FrameDemo {


public static void main(String[] args) {
JFrame frame = new JFrame("My Frame");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Explanation:

JFrame: Creates a frame with a title, sets its size, specifies the default close operation, and
makes it visible.

b. Understanding Keyboard and Mouse Events using Adapter Classes


Program:

//java code:

import javax.swing.JFrame;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class EventDemo extends JFrame {


public EventDemo() {
setSize(400, 300);
setTitle("Event Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("Key Pressed: " + e.getKeyChar());
}
});

addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse Clicked at: (" + e.getX() + ", " + e.getY() + ")");
}
});
}

public static void main(String[] args) {


EventDemo frame = new EventDemo();
frame.setVisible(true);
}
}

Explanation:

KeyAdapter: Handles key events such as key presses.


MouseAdapter: Handles mouse events such as mouse clicks.

14. Layout Managers and Swing Components


a. Demonstrating a Layout Manager
Program: Using BorderLayout

java code:

import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.BorderLayout;

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 21/23


11/9/24, 1:38 PM java lab solutions.java
public class BorderLayoutDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("BorderLayout Demo");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());

frame.add(new JButton("North"), BorderLayout.NORTH);


frame.add(new JButton("South"), BorderLayout.SOUTH);
frame.add(new JButton("East"), BorderLayout.EAST);
frame.add(new JButton("West"), BorderLayout.WEST);
frame.add(new JButton("Center"), BorderLayout.CENTER);

frame.setVisible(true);
}
}

Explanation:

BorderLayout: Arranges components in five regions: North, South, East, West, and Center.

b. GUI Application with Swing Components and Event Handling


Program:

java code:

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SwingComponentsDemo {


public static void main(String[] args) {
JFrame frame = new JFrame("Swing Components Demo");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel();


JLabel label = new JLabel("Click the button");
JButton button = new JButton("Click Me");

button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText("Button Clicked!");
}
});

panel.add(label);
panel.add(button);
frame.add(panel);

frame.setVisible(true);
}
}

Explanation:

Swing Components: Uses JFrame, JPanel, JLabel, and JButton.


Event Handling: Changes the label text when the button is clicked using ActionListener.
These are the final three sets of problems solved step-by-step. Let me know if you need more
solutions or any modifications.

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 22/23


11/9/24, 1:38 PM java lab solutions.java

file:///C:/Users/Hello/Desktop/OOPSJ/java lab solutions.java 23/23

You might also like