Javaa Aat
Javaa Aat
COLLEGE OF ENGINEERING
(Autonomous college under VTU)
Bull Temple Rd, Basavanagudi, Bengaluru, Karnataka 560019
2024-2026
Department of Computer Applications
AAT-1. 1. The following table shows the employees code and the percentage of 10-17
bonus for the value of basic pay.
Employee code Bonus
100 5
200 1
300 2
400 25
2. Write a program to display the following output using for loop:
( a)
1
12
123
1234
12345
( b)
1
22
333
4444
55555
( c)
*****
****
***
**
*
3. Write a program that performs the following: If the user gives input as 1,
the output is 2; if the input is 2 then the output becomes 1.
4. Write and run a Java program that inputs three names and print them in
their alphabetical order.
5. A number is said to be palindrome if it is invariant under reversion; that
is, the number is the same if its digits are reversed. For example, 3456543
is palindromic. Write a program that checks each of the fi rst 10,000 prime
numbers and prints those that are palindromic.
6. Design a class to represent account, include the following members.
Data Members:
• Name of depositor—string
• Account Number—int
• Type of Account—boolean
• Balance amount—double
Methods
AAT-4. 1. Provided that you have a given number of small rice bags (1 kilo each) and big 29-37
rice bags (5kilos each), write a method that returns true if it is possible to make a
package with goal kilos of rice.
2. Write a class called Employee, which models an employee with an ID, name
and salary, is designed as shown in the following class diagram. The method
raiseSalary(percent) increases the salary by the given percentage. Write the
Employee class.
3. Write a class called Author (as shown in the class diagram) is designed to
model a book's author. It contains:
• Three private instance variables: name (String), email (String), and gender (char
of either 'm' or 'f');
• One constructor to initialize the name, email and gender with the given values;
public Author (String name, String email, char gender) {......}
• public getters/setters: getName(), getEmail(), setEmail(), and getGender();
• A toString() method that returns "Author[name=?,email=?,gender=?]", e.g.,
"Author[name=Tan Ah Teck,email=ahTeck@somewhere.com,gender=m]".
4. In this exercise, a subclass called Cylinder is derived from the superclass Circle
as shown in the
class diagram. Study how the subclass Cylinder invokes the superclass'
constructors (via super() and super(radius)) and inherits the variables and methods
from the superclass Circle.
• The subclass Cylinder inherits getArea() method from its superclass Circle. Try
overriding the getArea() method in the subclass Cylinder to compute the surface
area(=2π×radius×height + 2×base-area) of the cylinder instead of base area.
o That is, if getArea() is called by a Circle instance, it returns the area.
o If getArea() is called by a Cylinder instance, it returns the surface area of the
cylinder.
• If you override the getArea() in the subclass Cylinder, the getVolume() no longer
works. This is because the getVolume() uses the overridden getArea() method
found in the same class. Fix the getVolume().
5. Define a class CARRENTAL with the following details :
• Class Members are: CarId of int type, CarType of string type and Rent of float
type.
• Define GetCar() method which accepts CarId and CarType.
• GetRent() method which return rent of the car on the basis of car type, i.e. Small
Car= 1000, Van = 800, SUV = 2500
• ShowCar() method which allow user to view the contents of cars i.e. id, type and
rent.
AAT-5. 1. Create an abstract class “BankAccount” with abstract methods “deposit()” and 38-45
“withdraw()”. Implement two subclasses “SavingsAccount”
and“CheckingAccount” which extend “BankAccount” and implement the abstract
methods. Create a“Customer” class which contains a list of “BankAccount”
objects. Add methods to the “Customer” class to display account balances,
deposit/withdraw money, etc. Create objects of all classes and test their behavior.
2. An abstract class called “Marks” is needed to calculate the percentage of marks
earned by students A in three subjects (with each subject out of 100) and student
B in four subjects (with each subject out of 100). This class must contain the
abstract method “getPercentage,” which two other classes, “A” and “B,” will
inherit. The method “getPercentage,” which provides the percentage of students,
is shared by classes “A” and “B.”
The constructor of class ‘A’ will accept the marks obtained in three subjects as its
parameters and the constructor of class ‘B’ will accept the marks obtained in four
subjects as its parameters. To test the implementation, objects for both the classes
need to be created and the percentage of marks for each student should be printed.
3. Write a Java program using a function root to calculate and display all roots of
the quadratic AX2 + BX + C = 0.
4. Write a program to fi nd the volume of a box that has its sides w, h, d as width,
height, and depth, respectively. Its volume is v = w * h * d and also fi nd the
surface area given by the formula s = 2(wh + hd + dw).
5. A class weight is having a data member pound, which will have the weight in
pounds. Using a conversion function, convert the weight in pounds to weight in
kilograms which is of double type. Write a program to do this.
1 pounds =1 kg/0.453592
Use default constructor to initial assignment of 1000 pounds.
AAT-6. 1. Write a package called Clear, it contains one public method clrscr() to clear the 46-50
screen, import the package and use it in another programs. Add another public
method starline(). It prints the line of 15 starts.
2. Define an exception called " No Equal Exception " that is thrown when a float
value is not equal to 3.14. Write a program that uses the above user defi ned
exception.
3. Write a java program using threads to simulate traffic lights switch between
Red, Green, and Yellow with fixed delays.
AAT-7. 1. Write a package called Clear, it contains one public method clrscr() to clear the 51-55
screen, import the package and use it in another programs. Add another public
method starline(). It prints the line of 15 stars.
2. Write a program in Java. A class Teacher contains two fi elds, Name and Qualifi
cation. Extend the class to Department, it contains Dept. No and Dept. Name. An
interface named as College contains one fi eld Name of the college. Using the
above classes and Interface get the appropriate information and display it.
3. Write and run the following Java program that does the following:
a) Declare a string object named s1 containing the string "Object Oriented
Programming-
Java 5".
b) Print the entire string.
c) Use the length() method to find the length of the string.
d) Use the charAt() method to find the first character in the string.
e) Use charAt() and length() methods to print the last character in the string.
f) Use the indexOf() and the substring() method to print the first word in the String.
AAT-8. 1. Write a program that accepts a name list of five students from the command 56-60
line and store in a vector.
2. Write and run the following Java program that does the following:
a) Declare a string object named s1 containing the string "Object Oriented
Programming-Java 5".
b) Print the entire string.
c) Use the length() method to find the length of the string.
d) Use the charAt() method to find the first character in the string.
e) Use charAt() and length() methods to print the last character in the string.
f) Use the indexOf() and the substring() method to print the first word in the
String.
3. Define an exception called " No Equal Exception " that is thrown when a fl oat
value is not equal to 3.14. Write a program that uses the above user defi ned
exception.
4. Write a java program using threads to simulate traffic lights switch between
Red, Green, and Yellow with fixed delays.
5. Write a Java program to accept two parameters on the command line. If there
are no
command line arguments entered, the program should print the error message
and exit. The program should check whether the first fi le exists and if it is an
ordinary file. If it is so, then the content is copied to the second file.
AAT-9. 1. Write a Java program to check whether the file is readable, writable and 61-66
hidden.
2. Write a program using Lambda expression to filter the Employee objects.
Each employee has
a name, department, and salary.
• Employees with salary > 50,000
• Employees in the "IT" department
3. You’re building a system that handles different types of items in an online
store. You want to
create an Inventory<T> class that can store any type of item (books, electronics,
etc.).
4. Write a program using autoboxing to calculate the discounted prices for a
shopping cart. The
system stores prices as Double, but the calculations are done using double.
AAT-1
1. The following table shows the employees code and the percentage of bonus for the value of basic pay.
Employee code Bonus
100 5
200 1
300 2
400 25
CODE-
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
if (bonusMap.containsKey(code)) {
double bonus = (pay * bonusMap.get(code)) / 100;
System.out.println("Bonus: " + bonus);
} else {
System.out.println("Invalid Employee Code!");
}
scanner.close();
}
}
10
1BM24MC046|Java Programming
Output-
( a)
1
12
123
1234
12345
CODE-
}
System.out.println();
}
}
}
OUTPUT-
11
1BM24MC046|Java Programming
( b)
1
22
333
4444
55555
CODE-
public class NumberPattern {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(i + " ");
}
System.out.println();
}
}
}
OUTPUT-
( c)
*****
****
***
**
*
CODE-
public class StarPattern {
public static void main(String[] args) {
for (int i = 5; i >= 1; i--) {
Department of Computer Application,BMSCE
12
1BM24MC046|Java Programming
}
OUTPUT-
3. Write a program that performs the following: If the user gives input as 1, the output is 2;
if the input is 2 then the output becomes 1.
CODE-
import java.util.Scanner;
13
1BM24MC046|Java Programming
OUTPUT-
4. Write and run a Java program that inputs three names and print them in their alphabetical order.
CODE-
import java.util.Scanner;
14
1BM24MC046|Java Programming
OUTPUT-
5. A number is said to be palindrome if it is invariant under reversion; that is, the number is the same if its
digits are reversed. For example, 3456543 is palindromic. Write a program that checks each of the first
10,000 prime numbers and prints those that are palindromic.
CODE-
public class PalindromicPrimes {
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static boolean isPalindrome(int n) {
String numStr = Integer.toString(n);
String reversedStr = new StringBuilder(numStr).reverse().toString();
return numStr.equals(reversedStr);
}
15
1BM24MC046|Java Programming
count++;
}
num++;
}
}
}
OUTPUT-
• Name of depositor—string
• Account Number—int
• Type of Account—boolean
• Balance amount—double
Methods
16
1BM24MC046|Java Programming
CODE-
public class Account {
String name;
int accountNumber;
boolean accountType;
double balance;
public Account(String name, int accountNumber, boolean accountType, double balance) {
this.name = name;
this.accountNumber = accountNumber;
this.accountType = accountType;
this.balance = balance;
}
public void deposit(double amount) {
if (balance + amount >= 50) {
balance += amount;
System.out.println("Deposited: " + amount);
} else {
System.out.println("Deposit failed: Balance cannot go below 50.");
}
}
public void display() {
System.out.println("Name: " + name);
System.out.println("Balance: " + balance);
}
OUTPUT-
17
1BM24MC046|Java Programming
AAT-2
CODE-
public class SumAverageRunningInt {
public static void main(String[] args) {
int lowerbound = 1;
int upperbound = 100;
int sum = 0;
for (int n = lowerbound; n <= upperbound; n++) {
sum += n;
}
double average = (double) sum / (upperbound - lowerbound + 1);
System.out.println("The sum of " + lowerbound + " to " + upperbound + " is " + sum);
System.out.println("The average is " + average);
}
}
OUTPUT-
18
1BM24MC046|Java Programming
CODE-
public class HarmonicSum {
public static void main(String[] args) {
int n = 50000;
double sumLtoR = 0;
double sumRtoL = 0;
for(int i =1; i <=n; i++) sumLtoR +=1.0/i;
for(int i =n; i >=1; i--) sumRtoL +=1.0/i;
double different = Math.abs(sumLtoR - sumRtoL);
System.out.println("Left-to-Right sum: " + sumLtoR);
System.out.println("Right-to-Left sum: " + sumRtoL);
System.out.println("Absolute difference: " + different);
System.out.println((sumRtoL > sumLtoR ? "Right-to-left " : "Left-to-right ") + "is more accurate.");
}
}
OUTPUT-
19
1BM24MC046|Java Programming
3. Write a program called Fibonacci to print the first 20 Fibonacci numbers F(n), where
F(n)=F(n–1) +F(n–2) and F (1) =F (2) =1. Also compute their average.
The output shall look like:
The first 20 Fibonacci numbers are:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
The average is 885.5
CODE-
OUTPUT-
20
1BM24MC046|Java Programming
4. Write a program called ExtractDigits to extract each digit from an int, in the reverse
order.
For example, if the int is 15423, the output shall be "3 2 4 5 1", with a space separating
the digits.
CODE-
import java.util.Scanner;
public class ExtractDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
while(n>0){
OUTPUT-
21
1BM24MC046|Java Programming
AAT-3
CODE-
import java.util.Scanner;
while (true) {
System.out.print("Enter the taxable income: $");
int taxableIncome = scanner.nextInt();
if (taxableIncome == -1) {
System.out.println("bye!");
break;
}
double tax = 0;
if (taxableIncome > 20000) {
tax += 20000 * 0.10;
taxableIncome -= 20000;
}
if (taxableIncome > 20000) {
tax += 20000 * 0.20;
Department of Computer Application,BMSCE
22
1BM24MC046|Java Programming
taxableIncome -= 20000;
}
if (taxableIncome > 0) {
tax += taxableIncome * 0.30;
}
scanner.close();
}
}
OUTPUT-
23
1BM24MC046|Java Programming
CODE-
import java.util.Scanner;
}
else if (age <= 60)
24
1BM24MC046|Java Programming
{
employeeContribution = contriSalary * 0.13;
employerContribution = contriSalary * 0.13;
}
else if (age <= 65)
{
employeeContribution = contriSalary * 0.075;
25
1BM24MC046|Java Programming
3.Write a program called ReverseString, which prompts user for a String, and prints the reverse of
the String by extracting and processing each character.
The output shall look like:
Enter a String: abcdef
The reverse of the String "abcdef" is "fedcba"
CODE-
import java.util.Scanner;
System.out.println("The reverse of the String \"" + input + "\" is \"" + reversed.toString() + "\"");
scanner.close();
}
}
OUTPUT-
26
1BM24MC046|Java Programming
4.Write a program called CountVowelsDigits, which prompts the user for a String, counts the
number of vowels (a, e, i, o, u, A, E, I, O, U) and digits (0-9) contained in the string, and prints
the counts and the percentages (rounded to 2 decimal places).
For example,
Enter a String: testing12345
Number of vowels: 2 (16.67%)
Number of digits: 5 (41.67%)
CODE-
import java.util.Scanner;
int vowelCount = 0;
int digitCount = 0;
int totalLength = input.length();
if ("aeiouAEIOU".indexOf(ch) != -1) {
vowelCount++;
}
else if (Character.isDigit(ch)) {
digitCount++;
}
}
scanner.close();
}
}
27
1BM24MC046|Java Programming
OUTPUT-
5.Write a program called Bin2Dec to convert an input binary string into its equivalent decimal
number.
Your output shall look like:
Enter a Binary string: 1011
The equivalent decimal number for binary "1011" is: 11
CODE-
import java.util.Scanner;
try {
int decimalValue = Integer.parseInt(binaryString, 2);
System.out.println("The equivalent decimal number for binary \"" + binaryString + "\" is: " +
decimalValue);
} catch (NumberFormatException e) {
System.out.println("Invalid binary string.");
}
scanner.close();
}
}
OUTPUT-
28
1BM24MC046|Java Programming
AAT-4
1. Provided that you have a given number of small rice bags (1 kilo each) and big rice bags (5
kilos each), write a method that returns true if it is possible to make a package with goal kilos
of rice.
CODE-
OUTPUT-
29
1BM24MC046|Java Programming
2. Write a class called Employee, which models an employee with an ID, name and salary, is designed as
shown in the following class diagram. The method raiseSalary(percent) increases the salary by the
given percentage. Write the Employee class.
CODE-
30
1BM24MC046|Java Programming
3. Write a class called Author (as shown in the class diagram) is designed to model a book's
author. It contains:
• Three private instance variables: name (String), email (String), and gender (char of
either 'm' or 'f');
• One constructor to initialize the name, email and gender with the given values;
public Author (String name, String email, char gender) {......}
• public getters/setters: getName(), getEmail(), setEmail(), and getGender();
• A toString() method that returns "Author[name=?,email=?,gender=?]", e.g.,
"Author[name=Tan Ah Teck,email=ahTeck@somewhere.com,gender=m]".
CODE-
import java.util.Scanner;
31
1BM24MC046|Java Programming
scanner.close();
}
}
OUTPUT-
32
1BM24MC046|Java Programming
4. In this exercise, a subclass called Cylinder is derived from the superclass Circle as shown in the
class diagram. Study how the subclass Cylinder invokes the superclass' constructors (via super
() and super(radius)) and inherits the variables and methods from the superclass Circle.
• The subclass Cylinder inherits getArea() method from its superclass Circle. Try
overriding the getArea() method in the subclass Cylinder to compute the surface area
(=2π×radius×height + 2×base-area) of the cylinder instead of base area.
o That is, if getArea() is called by a Circle instance, it returns the area.
• If you override the getArea() in the subclass Cylinder, the getVolume() no longer
works. This is because the getVolume() uses the overridden getArea() method found
in the same class. Fix the getVolume().
CODE-
class Circle
{
private double radius;
private String color;
public Circle()
{
this.radius = 1.0;
this.color = "red";
}
public Circle(double radius)
{
this.radius = radius;
this.color = "red";
}
public Circle(double radius, String color)
{
this.radius = radius;
this.color = color;
}
public double getRadius()
{
return radius;
}
public void setRadius(double radius)
{
this.radius = radius;
Department of Computer Application,BMSCE
33
1BM24MC046|Java Programming
}
public String getColor()
{
return color;
}
public void setColor(String color)
{
this.color = color;
}
public double getArea()
{
return Math.PI * radius * radius;
}
public String toString()
{
return "Circle[radius=" + radius + ",color=" + color + "]";
}
}
}
public Cylinder(double radius)
{
super(radius);
this.height = 1.0;
}
public Cylinder(double radius, double height)
{
super(radius);
this.height = height;
}
public Cylinder(double radius, double height, String color)
{
super(radius, color);
this.height = height;
}
public double getHeight()
{
Department of Computer Application,BMSCE
34
1BM24MC046|Java Programming
return height;
}
public void setHeight(double height)
{
this.height = height;
}
public double getVolume()
{
double baseArea = super.getArea();
return baseArea * height;
}
public double getArea()
{
double baseArea = super.getArea();
return 2 * Math.PI * getRadius() * height + 2 * baseArea;
}
OUTPUT-
35
1BM24MC046|Java Programming
CODE-
import java.util.Scanner;
}
}
36
1BM24MC046|Java Programming
scanner.nextLine();
System.out.print("Enter Car Type (Small Car, Van, SUV):");
String carType = scanner.nextLine();
carRental.getCar(carId, carType);
carRental.getRent();
carRental.showCar();
scanner.close();
}
}
OUTPUT-
37
1BM24MC046|Java Programming
AAT-5
CODE-
import java.util.*;
class Customer {
38
1BM24MC046|Java Programming
OUTPUT-
39
1BM24MC046|Java Programming
CODE-
import java.util.Scanner;
}
}
40
1BM24MC046|Java Programming
int a2 = sc.nextInt();
int a3 = sc.nextInt();
sc.close();
}
}
OUTPUT-
41
1BM24MC046|Java Programming
3. Write a Java program using a function root to calculate and display all roots of the
quadratic
AX2 + BX + C = 0.
CODE-
import java.util.Scanner;
double discriminant = b * b - 4 * a * c;
double denom = 2 * a;
if (discriminant > 0) {
double r1 = (-b + Math.sqrt(discriminant)) / denom;
double r2 = (-b - Math.sqrt(discriminant)) / denom;
System.out.println("Two real roots: " + r1 + " and " + r2);
} else if (discriminant == 0) {
double r = -b / denom;
System.out.println("One real root: " + r);
} else {
// Complex roots
double real = -b / denom;
double imag = Math.sqrt(-discriminant) / denom;
System.out.println("Two complex roots: " + real + " + " + imag + "i and "
+ real + " - " + imag + "i");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
42
1BM24MC046|Java Programming
OUTPUT-
43
1BM24MC046|Java Programming
4. Write a program to fi nd the volume of a box that has its sides w, h, d as width,
height, and depth, respectively. Its volume is v = w * h * d and also fi nd the
surface area given by the formula s = 2(wh + hd + dw).
CODE-
import java.util.Scanner;
double volume = w * h * d;
double surfaceArea = 2 * (w * h + h * d + d * w);
sc.close();
}
}
OUTPUT-
44
1BM24MC046|Java Programming
5. A class weight is having a data member pound, which will have the weight in
pounds. Using a conversion function, convert the weight in pounds to weight in
kilograms which is of double type. Write a program to do this.
1 pounds =1 kg/0.453592
Use default constructor to initial assignment of 1000 pounds.
CODE-
int pound;
Weight() {
pound = 1000;
}
double toKilograms() {
return pound * 0.453592;
}
public static void main(String[] args) {
Weight w = new Weight();
System.out.println("Weight in pounds: " + w.pound);
System.out.println("Weight in kilograms: " + w.toKilograms());
}
}
OUTPUT-
45
1BM24MC046|Java Programming
AAT-6
1. Write a package called Clear, it contains one public method clrscr() to clear the screen,
import the package and use it in another programs. Add another public method
starline(). It prints the line of 15 starts.
CODE-
Clear/Clear.java
package Clear;
OUTPUT-
46
1BM24MC046|Java Programming
2. Define an exception called " No Equal Exception " that is thrown when a float value is
not equal to 3.14. Write a program that uses the above user defi ned exception.
CODE-
try {
checkValue(input);
} catch (NoEqualException e) {
System.out.println("Exception caught: " + e.getMessage());
}
sc.close();
}
}
47
1BM24MC046|Java Programming
OUTPUT-
try {
checkValue(input);
} catch (NoEqualException e) {
System.out.println("Exception caught: " + e.getMessage());
}
sc.close();
}
}
OUTPUT-
48
1BM24MC046|Java Programming
3. Write a java program using threads to simulate traffic lights switch between Red
Green,andYellow with fixed delays.
CODE-
49
1BM24MC046|Java Programming
OUTPUT-
50
1BM24MC046|Java Programming
AAT-7
1. Write a package called Clear, it contains one public method clrscr() to clear the screen, import
the package and use it in another programs. Add another public method starline(). It prints
the line of 15 stars.
CODE-
package Clear;
OUTPUT-
51
1BM24MC046|Java Programming
2. Write a program in Java. A class Teacher contains two fi elds, Name and Qualifi cation. Extend
the class to Department, it contains Dept. No and Dept. Name. An interface named as College
contains one fi eld Name of the college. Using the above classes and Interface get the
appropriate information and display it.
CODE-
import java.util.Scanner;
interface College {
String collegeName = "Bright Future College";
}
class Teacher {
protected String name;
protected String qualification;
52
1BM24MC046|Java Programming
sc.close();
}
}
OUTPUT-
53
1BM24MC046|Java Programming
3. Write and run the following Java program that does the following:
a) Declare a string object named s1 containing the string "Object Oriented Programming-
Java 5".
CODE-
import java.util.Scanner;
class StringProcessor {
private String s1;
54
1BM24MC046|Java Programming
sc.close();
}
}
OUTPUT-
55
1BM24MC046|Java Programming
AAT-8
1.Write a program that accepts a name list of five students from the command line and store in
a vector.
CODE-
import java.util.Scanner;
import java.util.Vector;
OUTPUT-
56
1BM24MC046|Java Programming
2. Write and run the following Java program that does the following:
a) Declare a string object named s1 containing the string "Object Oriented Programming-
Java 5".
b) Print the entire string.
c) Use the length() method to find the length of the string.
d) Use the charAt() method to find the first character in the string.
e) Use charAt() and length() methods to print the last character in the string.
f) Use the indexOf() and the substring() method to print the first word in the String.
CODE-
OUTPUT-
57
1BM24MC046|Java Programming
3.Define an exception called " No Equal Exception " that is thrown when a float value is not
equal to 3.14. Write a program that uses the above user defined exception.
CODE-
class NoEqualException extends Exception {
OUTPUT-
58
1BM24MC046|Java Programming
4. Write a java program using threads to simulate traffic lights switch between Red, Green, and
Yellow with fixed delays.
CODE-
System.out.println("Green Light");
sleepFor(5000);
System.out.println("Yellow Light");
sleepFor(2000);
}
}
59
1BM24MC046|Java Programming
5. Write a Java program to accept two parameters on the command line. If there are no
command line arguments entered, the program should print the error message and exit. The
program should check whether the first fi le exists and if it is an ordinary fi le. If it is so, then
the content is copied to the second file.
CODE-
import java.io.*;
if (!sourceFile.exists() || !sourceFile.isFile()) {
System.out.println("Error: Source file does not exist or is not a regular file.");
return;
}
try (
FileReader fr = new FileReader(sourceFile);
FileWriter fw = new FileWriter(destFile);
){
int ch;
while ((ch = fr.read()) != -1) {
fw.write(ch);
}
System.out.println("File copied successfully.");
} catch (IOException e) {
System.out.println("Error during file copy: " + e.getMessage());
}
}
}
OUTPUT-
60
1BM24MC046|Java Programming
AAT-9
1. Write a Java program to check whether the file is readable, writable and hidden.
CODE-
import java.io.File;
OUTPUT-
61
1BM24MC046|Java Programming
2. Write a program using Lambda expression to filter the Employee objects. Each employee has
a name, department, and salary.
• Employees with salary > 50,000
• Employees in the "IT" department
CODE-
import java.util.Arrays;
import java.util.List;
class Employee {
String name, department;
double salary;
Employee(String name, String dept, double salary) {
this.name = name;
this.department = dept;
this.salary = salary;
}
public String toString() {
return name + " | " + department + " | $" + salary;
}
}
public class EmployeeFilter {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee("Amit", "IT", 60000),
new Employee("Neha", "HR", 45000),
new Employee("Ravi", "IT", 48000),
new Employee("Sonal", "Finance", 52000),
new Employee("Priya", "IT", 70000)
);
System.out.println("Salary > 50,000:");
for (Employee e : employees) {
if (e.salary > 50000) System.out.println(e);
}
System.out.println("\nDepartment = IT:");
for (Employee e : employees) {
if (e.department.equalsIgnoreCase("IT")) System.out.println(e);
}
}
}
62
1BM24MC046|Java Programming
OUTPUT-
63
1BM24MC046|Java Programming
3. You’re building a system that handles different types of items in an online store. You want to
create an Inventory<T> class that can store any type of item (books, electronics, etc.).
CODE-
import java.util.*;
class Inventory<T> {
private List<T> items = new ArrayList<>();
void addItem(T item) { items.add(item); }
void displayItems() {
for (T item : items) {
System.out.println(item);
}
}
}
class Book {
String title, author;
Book(String t, String a) { title = t; author = a; }
public String toString() { return "Book: " + title + " by " + author; }
}
class Electronic {
String name, brand;
Electronic(String n, String b) { name = n; brand = b; }
public String toString() { return "Electronic: " + name + " (" + brand + ")"; }
}
public class Main {
public static void main(String[] args) {
Inventory<Book> books = new Inventory<>();
books.addItem(new Book("1984", "George Orwell"));
books.addItem(new Book("To Kill a Mockingbird", "Harper Lee"));
Inventory<Electronic> electronics = new Inventory<>();
electronics.addItem(new Electronic("Smartphone", "Samsung"));
electronics.addItem(new Electronic("Laptop", "Dell"));
System.out.println("Books in inventory:");
books.displayItems();
System.out.println("\nElectronics in inventory:");
electronics.displayItems();
}
}
64
1BM24MC046|Java Programming
OUTPUT-
65
1BM24MC046|Java Programming
4. Write a program using autoboxing to calculate the discounted prices for a shopping cart. The
system stores prices as Double, but the calculations are done using double.
CODE-
import java.util.ArrayList;
import java.util.List;
public class ShoppingCart {
public static void main(String[] args) {
List<Double> cart = new ArrayList<>();
cart.add(59.99);
cart.add(99.49);
cart.add(15.75);
cart.add(25.60);
double discountPercentage = 0.20;
System.out.println("Original prices and discounted prices:");
for (Double price : cart) {
double originalPrice = price;
double discountedPrice = originalPrice - (originalPrice * discountPercentage);
System.out.printf("Original Price: $%.2f, Discounted Price: $%.2f%n", originalPrice, discountedPrice);
}
}
}
OUTPUT-
66
1BM24MC046|Java Programming
AAT-10
CODE-
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
Calculator() {
setTitle("Calculator");
setSize(250, 350);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(panel);
setVisible(true);
Department of Computer Application,BMSCE
67
1BM24MC046|Java Programming
if (cmd.matches("[0-9]")) {
textField.setText(textField.getText() + cmd);
} else if (cmd.equals("C")) {
textField.setText("");
operator = "";
num1 = 0;
} else if (cmd.equals("=")) {
double num2 = Double.parseDouble(textField.getText());
switch (operator) {
case "+": textField.setText("" + (num1 + num2)); break;
case "-": textField.setText("" + (num1 - num2)); break;
case "*": textField.setText("" + (num1 * num2)); break;
case "/": textField.setText(num2 == 0 ? "Error" : "" + (num1 / num2)); break;
}
} else {
num1 = Double.parseDouble(textField.getText());
operator = cmd;
textField.setText("");
}
}
68
1BM24MC046|Java Programming
CODE-
import javax.swing.*;
menuBar.add(booksMenu);
menuBar.add(languageMenu);
Department of Computer Application,BMSCE
69
1BM24MC046|Java Programming
menuBar.add(fileMenu);
menuBar.add(searchMenu);
setJMenuBar(menuBar);
setVisible(true);
}
OUTPUT-
70
1BM24MC046|Java Programming
3. Write a Java program to display the different prices of the books using the choice object.
CODE-
import java.awt.*;
import java.awt.event.*;
71
1BM24MC046|Java Programming
OUTPUT-
72
1BM24MC046|Java Programming
4. Write Java program to display the different car names using list object.
CODE-
import java.awt.*;
import java.awt.event.*;
public class CarListViewer extends Frame implements ActionListener {
List carList;
Label selectedCarLabel;
public CarListViewer() {
setTitle("Car List Viewer");
setSize(300, 200);
setLayout(new FlowLayout());
setVisible(true);
Label label = new Label("Select a Car:");
add(label);
carList = new List(5, false);
carList.add("Toyota");
carList.add("Honda");
carList.add("Ford");
carList.add("BMW");
carList.add("Mercedes");
carList.add("Tesla");
add(carList);
73
1BM24MC046|Java Programming
OUTPUT-
74
1BM24MC046|Java Programming
5. Write a Java program to display the different IIT’s names in India using the choice object
and list object.
CODE-
import java.awt.*;
import java.awt.event.*;
public class IITViewer extends Frame implements ItemListener, ActionListener {
Choice iitChoice;
List iitList;
Label selectedLabel;
public IITViewer() {
setTitle("IITs in India");
setSize(400, 300);
setLayout(new FlowLayout());
Label choiceLabel = new Label("Select IIT (Choice):");
add(choiceLabel);
iitChoice = new Choice();
iitChoice.add("IIT Bombay");
iitChoice.add("IIT Delhi");
iitChoice.add("IIT Madras");
iitChoice.add("IIT Kanpur");
iitChoice.add("IIT Kharagpur");
add(iitChoice);
Label listLabel = new Label("Select IIT (List):");
add(listLabel);
iitList = new List(5, false); // 5 visible rows, single selection
iitList.add("IIT Roorkee");
iitList.add("IIT Guwahati");
iitList.add("IIT Hyderabad");
iitList.add("IIT Bhubaneswar");
iitList.add("IIT Gandhinagar");
add(iitList);
selectedLabel = new Label("Selected: ");
add(selectedLabel);
iitChoice.addItemListener(this);
iitList.addActionListener(this);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose();
}
});
setVisible(true);
}
Department of Computer Application,BMSCE
75
1BM24MC046|Java Programming
76
1BM24MC046|Java Programming
6. Write a Java program to display the following 3 × 3 magic square (total = 15) using
JTable:
294
753
618
CODE-
import javax.swing.*;
import java.awt.*;
public class MagicSquareTable extends JFrame {
public MagicSquareTable() {
setTitle("3x3 Magic Square");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Object[][] data = {
{2, 9, 4},
{7, 5, 3},
{6, 1, 8}
};
String[] columnNames = {"", "", ""};
JTable table = new JTable(data, columnNames);
table.setRowHeight(40);
table.setEnabled(false); // Make it non-editable
table.setFont(new Font("Arial", Font.BOLD, 18));
table.setGridColor(Color.BLACK);
table.setShowGrid(true);
add(new JScrollPane(table));
setVisible(true);
}
public static void main(String[] args) {
new MagicSquareTable();
}
}
77
1BM24MC046|Java Programming
OUTPUT-
78