KEMBAR78
Javaa Aat | PDF | Inheritance (Object Oriented Programming) | Method (Computer Programming)
0% found this document useful (0 votes)
21 views78 pages

Javaa Aat

This document is a report submitted by Krishna Raman for the fulfillment of AAT work in Java Programming at B.M.S. College of Engineering. It includes various programming tasks and exercises related to Java, covering topics such as employee bonus calculations, Fibonacci series, income tax calculations, and object-oriented programming concepts. The report is structured into multiple sections, each containing specific programming assignments with detailed requirements.

Uploaded by

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

Javaa Aat

This document is a report submitted by Krishna Raman for the fulfillment of AAT work in Java Programming at B.M.S. College of Engineering. It includes various programming tasks and exercises related to Java, covering topics such as employee bonus calculations, Fibonacci series, income tax calculations, and object-oriented programming concepts. The report is structured into multiple sections, each containing specific programming assignments with detailed requirements.

Uploaded by

YashuChitluru
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

B.M.S.

COLLEGE OF ENGINEERING
(Autonomous college under VTU)
Bull Temple Rd, Basavanagudi, Bengaluru, Karnataka 560019
2024-2026
Department of Computer Applications

Report is submitted for fulfillment of AAT work in the subject


JAVA PROGRAMMING
(“MMC204”)
BY
KRISHNA RAMAN
(1BM24MC046)

Under the Guidance


Prof. R.V. Raghavendra Rao
(Assistant Professor)
CONTENTS

SL. Programs Page No


No.

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

• To assign initial values (using constructor)


• To deposit an amount after checking balance and minimum balance
50.
• To display the name and balance.

AAT-2. 1. Write a program called SumAverageRunningInt to produce the sum of 1, 2, 3, 18-21


..., to
100. Store 1 and 100 in variables lowerbound and upperbound, so that we can
change
their values easily. Also compute and display the average.
The output shall look like:
The sum of 1 to 100 is 5050
The average is 50.5
2. Write a program called HarmonicSum to compute the sum of a harmonic series,
as
shown below, where n=50000. The program shall compute the sum from left-to-
right
as well as from the right-to-left. Are the two sums the same? Obtain the absolute
difference between these two sums and explain the difference. Which sum is more
accurate?
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
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.
AAT-3. 1. The progressive income tax rate is mandated as follows: 22-28
Taxable Income Rate (%)
First $20,000 0
Next $20,000 10
Next $20,000 20
The remaining 30
For example, suppose that the taxable income is $85000, the income tax payable
is
$20000*0% + $20000*10% + $20000*20% + $25000*30%.
Write a program called IncomeTaxCalculator that reads the taxable income (in
int). The
program shall calculate the income tax payable (in double); and print the result
rounded to 2
decimal places. Program shall repeat the calculation until user enter -1.
For example,
Enter the taxable income: $41234
The income tax payable is: $2246.80
Enter the taxable income: $-1
bye!
2. Both the employer and the employee are mandated to contribute a certain
percentage of the
employee's salary towards the employee's pension fund. The rate is tabulated
as follows:

However, the contribution is subjected to a salary ceiling of $6,000. In other


words, if an
employee earns $6800, only $6000 attracts employee's and employer's
contributions, the
remaining $800 does not.
Write a program called PensionContributionCalculator that reads the monthly
salary and age
(in int) of an employee. Your program shall calculate the employee's, employer's
and total
contributions (in double); and print the results rounded to 2 decimal places.
For example,
Enter the monthly salary: $3000
Enter the age: 30
The employee's contribution is: $600.00
The employer's contribution is: $510.00
The total contribution is: $1110.00
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"
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%)
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

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-10. 1. Write a program to create a calculator using event handling. 67-78


2. Create a menu is a frame as shown below:
Books Language Film Search
• The Books menu has the following items: C, C++, Java, Oracle, VB, and ASP.
• The language menu consists of French, German, English, Tamil, and Hindi.
• The File menu has the following: Titanic, Jurassic Park, Tomorrow never Dies,
Jeans, and Slumdog.
• The search engine consists of Yahoo, Hotmail, Sify, Google, and Lycos.
3. Write a Java program to display the different prices of the books using the
choice object.
4. Write Java program to display the different car names using list object.
5. Write a Java program to display the different IIT’s names in India using the
choice object and list object.
6. Write a Java program to display the following 3 × 3 magic square (total = 15)
using JTable:

7. You’re building a system that handles different types of items in an online


store. You want tocreate an Inventory<T> class that can store any type of item
(books, electronics, etc.).
1BM24MC046|Java Programming

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;

public class EmployeeBonus {

public static void main(String[] args) {


Map<Integer, Integer> bonusMap = new HashMap<>();
bonusMap.put(100, 5);
bonusMap.put(200, 1);
bonusMap.put(300, 2);
bonusMap.put(400, 25);

Scanner scanner = new Scanner(System.in);


System.out.print("Enter Employee Code: ");
int code = scanner.nextInt();
System.out.print("Enter Basic Pay: ");
double pay = scanner.nextDouble();

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();
}
}

Department of Computer Application,BMSCE

10
1BM24MC046|Java Programming

Output-

2. Write a program to display the following output using for loop:

( a)
1
12
123
1234
12345

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(j +"");

}
System.out.println();
}
}
}
OUTPUT-

Department of Computer Application,BMSCE

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

for (int j = 1; j <= i; j++) {


System.out.print("* ");
}
System.out.println();
}
}

}
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;

public class ToggleInput {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter 1 or 2: ");
int input = scanner.nextInt();
if (input == 1) {
System.out.println("Output: 2");
} else if (input == 2) {
System.out.println("Output: 1");
} else {
System.out.println("Invalid input! Please enter 1 or 2.");
}
scanner.close();
}
}

Department of Computer Application,BMSCE

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;

public class AlphabeticalOrder {


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

System.out.print("Enter the first name: ");


String name1 = scanner.nextLine();

System.out.print("Enter the second name: ");


String name2 = scanner.nextLine();

System.out.print("Enter the third name: ");


String name3 = scanner.nextLine();

String[] names = {name1, name2, name3};


java.util.Arrays.sort(names);

System.out.println("\nNames in alphabetical order:");


for (String name : names) {
System.out.println(name);
}
scanner.close();
}
}

Department of Computer Application,BMSCE

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);
}

public static void main(String[] args) {


int count = 0;
int num = 2;

while (count < 10000) {


if (isPrime(num) && isPalindrome(num)) {
System.out.println(num);
Department of Computer Application,BMSCE

15
1BM24MC046|Java Programming

count++;
}
num++;
}
}
}
OUTPUT-

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

• To assign initial values (using constructor)


• To deposit an amount after checking balance and minimum balance 50.
• To display the name and balance.

Department of Computer Application,BMSCE

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);
}

public static void main(String[] args) {

Account account = new Account("Krishna", 2004, true, 1000.0);


account.display();
account.deposit(200.0);
account.display();
}
}

OUTPUT-

Department of Computer Application,BMSCE

17
1BM24MC046|Java Programming

AAT-2

1. Write a program called SumAverageRunningInt to produce the sum of 1, 2, 3, ..., to


100. Store 1 and 100 in variables lowerbound and upperbound, so that we can change
their values easily. Also compute and display the average.
The output shall look like:
The sum of 1 to 100 is 5050
The average is 50.5

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-

Department of Computer Application,BMSCE

18
1BM24MC046|Java Programming

2. Write a program called HarmonicSum to compute the sum of a harmonic series, as


shown below, where n=50000. The program shall compute the sum from left-to-right
as well as from the right-to-left. Are the two sums the same? Obtain the absolute
difference between these two sums and explain the difference. Which sum is more
accurate?

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-

Department of Computer Application,BMSCE

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-

public class Fibonacci {


public static void main(String[] args) {
int f1 = 1, f2 = 1, sum = 2, n = 20;
System.out.print("The first 20 Fibonacci numbers are:\n1 1 ");
for (int i = 3; i <= n; i++) {
int f3 = f1 + f2;
System.out.print(f3 + " ");
sum += f3;
f1 = f2;
f2 = f3;
}
System.out.println("\nThe average is " + (sum / (double)n));
}
}

OUTPUT-

Department of Computer Application,BMSCE

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){

System.out.print(n%10 + " " );


n=n/10;
}
}
}

OUTPUT-

Department of Computer Application,BMSCE

21
1BM24MC046|Java Programming

AAT-3

1. The progressive income tax rate is mandated as follows:


Taxable Income Rate (%)
First $20,000 0
Next $20,000 10
Next $20,000 20
The remaining 30
For example, suppose that the taxable income is $85000, the income tax payable is
$20000*0% + $20000*10% + $20000*20% + $25000*30%.
Write a program called IncomeTaxCalculator that reads the taxable income (in int). The
program shall calculate the income tax payable (in double); and print the result rounded to 2
decimal places. Program shall repeat the calculation until user enter -1.
For example,
Enter the taxable income: $41234
The income tax payable is: $2246.80
Enter the taxable income: $-1
bye!

CODE-

import java.util.Scanner;

public class IncomeTaxCalculator {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

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;
}

System.out.printf("The income tax payable is: $%.2f%n", tax);


}

scanner.close();
}
}

OUTPUT-

Department of Computer Application,BMSCE

23
1BM24MC046|Java Programming

CODE-

import java.util.Scanner;

public class PensionContributionCalculator


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
double employeeContribution;
double employerContribution;
System.out.print("Enter the monthly salary: $");
int salary = sc.nextInt();
System.out.print("Enter the age: ");
int age = sc.nextInt();
int sal_ceiling= 6000;
int contriSalary = Math.min(salary, sal_ceiling);
if (age <= 55)
{
employeeContribution = contriSalary * 0.2;
employerContribution = contriSalary * 0.17;

}
else if (age <= 60)

Department of Computer Application,BMSCE

24
1BM24MC046|Java Programming

{
employeeContribution = contriSalary * 0.13;
employerContribution = contriSalary * 0.13;
}
else if (age <= 65)
{
employeeContribution = contriSalary * 0.075;

employerContribution = contriSalary * 0.09;


}
else
{
employeeContribution = contriSalary * 0.05;
employerContribution = contriSalary * 0.075;
}
double totalContribution = employeeContribution + employerContribution;
System.out.printf("The employee's contribution is: $%.2f\n", employeeContribution);
System.out.printf("The employer's contribution is: $%.2f\n", employerContribution);
System.out.printf("The total contribution is: $%.2f\n", totalContribution);
}
}
OUTPUT-

Department of Computer Application,BMSCE

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;

public class ReverseString {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter a String: ");


String input = scanner.nextLine();

StringBuilder reversed = new StringBuilder();

for (int i = input.length() - 1; i >= 0; i--) {


reversed.append(input.charAt(i));
}

System.out.println("The reverse of the String \"" + input + "\" is \"" + reversed.toString() + "\"");

scanner.close();
}
}

OUTPUT-

Department of Computer Application,BMSCE

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;

public class CountVowelsDigits {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter a String: ");
String input = scanner.nextLine();

int vowelCount = 0;
int digitCount = 0;
int totalLength = input.length();

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


char ch = input.charAt(i);

if ("aeiouAEIOU".indexOf(ch) != -1) {
vowelCount++;
}

else if (Character.isDigit(ch)) {
digitCount++;
}
}

double vowelPercentage = (vowelCount / (double) totalLength) * 100;


double digitPercentage = (digitCount / (double) totalLength) * 100;
System.out.printf("Number of vowels: %d (%.2f%%)%n", vowelCount, vowelPercentage);
System.out.printf("Number of digits: %d (%.2f%%)%n", digitCount, digitPercentage);

scanner.close();
}
}

Department of Computer Application,BMSCE

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;

public class Bin2Dec {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter a Binary string: ");
String binaryString = scanner.nextLine();

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-

Department of Computer Application,BMSCE

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-

public class RicePackage {

public static boolean canPack(int small, int big, int goal) {


int bigBagsUsed = Math.min(goal / 5, big);
goal -= bigBagsUsed * 5;
return goal <= small;
}
public static void main(String[] args) {
System.out.println(canPack(3, 1, 8));
System.out.println(canPack(3, 1, 9));
System.out.println(canPack(6, 2, 17));
}
}

OUTPUT-

Department of Computer Application,BMSCE

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-

public class Employee {

private int id;


private String name;
private double salary;
public Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
public void raiseSalary(double percent) {
salary += salary * percent / 100;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
public static void main(String[] args) {
Employee emp = new Employee(1,"Krishna",65000);
System.out.println("Employee Name:" + emp.getName());
System.out.println("Original Salary:" + emp.getSalary());
emp.raiseSalary(10);
System.out.println("New Salary after 10% raise:" + emp.getSalary());
}
}
OUTPUT-

Department of Computer Application,BMSCE

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;

public class Author {


private String name;
private String email;
private char gender;

public Author(String name, String email, char gender) {


this.name = name;
this.email = email;
this.gender = gender;
}

public String getName() {


return name;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

public char getGender() {


return gender;
}

public String toString() {


return "Author[name=" + name +",email=" + email +",gender=" + gender + "]";
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Department of Computer Application,BMSCE

31
1BM24MC046|Java Programming

System.out.print("Enter author's name:");


String name = scanner.nextLine();

System.out.print("Enter author's email:");


String email = scanner.nextLine();

System.out.print("Enter author's gender (m/f):");


char gender = scanner.next().charAt(0);

Author author = new Author(name, email, gender);


System.out.println(author.toString());

scanner.close();
}
}

OUTPUT-

Department of Computer Application,BMSCE

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.

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().

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 + "]";
}
}

class Cylinder extends Circle


{
private double height;
public Cylinder()
{
super();
this.height = 1.0;

}
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;
}

public String toString()


{
return "Cylinder[radius=" + getRadius() + ",height=" + height + ",color=" + getColor() + "]";
}
}
public class main
{
public static void main(String[] args)
{
Circle circle = new Circle(5, "blue");

System.out.println("Circle Area:" + circle.getArea());


System.out.println(circle.toString());
Cylinder cylinder = new Cylinder(5, 10, "green");
System.out.println("Cylinder Surface Area:" + cylinder.getArea());
System.out.println("Cylinder Volume:" + cylinder.getVolume());
System.out.println(cylinder.toString());
}
}

OUTPUT-

Department of Computer Application,BMSCE

35
1BM24MC046|Java Programming

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.

CODE-
import java.util.Scanner;

public class CarRental {


private int carId;
private String carType;
private float rent;

public void getCar(int carId, String carType) {


this.carId = carId;
this.carType = carType;
}

public void getRent() {


switch (carType) {
case "Small Car":
rent = 1000;
break;
case "Van":
rent = 800;
break;
case "SUV":
rent = 2500;
break;
default:
rent = 0;
System.out.println("Invalid car type!");

}
}

public void showCar() {


System.out.println("Car ID:" + carId);
System.out.println("Car Type:" + carType);
System.out.println("Rent:" + rent);
}

public static void main(String[] args) {


Department of Computer Application,BMSCE

36
1BM24MC046|Java Programming

Scanner scanner = new Scanner(System.in);

CarRental carRental = new CarRental();

System.out.print("Enter Car ID:");


int carId = scanner.nextInt();

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-

Department of Computer Application,BMSCE

37
1BM24MC046|Java Programming

AAT-5

1. Create an abstract class “BankAccount” with abstract methods “deposit()” and


“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.

CODE-

import java.util.*;

abstract class BankAccount {


String id; double balance;
BankAccount(String id, double b) { this.id = id; this.balance = b; }
abstract void deposit(double a);
abstract void withdraw(double a);
public String toString() { return id + ": $" + balance; }
}

class SavingsAccount extends BankAccount {


SavingsAccount(String id, double b) { super(id, b); }
void deposit(double a) { if(a>0) balance+=a; }
void withdraw(double a) { if(a>0 && a<=balance) balance-=a; }
}

class CheckingAccount extends BankAccount {


double overdraft = 200;
CheckingAccount(String id, double b) { super(id, b); }
void deposit(double a) { if(a>0) balance+=a; }
void withdraw(double a) { if(a>0 && a<=balance+overdraft) balance-=a; }
}

class Customer {

String name; List<BankAccount> accounts = new ArrayList<>();


Customer(String n) { name=n; }
void add(BankAccount a) { accounts.add(a); }
void deposit(String id, double a) { for(BankAccount b:accounts) if(b.id.equals(id)) b.deposit(a); }
void withdraw(String id, double a) { for(BankAccount b:accounts) if(b.id.equals(id)) b.withdraw(a); }
void show() { System.out.println(name+"'s accounts:"); for(BankAccount b:accounts) System.out.println(b); }
}

public class Main {


Department of Computer Application,BMSCE

38
1BM24MC046|Java Programming

public static void main(String[] args) {


Customer c = new Customer("KRISHNA");
c.add(new SavingsAccount("S1", 1000));
c.add(new CheckingAccount("C1", 500));
c.show();
c.deposit("S1", 200);
c.withdraw("C1", 600);
c.show();
}
}

OUTPUT-

Department of Computer Application,BMSCE

39
1BM24MC046|Java Programming

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.

CODE-
import java.util.Scanner;

abstract class Marks {


abstract double getPercentage();
}

class A extends Marks {


int m1, m2, m3;
A(int m1, int m2, int m3) {
this.m1 = m1; this.m2 = m2; this.m3 = m3;
}
double getPercentage() {
return (m1 + m2 + m3) / 3.0;
}
}

class B extends Marks {


int m1, m2, m3, m4;
B(int m1, int m2, int m3, int m4) {
this.m1 = m1; this.m2 = m2; this.m3 = m3; this.m4 = m4;
}
double getPercentage() {
return (m1 + m2 + m3 + m4) / 4.0;

}
}

public class Main {


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

System.out.println("Enter 3 marks for student A:");


int a1 = sc.nextInt();
Department of Computer Application,BMSCE

40
1BM24MC046|Java Programming

int a2 = sc.nextInt();
int a3 = sc.nextInt();

System.out.println("Enter 4 marks for student B:");


int b1 = sc.nextInt();
int b2 = sc.nextInt();
int b3 = sc.nextInt();
int b4 = sc.nextInt();
A studentA = new A(a1, a2, a3);
B studentB = new B(b1, b2, b3, b4);
System.out.println("Percentage of Student A: " + studentA.getPercentage() + "%");
System.out.println("Percentage of Student B: " + studentB.getPercentage() + "%");

sc.close();
}
}

OUTPUT-

Department of Computer Application,BMSCE

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;

public class QuadraticRoots {

public static void root(double a, double b, double c) {


if (a == 0) {
System.out.println("Not a quadratic equation.");
return;
}

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);

System.out.println("Enter coefficients A, B, and C:");


double a = sc.nextDouble();
double b = sc.nextDouble();
double c = sc.nextDouble();
root(a, b, c);
sc.close();
}
}
Department of Computer Application,BMSCE

42
1BM24MC046|Java Programming

OUTPUT-

Department of Computer Application,BMSCE

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;

public class Box {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter width (w): ");


double w = sc.nextDouble();

System.out.print("Enter height (h): ");


double h = sc.nextDouble();

System.out.print("Enter depth (d): ");


double d = sc.nextDouble();

double volume = w * h * d;
double surfaceArea = 2 * (w * h + h * d + d * w);

System.out.println("Volume of the box: " + volume);


System.out.println("Surface area of the box: " + surfaceArea);

sc.close();
}
}

OUTPUT-

Department of Computer Application,BMSCE

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-

public class Weight {

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-

Department of Computer Application,BMSCE

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;

public class Clear {


public static void clrscr() {
try {
if (System.getProperty("os.name").contains("Windows")) {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
} else {
System.out.print("\033[H\033[2J");
System.out.flush();
}
} catch (Exception e) {
System.out.println("Error clearing screen");
}
}

// Method to print 15 stars in a line


public static void starline() {
System.out.println("***************"); // 15 stars
}
}
import Clear.Clear;

public class MainProgram {


public static void main(String[] args) {
Clear.clrscr();
Clear.starline();

System.out.println("This is a test after clearing the screen.");


Clear.starline();
}
}

OUTPUT-

Department of Computer Application,BMSCE

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-

public class NoEqualException extends Exception {

public NoEqualException(String message) {


super(message);
}
}
import java.util.Scanner;
public class TestNoEqualException {
static void checkValue(float value) throws NoEqualException {
if (value != 3.14f) {
throw new NoEqualException("Value " + value + " is not equal to 3.14");
} else {
System.out.println("Value is equal to 3.14");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a float value: ");
float input = sc.nextFloat();

try {

checkValue(input);
} catch (NoEqualException e) {
System.out.println("Exception caught: " + e.getMessage());
}
sc.close();
}
}

Department of Computer Application,BMSCE

47
1BM24MC046|Java Programming

OUTPUT-

public class NoEqualException extends Exception {

public NoEqualException(String message) {


super(message);
}
}
import java.util.Scanner;
public class TestNoEqualException {
static void checkValue(float value) throws NoEqualException {
if (value != 3.14f) {
throw new NoEqualException("Value " + value + " is not equal to 3.14");
} else {
System.out.println("Value is equal to 3.14");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a float value: ");
float input = sc.nextFloat();

try {

checkValue(input);
} catch (NoEqualException e) {
System.out.println("Exception caught: " + e.getMessage());
}
sc.close();
}
}
OUTPUT-

Department of Computer Application,BMSCE

48
1BM24MC046|Java Programming

3. Write a java program using threads to simulate traffic lights switch between Red
Green,andYellow with fixed delays.

CODE-

public class TrafficLight implements Runnable {

private String[] colors = {"Red", "Green", "Yellow"};


private int[] delays = {5000, 5000, 2000}; // milliseconds

public void run() {


try {
int i = 0;
while (true) {
System.out.println(colors[i] + " Light");
Thread.sleep(delays[i]);
i = (i + 1) % colors.length;
}
} catch (InterruptedException e) {
System.out.println("Simulation stopped.");
}
}

public static void main(String[] args) throws InterruptedException {

Thread t = new Thread(new TrafficLight());


t.start();
Thread.sleep(30000); // run for 30 seconds
t.interrupt();
}
}

Department of Computer Application,BMSCE

49
1BM24MC046|Java Programming

OUTPUT-

Department of Computer Application,BMSCE

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;

public class ClearScreen {


public static void clrscr() {
for (int i = 0; i < 50; i++) {
System.out.println();
}
}
public static void starline() {
System.out.println("***************");
}
}
import Clear.ClearScreen;

public class MainApp {


public static void main(String[] args) {
ClearScreen.clrscr();
System.out.println("Welcome!");
ClearScreen.starline();
}
}

OUTPUT-

Department of Computer Application,BMSCE

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;

public Teacher(String name, String qualification) {


this.name = name;
this.qualification = qualification;
}
}

class Department extends Teacher implements College {


private int deptNo;
private String deptName;

public Department(String name, String qualification, int deptNo, String deptName) {


super(name, qualification);
this.deptNo = deptNo;
this.deptName = deptName;
}

public void displayInfo() {


System.out.println("College: " + collegeName);
System.out.println("Teacher Name: " + name);

System.out.println("Qualification: " + qualification);


System.out.println("Department No: " + deptNo);
System.out.println("Department Name: " + deptName);
}
}

public class Main {


public static void main(String[] args) {
Department of Computer Application,BMSCE

52
1BM24MC046|Java Programming

Scanner sc = new Scanner(System.in);

System.out.print("Enter Teacher Name: ");


String name = sc.nextLine();

System.out.print("Enter Qualification: ");


String qualification = sc.nextLine();

System.out.print("Enter Department Number: ");


int deptNo = sc.nextInt();
sc.nextLine(); // Consume leftover newline

System.out.print("Enter Department Name: ");


String deptName = sc.nextLine();

Department d = new Department(name, qualification, deptNo, deptName);


d.displayInfo();

sc.close();
}
}

OUTPUT-

Department of Computer Application,BMSCE

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".

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-

import java.util.Scanner;

class StringProcessor {
private String s1;

public StringProcessor(String text) {


this.s1 = text;
}

public void process() {


System.out.println("Original String: " + s1);
System.out.println("Length: " + s1.length());
System.out.println("First character: " + s1.charAt(0));
System.out.println("Last character: " + s1.charAt(s1.length() - 1));

int firstSpace = s1.indexOf(" ");


if (firstSpace != -1) {
System.out.println("First word: " + s1.substring(0, firstSpace));
} else {
System.out.println("No space found to extract first word.");
}
}
}

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = sc.nextLine();

StringProcessor processor = new StringProcessor(input);


processor.process();
Department of Computer Application,BMSCE

54
1BM24MC046|Java Programming

sc.close();
}
}

OUTPUT-

Department of Computer Application,BMSCE

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;

public class StudentVector {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Vector<String> students = new Vector<>();

System.out.println("Enter names of 4 students:");

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


System.out.print("Enter student " + (i + 1) + ": ");
String name = sc.nextLine();
students.add(name);
}

System.out.println("Student names in vector: " + students);


}
}

OUTPUT-

Department of Computer Application,BMSCE

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-

public class StringDemo {

public static void main(String[] args) {


String s1 = "Object Oriented Programming-Java 5";
System.out.println("The string is: " + s1);
System.out.println("Length of the string: " + s1.length());
System.out.println("First character: " + s1.charAt(0));
System.out.println("Last character: " + s1.charAt(s1.length() - 1));
int spaceIndex = s1.indexOf(" ");
String firstWord = s1.substring(0, spaceIndex);
System.out.println("First word: " + firstWord);
}
}

OUTPUT-

Department of Computer Application,BMSCE

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 {

public NoEqualException(String message) {


super(message);
}
}
public class FloatCheck {
public static void checkValue(float value) throws NoEqualException {
if (value != 3.14f) {
throw new NoEqualException("Value is not equal to 3.14");
} else {
System.out.println("Value is equal to 3.14");
}
}
public static void main(String[] args) {
try {
float num = 2.71f; // Change this to test different values
checkValue(num);
} catch (NoEqualException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}

OUTPUT-

Department of Computer Application,BMSCE

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-

public class TrafficLight extends Thread {

public void run() {


while (true) {
System.out.println("Red Light");
sleepFor(3000);

System.out.println("Green Light");
sleepFor(5000);

System.out.println("Yellow Light");
sleepFor(2000);
}
}

private void sleepFor(int milliseconds) {


try {
Thread.sleep(milliseconds);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
}

public static void main(String[] args) {


TrafficLight t = new TrafficLight();
t.start();
}
}
OUTPUT-

Department of Computer Application,BMSCE

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.*;

public class FileCopy {


public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Error: Please provide source and destination file names as command-line arguments.");
return;
}

File sourceFile = new File(args[0]);


File destFile = new File(args[1]);

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-

Department of Computer Application,BMSCE

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;

public class FileCheck {


public static void main(String[] args) {
File file = new File("C:/Users/student/Downloads/files.txt");
if (!file.exists()) {
System.out.println("File does not exist.");
return;
}
System.out.println("File: " + file.getAbsolutePath());
System.out.println("Readable: " + file.canRead());
System.out.println("Writable: " + file.canWrite());
System.out.println("Hidden: " + file.isHidden());
}
}

OUTPUT-

Department of Computer Application,BMSCE

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);
}
}
}

Department of Computer Application,BMSCE

62
1BM24MC046|Java Programming

OUTPUT-

Department of Computer Application,BMSCE

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();
}
}

Department of Computer Application,BMSCE

64
1BM24MC046|Java Programming

OUTPUT-

Department of Computer Application,BMSCE

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-

Department of Computer Application,BMSCE

66
1BM24MC046|Java Programming

AAT-10

1. Write a program to create a calculator using event handling.

CODE-

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

public class Calculator extends JFrame implements ActionListener {


JTextField textField;
String operator = "";
double num1 = 0;

Calculator() {
setTitle("Calculator");
setSize(250, 350);
setDefaultCloseOperation(EXIT_ON_CLOSE);

textField = new JTextField();


textField.setFont(new Font("Arial", Font.PLAIN, 20));
textField.setHorizontalAlignment(SwingConstants.RIGHT);
textField.setEditable(false);
add(textField, BorderLayout.NORTH);

JPanel panel = new JPanel(new GridLayout(4, 4, 5, 5));


String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", "C", "=", "+"
};

for (String text : buttons) {

JButton btn = new JButton(text);


btn.setFont(new Font("Arial", Font.BOLD, 18));
btn.addActionListener(this);
panel.add(btn);
}

add(panel);
setVisible(true);
Department of Computer Application,BMSCE

67
1BM24MC046|Java Programming

public void actionPerformed(ActionEvent e) {


String cmd = e.getActionCommand();

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("");

}
}

public static void main(String[] args) {


new Calculator();
}
}
OUTPUT-

Department of Computer Application,BMSCE

68
1BM24MC046|Java Programming

2-Create a menu is a frame as shown below:


Books Language Film Search
• The Books menu has the following items: C, C++, Java, Oracle, VB, and ASP.
• The language menu consists of French, German, English, Tamil, and Hindi.
• The File menu has the following: Titanic, Jurassic Park, Tomorrow never Dies, Jeans,
and Slumdog.
• The search engine consists of Yahoo, Hotmail, Sify, Google, and Lycos.

CODE-
import javax.swing.*;

public class MenuExample extends JFrame {


public MenuExample() {
setTitle("Menu Example");
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);

JMenuBar menuBar = new JMenuBar();

JMenu booksMenu = new JMenu("Books");


String[] books = {"C", "C++", "Java", "Oracle", "VB", "ASP"};
for (String item : books) {
booksMenu.add(new JMenuItem(item));
}

JMenu languageMenu = new JMenu("Language");


String[] languages = {"French", "German", "English", "Tamil", "Hindi"};
for (String item : languages) {
languageMenu.add(new JMenuItem(item));
}

JMenu fileMenu = new JMenu("Film");


String[] films = {"Titanic", "Jurassic Park", "Tomorrow never Dies", "Jeans", "Slumdog"};
for (String item : films) {
fileMenu.add(new JMenuItem(item));
}

JMenu searchMenu = new JMenu("Search");


String[] searchEngines = {"Yahoo", "Hotmail", "Sify", "Google", "Lycos"};
for (String item : searchEngines) {
searchMenu.add(new JMenuItem(item));
}

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);
}

public static void main(String[] args) {


new MenuExample();
}
}

OUTPUT-

Department of Computer Application,BMSCE

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.*;

public class BookPriceViewer extends Frame implements ItemListener {


Choice bookChoice;
Label priceLabel;
public BookPriceViewer() {
setTitle("Book Price Viewer");
setSize(300, 200);
setLayout(new FlowLayout());
setVisible(true);
Label label = new Label("Select a Book:");
add(label);
bookChoice = new Choice();
bookChoice.add("C");
bookChoice.add("C++");
bookChoice.add("Java");
bookChoice.add("Oracle");
bookChoice.add("VB");
bookChoice.add("ASP");
add(bookChoice);
priceLabel = new Label("Price: ");
add(priceLabel);
bookChoice.addItemListener(this);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
public void itemStateChanged(ItemEvent e) {
String selectedBook = bookChoice.getSelectedItem();
String price = "";
switch (selectedBook) {
case "C": price = "Rs. 200"; break;
case "C++": price = "Rs. 250"; break;
case "Java": price = "Rs. 300"; break;
case "Oracle": price = "Rs. 350"; break;
case "VB": price = "Rs. 220"; break;
case "ASP": price = "Rs. 270"; break;
}
Department of Computer Application,BMSCE

71
1BM24MC046|Java Programming

priceLabel.setText("Price: " + price);


}
public static void main(String[] args) {
new BookPriceViewer();
}
}

OUTPUT-

Department of Computer Application,BMSCE

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);

selectedCarLabel = new Label("Selected Car: ");


add(selectedCarLabel);
carList.addActionListener(this);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
}
public void actionPerformed(ActionEvent e) {
String selectedCar = carList.getSelectedItem();
selectedCarLabel.setText("Selected Car: " + selectedCar);
}
public static void main(String[] args) {
new CarListViewer();
}
}

Department of Computer Application,BMSCE

73
1BM24MC046|Java Programming

OUTPUT-

Department of Computer Application,BMSCE

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

public void itemStateChanged(ItemEvent e) {


String selected = iitChoice.getSelectedItem();
selectedLabel.setText("Selected (Choice): " + selected);
}
public void actionPerformed(ActionEvent e) {
String selected = iitList.getSelectedItem();
selectedLabel.setText("Selected (List): " + selected);
}

public static void main(String[] args) {


new IITViewer();
}
}
OUTPUT-

Department of Computer Application,BMSCE

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();
}
}

Department of Computer Application,BMSCE

77
1BM24MC046|Java Programming

OUTPUT-

Department of Computer Application,BMSCE

78

You might also like