Java Lab Solutions (1)
Java Lab Solutions (1)
java
java code:
// 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).
b. Checking and Printing the Grade of a Student Using Switch Statement and If-Else
Using Switch Statement:
java code:
javacode:
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.
java code:
Explanation:
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);
}
obj1.display();
obj2.display();
obj3.display("Values are ");
}
}
Explanation:
b. Type Casting
Program:
java code:
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:
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.
java code:
import java.util.Arrays;
Arrays.sort(numbers);
java code:
import java.util.Arrays;
if (result >= 0) {
System.out.println("Element found at index: " + result);
} else {
System.out.println("Element not found");
}
}
}
Explanation:
java code:
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.
java code:
Explanation:
System.gc() and Runtime.gc() are used to suggest the JVM to perform garbage collection.
java code:
class Employee {
String name;
int id;
void display() {
System.out.println("Name: " + name + ", ID: " + id);
}
}
@Override
void display() {
super.display();
System.out.println("Department: " + department);
}
}
@Override
void display() {
super.display();
System.out.println("Role: " + role);
}
}
prof.display();
admin.display();
}
Explanation:
Inheritance: Professor and AdminStaff classes inherit from the Employee class.
Method Overriding: Each subclass overrides the display() method to include additional information.
java code:
class Employee {
String name;
Employee(String name) {
this.name = name;
}
double computeSalary() {
return 0.0;
}
}
@Override
double computeSalary() {
return 50000 + bonus;
}
}
Polymorphism: The computeSalary() method of the Manager class is invoked at runtime even though
the reference type is Employee.
java code:
class Account {
String accountNumber;
double balance;
void display() {
System.out.println("Account Number: " + accountNumber + ", Balance: " + balance);
}
}
void addInterest() {
balance += balance * interestRate / 100;
}
@Override
void display() {
super.display();
System.out.println("Interest Rate: " + interestRate);
}
}
class Customer {
String name;
Account account;
void display() {
System.out.println("Customer Name: " + name);
account.display();
}
}
class Employee {
String name;
String employeeId;
void display() {
System.out.println("Employee Name: " + name + ", Employee ID: " + employeeId);
}
}
customer.display();
employee.display();
Program:
java code:
@Override
void display() {
System.out.println("Student Name: " + name + ", Age: " + age + ", Student ID: " +
studentId);
}
}
@Override
void display() {
System.out.println("Faculty Name: " + name + ", Age: " + age + ", Faculty ID: " +
facultyId);
}
}
student.display();
faculty.display();
Explanation:
Program:
java code:
interface Printable {
void print();
}
interface Showable {
void show();
}
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:
// String length
System.out.println("Length: " + str.length());
// 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"));
// 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().
java code:
// 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);
}
}
java code:
// Append
sb.append(" World");
System.out.println("Appended String: " + sb);
// Insert
sb.insert(5, " Java");
// 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:
8. Exception Handling
a. Demonstrating the Usage of Try and Associated Keywords
Program:
java code:
Explanation:
java code:
Explanation:
java code:
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
java code:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
int data;
while ((data = fis.read()) != -1) {
fos.write(data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation:
java code:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
int data;
while ((data = fr.read()) != -1) {
fw.write(data);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation:
Program:
java code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
Explanation:
java code:
import java.io.StringReader;
import java.io.StringWriter;
import java.util.StringTokenizer;
// 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:
java code:
// Assertion
int x = 1;
assert x > 0 : "x is not greater than 0";
System.out.println("x is greater than 0");
}
}
Explanation:
java code:
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:
java code:
Explanation:
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.
//java code:
class SharedResource {
private int data;
private boolean available = false;
Consumer(SharedResource resource) {
this.resource = 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.
Program:
java code:
Explanation:
//java code:
import java.util.Arrays;
// 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.");
}
}
JUnit Tests:
java code:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
@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:
Explanation:
JFrame: Creates a frame with a title, sets its size, specifies the default close operation, and
makes it visible.
//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;
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() + ")");
}
});
}
Explanation:
java code:
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.BorderLayout;
frame.setVisible(true);
}
}
Explanation:
BorderLayout: Arranges components in five regions: North, South, East, West, and Center.
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;
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: