0% found this document useful (0 votes)
18 views89 pages

Java Lab Manual for Engineering Students

The document is a Java Lab Manual from Avanthi Institute of Engineering and Technology, detailing various programming exercises. It includes implementations for string concatenation, circle calculations, class and object usage, constructors, and array manipulations. Additionally, it covers sales analysis, box volume calculation, and a calculator class for power operations.

Uploaded by

gavaraveekshith
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views89 pages

Java Lab Manual for Engineering Students

The document is a Java Lab Manual from Avanthi Institute of Engineering and Technology, detailing various programming exercises. It includes implementations for string concatenation, circle calculations, class and object usage, constructors, and array manipulations. Additionally, it covers sales analysis, box volume calculation, and a calculator class for power operations.

Uploaded by

gavaraveekshith
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY

(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]

JAVA LAB MANUAL

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]

1. a) Implement the following programs using command line arguments and Scanner class
i) Accept two strings from the user and print it on console with concatenation of “and”in the middle of the
strings. CO’s-CO1
Program Code:
import [Link];
public class StringConcatenation {
public static void main(String[] args) {
// Using Scanner class
Scanner scanner = new Scanner([Link]);

[Link]("Enter first string: ");


String str1 = [Link]();

[Link]("Enter second string: ");


String str2 = [Link]();

String result = str1 + " and " + str2;


[Link]("Result: " + result);

// Using command line arguments


if ([Link] >= 2) {
String cmdResult = args[0] + " and " + args[1];
[Link]("Command line result: " + cmdResult);
}

[Link]();
}
}

ii) To find the perimeter and area of a circle given a value of radius. CO’s-CO1
Program Code:

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
import [Link];

public class CircleCalculator {


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

[Link]("Enter radius: ");


double radius = [Link]();

double perimeter = 2 * [Link] * radius;


double area = [Link] * radius * radius;

[Link]("Perimeter: %.2f\n", perimeter);


[Link]("Area: %.2f\n", area);

// Using command line arguments


if ([Link] > 0) {
double cmdRadius = [Link](args[0]);
[Link]("CMD Perimeter: %.2f\n", 2 * [Link] * cmdRadius);
[Link]("CMD Area: %.2f\n", [Link] * cmdRadius * cmdRadius);
}

[Link]();
}
}
b) Write a program using classes and objects in java? CO’s-CO1
Program Code:
class Student {
private String name;
private int age;
private String grade;

// Constructor
public Student(String name, int age, String grade) {

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
[Link] = name;
[Link] = age;
[Link] = grade;
}

// Getter methods
public String getName() { return name; }
public int getAge() { return age; }
public String getGrade() { return grade; }

// Setter methods
public void setName(String name) { [Link] = name; }
public void setAge(int age) { [Link] = age; }
public void setGrade(String grade) { [Link] = grade; }

public void displayInfo() {


[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("Grade: " + grade);
}
}

public class StudentDemo {


public static void main(String[] args) {
Student student = new Student("John Doe", 20, "A");
[Link]();

// Modify using setters


[Link](21);
[Link]();
}
}
2. a) Write a program to call default constructor first and then any other constructor in the class? CO’s-
CO1

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
Program Code:
class Person {
private String name;
private int age;
private String city;

// Default constructor calls parameterized constructor


public Person() {
this("Unknown", 0); // Calls two-parameter constructor
[Link]("Default constructor called");
}

// Two-parameter constructor calls three-parameter constructor


public Person(String name, int age) {
this(name, age, "Unknown City"); // Calls three-parameter constructor
[Link]("Two-parameter constructor called");
}

// Three-parameter constructor (base constructor)


public Person(String name, int age, String city) {
[Link]("Three-parameter constructor called");
[Link] = name;
[Link] = age;
[Link] = city;
}

public void display() {


[Link]("Name: " + name + ", Age: " + age + ", City: " + city);
}
}

b) Write a program that accepts an array of integers and print those which are both odd and prime. If no
such element in that array print “Not found”. CO’s-CO1
Program Code:

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
import [Link];
import [Link];

public class OddPrimeFinder {


public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;

for (int i = 5; i * i <= n; i += 6) {


if (n % i == 0 || n % (i + 2) == 0)
return false;
}
return true;
}

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);
[Link]("Enter array size: ");
int n = [Link]();

int[] arr = new int[n];


[Link]("Enter elements:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

ArrayList<Integer> oddPrimes = new ArrayList<>();


for (int num : arr) {
if (num % 2 != 0 && isPrime(num)) {
[Link](num);
}
}

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
if ([Link]()) {
[Link]("Not found");
} else {
[Link]("Odd primes: " + oddPrimes);
}
}
}
c) Write a program to accept contents into an Integer Array and print the frequency of each number in the
order of their number of occurrences. CO’s-CO1
Program Code:
import [Link].*;

public class FrequencyCounter {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter array size: ");
int n = [Link]();

int[] arr = new int[n];


[Link]("Enter elements:");
for (int i = 0; i < n; i++) {
arr[i] = [Link]();
}

// Count frequencies
Map<Integer, Integer> frequencyMap = new HashMap<>();
for (int num : arr) {
[Link](num, [Link](num, 0) + 1);
}

// Sort by frequency (descending)


List<[Link]<Integer, Integer>> sortedList = new ArrayList<>([Link]());
[Link]((a, b) -> [Link]().compareTo([Link]()));

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
[Link]("Numbers by frequency:");
for ([Link]<Integer, Integer> entry : sortedList) {
[Link]("Number " + [Link]() +
" appears " + [Link]() + " times");
}
}
}
d) Write a program that accepts an ‘m x n’ double dimension array, where ‘m’ represents financial years
and ‘n’ represents Ids of the items sold. Each element in the array represents number of items sold in a
particular year. Identify the year and id of the item which has more demand. CO’s-CO2
Program Code:
import [Link];

public class SalesAnalysis {


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

[Link]("Enter number of years (m): ");


int m = [Link]();
[Link]("Enter number of items (n): ");
int n = [Link]();

double[][] sales = new double[m][n];

[Link]("Enter sales data:");


for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
[Link]("Year " + (i+1) + ", Item " + (j+1) + ": ");
sales[i][j] = [Link]();
}
}

// Find maximum sales


double maxSales = sales[0][0];

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
int maxYear = 0, maxItem = 0;

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


for (int j = 0; j < n; j++) {
if (sales[i][j] > maxSales) {
maxSales = sales[i][j];
maxYear = i;
maxItem = j;
}
}
}

[Link]("Highest demand:");
[Link]("Year: " + (maxYear + 1));
[Link]("Item ID: " + (maxItem + 1));
[Link]("Sales: " + maxSales);
}
}
3. a) Create a class Box that uses a parameterized constructor to initialize the dimensions of abox. The
dimensions of the Box are width, height, depth. The class should have a method that can return the
volume of the box. Create an object of the Box class and test the functionalities. CO’s-CO2
Program Code:
class Box {
private double width, height, depth;

// Parameterized constructor
public Box(double width, double height, double depth) {
[Link] = width;
[Link] = height;
[Link] = depth;
}

// Method to calculate volume


public double getVolume() {

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
return width * height * depth;
}

// Method to display box dimensions


public void displayDimensions() {
[Link]("Box Dimensions:");
[Link]("Width: " + width);
[Link]("Height: " + height);
[Link]("Depth: " + depth);
[Link]("Volume: " + getVolume());
}
}

public class BoxDemo {


public static void main(String[] args) {
// Create Box object
Box box1 = new Box(10.5, 8.0, 6.5);
[Link]();

Box box2 = new Box(5.0, 5.0, 5.0);


[Link]("Cube volume: " + [Link]());
}
}
b) Create a new class called Calculator with the following methods:
A static method called power Int(int num1,int num2) This method should return num1 to the power num2.
A static method called power Double (double num1,double num2). This method should returnnum1 to the
power num2.
Invoke both the methods and test the functionality. Also count the number of objects created.
Program Code:
class Calculator {
private static int objectCount = 0;

// Constructor to count objects


public Calculator() {

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
objectCount++;
}

// Static method for integer power


public static int powerInt(int num1, int num2) {
return (int) [Link](num1, num2);
}

// Static method for double power


public static double powerDouble(double num1, double num2) {
return [Link](num1, num2);
}

// Static method to get object count


public static int getObjectCount() {
return objectCount;
}
}

public class CalculatorDemo {


public static void main(String[] args) {
// Test static methods without creating objects
[Link]("2^3 = " + [Link](2, 3));
[Link]("2.5^2.0 = " + [Link](2.5, 2.0));

// Create objects to test counting


Calculator calc1 = new Calculator();
Calculator calc2 = new Calculator();

[Link]("Objects created: " + [Link]());


}
}
4. a) Accept a String and a number ‘n’ from user. Divide the given string into substrings each of size ‘n’
and sort them lexicographically. CO’s-CO1

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
Program Code:
import [Link].*;

public class StringDivider {


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

[Link]("Enter a string: ");


String str = [Link]();

[Link]("Enter division size (n): ");


int n = [Link]();

// Divide string into substrings


List<String> substrings = new ArrayList<>();

for (int i = 0; i < [Link](); i += n) {


int endIndex = [Link](i + n, [Link]());
[Link]([Link](i, endIndex));
}

// Sort lexicographically
[Link](substrings);

[Link]("Original string: " + str);


[Link]("Division size: " + n);
[Link]("Substrings (sorted): " + substrings);

[Link]();
}
}
b) Accept an array of strings and display the number of vowels and consonants occurred in each string.
CO’s-CO1
Program Code:

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
import [Link];

public class VowelConsonantCounter {


public static void countVowelsConsonants(String str) {
int vowels = 0, consonants = 0;
String vowelChars = "aeiouAEIOU";

for (char c : [Link]()) {


if ([Link](c)) {
if ([Link](c) != -1) {
vowels++;
} else {
consonants++;
}
}
}

[Link]("String: " + str);


[Link]("Vowels: " + vowels + ", Consonants: " + consonants);
[Link]();
}

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

[Link]("Enter number of strings: ");


int n = [Link]();
[Link](); // consume newline

String[] strings = new String[n];

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


[Link]("Enter string " + (i + 1) + ": ");
strings[i] = [Link]();

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
}

[Link]("\nResults:");
for (String str : strings) {
countVowelsConsonants(str);
}

[Link]();
}
}
c) Accept two strings from the user and determine if the strings are anagrams or not. CO’s-CO1
Program Code:
import [Link].*;

public class AnagramChecker {


public static boolean areAnagrams(String str1, String str2) {
// Remove spaces and convert to lowercase
str1 = [Link]("\\s+", "").toLowerCase();
str2 = [Link]("\\s+", "").toLowerCase();

// Check if lengths are different


if ([Link]() != [Link]()) {
return false;
}

// Convert to char arrays and sort


char[] arr1 = [Link]();
char[] arr2 = [Link]();

[Link](arr1);
[Link](arr2);

// Compare sorted arrays


return [Link](arr1, arr2);

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
}

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

[Link]("Enter first string: ");


String str1 = [Link]();

[Link]("Enter second string: ");


String str2 = [Link]();

if (areAnagrams(str1, str2)) {
[Link]("The strings are anagrams!");
} else {
[Link]("The strings are not anagrams.");
}

[Link]();
}
}
5. a) Create a multilevel inheritance for classes vehicle, brand and cost. The vehicle class determines the
type of vehicle which is inherited by the class brand which determines the brand of the vehicle. Brand
class is inherited by cost class, which tells about the cost of the vehicle. Create another class which calls
the constructor of cost class and method that displays the total vehicle information from the attributes
available in the super classes. CO’s-CO2
Program Code:
class Vehicle {
protected String vehicleType;

public Vehicle(String vehicleType) {


[Link] = vehicleType;
[Link]("Vehicle constructor called");
}

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
public void displayVehicleType() {
[Link]("Vehicle Type: " + vehicleType);
}
}

// Derived class from Vehicle


class Brand extends Vehicle {
protected String brandName;

public Brand(String vehicleType, String brandName) {


super(vehicleType);
[Link] = brandName;
[Link]("Brand constructor called");
}

public void displayBrand() {


[Link]("Brand: " + brandName);
}
}

// Derived class from Brand


class Cost extends Brand {
private double cost;

public Cost(String vehicleType, String brandName, double cost) {


super(vehicleType, brandName);
[Link] = cost;
[Link]("Cost constructor called");
}

public void displayCost() {


[Link]("Cost: $" + cost);
}

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
public void displayAllInfo() {
displayVehicleType();
displayBrand();
displayCost();
}
}

public class VehicleDemo {


public static void main(String[] args) {
Cost vehicle = new Cost("Car", "Toyota", 25000.0);
[Link]();
}
}
b) Create an inheritance hierarchy of Figure_3D, Cylinder, Cone, Sphere etc. In the base class provides
methods that are common to all Figure_3Ds and override these in the derived classes to perform different
behaviors, depending on the specific type ofFigure_3D. Create an array of Figure_3D, fill it with different
specific types ofFigure_3Ds and call your base class methods. CO’s-CO2
Program Code:
// Abstract base class
abstract class Figure3D {
protected String name;

public Figure3D(String name) {


[Link] = name;
}

public abstract double calculateVolume();


public abstract double calculateSurfaceArea();

public void displayInfo() {


[Link]("Figure: " + name);
[Link]("Volume: %.2f\n", calculateVolume());
[Link]("Surface Area: %.2f\n", calculateSurfaceArea());
}

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
}

class Cylinder extends Figure3D {


private double radius, height;

public Cylinder(double radius, double height) {


super("Cylinder");
[Link] = radius;
[Link] = height;
}

public double calculateVolume() {


return [Link] * radius * radius * height;
}

public double calculateSurfaceArea() {


return 2 * [Link] * radius * (radius + height);
}
}

class Sphere extends Figure3D {


private double radius;

public Sphere(double radius) {


super("Sphere");
[Link] = radius;
}

public double calculateVolume() {


return (4.0/3.0) * [Link] * radius * radius * radius;
}

public double calculateSurfaceArea() {


return 4 * [Link] * radius * radius;

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
}
}

public class FigureDemo {


public static void main(String[] args) {
Figure3D[] figures = {
new Cylinder(5.0, 10.0),
new Sphere(7.0)
};

for (Figure3D figure : figures) {


[Link]();
[Link]();
}
}
}
6. a) Design a package to contain the class Student that contains data members such as name,roll number
and another package contains the interface Sports which contains some sports information. Import these
two packages in a package called Report which process both Student and Sport and give the report. CO’s-
CO2
Program Code:
// Package: student
package student;

public class Student {


private String name;
private int rollNumber;

public Student(String name, int rollNumber) {


[Link] = name;
[Link] = rollNumber;
}

public String getName() { return name; }

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
public int getRollNumber() { return rollNumber; }
}

// Package: sports
package sports;

public interface Sports {


String getSportName();
int getScore();
String getPerformanceLevel();
}

public class SportInfo implements Sports {


private String sportName;
private int score;

public SportInfo(String sportName, int score) {


[Link] = sportName;
[Link] = score;
}

public String getSportName() { return sportName; }


public int getScore() { return score; }

public String getPerformanceLevel() {


if (score >= 90) return "Excellent";
else if (score >= 75) return "Good";
else if (score >= 60) return "Average";
else return "Needs Improvement";
}
}

// Package: report
package report;

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]

import [Link];
import [Link];

public class Report {


public static void generateReport(Student student, SportInfo sport) {
[Link]("=== STUDENT SPORTS REPORT ===");
[Link]("Student Name: " + [Link]());
[Link]("Roll Number: " + [Link]());
[Link]("Sport: " + [Link]());
[Link]("Score: " + [Link]());
[Link]("Performance: " + [Link]());
}
}
b) Write a program that accepts values of different data types and convert them to corresponding wrapper
classes and display using the vector. CO’s-CO1
Program Code:
import [Link];
import [Link];

public class WrapperDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
Vector<Object> vector = new Vector<>();

// Accept different data types


[Link]("Enter an integer: ");
int intValue = [Link]();
Integer intWrapper = new Integer(intValue); // Boxing
[Link](intWrapper);

[Link]("Enter a double: ");


double doubleValue = [Link]();
Double doubleWrapper = new Double(doubleValue); // Boxing

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
[Link](doubleWrapper);

[Link]("Enter a boolean: ");


boolean boolValue = [Link]();
Boolean boolWrapper = new Boolean(boolValue); // Boxing
[Link](boolWrapper);

[Link]("Enter a character: ");


char charValue = [Link]().charAt(0);
Character charWrapper = new Character(charValue); // Boxing
[Link](charWrapper);

// Display vector contents


[Link]("\nVector contents:");
for (int i = 0; i < [Link](); i++) {
Object obj = [Link](i);
[Link]("Element " + i + ": " + obj +
" (Type: " + [Link]().getSimpleName() + ")");
}

// Demonstrate unboxing
if ([Link](0) instanceof Integer) {
int unboxedInt = (Integer) [Link](0); // Unboxing
[Link]("Unboxed integer: " + unboxedInt);
}

[Link]();
}
}
7. a) Write a program to generate a set of random numbers between two numbers x1 and x2,and x1>0.
CO’s-CO1
Program Code:
import [Link];
import [Link];

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]

public class RandomNumberGenerator {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
Random random = new Random();

[Link]("Enter x1 (lower bound, x1 > 0): ");


int x1 = [Link]();

[Link]("Enter x2 (upper bound): ");


int x2 = [Link]();

// Validate input
if (x1 <= 0) {
[Link]("Error: x1 must be greater than 0");
return;
}

if (x1 >= x2) {


[Link]("Error: x2 must be greater than x1");
return;
}

[Link]("How many random numbers to generate? ");


int count = [Link]();

[Link]("\nRandom numbers between " + x1 + " and " + x2 + ":");

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


// Generate random number in range [x1, x2]
int randomNum = [Link](x2 - x1 + 1) + x1;
[Link](randomNum + " ");
}

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
[Link]();
[Link]();
}
}
b) Write a program to implement a new Array List class. It should contain add(),get(),remove(), size()
methods. Use dynamic array logic. CO’s-CO2
Program Code:
import [Link];

public class CustomArrayList<T> {


private Object[] array;
private int size;
private int capacity;
private static final int DEFAULT_CAPACITY = 10;

// Constructor
public CustomArrayList() {
[Link] = DEFAULT_CAPACITY;
[Link] = new Object[capacity];
[Link] = 0;
}

// Constructor with initial capacity


public CustomArrayList(int initialCapacity) {
if (initialCapacity < 0) {
throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
}
[Link] = initialCapacity;
[Link] = new Object[capacity];
[Link] = 0;
}

// Add method - adds element to the end


public boolean add(T element) {

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
// Check if we need to resize
if (size >= capacity) {
resize();
}

array[size] = element;
size++;
return true;
}

// Add method with index


public void add(int index, T element) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}

if (size >= capacity) {


resize();
}

// Shift elements to the right


for (int i = size; i > index; i--) {
array[i] = array[i - 1];
}

array[index] = element;
size++;
}

// Get method - returns element at specified index


@SuppressWarnings("unchecked")
public T get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
}
return (T) array[index];
}

// Remove method - removes element at specified index


@SuppressWarnings("unchecked")
public T remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}

T removedElement = (T) array[index];

// Shift elements to the left


for (int i = index; i < size - 1; i++) {
array[i] = array[i + 1];
}

size--;
array[size] = null; // Clear reference

return removedElement;
}

// Remove by object
public boolean remove(Object obj) {
for (int i = 0; i < size; i++) {
if (obj == null ? array[i] == null : [Link](array[i])) {
remove(i);
return true;
}
}
return false;
}

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]

// Size method - returns current size


public int size() {
return size;
}

// Check if list is empty


public boolean isEmpty() {
return size == 0;
}

// Clear all elements


public void clear() {
for (int i = 0; i < size; i++) {
array[i] = null;
}
size = 0;
}

// Check if contains element


public boolean contains(Object obj) {
return indexOf(obj) >= 0;
}

// Find index of element


public int indexOf(Object obj) {
for (int i = 0; i < size; i++) {
if (obj == null ? array[i] == null : [Link](array[i])) {
return i;
}
}
return -1;
}

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
// Private method to resize array when needed
private void resize() {
int newCapacity = capacity * 2;
Object[] newArray = new Object[newCapacity];

// Copy existing elements


for (int i = 0; i < size; i++) {
newArray[i] = array[i];
}

array = newArray;
capacity = newCapacity;

[Link]("Array resized to capacity: " + capacity);


}

// Get current capacity


public int getCapacity() {
return capacity;
}

// toString method for display


@Override
public String toString() {
if (size == 0) {
return "[]";
}

StringBuilder sb = new StringBuilder();


[Link]("[");
for (int i = 0; i < size; i++) {
[Link](array[i]);
if (i < size - 1) {
[Link](", ");

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
}
}
[Link]("]");
return [Link]();
}
}

// Demo class to test the CustomArrayList


public class ArrayListDemo {
public static void main(String[] args) {
CustomArrayList<String> list = new CustomArrayList<>();

// Test add method


[Link]("Adding elements...");
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link]("List: " + list);
[Link]("Size: " + [Link]());

// Test get method


[Link]("\nGetting elements...");
[Link]("Element at index 1: " + [Link](1));

// Test remove method


[Link]("\nRemoving element at index 1...");
String removed = [Link](1);
[Link]("Removed: " + removed);
[Link]("List: " + list);
[Link]("Size: " + [Link]());

// Test capacity expansion


[Link]("\nTesting capacity expansion...");
for (int i = 0; i < 15; i++) {

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
[Link]("Item" + i);
}
[Link]("Final list: " + list);
[Link]("Final size: " + [Link]());
[Link]("Final capacity: " + [Link]());
}
}
c) Create an employee class containing at least 3 details along with Id, setters, and [Link] the
employee objects dynamically key as employee id and value as its corresponding object into a HashMap.
Perform Id based search operation on the HashMap. CO’s-CO2
Program Code:

8. a) Write a program that reads file name from the user then displays information about that file, also
read the contents from the file in byte stream to count the number of alphabets,numeric values, and
special symbols. Write these statistics into another file using byte streams CO’s-CO3
Program Code:
import [Link].*;
import [Link];
public class FileStatistics
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
// Read file name from user
[Link]("Enter file name: ");
String fileName = [Link]();
try
{
// Display file information
File file = new File(fileName);
[Link]("File Name: " + [Link]());
[Link]("File Size: " + [Link]() + " bytes");
[Link]("Last Modified: " + [Link]());
// Read file using byte stream FileInputStream fis = new FileInputStream(file);
Avanthi Institute of Engineering and Technology
AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
int alphabets = 0, numerics = 0, specials = 0;
int byteData;
while ((byteData = [Link]()) != -1)
{
char ch = (char) byteData;
if ([Link](ch))
{
alphabets++;
}
else if ([Link](ch))
{
numerics++;
}
else if (![Link](ch))
{
specials++;
}
}
[Link]();
// Write statistics to output file
FileOutputStream fos = new FileOutputStream("[Link]");
String stats = "File Statistics:\n" + "Alphabets: " + alphabets + "\n" + "Numerics: " + numerics + "\n" +
"Special Symbols: " + specials + "\n";
[Link]([Link]());
[Link]();
[Link]("Statistics written to [Link]");
}
catch (IOException e)
{
[Link]("Error: " + [Link]());
}
}
}
b) Write a program that reads a CSV file containing a super market data containing product ID, Name,
Avanthi Institute of Engineering and Technology
AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
Cost and Quantity of sales and calculate the total revenue of the supermarket also sort the products in the
order of their demand. CO’s-CO3
Program Code:
import [Link].*;
import [Link].*;
class Product
{
String id, name;
double cost;
int quantity;
public Product(String id, String name, double cost, int quantity)
{
[Link] = id;
[Link] = name;
[Link] = cost;
[Link] = quantity;
}
public double getRevenue()
{
return cost * quantity;
}
}
public class SupermarketAnalysis
{
public static void main(String[] args)
{
List<Product> products = new ArrayList<>();
double totalRevenue = 0;
try
{
// Read CSV file
BufferedReader br = new BufferedReader(new FileReader("[Link]"));
String line;
[Link]();
Avanthi Institute of Engineering and Technology
AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
// Skip header
while ((line = [Link]()) != null)
{
String[] data = [Link](",");
Product product = new Product( data[0], data[1], [Link](data[2]),
[Link](data[3]) ); [Link](product); totalRevenue += [Link]();
}
[Link]();
// Sort by demand (quantity) [Link]((p1, p2) -> [Link]([Link], [Link])); //
Display results [Link]("Total Revenue: $" + totalRevenue);
[Link]("\nProducts sorted by demand:"); for (Product p : products) { [Link]("%s:
%s - Qty: %d, Revenue: $%.2f\n", [Link], [Link], [Link], [Link]());
}
}
catch (IOException e)
{
[Link]("Error reading file: " + [Link]());
}
}
}
c) Write a program that reads a text file containing some technical content and identify the technical terms
and sort them alphabetically. CO’s-CO3
Note: use a file containing stop words (general English and Grammar terms as many as possible)
Program Code:
import [Link].*;
import [Link].*;
public class TechnicalTermsExtractor
{
private static Set<String> stopWords = new HashSet<>();
public static void main(String[] args)
{
try
{
// Load stop words from file
Avanthi Institute of Engineering and Technology
AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
loadStopWords("[Link]");
// Read technical content BufferedReader br = new BufferedReader(new
FileReader("technical_content.txt"));
StringBuilder content = new StringBuilder();
String line;
while ((line = [Link]()) != null)
{
[Link](line).append(" ");
}
[Link]();
// Extract and sort technical terms
Set<String> technicalTerms = extractTechnicalTerms([Link]());
List<String> sortedTerms = new ArrayList<>(technicalTerms);
[Link](sortedTerms);
// Write results to file
PrintWriter pw = new PrintWriter("technical_terms.txt");
[Link]("Technical Terms (Alphabetically Sorted):");
for (String term : sortedTerms)
{
[Link](term);
[Link](term);
}
[Link]();
}
catch (IOException e)
{
[Link]("Error: " + [Link]());
}
}
private static void loadStopWords(String fileName) throws IOException
{
BufferedReader br = new BufferedReader(new FileReader(fileName));
String word;
while ((word = [Link]()) != null)
Avanthi Institute of Engineering and Technology
AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
{
[Link]([Link]().trim());
}
[Link]();
}
private static Set<String> extractTechnicalTerms(String content)
{
Set<String> terms = new TreeSet<>();
String[] words = [Link]().replaceAll("[^a-zA-Z\\s]", "").split("\\s+"); for (String word :
words)
{
if ([Link]() > 2 && ![Link](word))
{
[Link](word);
}
}
return terms;
}
}

9. a) Write a program that reads two numbers from the user to perform integer division into Num1 and
Num2 variables. The division of Num1 and Num2 is displayed if they are integers. If Num1 or Num2
were not an integer, the program would throw a Number Format Exception. If Num2 were Zero, the
program would throw an Arithmetic Exception. CO’s-CO3
Program Code:
import [Link];
public class IntegerDivision
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
try
{
// Read two numbers from user
Avanthi Institute of Engineering and Technology
AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
[Link]("Enter first number (Num1): ");
String input1 = [Link](); [Link]("Enter second number (Num2): ");
String input2 = [Link]();
// Parse strings to integers (may throw NumberFormatException)
int num1 = [Link](input1);
int num2 = [Link](input2);
// Perform division (may throw ArithmeticException)
int result = num1 / num2;
// Display result if successful
[Link]("Division Result: " + num1 + " / " + num2 + " = " + result);
[Link]("Remainder: " + (num1 % num2));
}
catch (NumberFormatException e)
{
[Link]("NumberFormatException: Invalid input! Please enter valid integers.");
[Link]("Error details: " + [Link]());
}
catch (ArithmeticException e)
{
[Link]("ArithmeticException: Division by zero is not allowed!");
[Link]("Error details: " + [Link]());
}
catch (Exception e)
{
[Link]("Unexpected error occurred: " + [Link]());
}
finally
{
[Link]("Program execution completed.");
[Link]();
}
}
}
b) Create a user defined exception. CO’s-CO3
Avanthi Institute of Engineering and Technology
AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
Program Code:
// Custom Exception Classes class InvalidAgeException extends Exception { public
InvalidAgeException(String message) { super(message); } } class InsufficientFundsException extends
Exception { private double balance; private double withdrawAmount; public
InsufficientFundsException(double balance, double withdrawAmount) { super("Insufficient funds!
Balance: $" + balance + ", Attempted withdrawal: $" + withdrawAmount); [Link] = balance;
[Link] = withdrawAmount; } public double getBalance() { return balance; } public double
getWithdrawAmount() { return withdrawAmount; } } // Main Application Class public class
UserDefinedException { // Method to validate age public static void validateAge(int age) throws
InvalidAgeException { if (age < 18) { throw new InvalidAgeException( "Age must be 18 or above.
Current age: " + age ); } [Link]("Age validation successful: " + age + " years old"); } //
Method to simulate bank withdrawal public static void withdraw(double balance, double amount) throws
InsufficientFundsException { if (amount > balance) { throw new InsufficientFundsException(balance,
amount); } double newBalance = balance - amount; [Link]("Withdrawal successful!");
[Link]("Amount withdrawn: $" + amount); [Link]("Remaining balance: $" +
newBalance); } public static void main(String[] args) { Scanner scanner = new Scanner([Link]); try
{ // Test age validation [Link]("Enter your age: "); int age = [Link]();
validateAge(age); // Test bank withdrawal [Link]("Enter account balance: "); double balance =
[Link](); [Link]("Enter withdrawal amount: "); double withdrawAmount =
[Link](); withdraw(balance, withdrawAmount); } catch (InvalidAgeException e)
{ [Link]("Custom Exception - InvalidAgeException: " + [Link]()); } catch
(InsufficientFundsException e) { [Link]("Custom Exception - InsufficientFundsException: " +
[Link]()); [Link]("Available balance: $" + [Link]());
[Link]("Shortfall: $" + ([Link]() - [Link]())); } catch (Exception e)
{ [Link]("Unexpected error: " + [Link]()); } finally { [Link]("Thank you
for using our application!"); [Link](); } } }
10. a) Write a program that creates 3 threads by extending the Thread class. First thread displays “Good
Morning” every 1 sec, the second thread displays “Hello” every 2seconds and the third displays
Welcome” every 3 seconds. (Repeat the same by implementing Runnable). CO’s-CO3
Program Code:
// Method 1: Extending Thread Class class GoodMorningThread extends Thread { private volatile
boolean running = true; public void run() { while (running) { try { [Link]("Good Morning - "
+ new [Link]() + " [Thread: " + [Link]().getName() + "]"); [Link](1000); // 1
second } catch (InterruptedException e) { [Link]("GoodMorningThread interrupted");
Avanthi Institute of Engineering and Technology
AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
break; } } } public void stopThread() { running = false; } } class HelloThread extends Thread { private
volatile boolean running = true; public void run() { while (running) { try { [Link]("Hello - " +
new [Link]() + " [Thread: " + [Link]().getName() + "]"); [Link](2000); // 2
seconds } catch (InterruptedException e) { [Link]("HelloThread interrupted"); break; } } }
public void stopThread() { running = false; } } class WelcomeThread extends Thread { private volatile
boolean running = true; public void run() { while (running) { try { [Link]("Welcome - " +
new [Link]() + " [Thread: " + [Link]().getName() + "]"); [Link](3000); // 3
seconds } catch (InterruptedException e) { [Link]("WelcomeThread interrupted");
break; } } } public void stopThread() { running = false; } } // Method 2: Implementing Runnable
Interface class GoodMorningRunnable implements Runnable { private volatile boolean running = true;
public void run() { while (running) { try { [Link]("Good Morning - " + new [Link]() +
" [Thread: " + [Link]().getName() + "]"); [Link](1000); } catch
(InterruptedException e) { [Link]("GoodMorningRunnable interrupted"); break; } } } public
void stop() { running = false; } } public class ThreadDemo { public static void main(String[] args)
{ [Link]("=== Extending Thread Class ==="); // Create and start threads by extending Thread
class GoodMorningThread t1 = new GoodMorningThread(); HelloThread t2 = new HelloThread();
WelcomeThread t3 = new WelcomeThread(); [Link]("GoodMorning-Thread"); [Link]("Hello-
Thread"); [Link]("Welcome-Thread"); [Link](); [Link](); [Link](); try { [Link](10000); //
Run for 10 seconds } catch (InterruptedException e) { [Link](); } // Stop threads
[Link](); [Link](); [Link](); [Link]("\n=== Implementing Runnable
Interface ==="); // Create and start threads by implementing Runnable GoodMorningRunnable r1 = new
GoodMorningRunnable(); HelloRunnable r2 = new HelloRunnable(); WelcomeRunnable r3 = new
WelcomeRunnable(); Thread thread1 = new Thread(r1, "GoodMorning-Runnable"); Thread thread2 =
new Thread(r2, "Hello-Runnable"); Thread thread3 = new Thread(r3, "Welcome-Runnable");
[Link](); [Link](); [Link](); } }
b) Write a program to illustrate Thread synchronization. CO’s-CO3
Program Code:
// Shared resource class class BankAccount { private int balance = 1000; // Unsynchronized method - can
cause race conditions public void withdrawUnsafe(int amount, String threadName) { if (balance >=
amount) { [Link](threadName + ": Checking balance... Current: " + balance); try
{ [Link](100); // Simulate processing time } catch (InterruptedException e)
{ [Link]().interrupt(); } balance -= amount; [Link](threadName + ":
Withdrawal successful. New balance: " + balance); } else { [Link](threadName + ":
Insufficient funds. Balance: " + balance); } } // Synchronized method - thread safe public synchronized
Avanthi Institute of Engineering and Technology
AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
void withdrawSafe(int amount, String threadName) { if (balance >= amount)
{ [Link](threadName + ": Checking balance... Current: " + balance); try
{ [Link](100); // Simulate processing time } catch (InterruptedException e)
{ [Link]().interrupt(); } balance -= amount; [Link](threadName + ":
Withdrawal successful. New balance: " + balance); } else { [Link](threadName + ":
Insufficient funds. Balance: " + balance); } } // Alternative: Using synchronized block public void
withdrawWithSyncBlock(int amount, String threadName) { synchronized(this) { if (balance >= amount)
{ [Link](threadName + ": Checking balance... Current: " + balance); try
{ [Link](100); } catch (InterruptedException e) { [Link]().interrupt(); } balance -=
amount; [Link](threadName + ": Withdrawal successful. New balance: " + balance); } else
{ [Link](threadName + ": Insufficient funds. Balance: " + balance); } } } public synchronized
int getBalance() { return balance; } public synchronized void resetBalance() { balance = 1000; } } //
Thread class for bank operations class BankThread extends Thread { private BankAccount account;
private boolean useSynchronization; private volatile boolean running = true; public
BankThread(BankAccount account, String name, boolean useSynchronization) { super(name);
[Link] = account; [Link] = useSynchronization; } public void run() { while
(running) { try { if (useSynchronization) { [Link](200, getName()); } else
{ [Link](200, getName()); } [Link](500); } catch (InterruptedException e)
{ [Link](getName() + " interrupted"); break; } } } public void stopThread() { running = false;
} } public class ThreadSynchronizationDemo { public static void main(String[] args) { BankAccount
account = new BankAccount(); [Link]("=== Without Synchronization ===");
[Link]("Initial Balance: " + [Link]()); // Create threads without synchronization
BankThread t1 = new BankThread(account, "Thread-1", false); BankThread t2 = new
BankThread(account, "Thread-2", false); BankThread t3 = new BankThread(account, "Thread-3", false);
[Link](); [Link](); [Link](); try { [Link](3000); } catch (InterruptedException e)
{ [Link](); } [Link](); [Link](); [Link](); [Link]("\n===
With Synchronization ==="); [Link](); [Link]("Reset Balance: " +
[Link]()); // Create threads with synchronization BankThread t4 = new BankThread(account,
"SyncThread-1", true); BankThread t5 = new BankThread(account, "SyncThread-2", true); BankThread
t6 = new BankThread(account, "SyncThread-3", true); [Link](); [Link](); [Link](); } }
11. a) Create a JApplet that displays a message which is scrolling from left to right. CO’s-CO3
Program Code
import [Link].*;
import [Link].*;

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
public class ScrollingMessageApplet extends JApplet implements Runnable {
private String message = "Welcome to Java GUI Programming! This message scrolls from left to
right!";
private int x = getWidth();
private Thread scrollThread;
private boolean running = true;

// Initialize the applet


public void init() {
setBackground([Link]);
setForeground([Link]);
setFont(new Font("Arial", [Link], 24));

// Start the scrolling thread


scrollThread = new Thread(this);
[Link]();
}

// Paint method to draw the scrolling message


public void paint(Graphics g) {
[Link](g);

// Set font and color


[Link](getFont());
[Link](getForeground());

// Draw the message at current x position


FontMetrics fm = [Link]();
int y = (getHeight() + [Link]()) / 2;
[Link](message, x, y);
}

// Thread run method for animation


public void run() {
while (running) {
try {
// Move message from right to left
x -= 3;

// Reset position when message goes off screen


if (x < -getFontMetrics(getFont()).stringWidth(message)) {
x = getWidth();
}

// Repaint and pause


repaint();
[Link](50);

} catch (InterruptedException e) {
break;
}

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
}
}

// Stop the applet


public void stop() {
running = false;
if (scrollThread != null) {
[Link]();
}
}

// Main method for standalone execution


public static void main(String[] args) {
JFrame frame = new JFrame("Scrolling Message Applet");
ScrollingMessageApplet applet = new ScrollingMessageApplet();

[Link](applet);
[Link](800, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](null);

[Link]();
[Link](true);
}
}

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]

b) Write a program that displays a sample registration page using Swing controls use appropriate layout
managers. CO’s-CO3
Program Code
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class RegistrationForm extends JFrame implements ActionListener {

// Form Components Declaration


private JTextField firstNameField, lastNameField, emailField, phoneField;
private JPasswordField passwordField, confirmPasswordField;
private JComboBox<String> courseCombo, countryCombo, stateCombo;
private JRadioButton maleRadio, femaleRadio, otherRadio;
private ButtonGroup genderGroup;
private JCheckBox sportsCheck, musicCheck, readingCheck, travelCheck;
private JCheckBox termsCheck, newsletterCheck;
private JTextArea addressArea, commentsArea;
private JSpinner ageSpinner;
private JSlider experienceSlider;
private JButton submitBtn, resetBtn, previewBtn, exitBtn;
private JLabel experienceLabel;

public RegistrationForm() {
initializeComponents();
setupLayout();
addEventListeners();
configureFrame();
}

private void initializeComponents() {


// Text Fields

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
firstNameField = new JTextField(15);
lastNameField = new JTextField(15);
emailField = new JTextField(20);
phoneField = new JTextField(15);

// Password Fields
passwordField = new JPasswordField(15);
confirmPasswordField = new JPasswordField(15);

// Combo Boxes
String[] courses = {"Select Course", "Computer Science", "Information Technology",
"Electronics Engineering", "Mechanical Engineering",
"Civil Engineering", "Business Administration"};
courseCombo = new JComboBox<>(courses);

String[] countries = {"Select Country", "India", "USA", "UK", "Canada", "Australia"};


countryCombo = new JComboBox<>(countries);

String[] states = {"Select State", "Maharashtra", "Karnataka", "Tamil Nadu",


"Gujarat", "Rajasthan", "Punjab"};
stateCombo = new JComboBox<>(states);

// Radio Buttons for Gender


maleRadio = new JRadioButton("Male");
femaleRadio = new JRadioButton("Female");
otherRadio = new JRadioButton("Other");
genderGroup = new ButtonGroup();
[Link](maleRadio);
[Link](femaleRadio);
[Link](otherRadio);

// Checkboxes for Hobbies


sportsCheck = new JCheckBox("Sports");
musicCheck = new JCheckBox("Music");

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
readingCheck = new JCheckBox("Reading");
travelCheck = new JCheckBox("Travel");

// Agreement Checkboxes
termsCheck = new JCheckBox("I agree to Terms and Conditions");
newsletterCheck = new JCheckBox("Subscribe to Newsletter");

// Text Areas
addressArea = new JTextArea(3, 25);
[Link](true);
[Link](true);

commentsArea = new JTextArea(4, 25);


[Link](true);
[Link](true);

// Spinner for Age


ageSpinner = new JSpinner(new SpinnerNumberModel(18, 16, 100, 1));

// Slider for Experience


experienceSlider = new JSlider(0, 20, 0);
[Link](5);
[Link](1);
[Link](true);
[Link](true);
experienceLabel = new JLabel("Experience: 0 years");

// Buttons
submitBtn = new JButton("Submit Registration");
resetBtn = new JButton("Reset Form");
previewBtn = new JButton("Preview Data");
exitBtn = new JButton("Exit");

// Button Styling

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}

private void setupLayout() {


setLayout(new BorderLayout());

// Title Panel (North)


JPanel titlePanel = new JPanel(new FlowLayout());
[Link]([Link]);
JLabel titleLabel = new JLabel("STUDENT REGISTRATION FORM");
[Link](new Font("Arial", [Link], 24));
[Link]([Link]);
[Link](titleLabel);

// Main Form Panel (Center) - Using GridBagLayout


JPanel mainPanel = new JPanel(new GridBagLayout());
[Link]([Link](20, 20, 20, 20));
GridBagConstraints gbc = new GridBagConstraints();
[Link] = new Insets(8, 8, 8, 8);
[Link] = [Link];

// Personal Information Section


addSectionTitle(mainPanel, "Personal Information", gbc, 0);

// Name Fields (Row 1)


[Link] = 0; [Link] = 1;
[Link](new JLabel("First Name:"), gbc);
[Link] = 1;

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
[Link](firstNameField, gbc);
[Link] = 2;
[Link](new JLabel("Last Name:"), gbc);
[Link] = 3;
[Link](lastNameField, gbc);

// Email and Phone (Row 2)


[Link] = 0; [Link] = 2;
[Link](new JLabel("Email:"), gbc);
[Link] = 1; [Link] = 2;
[Link](emailField, gbc);
[Link] = 1; [Link] = 3;
[Link](phoneField, gbc);

// Age and Gender (Row 3)


[Link] = 0; [Link] = 3;
[Link](new JLabel("Age:"), gbc);
[Link] = 1;
[Link](ageSpinner, gbc);
[Link] = 2;
[Link](new JLabel("Gender:"), gbc);
[Link] = 3;
JPanel genderPanel = new JPanel(new FlowLayout([Link], 0, 0));
[Link](maleRadio);
[Link](femaleRadio);
[Link](otherRadio);
[Link](genderPanel, gbc);

// Academic Information Section


addSectionTitle(mainPanel, "Academic Information", gbc, 4);

// Course and Country (Row 5)


[Link] = 0; [Link] = 5;
[Link](new JLabel("Course:"), gbc);

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
[Link] = 1; [Link] = 2;
[Link](courseCombo, gbc);
[Link] = 1; [Link] = 3;
[Link](countryCombo, gbc);

// Experience Slider (Row 6)


[Link] = 0; [Link] = 6;
[Link](experienceLabel, gbc);
[Link] = 1; [Link] = 3;
[Link](experienceSlider, gbc);

// Address Section
[Link] = 1;
addSectionTitle(mainPanel, "Address Information", gbc, 7);

[Link] = 0; [Link] = 8;
[Link](new JLabel("Address:"), gbc);
[Link] = 1; [Link] = 3;
[Link](new JScrollPane(addressArea), gbc);

// Hobbies Section
[Link] = 1;
addSectionTitle(mainPanel, "Hobbies & Interests", gbc, 9);

[Link] = 0; [Link] = 10;


[Link](new JLabel("Hobbies:"), gbc);
[Link] = 1; [Link] = 3;
JPanel hobbiesPanel = new JPanel(new FlowLayout([Link]));
[Link](sportsCheck);
[Link](musicCheck);
[Link](readingCheck);
[Link](travelCheck);
[Link](hobbiesPanel, gbc);

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
// Comments Section
[Link] = 1;
[Link] = 0; [Link] = 11;
[Link](new JLabel("Comments:"), gbc);
[Link] = 1; [Link] = 3;
[Link](new JScrollPane(commentsArea), gbc);

// Agreement Checkboxes
[Link] = 4; [Link] = 0; [Link] = 12;
JPanel agreementPanel = new JPanel(new FlowLayout([Link]));
[Link](termsCheck);
[Link](newsletterCheck);
[Link](agreementPanel, gbc);

// Button Panel (South)


JPanel buttonPanel = new JPanel(new FlowLayout());
[Link](submitBtn);
[Link](previewBtn);
[Link](resetBtn);
[Link](exitBtn);

// Add panels to frame


add(titlePanel, [Link]);
add(new JScrollPane(mainPanel), [Link]);
add(buttonPanel, [Link]);
}

private void addSectionTitle(JPanel panel, String title, GridBagConstraints gbc, int row) {
[Link] = 0; [Link] = row; [Link] = 4;
JLabel sectionLabel = new JLabel(title);
[Link](new Font("Arial", [Link], 16));
[Link]([Link]);
[Link]([Link](0, 0, 2, 0, [Link]));
[Link](sectionLabel, gbc);

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
[Link] = 1; // Reset gridwidth
}

private void addEventListeners() {


[Link](this);
[Link](this);
[Link](this);
[Link](this);

// Experience slider listener


[Link](e -> {
int value = [Link]();
[Link]("Experience: " + value + " years");
});

// Country combo listener


[Link](e -> {
if ([Link]().equals("India")) {
[Link](true);
} else {
[Link](false);
[Link](0);
}
});
}

private void configureFrame() {


setTitle("Student Registration System");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 700);
setLocationRelativeTo(null);
setResizable(true);
}

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
@Override
public void actionPerformed(ActionEvent e) {
if ([Link]() == submitBtn) {
submitForm();
} else if ([Link]() == resetBtn) {
resetForm();
} else if ([Link]() == previewBtn) {
previewData();
} else if ([Link]() == exitBtn) {
int choice = [Link](this,
"Are you sure you want to exit?", "Confirm Exit",
JOptionPane.YES_NO_OPTION);
if (choice == JOptionPane.YES_OPTION) {
[Link](0);
}
}
}

private void submitForm() {


// Validation
if (!validateForm()) {
return;
}

// Success message
[Link](this,
"Registration submitted successfully!\nThank you " +
[Link]() + " " + [Link]() + "!",
"Success", JOptionPane.INFORMATION_MESSAGE);

resetForm();
}

private boolean validateForm() {

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
StringBuilder errors = new StringBuilder();

if ([Link]().trim().isEmpty()) {
[Link]("• First Name is required\n");
}
if ([Link]().trim().isEmpty()) {
[Link]("• Last Name is required\n");
}
if ([Link]().trim().isEmpty()) {
[Link]("• Email is required\n");
}
if ([Link]() == 0) {
[Link]("• Please select a course\n");
}
if (![Link]() && ![Link]() && ![Link]()) {
[Link]("• Please select gender\n");
}
if (![Link]()) {
[Link]("• Please accept terms and conditions\n");
}

if ([Link]() > 0) {
[Link](this,
"Please fix the following errors:\n\n" + [Link](),
"Validation Error", JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}

private void previewData() {


StringBuilder preview = new StringBuilder();
[Link]("REGISTRATION PREVIEW\n");
[Link]("========================\n\n");

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]

[Link]("Name: ").append([Link]())
.append(" ").append([Link]()).append("\n");
[Link]("Email: ").append([Link]()).append("\n");
[Link]("Age: ").append([Link]()).append("\n");
[Link]("Course: ").append([Link]()).append("\n");
[Link]("Experience: ").append([Link]()).append(" years\n");

String gender = [Link]() ? "Male" :


[Link]() ? "Female" :
[Link]() ? "Other" : "Not specified";
[Link]("Gender: ").append(gender).append("\n");

JTextArea previewArea = new JTextArea([Link]());


[Link](false);
[Link](new Font("Courier New", [Link], 12));

[Link](this, new JScrollPane(previewArea),


"Registration Preview", JOptionPane.INFORMATION_MESSAGE);
}

private void resetForm() {


[Link]("");
[Link]("");
[Link]("");
[Link]("");
[Link]("");
[Link]("");
[Link](0);
[Link](0);
[Link](0);
[Link]();
[Link](18);
[Link](0);

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
[Link]("");
[Link]("");
[Link](false);
[Link](false);
[Link](false);
[Link](false);
[Link](false);
[Link](false);
}

public static void main(String[] args) {


try {
[Link]([Link]());
} catch (Exception e) {
[Link]();
}

[Link](() -> {
new RegistrationForm().setVisible(true);
});
}
}
c) Write a program for handling mouse events with adapter classes. CO’s-CO3
Program Code
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link];

public class MouseEventsDemo extends JFrame {

// Components for the demo


private JTextArea eventLog;

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
private JPanel mousePanel, drawingPanel;
private JLabel coordinatesLabel, statusLabel;
private JLabel clickCountLabel, dragCountLabel, moveCountLabel;

// Event counters
private int clickCount = 0, dragCount = 0, moveCount = 0;
private int wheelCount = 0, doubleClickCount = 0;

// Drawing variables
private ArrayList<Point> drawingPoints;
private boolean isDrawing = false;
private Color currentColor = [Link];

// Date formatter for timestamps


private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:[Link]");

public MouseEventsDemo() {
drawingPoints = new ArrayList<>();
initializeComponents();
setupLayout();
addMouseListeners();
configureFrame();
}

private void initializeComponents() {


// Event log area
eventLog = new JTextArea(15, 40);
[Link](false);
[Link]([Link]);
[Link]([Link]);
[Link](new Font("Courier New", [Link], 12));

// Mouse interaction panel


mousePanel = new JPanel();

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
[Link](Color.LIGHT_GRAY);
[Link](new Dimension(400, 300));
[Link]([Link](
[Link]([Link], 2),
"Mouse Event Testing Area"));
[Link]([Link](Cursor.CROSSHAIR_CURSOR));

// Drawing panel
drawingPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
[Link](g);
Graphics2D g2d = (Graphics2D) g;
[Link](RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
[Link](currentColor);
[Link](new BasicStroke(3));

for (int i = 1; i < [Link](); i++) {


Point p1 = [Link](i - 1);
Point p2 = [Link](i);
if (p1 != null && p2 != null) {
[Link](p1.x, p1.y, p2.x, p2.y);
}
}
}
};
[Link]([Link]);
[Link](new Dimension(400, 300));
[Link]([Link](
[Link]([Link], 2),
"Drawing Area - Click and Drag to Draw"));

// Status labels

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
coordinatesLabel = new JLabel("Mouse Position: (0, 0)");
[Link](new Font("Courier New", [Link], 14));

statusLabel = new JLabel("Status: Ready");


[Link](new Font("Arial", [Link], 14));
[Link]([Link]);

// Counter labels
clickCountLabel = new JLabel("Clicks: 0");
dragCountLabel = new JLabel("Drags: 0");
moveCountLabel = new JLabel("Moves: 0");
}

private void setupLayout() {


setLayout(new BorderLayout());

// Title panel
JPanel titlePanel = new JPanel();
[Link](Color.DARK_GRAY);
JLabel titleLabel = new JLabel("Mouse Events Demo with Adapter Classes");
[Link](new Font("Arial", [Link], 20));
[Link]([Link]);
[Link](titleLabel);

// Main content panel


JPanel mainPanel = new JPanel(new GridLayout(2, 2, 10, 10));
[Link]([Link](10, 10, 10, 10));

// Add components to main panel


[Link](mousePanel);
[Link](drawingPanel);
[Link](new JScrollPane(eventLog));

// Statistics panel

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
JPanel statsPanel = new JPanel(new GridLayout(3, 1, 5, 5));
[Link]([Link]("Event Statistics"));
[Link](clickCountLabel);
[Link](dragCountLabel);
[Link](moveCountLabel);
[Link](statsPanel);

// Status panel
JPanel statusPanel = new JPanel(new FlowLayout());
[Link](coordinatesLabel);
[Link](new JLabel(" | "));
[Link](statusLabel);

// Control buttons
JPanel controlPanel = new JPanel(new FlowLayout());
JButton clearLogBtn = new JButton("Clear Log");
JButton clearDrawingBtn = new JButton("Clear Drawing");
JButton resetCountersBtn = new JButton("Reset Counters");
JButton changeColorBtn = new JButton("Change Color");

// Button actions
[Link](e -> {
[Link]("Event log cleared at " + [Link](new Date()) + "\n");
});

[Link](e -> {
[Link]();
[Link]();
logEvent("DRAWING_CLEARED", 0, 0, "");
});

[Link](e -> {
clickCount = dragCount = moveCount = wheelCount = doubleClickCount = 0;
updateCounters();

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
logEvent("COUNTERS_RESET", 0, 0, "");
});

[Link](e -> {
Color newColor = [Link](this, "Choose Drawing Color", currentColor);
if (newColor != null) {
currentColor = newColor;
logEvent("COLOR_CHANGED", 0, 0, "RGB(" + [Link]() + "," +
[Link]() + "," + [Link]() + ")");
}
});

[Link](clearLogBtn);
[Link](clearDrawingBtn);
[Link](resetCountersBtn);
[Link](changeColorBtn);

// Add panels to frame


add(titlePanel, [Link]);
add(mainPanel, [Link]);
JPanel bottomPanel = new JPanel(new BorderLayout());
[Link](statusPanel, [Link]);
[Link](controlPanel, [Link]);
add(bottomPanel, [Link]);
}

private void addMouseListeners() {


// Mouse listener using MouseAdapter for mouse panel
[Link](new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
clickCount++;
String clickType = ([Link]() == 2) ? "DOUBLE" : "SINGLE";
if ([Link]() == 2) doubleClickCount++;

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]

String button = getButtonName([Link]());


logEvent("MOUSE_CLICKED", [Link](), [Link](),
clickType + " " + button + " Count:" + [Link]());
updateCounters();

// Visual feedback
[Link]([Link]);
Timer timer = new Timer(200, evt -> [Link](Color.LIGHT_GRAY));
[Link](false);
[Link]();
}

@Override
public void mousePressed(MouseEvent e) {
String button = getButtonName([Link]());
logEvent("MOUSE_PRESSED", [Link](), [Link](), button);
[Link]([Link]);
[Link]("Status: Mouse Pressed");
}

@Override
public void mouseReleased(MouseEvent e) {
String button = getButtonName([Link]());
logEvent("MOUSE_RELEASED", [Link](), [Link](), button);
[Link](Color.LIGHT_GRAY);
[Link]("Status: Mouse Released");
}

@Override
public void mouseEntered(MouseEvent e) {
logEvent("MOUSE_ENTERED", [Link](), [Link](), "Panel");
[Link]([Link]);
[Link]("Status: Mouse in Panel");

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
}

@Override
public void mouseExited(MouseEvent e) {
logEvent("MOUSE_EXITED", [Link](), [Link](), "Panel");
[Link](Color.LIGHT_GRAY);
[Link]("Status: Mouse Left Panel");
}
});

// Mouse motion listener using MouseMotionAdapter


[Link](new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
moveCount++;
[Link]("Mouse Position: (" + [Link]() + ", " + [Link]() + ")");

// Log every 50th movement to avoid spam


if (moveCount % 50 == 0) {
logEvent("MOUSE_MOVED", [Link](), [Link](), "Count:" + moveCount);
updateCounters();
}
}

@Override
public void mouseDragged(MouseEvent e) {
dragCount++;
logEvent("MOUSE_DRAGGED", [Link](), [Link](), "Count:" + dragCount);
[Link]([Link]);
[Link]("Status: Dragging");
updateCounters();
}
});

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
// Mouse wheel listener
[Link](new MouseAdapter() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
wheelCount++;
String direction = ([Link]() < 0) ? "UP" : "DOWN";
String scrollType = [Link]() == MouseWheelEvent.WHEEL_UNIT_SCROLL ?
"UNIT" : "BLOCK";
logEvent("MOUSE_WHEEL", [Link](), [Link](),
direction + " " + scrollType + " Units:" + [Link]());
}
});

// Drawing panel mouse listeners


[Link](new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
isDrawing = true;
[Link](new Point([Link](), [Link]()));
logEvent("DRAWING_STARTED", [Link](), [Link](), "Color:" + [Link]());
}

@Override
public void mouseReleased(MouseEvent e) {
isDrawing = false;
[Link](null); // Separator for line segments
logEvent("DRAWING_ENDED", [Link](), [Link](), "Points:" + [Link]());
}
});

[Link](new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
if (isDrawing) {

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
[Link](new Point([Link](), [Link]()));
[Link]();
}
}
});
}

private String getButtonName(int button) {


switch (button) {
case MouseEvent.BUTTON1: return "LEFT";
case MouseEvent.BUTTON2: return "MIDDLE";
case MouseEvent.BUTTON3: return "RIGHT";
default: return "UNKNOWN";
}
}

private void logEvent(String eventType, int x, int y, String details) {


String timestamp = [Link](new Date());
String logEntry = [Link]("[%s] %s at (%d,%d) %s\n",
timestamp, eventType, x, y, details);
[Link](logEntry);
[Link]([Link]().getLength());
}

private void updateCounters() {


[Link]("Clicks: " + clickCount);
[Link]("Drags: " + dragCount);
[Link]("Moves: " + moveCount);
}

private void configureFrame() {


setTitle("Mouse Events Demo with Adapter Classes");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(900, 700);

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
setLocationRelativeTo(null);
setResizable(true);

// Initialize log
[Link]("Mouse Events Demo Started at " + [Link](new Date()) +
"\nInteract with the panels above to see events...\n\n");
}

public static void main(String[] args) {


try {
[Link]([Link]());
} catch (Exception e) {
[Link]();
}

[Link](() -> {
new MouseEventsDemo().setVisible(true);
});
}
}
12. a) Create an interface containing 3 radio buttons named line, rectangle, and oval. Based on the radio
button selected, allow user to draw lines, rectangles, or ovals as per the locations selected by the user.
CO’s-CO3
Program Code

b) Write a program to create a Table inside a JFrame. CO’s-CO3


Program Code

c) Create an interface that illustrates JFile Chooser class and read CSV file containing employee data of
various departments and display the records department wise on the interface. CO’s-CO3
Program Code

13. a) Check all the fields filled or not, display success dialogue if all fields are filled with the help of
Action Listener for program CO’s-CO3

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
Program Code

b) Display respective error dialogue if a field is empty. CO’s-CO3


Program Code

14. Write a program to create three JSliders where each represents colors RED, GREEN and BLUE. Each
slider has a value from 0 to 255. The background color of the applet is set based on the values retrieved
from each slider to form a color using the color class constructor. On sliding any slider, the background
color of the applet changes. CO’s-CO3
Program Code
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class RGBColorMixer extends JApplet implements ChangeListener {

// JSlider components for RGB values


private JSlider redSlider, greenSlider, blueSlider;

// Labels to display current values


private JLabel redLabel, greenLabel, blueLabel;
private JLabel redValueLabel, greenValueLabel, blueValueLabel;
private JLabel colorInfoLabel;

// Panel to display the current color


private JPanel colorDisplayPanel;

// Current RGB values


private int redValue = 128, greenValue = 128, blueValue = 128;

@Override
public void init() {
// Set layout manager

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
setLayout(new BorderLayout());

// Initialize components
initializeComponents();
setupLayout();
addEventListeners();

// Set initial background color


updateBackgroundColor();

// Set applet background


getContentPane().setBackground(new Color(redValue, greenValue, blueValue));
}

private void initializeComponents() {


// Create RED slider (0-255)
redSlider = new JSlider([Link], 0, 255, redValue);
[Link](51); // Ticks at 0, 51, 102, 153, 204, 255
[Link](17);
[Link](true);
[Link](true);
[Link]([Link]);

// Create GREEN slider (0-255)


greenSlider = new JSlider([Link], 0, 255, greenValue);
[Link](51);
[Link](17);
[Link](true);
[Link](true);
[Link]([Link]);

// Create BLUE slider (0-255)


blueSlider = new JSlider([Link], 0, 255, blueValue);
[Link](51);

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
[Link](17);
[Link](true);
[Link](true);
[Link]([Link]);

// Create labels
redLabel = new JLabel("RED", [Link]);
[Link](new Font("Arial", [Link], 16));
[Link]([Link]);

greenLabel = new JLabel("GREEN", [Link]);


[Link](new Font("Arial", [Link], 16));
[Link]([Link]);

blueLabel = new JLabel("BLUE", [Link]);


[Link](new Font("Arial", [Link], 16));
[Link]([Link]);

// Value display labels


redValueLabel = new JLabel([Link](redValue), [Link]);
[Link](new Font("Arial", [Link], 24));
[Link]([Link]);
[Link](true);
[Link]([Link]);
[Link]([Link]([Link], 2));

greenValueLabel = new JLabel([Link](greenValue), [Link]);


[Link](new Font("Arial", [Link], 24));
[Link]([Link]);
[Link](true);
[Link]([Link]);
[Link]([Link]([Link], 2));

blueValueLabel = new JLabel([Link](blueValue), [Link]);

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
[Link](new Font("Arial", [Link], 24));
[Link]([Link]);
[Link](true);
[Link]([Link]);
[Link]([Link]([Link], 2));

// Color display panel


colorDisplayPanel = new JPanel();
[Link](new Dimension(400, 100));
[Link]([Link](
[Link]([Link], 3),
"Current Color Preview"));

// Color information label


colorInfoLabel = new JLabel(getColorInfo(), [Link]);
[Link](new Font("Courier New", [Link], 14));
[Link](true);
[Link]([Link]);
[Link]([Link]);
[Link]([Link](10, 10, 10, 10));
}

private void setupLayout() {


// Title panel
JPanel titlePanel = new JPanel();
[Link](Color.DARK_GRAY);
JLabel titleLabel = new JLabel("RGB Color Mixer - Adjust Sliders to Change Background");
[Link](new Font("Arial", [Link], 18));
[Link]([Link]);
[Link](titleLabel);

// Main control panel with GridBagLayout for better control


JPanel controlPanel = new JPanel(new GridBagLayout());
[Link]([Link]);

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
[Link]([Link](20, 20, 20, 20));

GridBagConstraints gbc = new GridBagConstraints();


[Link] = new Insets(10, 10, 10, 10);
[Link] = [Link];

// RED slider section


[Link] = 0; [Link] = 0; [Link] = 1;
[Link](redLabel, gbc);
[Link] = 1; [Link] = 2;
[Link](redSlider, gbc);
[Link] = 3; [Link] = 1;
[Link](redValueLabel, gbc);

// GREEN slider section


[Link] = 0; [Link] = 1; [Link] = 1;
[Link](greenLabel, gbc);
[Link] = 1; [Link] = 2;
[Link](greenSlider, gbc);
[Link] = 3; [Link] = 1;
[Link](greenValueLabel, gbc);

// BLUE slider section


[Link] = 0; [Link] = 2; [Link] = 1;
[Link](blueLabel, gbc);
[Link] = 1; [Link] = 2;
[Link](blueSlider, gbc);
[Link] = 3; [Link] = 1;
[Link](blueValueLabel, gbc);

// Color display panel


[Link] = 0; [Link] = 3; [Link] = 4;
[Link] = [Link];
[Link](colorDisplayPanel, gbc);

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]

// Color information panel


[Link] = 0; [Link] = 4; [Link] = 4;
[Link] = [Link];
[Link](colorInfoLabel, gbc);

// Preset buttons panel


JPanel presetPanel = createPresetPanel();
[Link] = 0; [Link] = 5; [Link] = 4;
[Link](presetPanel, gbc);

// Add panels to applet


add(titlePanel, [Link]);
add(controlPanel, [Link]);
}

private JPanel createPresetPanel() {


JPanel presetPanel = new JPanel(new FlowLayout());
[Link]([Link]("Preset Colors"));
[Link]([Link]);

// Create preset color buttons


addPresetButton(presetPanel, "Red", 255, 0, 0);
addPresetButton(presetPanel, "Green", 0, 255, 0);
addPresetButton(presetPanel, "Blue", 0, 0, 255);
addPresetButton(presetPanel, "Yellow", 255, 255, 0);
addPresetButton(presetPanel, "Cyan", 0, 255, 255);
addPresetButton(presetPanel, "Magenta", 255, 0, 255);
addPresetButton(presetPanel, "White", 255, 255, 255);
addPresetButton(presetPanel, "Black", 0, 0, 0);

return presetPanel;
}

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
private void addPresetButton(JPanel panel, String name, int r, int g, int b) {
JButton button = new JButton(name);
[Link](new Color(r, g, b));
[Link]((r + g + b) > 384 ? [Link] : [Link]);
[Link](new Font("Arial", [Link], 12));
[Link](new Dimension(80, 30));

[Link](e -> {
[Link](r);
[Link](g);
[Link](b);
});

[Link](button);
}

private void addEventListeners() {


// Add change listeners to all sliders
[Link](this);
[Link](this);
[Link](this);
}

@Override
public void stateChanged(ChangeEvent e) {
// Get current values from sliders
redValue = [Link]();
greenValue = [Link]();
blueValue = [Link]();

// Update value labels


[Link]([Link](redValue));
[Link]([Link](greenValue));
[Link]([Link](blueValue));

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]

// Update background color and displays


updateBackgroundColor();
updateColorInfo();
}

private void updateBackgroundColor() {


// Create new color using RGB values
Color newColor = new Color(redValue, greenValue, blueValue);

// Set applet background color


getContentPane().setBackground(newColor);

// Set color display panel background


[Link](newColor);

// Repaint to show changes


repaint();
}

private void updateColorInfo() {


[Link](getColorInfo());
}

private String getColorInfo() {


String hexColor = [Link]("#%02X%02X%02X", redValue, greenValue, blueValue);
return [Link](
"RGB(%d, %d, %d) | HEX: %s | Brightness: %.1f%%",
redValue, greenValue, blueValue, hexColor,
(redValue * 0.299 + greenValue * 0.587 + blueValue * 0.114) / 255 * 100
);
}

// Alternative main method for running as application

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
public static void main(String[] args) {
JFrame frame = new JFrame("RGB Color Mixer");
RGBColorMixer applet = new RGBColorMixer();

[Link]();
[Link](applet);
[Link](600, 500);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](null);
[Link](true);
}
}

15. Complete the code to develop an ADVANCED CALCULATOR that emulates all the functions of the
GUI Calculator as shown in the image. CO’s-CO3
Program Code
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link];

public class AdvancedCalculator extends JFrame implements ActionListener {

// Display components
private JTextField display;
private JLabel memoryDisplay;
private JTextArea historyArea;

// Calculator state variables


private double result = 0;
private double operand = 0;
private String operator = "";
private boolean startNewNumber = true;

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
private boolean operatorPressed = false;

// Memory and history


private double memory = 0;
private ArrayList<String> history = new ArrayList<>();

// Formatting
private DecimalFormat df = new DecimalFormat("#.##########");

// Button arrays for easy creation


private String[][] buttonLayout = {
{"MC", "MR", "M+", "M-", "MS"},
{"(", ")", "CE", "C", "⌫"},
{"1/x", "x²", "√", "÷", "%"},
{"7", "8", "9", "×", "sin"},
{"4", "5", "6", "-", "cos"},
{"1", "2", "3", "+", "tan"},
{"±", "0", ".", "=", "log"}
};

public AdvancedCalculator() {
initializeComponents();
setupLayout();
configureFrame();
}

private void initializeComponents() {


// Main display
display = new JTextField("0");
[Link](new Font("Courier New", [Link], 24));
[Link]([Link]);
[Link](false);
[Link]([Link]);
[Link]([Link]);

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
[Link]([Link](10, 10, 10, 10));

// Memory display
memoryDisplay = new JLabel("Memory: 0");
[Link](new Font("Arial", [Link], 12));
[Link]([Link]);
[Link]([Link]);

// History area
historyArea = new JTextArea(8, 25);
[Link](new Font("Courier New", [Link], 12));
[Link](false);
[Link](Color.LIGHT_GRAY);
[Link]("Calculator History:\n");
}

private void setupLayout() {


setLayout(new BorderLayout());

// Top panel with display and memory


JPanel topPanel = new JPanel(new BorderLayout());
[Link]([Link](10, 10, 10, 10));
[Link](display, [Link]);
[Link](memoryDisplay, [Link]);

// Button panel
JPanel buttonPanel = createButtonPanel();

// History panel
JPanel historyPanel = new JPanel(new BorderLayout());
[Link]([Link]("History"));
[Link](new JScrollPane(historyArea), [Link]);

// History control buttons

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
JPanel historyControls = new JPanel(new FlowLayout());
JButton clearHistoryBtn = new JButton("Clear History");
[Link](e -> {
[Link]();
[Link]("Calculator History:\n");
});
[Link](clearHistoryBtn);
[Link](historyControls, [Link]);

// Main layout
JPanel mainPanel = new JPanel(new BorderLayout());
[Link](topPanel, [Link]);
[Link](buttonPanel, [Link]);

add(mainPanel, [Link]);
add(historyPanel, [Link]);
}

private JPanel createButtonPanel() {


JPanel panel = new JPanel(new GridLayout(7, 5, 5, 5));
[Link]([Link](10, 10, 10, 10));

for (int row = 0; row < [Link]; row++) {


for (int col = 0; col < buttonLayout[row].length; col++) {
String buttonText = buttonLayout[row][col];
JButton button = createStyledButton(buttonText);
[Link](this);
[Link](button);
}
}

return panel;
}

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
private JButton createStyledButton(String text) {
JButton button = new JButton(text);
[Link](new Font("Arial", [Link], 14));
[Link](new Dimension(70, 50));
[Link](false);

// Color coding based on button type


if ([Link]("[0-9]")) {
// Numbers
[Link](Color.LIGHT_GRAY);
[Link]([Link]);
} else if ([Link]("[+\\-×÷=]")) {
// Basic operators
[Link]([Link]);
[Link]([Link]);
} else if ([Link]("M")) {
// Memory functions
[Link]([Link]);
[Link]([Link]);
} else if ([Link]("sin|cos|tan|log")) {
// Scientific functions
[Link]([Link]);
[Link]([Link]);
} else {
// Other functions
[Link]([Link]);
[Link]([Link]);
}

return button;
}

@Override
public void actionPerformed(ActionEvent e) {

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
String command = [Link]();

try {
if ([Link]("[0-9]")) {
handleNumber(command);
} else if ([Link](".")) {
handleDecimal();
} else if ([Link]("[+\\-×÷]")) {
handleOperator(command);
} else if ([Link]("=")) {
handleEquals();
} else if ([Link]("C")) {
handleClear();
} else if ([Link]("CE")) {
handleClearEntry();
} else if ([Link]("⌫")) {
handleBackspace();
} else if ([Link]("±")) {
handlePlusMinus();
} else if ([Link]("%")) {
handlePercent();
} else if ([Link]("√")) {
handleSquareRoot();
} else if ([Link]("x²")) {
handleSquare();
} else if ([Link]("1/x")) {
handleReciprocal();
} else if ([Link]("M")) {
handleMemory(command);
} else if ([Link]("sin|cos|tan|log")) {
handleScientific(command);
}
} catch (Exception ex) {
[Link]("Error");
Avanthi Institute of Engineering and Technology
AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
addToHistory("Error: " + [Link]());
}
}

private void handleNumber(String number) {


if (startNewNumber) {
[Link](number);
startNewNumber = false;
} else {
[Link]([Link]() + number);
}
}

private void handleDecimal() {


if (startNewNumber) {
[Link]("0.");
startNewNumber = false;
} else if (![Link]().contains(".")) {
[Link]([Link]() + ".");
}
}

private void handleOperator(String op) {


if (!operatorPressed) {
if (![Link]()) {
calculate();
} else {
result = [Link]([Link]());
}
}

operator = op;
operand = result;
operatorPressed = true;

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
startNewNumber = true;
}

private void handleEquals() {


if (![Link]()) {
String calculation = [Link](operand) + " " + operator + " " +
[Link]() + " = ";
calculate();
calculation += [Link](result);
addToHistory(calculation);

operator = "";
operatorPressed = false;
startNewNumber = true;
}
}

private void calculate() {


double currentValue = [Link]([Link]());

switch (operator) {
case "+":
result = operand + currentValue;
break;
case "-":
result = operand - currentValue;
break;
case "×":
result = operand * currentValue;
break;
case "÷":
if (currentValue == 0) {
throw new ArithmeticException("Division by zero");
}

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
result = operand / currentValue;
break;
}

[Link]([Link](result));
}

private void handleClear() {


[Link]("0");
result = 0;
operand = 0;
operator = "";
startNewNumber = true;
operatorPressed = false;
}

private void handleClearEntry() {


[Link]("0");
startNewNumber = true;
}

private void handleBackspace() {


String text = [Link]();
if ([Link]() > 1) {
[Link]([Link](0, [Link]() - 1));
} else {
[Link]("0");
startNewNumber = true;
}
}

private void handlePlusMinus() {


double value = [Link]([Link]());
value = -value;

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
[Link]([Link](value));
}

private void handlePercent() {


double value = [Link]([Link]());
value = value / 100;
[Link]([Link](value));
addToHistory([Link]() + " % = " + [Link](value));
}

private void handleSquareRoot() {


double value = [Link]([Link]());
if (value < 0) {
throw new ArithmeticException("Square root of negative number");
}
double result = [Link](value);
[Link]([Link](result));
addToHistory("√" + [Link](value) + " = " + [Link](result));
}

private void handleSquare() {


double value = [Link]([Link]());
double result = value * value;
[Link]([Link](result));
addToHistory([Link](value) + "² = " + [Link](result));
}

private void handleReciprocal() {


double value = [Link]([Link]());
if (value == 0) {
throw new ArithmeticException("Division by zero");
}
double result = 1 / value;
[Link]([Link](result));

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
addToHistory("1/" + [Link](value) + " = " + [Link](result));
}

private void handleMemory(String command) {


double value = [Link]([Link]());

switch (command) {
case "MC":
memory = 0;
addToHistory("Memory Cleared");
break;
case "MR":
[Link]([Link](memory));
addToHistory("Memory Recalled: " + [Link](memory));
startNewNumber = true;
break;
case "M+":
memory += value;
addToHistory("Memory + " + [Link](value) + " = " + [Link](memory));
break;
case "M-":
memory -= value;
addToHistory("Memory - " + [Link](value) + " = " + [Link](memory));
break;
case "MS":
memory = value;
addToHistory("Memory Stored: " + [Link](memory));
break;
}

[Link]("Memory: " + [Link](memory));


}

private void handleScientific(String function) {

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
double value = [Link]([Link]());
double result = 0;

switch (function) {
case "sin":
result = [Link]([Link](value));
break;
case "cos":
result = [Link]([Link](value));
break;
case "tan":
result = [Link]([Link](value));
break;
case "log":
if (value <= 0) {
throw new ArithmeticException("Logarithm of non-positive number");
}
result = Math.log10(value);
break;
}

[Link]([Link](result));
addToHistory(function + ("(" + [Link](value) + ") = " + [Link](result));
startNewNumber = true;
}

private void addToHistory(String entry) {


[Link](entry);
[Link](entry + "\n");
[Link]([Link]().getLength());
}

private void configureFrame() {


setTitle("Advanced Calculator");

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
pack();
setLocationRelativeTo(null);

// Add keyboard support


addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
String key = [Link]([Link]());
if ([Link]("[0-9+\\-*/=.]") || [Link]() == KeyEvent.VK_ENTER) {
if ([Link]() == KeyEvent.VK_ENTER) key = "=";
if ([Link]("*")) key = "×";
if ([Link]("/")) key = "÷";

// Simulate button press


ActionEvent ae = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, key);
actionPerformed(ae);
}
}
});

setFocusable(true);
}

public static void main(String[] args) {


try {
[Link]([Link]());
} catch (Exception e) {
[Link]();
}

[Link](() -> {
new AdvancedCalculator().setVisible(true);

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
});
}
}

16. Write a program that implements a simple client/server application. The client sends data to a server.
The server receives the data, uses it to produce a result, and then sends the result back to the client. The
client displays the result on the console. For ex: The data sent from the client is the radius of a circle,
and the result produced by the server is the area of the circle. CO’s-CO3
Program Code
Complete Server Code - [Link]:
import [Link].*;
import [Link].*;
import [Link];

public class CircleAreaServer {


private static final int PORT = 12345;
private static final DecimalFormat df = new DecimalFormat("#.####");

public static void main(String[] args) {


ServerSocket serverSocket = null;

try {
// Create server socket
serverSocket = new ServerSocket(PORT);
[Link]("🟢 Circle Area Server started on port " + PORT);
[Link]("📡 Waiting for client connections...");
[Link]("" + "=".repeat(50));

int clientCount = 0;

// Server runs indefinitely


while (true) {
try {
// Accept client connection
Socket clientSocket = [Link]();
clientCount++;

[Link]("👤 Client #" + clientCount + " connected from: " +


[Link]().getHostAddress());

// Handle client in separate thread


new Thread(new ClientHandler(clientSocket, clientCount)).start();

} catch (IOException e) {
[Link]("❌ Error accepting client connection: " + [Link]());
}

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
}

} catch (IOException e) {
[Link]("❌ Server startup error: " + [Link]());
} finally {
if (serverSocket != null) {
try {
[Link]();
[Link]("🔴 Server socket closed.");
} catch (IOException e) {
[Link]("❌ Error closing server socket: " + [Link]());
}
}
}
}

// Inner class to handle individual client connections


static class ClientHandler implements Runnable {
private Socket clientSocket;
private int clientId;

public ClientHandler(Socket socket, int id) {


[Link] = socket;
[Link] = id;
}

@Override
public void run() {
BufferedReader in = null;
PrintWriter out = null;

try {
// Set up input and output streams
in = new BufferedReader(new InputStreamReader([Link]()));
out = new PrintWriter([Link](), true);

String inputLine;

// Process client requests


while ((inputLine = [Link]()) != null) {
[Link]("📨 Client #" + clientId + " sent: " + inputLine);

if ([Link]("EXIT")) {
[Link]("👋 Client #" + clientId + " requested disconnect");
[Link]("GOODBYE");
break;
}

try {
// Parse radius and calculate area
double radius = [Link](inputLine);

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]

if (radius < 0) {
[Link]("ERROR: Radius cannot be negative");
[Link]("⚠️ Client #" + clientId + " sent negative radius");
continue;
}

// Calculate circle area: π * r²


double area = [Link] * radius * radius;
String result = [Link](area);

// Send result back to client


[Link](result);

[Link]("🧮 Calculated area for radius " + radius + ": " + result);
[Link]("📤 Result sent to Client #" + clientId);

} catch (NumberFormatException e) {
[Link]("ERROR: Invalid number format. Please enter a valid radius.");
[Link]("⚠️ Client #" + clientId + " sent invalid number: " + inputLine);
}
}

} catch (IOException e) {
[Link]("❌ Error handling Client #" + clientId + ": " + [Link]());
} finally {
// Clean up resources
try {
if (in != null) [Link]();
if (out != null) [Link]();
if (clientSocket != null) [Link]();
[Link]("🔌 Client #" + clientId + " disconnected");
[Link]("" + "-".repeat(30));
} catch (IOException e) {
[Link]("❌ Error closing client resources: " + [Link]());
}
}
}
}
}
Complete Client Code - [Link]:
import [Link].*;
import [Link].*;
import [Link];

public class CircleAreaClient {


private static final String SERVER_HOST = "localhost";
private static final int SERVER_PORT = 12345;

public static void main(String[] args) {


Socket socket = null;
Avanthi Institute of Engineering and Technology
AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
PrintWriter out = null;
BufferedReader in = null;
Scanner scanner = new Scanner([Link]);

try {
// Connect to server
[Link]("🔄 Connecting to Circle Area Server...");
socket = new Socket(SERVER_HOST, SERVER_PORT);

[Link]("✅ Connected to server at " + SERVER_HOST + ":" + SERVER_PORT);


[Link]("" + "=".repeat(50));

// Set up input and output streams


out = new PrintWriter([Link](), true);
in = new BufferedReader(new InputStreamReader([Link]()));

[Link]("🎯 Circle Area Calculator Client");


[Link]("📝 Enter the radius of a circle to calculate its area");
[Link]("💡 Type 'EXIT' to quit");
[Link]("" + "-".repeat(50));

String userInput;
String serverResponse;

// Main client loop


while (true) {
[Link]("🔵 Enter radius: ");
userInput = [Link]().trim();

if ([Link]()) {
[Link]("⚠️ Please enter a valid radius or 'EXIT' to quit.");
continue;
}

// Send data to server


[Link]("📤 Sending to server: " + userInput);
[Link](userInput);

// Read response from server


serverResponse = [Link]();

if (serverResponse == null) {
[Link]("❌ Server connection lost.");
break;
}

if ([Link]("GOODBYE")) {
[Link]("👋 Server acknowledged disconnect. Goodbye!");
break;
}

Avanthi Institute of Engineering and Technology


AVANTHI INSTITUTE OF ENGINEERING AND TECHNOLOGY
(Autonomous)
(Approved by A.I.C.T.E., New Delhi& Permanently Affiliated to J.N.T.U-GV, Vizianagaram)
NAAC “A+” Accredited Institute
Cherukupally (Village), Near TagarapuvalasaBridge, Vizianagaram(Dist) -531162.
[Link], principal@[Link]
// Display result
[Link]("📨 Server response: " + serverResponse);

if ([Link]("ERROR")) {
[Link]("❌ " + serverResponse);
} else {
try {
double area = [Link](serverResponse);
double radius = [Link](userInput);

[Link]("🎯 RESULT:");
[Link](" 📏 Radius: " + radius);
[Link](" 🔵 Area: " + area + " square units");
[Link](" 📐 Formula: π × r² = π × " + radius + "² = " + area);

} catch (NumberFormatException e) {
[Link]("✅ Server response: " + serverResponse);
}
}

[Link]("" + "-".repeat(50));
}

} catch (UnknownHostException e) {
[Link]("❌ Unknown host: " + SERVER_HOST);
[Link]("💡 Make sure the server is running and the hostname is correct.");
} catch (IOException e) {
[Link]("❌ I/O error: " + [Link]());
[Link]("💡 Make sure the server is running on port " + SERVER_PORT);
} finally {
// Clean up resources
try {
if (out != null) [Link]();
if (in != null) [Link]();
if (socket != null) [Link]();
[Link]();
[Link]("🔌 Client disconnected.");
} catch (IOException e) {
[Link]("❌ Error closing resources: " + [Link]());
}
}
}
}

Avanthi Institute of Engineering and Technology

Common questions

Powered by AI

RGB sliders can be implemented using JSlider components for each color (Red, Green, Blue), configured to range from 0 to 255. Using the ChangeListener interface, you track slider adjustments to update both a display panel's background color and corresponding labels that show current RGB values. This involves retrieving current slider values in the stateChanged method, constructing a new Color object for the panel's background, and updating label texts to reflect the sliders' numeric positions. This process is explained in .

Custom exception constructors, such as 'InsufficientFundsException,' can be designed to include current balance and attempted withdrawal amount in the error message. By extending Exception, you can store these values as object fields and format them into a comprehensive message via the constructor, thus aiding debugging and informing the user directly about why the transaction failed. This method provides direct, user-friendly feedback integrated into exception handling .

A key feature of such a client-server application is Socket programming, where the client sends a radius to the server, which computes the area of the circle (πr²). Both client and server handle streams for sending and receiving data . Invalid inputs are managed by try-catch blocks that capture NumberFormatException if the input cannot be parsed as a number, with error messages sent back to the client, guiding corrections. Specific exception handling ensures server stability and user feedback, as detailed in .

Key considerations include encapsulating the dimensions (width, height, depth) as private fields, using a parameterized constructor for initialization, and defining a method to calculate volume using the formula (width * height * depth). Additionally, object-oriented principles suggest including methods for accessing/modifying dimensions while ensuring proper encapsulation. Constructor checks might be required for valid dimensions (e.g., non-negative values). This is demonstrated through a class Box implementation described in .

Using Java Swing, you can design a panel with preset color buttons that set RGB values when clicked. By adding ActionListeners to buttons, clicking modifies the JSlider values that represent colors (redSlider, greenSlider, blueSlider) to the respective preset values. This dynamically updates a display panel's background and the sliders' positions. The interaction enables quick changes of color states while visually presenting current settings to the user, as illustrated in .

To implement a user-defined exception in Java, you need to define a new exception class extending the Exception class. Custom constructors can be used to pass specific error messages or data. For example, 'InvalidAgeException' might be used to throw an error if an age is below 18, using a method that checks age and throws the custom exception if validation fails. Similarly, an 'InsufficientFundsException' can manage bank-related errors, where withdrawal amounts exceed the current balance, encapsulating both balance and withdrawal amount as custom fields. Relevant examples are provided in .

To create a program for analyzing sales data across multiple years and items, you initialize a 2D array where each row represents a year and each column corresponds to an item’s sales figure for that year. After collecting sales data via loops, you iterate over the array to find the maximum sales value, storing its indices to identify the year and item ID. This requires tracking both current max sales and their respective indices, updating them during the iteration when a new maximum is found. This approach is demonstrated in .

Developing a registration form using GridBagLayout involves arranging components flexibly across a grid with specified constraints. GridBagConstraints assists in setting component position, size, and alignment, facilitating complex layouts. Advantages include precise control over design layout adjustments without nesting multiple panels, as each component's position and size can be individually configured. Ideal for forms with varying field sizes, spacing, and alignment, the layout maintains adaptability across different screen sizes and types. This is exemplified in .

To determine the frequency of elements in an integer array and display them in descending order, you can use a HashMap to count the occurrences of each element, and then sort these entries by their frequency. This involves reading input into an integer array, iterating over it to populate the HashMap, and then creating a list from this map's entries. The list is sorted based on frequency in descending order using a comparator. Implementation in Java includes initializing a Scanner for input, using a loop to fill the array, and further loops to count and sort using Collections. This is shown in the program from .

In Java, you can handle input and arithmetic exceptions during integer division using try-catch blocks. When reading inputs, these are parsed as integers using Integer.parseInt(), which can throw a NumberFormatException if inputs are non-integer. For division, a check is placed to capture ArithmeticException in case of division by zero. Both exceptions are handled in separate catch blocks, with error messages printed via System.err to notify the user. Additionally, unexpected errors are captured in a generic catch block, and a finally block ensures resource cleanup. This strategy is detailed in .

You might also like