Java
Java
Objective: Implementing the concepts of class variable, instance variable, use of “this”
keyword, use of reference variable in Java.
Assignments:
1. Create a “circle” class & a “point” class. The coordinates of the circle are given and used
within the “circle” class as object of the “point” class. Display the area of circle.
package Week5;
import java.util.*;
class circle{
double rad;
class point{
int x,y;
point(int x, int y){
this.x=x;
this.y=y;
}
}
2. Create a class called Time, which has three private instance variables – hour, min and
sec. It contains a method called add( ) which takes one Time object as parameter and print
the added value of the calling Time object and passes Time object. In the main method,
declare two Time objects and assign values using constructor and call the add() method.
package Week5;
import java.util.Scanner;
class time{
int hour,min,sec;
System.out.println("\nAdded Time t1+t2 is: "+hour+" hour "+min+" min "+sec+" sec ");
}
public class timeMain{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first Time int hh/mm/ss format: ");
int h1=sc.nextInt();
int m1=sc.nextInt();
int s1=sc.nextInt();
System.out.println("Enter the second Time int hh/mm/ss format: ");
int h2=sc.nextInt();
int m2=sc.nextInt();
int s2=sc.nextInt();
time t1=new time(h1,m1,s1);
time t2=new time(h2,m2,s2);
package Week5;
class Complex{
int real;
int imaginary;
this.real=this.real+op2.real;
this.imaginary=this.imaginary+op2.imaginary;
}
void display()
{
System.out.println(" The value: " + real +" + " + imaginary+"i");
}
}
System.out.println("Before add");
op.display();
op1.display();
op.add(op1);
System.out.println("After add");
op.display();
}
}
Enter the Real part of two numbers:
2
3
Enter the Imaginary part of two numbers:
8
6
Before add
The value: 2 + 8i
The value: 3 + 6i
After add
The value: 5 + 14i
4. Write a program to define a class having one 3-digit number, num as data member.
Initialize and display reverse of that number.
package Week5;
import java.util.*;
class Reverse
{
int num;
Reverse(int n)
{
num=n;
}
5. Write a program to define a class Student with four data members such as name, roll
no., sub1, and sub2. Define appropriate methods to initialize and display the values of data
members. Also calculate total marks and percentage scored by student.
package Week5;
import java.util.*;
class Student
{
int roll,sub1,sub2;
String name;
int total;
double per;
void Initialize(int roll,String name,int sub1,int sub2)
{
this.roll=roll;
this.name=name;
this.sub1=sub1;
this.sub2=sub2;
}
void calculate()
{
total=sub1+sub2;
per=total/2;
}
void display()
{
System.out.println("Name: "+ name);
System.out.println("Roll number: "+roll);
System.out.println("Marks of two subject: "+ sub1+" "+sub2);
System.out.println("Total : "+total+" Percentage: "+per);
}
}
public class StudentDrive
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter your name:");
String n=sc.nextLine();
System.out.println("Enter your Roll number:");
int r=sc.nextInt();
System.out.println("Enter the marks of two subject:");
int s1=sc.nextInt();
int s2=sc.nextInt();
Student a=new Student();
a.Initialize(r,n,s1,s2);
a.calculate();
a.display();
}
}
6. Write a program to define a class Employee to accept emp_id, emp _name, basic_salary
from the user and display the gross_salary.
package Week5;
import java.util.*;
class Employee
{
int emp_id;
String emp_name;
float basic_salary;
Employee(int emp_id, String emp_name, float basic_salary)
{
this.emp_id=emp_id;
this.emp_name=emp_name;
this.basic_salary=basic_salary;
}
void display()
{
float da=basic_salary*15/100;
float hra=basic_salary*10/100;
float gross_sal=basic_salary+da+hra;
System.out.println("YOUR DETAILS IS GIVEN BELOW: \n");
System.out.println ("Employee Id= "+emp_id);
System.out.println ("Emplyee Name= "+emp_name);
System.out.println ("Gross Salary= "+gross_sal);
}
}
public class EmpDrive
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println ("Enter Employee id");
int id = sc.nextInt();
System.out.println ("Enter Employee Name");
String name = sc.nextLine();
name = sc.nextLine();
System.out.println ("Enter Basic Salary");
float sal = sc.nextFloat();
Employee e = new Employee(id, name, sal);
e.display();
}
}
Enter Employee id
1
Enter Employee Name
Soumyadip
Enter Basic Salary
35000
YOUR DETAILS IS GIVEN BELOW:
Employee Id= 1
Emplyee Name= Soumyadip
Gross Salary= 43750.0
7. Write a program to define a class Fraction having data members numerator and
denominator. Initialize three objects using different constructors and display its fractional
value.
package Week5;
import java.util.*;
class Fraction
{
double numerator,denominator;
Fraction (int a, double b)
{
numerator=a;
denominator=b;
}
Fraction (int x, int y)
{
numerator=x;
denominator=y;
}
Fraction(double m, double n)
{
numerator=m;
denominator=n;
}
void display()
{
double fraction=numerator/denominator;
System.out.println ("Fraction = "+fraction);
}
}
public class FractionDrive
{
public static void main(String[] args)
{
8. Write a program to define a class Item containing code and price. Accept this data for
five objects using array of objects. Display code, price in tabular form and also, display
total price of all items.
package Week5;
import java.util.*;
class Item
{
int price;
int code;
Item(int m,int n)
{
code=m;
price=n;
}
void display()
{
System.out.print(code+" "+price);
System.out.println();
}
}
9. Write a program to define a class Tender containing data members cost and company
name. Accept data for five objects and display company name for which cost is minimum.
package Week5;
import java.util.*;
class Tender
{
int cost;
String name;
Tender(String a,int b)
{
name=a;
cost=b;
}
void display()
{
System.out.println(name+"\t"+cost);
}
}
public class MinDrive
{
public static void main(String args[])
{
int cost,k=-1;
String name;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number of tenders");
int n=sc.nextInt();
Tender obj[]=new Tender[n];
for(int i=0;i<n;i++)
{
System.out.print("Enter the Name of Company:");
name=sc.nextLine();
name=sc.nextLine();
System.out.print("Enter the Cost:");
cost=sc.nextInt();
obj[i]=new Tender(name,cost);
}
System.out.println("Company Name Cost");
for(int i=0;i<n;i++)
{
obj[i].display();
}
int min=obj[0].cost;
for(int i=1;i<n;i++)
{
if(obj[i].cost<min)
{
k=i;
min=obj[i].cost;
}
}
System.out.println("Minimum = "+min);
}
}
Enter the number of tenders
2
Enter the Name of Company:TC
Enter the Cost:90000
Enter the Name of Company:IC
Enter the Cost:100000
Company Name Cost
TC 90000
IC 100000
Minimum = 90000
10. Write a program to define a class 'employee' with data members as empid, name and
salary. Accept data for 5 objects using Array of objects and print it.
package Week5;
import java.util.*;
class Item1
{
int p,eid;
String c;
Item1(String m,int n,int e)
{
c=m;
p=n;
eid=e;
}
void display()
{
System.out.print(eid+" "+c + " " + p);
System.out.println();
}
}
• Two private instance variables: radius (of type double) and color (of type String),
• Initialize the variables radius and color with default value of 1.0 and "red", respectively
using default constructor.
• Include a second constructor that will use the default value for color and sets the
radius to the value passed as parameter.
• Two public methods: getRadius() and getArea() for returning the radius and area of
the circle
• Invoke the above methods and constructors in the main.
package Week5;
import java.util.*;
class AB
{
private double radius;
private String color;
AB()
{
radius=1.0;
color="red";
}
AB(double a,String col)
{
radius=a;
color=col;
}
double getRadius()
{
return radius;
}
double getArea()
{
double area=3.14*radius*radius;
return area;
}
}
public class CDrive
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Radius:");
double rad=sc.nextDouble();
System.out.println("Enter the color:");
String clr=sc.nextLine();
clr=sc.nextLine();
AB a=new AB();
AB b=new AB(rad,clr);
double q=a.getRadius();
System.out.println("Value of radius when we call getRadius() with non parameterized
constructor = "+q);
double g=b.getRadius();
System.out.println("Value of radius when we call getRadius() with parameterized
constructor = "+g);
double ar=b.getArea();
System.out.println("Area = "+ar);
System.out.println("Colour = "+clr);
}
}
Enter the Radius:
4
Enter the color:
Red
Value of radius when we call getRadius() with non parameterized constructor = 1.0
Value of radius when we call getRadius() with parameterized constructor = 4.0
Area = 50.24
Colour = Red
12. Write a program which will accept an integer from the user and pass the value to a
method called PrintNumberInWord that will print "ONE", "TWO",... , "NINE", "ZERO" if the
integer variable "number" is 1, 2,... , 9, or 0, respectively.
package Week5;
import java.util.Scanner;
class number
{
public static void numberToWord(int num, String val) {
String ones[] = {" ", " ONE", " TWO", " THREE", " FOUR", " FIVE", " SIX", " SEVEN", " EIGHT", " NINE",
" TEN", " ELEVEN", " TWELVE", " THIRTEEN", " FOURTEEN", " FIFTEEN", " SIXTEEN", " SEVENTEEN", "
EIGHTEEN", " NINETEEN"
};
String tens[] = {" ", " ", " TWENTY", " THIRTY", " FOURTY", " FIFTY", " SIXTY", " SEVENTY", " EIGHTY",
" NINETY"};
if (num > 19) {
System.out.print(tens[num / 10] + " " + ones[num % 10]);
} else {
System.out.print(ones[num]);
}
if (num > 0) {
System.out.print(val);
}
}
}
public class NumDrive
{
public static void main(String[] args) {
int number = 0;
Scanner scanner = new Scanner(System.in);
number n=new number();
System.out.print("Please type a number between 0 and 999 OR type -1 to exit: ");
number = scanner.nextInt();
while(number!=-1){
if(number>=0 && number<=999){
if(number==0){
System.out.print("NUMBER AFTER CONVERSION:\tZERO");
} else {
System.out.print("NUMBER AFTER CONVERSION:\t");
n.numberToWord(((number / 100) % 10), " HUNDRED");
n.numberToWord((number % 100), " ");
}
} else{
System.out.print("NUMBER OUT OF RANGE");
}
System.out.print("\nPlease type a number between 0 and 999 OR type -1 to exit: ");
number = scanner.nextInt();
}
}
}
Please type a number between 0 and 999 OR type -1 to exit: 191
NUMBER AFTER CONVERSION: ONE HUNDRED NINETY ONE
13. Design a class named Account that contains:
I. A private int data field named id for the account (default 0).
II. A private double data field named balance for the account (default 0).
III. A private double data field named annualInterestRate that stores the cur-rent interest
rate (default 0). Assume all accounts have the same interest rate.
IV. A private Date data field named dateCreated that stores the date when the account
was created.
V. A no-arg constructor that creates a default account.
VI. A constructor that creates an account with the specified id and initial balance.
VII. The accessor and mutator methods for id,balance, and annualInterestRate.
VIII. The accessor method for dateCreated.
IX. A method named getMonthlyInterestRate() that returns the monthly interest rate.
X. A method named getMonthlyInterest() that returns the monthly interest.
XI. A method named withdraw that withdraws a specified amount from the account.
XII. A method named deposit that deposits a specified amount to the account.
package Week5;
class Account {
private int id = 0;
private double balance = 0.0;
private static double annualInterestRate = 0.0;
private java.util.Date dateCreated;
public Account() {
dateCreated = new java.util.Date();
}
public Account(int id, double balace) {
this();
this.id = id;
this.balance = balance;
}
}
}
Balance: $500.0
Monthly Interest: 1.875
Date Created: Sun Aug 25 10:29:13 IST 2019
14. Write a test program that prompts the user to enter the investment amount (e.g.,
1000) and the interest rate (e.g., 9%), and print a table that displays future value for the
years from 1 to 30, as shown below:
class ADrive
{
public static void main(String[] args) {
Amt ob=new Amt(100.0);
ob.interest();
}
}
Years ....... future_value
1........109.38068976709839
2........119.64135293926222
3........130.86453709165366
4........143.1405333313711
5........156.56810269415706
6........171.25527068212796
7........187.32019633462298
8........204.89212282389357
9........224.1124172232252
10........245.13570781248114
11........268.1311280707507
12........293.28367736408916
13........320.7957092751521
14........350.888559548417
15........383.80432674789427
16........419.80781995281484
17........459.1886891606074
18........502.2637555363697
19........549.379560255814
20........600.9151524472612
21........657.2851386618252
22........718.9430184049334
23........786.3848325637133
24........860.1531540820313
25........940.8414529883785
26........1029.098870893479
27........1125.6354433687086
28........1231.2278122196296
29........1346.7254736101859
30........1473.057612304044
a. Computing a sales commission, given the sales amount and the commission rate.
b. Printing the calendar for a month, given the month and year.
c. Computing a square root.
d. Testing whether a number is even, and returning true if it is.
e. Printing a message a specified number of times.
f. Computing the monthly payment, given the loan amount, number of years, and annual
interest rate.
(a) public static double getCommission(double salesAmount, double commissionRate)
(b) public static void printCalendar(int month, int year)
(c) public static double sqrt(double value)
(d) public static boolean isEven(int value)
(e) public static void printMessage(String message, int times)
(f) public static double monthlyPayment(double loan, int numberOfYears, double annualInterestRate)
16. Write a program that reads ten numbers, computes their average, and finds out how
many numbers are above the average. [Use this keyword]
package Week5;
import java.util.*;
class B
{
static int a[],n;
B(int a[],int n)
{
this.a=a;
this.n=n;
}
void calc()
{
int avg=0;
int c=0;
for(int i=0;i<n;i++)
avg=avg+a[i];
avg=avg/n;
System.out.println("Average is :"+avg);
for(int i=0;i<n;i++)
{
if(a[i]>avg)
c++;
}
if(c>0)
System.out.println("There are "+c+" numbers that are above the average ");
else
System.out.println("There are no numbers that are below the average ");
}
}
class AvgDrive
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter n :");
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
{
System.out.println("Enter number :");
a[i]=sc.nextInt();
}
B obj=new B(a,n);
obj.calc();
}
}
Enter n :
3
Enter number :
55
Enter number :
66
Enter number :
77
Average is :66
There are 1 numbers that are above the average
17. Write a program that reads ten integers and displays them in the reverse of the order
in which they were read.
package Week5;
class Num
{
void rev(int[] num)
{
for(int i=9;i>=0;i--)
{
System.out.println ("in reverse order");
System.out.println (num[i]);
}
}
}
class Student1{
int rollno;
String name;
float fee;
Student1(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
package Week5;
class Demo
{
static void m1()
{
System.out.println("Demo of static");
}
}
public class StaticDrive
{
public static void main(String[] args)
{
Demo.m1();
}
}
Demo of static
20. Write a program to accept value of apple sales for each day of the week (using array of
type float) and then, calculate the average sale of the week.
package Week5;
class Sales
{
int x;
Double sum=0.0,avg;
21. Write program, which finds the sum of numbers formed by consecutive digits. Input :
2415 output : 24+41+15=80.
package Week5;
import java.util.*;
class Digit
{
int x;
int y=0,z=0,sum=0,m=0;
Digit(int x)
{
this.x=x;
}
void num()
{
while (x>9)
{
y=x%10;
x=x/10;
z=x%10;
m=z*10;
sum=sum+y+m;
}
System.out.println("sum of numbers formed by consecutiv digits="+sum);
}
1. Design an abstract class having two methods. Create Rectangle and Triangle classes by inheriting the
shape class and override the above methods to suitably implement for Rectangle and Triangle class.
return w*l;
}
public double perimeter(int w, int l) {
return 2*(w+l);
}
}
//Isosceles Triangle
return (h*b)/2;
}
public double perimeter(int h, int b) {
return (h+h+b);
}
}
public class Abstract_Rect_Tri {
interface Example{
System.out.print("This is Interface");
}
}
This is Interface
3. Create a general class ThreeDObject and derive the classes Box, Cube, Cylinder and Cone from it. The
class ThreeDObject has methods wholeSurfaceArea ( ) and volume( ). Override these two methods in
each of the derived classes to calculate the volume and whole surface area of each type of three-
dimensional objects. The dimensions of
the objects are to be taken from the users and passed through the respective constructors of each
derived class. Write a main method to test these classes.
import java.util.Scanner;
return (2*(h*w)+2*(h*l)+2*(w*l));
}
return (h*w*l);
}
}
return (6*a*b);
}
return (a*b*c);
}
}
class Cone extends ThreeDObject{
}
}
4. Write a program to create a class named Vehicle having protected instance variables regnNumber,
speed, color, ownerName and a method showData ( ) to show “This is a vehicle class”. Inherit the
Vehicle class into subclasses named Bus and Car having individual private instance variables
routeNumber in Bus and manufacturerName in Car and both of them having showData ( ) method
showing all details of Bus and Car respectively with content of the super class’s showData ( ) method.
class Vehicle_Main {
this.regnNumber = regnNumber;
this.speed = speed;
this.color = color;
this.ownerName = ownerName;
}
int routeNumber;
public Bus(int regnNumber, int speed, String color, String ownerName, int routeNumber) {
super(regnNumber, speed, color, ownerName);
this.routeNumber = routeNumber;
}
public String ShowData() {
return "Bus [routeNumber=" + routeNumber + ", regnNumber=" + regnNumber + ",
speed=" + speed + ", color="
+ color + ", ownerName=" + ownerName + "]";
}
String manufacturerName ;
public Car(int regnNumber, int speed, String color, String ownerName, String
manufacturerName ) {
super(regnNumber, speed, color, ownerName);
this.manufacturerName = manufacturerName ;
}
}
Bus [routeNumber=199, regnNumber=1010, speed=70, color=Black, ownerName=Soumyadip]
Car [manufacturerName=TATA, regnNumber=1010, speed=70, color=Black, ownerName=Soumyadip]
5. Create three interfaces, each with two methods. Inherit a new interface from the three, adding a new
method. Create a class by implementing the new interface and also inheriting from a concrete class.
Now write four methods, each of which takes one of the four interfaces as an argument. In main ( ),
create an object of your class and pass it to each of the methods.
interface Test1{
interface Test2{
interface Test3{
interface Test4{
}
Mehtod 1
Mehtod 2
Mehtod 3
Mehtod 4
Mehtod 5
Mehtod 6
Mehtod 7
Mehtod 8
Mehtod newMethod()
6. Create an interface Department containing attributes deptName and deptHead. It also has abstract
methods for printing the attributes. Create a class hostel containing hostelName, hostelLocation and
numberofRooms. The class contains methods for getting and printing the attributes. Then write Student
class extending the Hostel class and implementing the Department interface. This class contains
attributes studentName, regdNo, electiveSubject and avgMarks. Write suitable getData and printData
methods for this class. Also implement the abstract methods of the Department interface. Write a
driver class to test the Student class. The program should be menu driven containing the options:
For the third option a search is to be made on the basis of the entered registration number.
import java.util.Scanner;
interface Department{
class Hostel{
}
1: Admit
2: Migrate
3: Show
1
Enter Student Name
Soumyadip
Enter elected Subject
Java
Enter avgMarks
80
Enter hostelName
UEMK_HOSTEL
Enter hostelLocation
Newtown
Enter numberofRooms
3
Student Added::Reg IdUEMK3RD1
1: Admit
2: Migrate
3: Show
3
Enter the last digit of the id 1
Student [studentName=Soumyadip, regdNo=UEMK3RD1, electiveSubject=Java, avgMarks=80,
hostelName=UEMK_HOSTEL, hostelLocation=Newtown, numberofRooms=3, deptName=CSE,
deptHead=XYZ_Sir]
7. Create an interface called Player. The interface has an abstract method called play() that displays a
message describing the meaning of “play” to the class. Create classes called Child, Musician, and Actor
that all implement Player. Create an application that demonstrates the use of the classes
(UsePlayer.java)
interface Player{
System.out.println("This is Child");
}
}
class Musician implements Player{
public void play() {
System.out.println("This is Musician");
}
}
class Actor implements Player{
public void play() {
}
public class UsePlayer {
public static void main(String args[]) {
}
This is Child
This is Musician
This is Actor
Data Members:
Create a subclass of this class SavingsAccount and add the following details:
Data Members:
(a) rateOfInterest
Methods:
(a) calculateAount()
public SavingsAccount (String dipositor, String address, long ac, int ammount) {
super(dipositor, address, ac, ammount);
this.roi = 5;
}
}
else{
ammount-=am;
System.out.println("Ammount debited "+ammount);
System.out.println("Updated balance "+ammount);
}
int sum=ammount*(1+roi*12);
System.out.println("Intrestfor 12 months :"+sum);
System.out.println("Recent balance "+ammount);
}
Data Members:
Methods:
Data Members:
(b) discountRate
Methods:
(a) display() method to display the Car name, model number, price and the discount rate.
}
class Carthat extends MotorVehicle{
double discountRate;
Discount Price:960000.0
Carthat [discountRate=0.2, modelName=Duster, mmdelPrice=1200000, modelNumber=7768]
Here, Asset class is an abstract class containing an abstract method displayDetails() method. Stock, bond
and Savings class inherit the Asset class and displayDetails() method is defined in every class.
abstract class Asset{
int num_share;
int share_price;
int asset;
public Stock(String descriptor, String date, int currentvalue, int num_share, int share_price, int
asset) {
super(descriptor, date, currentvalue);
this.num_share = num_share;
this.share_price = share_price;
this.asset = asset;
}
int intrest_rate;
int asset;
public Bond(String descriptor, String date, int currentvalue, int intrest_rate, int asset) {
super(descriptor, date, currentvalue);
this.intrest_rate = intrest_rate;
this.asset = asset;
}
int intrest_rate;
int asset;
public Savings(String descriptor, String date, int currentvalue, int intrest_rate, int asset) {
super(descriptor, date, currentvalue);
this.intrest_rate = intrest_rate;
this.asset = asset;
}
}
Stock [num_share=10, share_price=2500, asset=25000, descriptor=Bruce, date=17-08-2019,
currentvalue=50000]
Bond [intrest_rate=5, asset=75000, descriptor=Barry, date=16-08-2019, currentvalue=40000]
Savings [intrest_rate=3, asset=50000, descriptor=Soumyadip, date=15-08-2019, currentvalue=70000]
11. Implement the below Diagram. Here AbstractProduct is only abstract class.
}
class Product extends AbstractProduct{
public Book(int productId, String name, String description, int price, int iSBN, String author,
String title) {
super(productId, name, description, price);
ISBN = iSBN;
Author = author;
Title = title;
}
public Travel_Guide(int productId, String name, String description, int price, int iSBN, String
author,
String title, String country) {
super(productId, name, description, price, iSBN, author, title);
Country = country;
}
public CompactDisc(int productId, String name, String description, int price, String artist, String
title) {
super(productId, name, description, price);
Artist = artist;
Title = title;
}
int SteeringHandle;
@Override
public String display() {
return "Two_Wheeler [SteeringHandle=" + SteeringHandle + ", ID=" + ID + ", name=" +
name + ", LicenseNumber="
+ LicenseNumber + "]";
}
int SteeringWheel;
System.out.println(obj.display());
System.out.println(obj1.display());
}
Two_Wheeler [SteeringHandle=1, ID=1011, name=KTM, LicenseNumber=WBIO0897]
Four_Wheeler [SteeringWheel=1, ID=1011, name=Baleno, LicenseNumber=WBIO4547]
13. Write a program to implement the Multiple Inheritance (Bank Interface, Customer & Account
classes).
interface Bank{
class Customer{
int acNo;
}
Account [acNo=12990991, CustomerName=Soumyadip]
14. Write a program to implement the Multiple Inheritance (Gross Interface, Employee & Salary
classes).
interface Gross{
class Employee{
int sal;
@Override
public String details() {
return "Salary [Salary=" + sal + ", EmployeeName=" + EmployeeName + "]";
}
}
}
Salary [sal=30000, EmployeeName=Soumyadip]
15. Program to create a interface 'Mango' and implement it in classes 'Winter' and 'Summer'.
interface Mango{
boolean Availability ;
Availability = availability;
}
public String Availability() {
return "Summer [Availability=" + Availability + "]";
}
}
boolean Availability ;
Availability = availability;
}
public String Availability() {
return "Winter [Availability=" + Availability + "]";
}
}
Summer [Availability=true]
Winter [Availability=false]
16. Program to implement the Multiple Inheritance (Exam Interface, Student & Result classes).
interface Exam{
class Student_Exam{
}
}
int percent;
public Results(String name, int percent) {
super(name);
this.percent = percent;
}
public String markSheet() {
return "Result [percentage=" + percent + ", name=" + name + "]";
}
}
public class Exam_Interface {
}
}
Result [percentage=85, name=Soumyadip]
interface A
{
public void displayA();
}
interface B extends A
{
public void displayB();
}
interface C extends A
{
public void displayC();
}
interface PayRoll{
class Employee_Pay{
int sal;
interface Exam_{
class Student_{
int per;
per=(marks1+marks2)/2;
System.out.println("Percentage :"+per);
}
Percentage :87
Student [name=Soumyadip, roll=35, marks1=85, marks2=90]
Result [percentage=87, name=Soumyadip, roll=35, marks1=85, marks2=90]
Week 7
Objective: Implement the concepts of Exception Handling in Java.
Assignments:
1. Write a Java program to show the use of all keywords for exception handling
int a=50;
try{
int sum=a/0;
}
catch(ArithmeticException e)
{
System.out.println("Exception: "+e);
}
finally{
System.out.println("Executing finally block");
}
}
}
Exception: java.lang.ArithmeticException: / by zero
Executing finally block
2. Write a Java program using try and catch to generate NegativeArrayIndex Exception and Arithmetic
Exception.
int arr[];
try{
arr=new int[-10];
}
catch(NegativeArraySizeException f){
System.out.println("Exception "+f);
}
int a=50;
try{
int sum=a/0;
}
catch(ArithmeticException e)
{
System.out.println("Exception: "+e);
}
}
Exception java.lang.NegativeArraySizeException
Exception: java.lang.ArithmeticException: / by zero
3. Define an exception called ¡§NoMatchFoundException¡¨ that is thrown when a string is not equal to
¡§University¡¨. Write a program that uses this exception.
NoMatchFoundException(String s){
super(s);
}
}
} catch (Exception e) {
System.out.println(e);
}
System.out.print("Rest Code");
}
}
NoMatchFoundException: NoMatchFoundException Gen
Rest Code
4. Write a class that keeps a running total of all characters passed to it (one at a time) and throws an
exception if it is passed a non-alphabetic character.
NonAlphabeticException(String s){
super(s);
}
}
class Alpha{
5. Write a program called Factorial.java that computes factorials and catches the result in an array of type
long for reuse. The long type of variable has its own range. For example 20! Is as high as the range of long
type. So check the argument passes and ¡§throw an exception¡¨, if it is too big or too small.
„h If x is above the length of the array throw an IllegalArgumentException with a message ¡§Result will
overflow¡¨.
NonAlphabeticException(String s){
super(s);
}
}
class Alpha{
import java.util.Scanner;
NoMatchFoundException(String s){
super(s);
}
}
} catch (Exception e) {
System.out.println(e);
}
System.out.print("Rest Code");
}
}
„h The first error is when the user provides no argument while executing the program and an
ArrayIndexOutOfBoundsException is raised. You must write a catch block for this.
„h The second error is NumberFormatException that is raised in case the user provides a non-integer (float
double) value at the command line.
„h The third error is IllegalArgumentException. This needs to be thrown manually if the value at the
command line is 0.
import java.util.Scanner;
int z=n;
int fact=1;
while(n>1)
{
fact*=n;
n--;
}
System.out.println("Factorial of "+z+" = "+fact);
} catch(ArrayIndexOutOfBoundsException e)
{
System.out.print(e);
}
catch(NumberFormatException e)
{
System.out.print(e);
}
catch(IllegalArgumentException e)
{
System.out.print(e);
}
}
}
1.00
java.lang.NumberFormatException: For input string: "1.00"
0
java.lang.IllegalArgumentException
5
Factorial of 5 = 120
9. Create a user-defined exception named CheckArgument to check the number of arguments passed
through the command line. If the number of argument is less than 5, throw the CheckArgumentexception,
else print the addition of all the five numbers.
import java.util.Scanner;
CheckArgumentexception(String s){
super(s);
}
}
}
}
10. Consider a Student examination database system that prints the mark sheet of students. Input the
following from the command line.
These marks should be between 0 to 50. If the marks are not in the specified range, raise a
RangeException, else find the total marks and prints the percentage of the students.
import java.util.Scanner;
RangeException(){
super("Marks should be between 0 to 50");
}
}
}
}
11. Write a java program to create an custom Exception that would handle at least 2 kind of Arithmetic
Exceptions while calculating a given equation (e.g. X+Y*(P/Q)Z-I)
import java.util.Scanner;
CustomArithmeticException(String s){
super(s);
}
}
try
{
if(q==0)
throw new CustomArithmeticException("Cannot divided by 0");
int sum=(x+y*(p/q)*z-l);
if(sum<0)
throw new CustomArithmeticException("Sum cannot be negetive");
System.out.print(sum);
}
catch(CustomArithmeticException e)
{
System.out.print(e);
}
}
}
Enter X
10
Enter Y
20
Enter P
30
Enter P
0
Enter Z
40
Enter L
50
CustomArithmeticException: Cannot divided by 0
Enter X
1
Enter Y
2
Enter P
3
Enter P
4
Enter Z
5
Enter L
6
CustomArithmeticException: Sum cannot be negative
12. Create two user-defined exceptions named ¡§TooHot¡¨ and ¡§TooCold¡¨ to check the temperature (in
Celsius) given by the user passed through the command line is too hot or too cold.
import java.util.Scanner;
TooHot(){
super("Temperature is too-hot");
}
}
try
{
if(x<0)
throw new TooCold();
if(x>35)
throw new TooHot();
System.out.println("Temperature is (Celsius):"+x);
System.out.print("Temperature is (Fahrenheit ):"+(x*(9/5)+32));
}
catch(TooHot e)
{
System.out.print(e);
}
catch(TooCold e)
{
System.out.print(e);
}
}
}
Enter the temperature (Celsius):
-3
TooCold: Temperature is too-cold
Enter the temperature (Celsius):
50
TooHot: Temperature is too-hot
Enter the temperature (Celsius):
19
Temperature is (Celsius):19
Temperature is (Fahrenheit ):51
13. Consider an Employee recruitment system that prints the candidate name based on the age criteria.
The name and age of the candidate are taken as Input.Create two user-defined exceptions named
¡§TooOlder¡¨ and ¡§TooYounger¡¨
„h If age>45, throw exception ¡§TooOlder¡¨.
import java.util.Scanner;
TooYounger(){
super("TooYounger");
}
}
TooOlder(){
super("TooOlder");
}
}
public class AgeException {
try
{
if(x<20)
throw new TooYounger();
if(x>40)
throw new TooOlder();
System.out.println("(Eligible) Name :"+name);
}
catch(TooYounger e)
{
System.out.print(e);
}
catch(TooOlder e)
{
System.out.print(e);
}
}
}
14. Consider a ¡§Binary to Decimal¡¨ Number conversion system which only accepts binary number as
Input. If user provides a decimal number a custom Exception ¡§WrongNumberFormat¡¨ exception will be
thrown. Otherwise, it will convert into decimal and print into the screen.
import java.util.Scanner;
WorngNumberException(){
super("Please enter the binary number");
}
}
int a=Integer.parseInt(str,2);
System.out.print("Decimal :"+a);
}
catch(Exception e)
{
System.out.print(e);
}
}
}
Enter the number (in binary):
121
WorngNumberException: Please enter the binary number
15. Write a Java Program that Implement the Nested Try Statements.
}
}
}
java.lang.ArithmeticException: / by zero
16. Write a Java Program to Create Account with 500 Rs Minimum Balance, Deposit Amount, Withdraw
Amount and Also Throws LessBalanceException.
Java Program Which has a Class Called LessBalanceException Which returns the Statement that Says
WithDraw Amount(_Rs) is Not Valid
Java Program that has a Class Which Creates 2 Accounts, Both Account Deposit Money and One Account
Tries to WithDraw more Money Which Generates a LessBalanceException Take Appropriate Action for the
Same.
import java.util.Scanner;
LessBalanceException(int i){
super("WithDraw Amount "+i+" is not valid");
}
}
int am=500;
System.out.println("Account created with initial balance 500");
int x=0;
Scanner sc=new Scanner(System.in);
while(x!=1)
{
System.out.println("1. Diposit");
System.out.println("2. Withdraw");
int a=sc.nextInt();
if(a==1)
{
System.out.println("Enter the ammount");
int z=sc.nextInt();
am+=z;
System.out.println("Current balance :"+am);
}
else if(a==2)
{
System.out.println("Enter the ammount");
int z=sc.nextInt();
if(z>am)
try {
throw new LessBalanceException(z);
} catch (LessBalanceException e) {
System.out.println(e);
}
else
am-=z;
System.out.println("Current balance :"+am);
}
else
{
x=1;
}
}
}
}
Account created with initial balance 500
1. Diposit
2. Withdraw
1
Enter the ammount
5000
Current balance :5500
1. Diposit
2. Withdraw
2
Enter the ammount
2000
Current balance :3500
1. Diposit
2. Withdraw
2
Enter the ammount
10000
LessBalanceException: WithDraw Amount 10000 is not valid
Current balance :3500
17. Consider a Library Management System, where a user wants to find a book. If the book is present in
Library (Hint: Use predefined array), then it will print the book. Otherwise it will throw an exception
¡§BookNotFoundException¡¨.
import java.awt.print.Book;
import java.util.Scanner;
class BookNotFoundException extends Exception{
BookNotFoundException(){
super("Book not found exception");
}
}
try
{
if(flag==0)
throw new BookNotFoundException();
else
System.out.print("Book found");
}
catch(BookNotFoundException e)
{
System.out.print(e);
}
}
}
Enter the book no.:
1010
BookNotFoundException: Book not found exception
import java.util.Scanner;
NotCorrectException(){
super("Wrong answer");
}
}
}
}
Captain of Indian Cricket team?
1: Virat Kohli
2: MS. Dhoni
2
NotCorrectException: Wrong answer
EX Prime Minister of India?
1: Dr. Manmohan Singh
2: Arvind Kejriwal
2
NotCorrectException: Wrong answer
Who wrote the C language?
1: Bill Gates
2: Dennis Ritchie
2
Good
JAVA is written in which year?
1: 1992
2: 1995
2
Good
When was TCS established?
1: 1 April 1968
2: 1 April 1972
2
NotCorrectException: Wrong answer
19. Write a program to raise a user defined exception if username is less than 6 characters and password
does not match.
import java.util.Scanner;
PasswordException(String s){
super(s);
}
}
20. Write a program to accept a password from the user and throw 'Authentication Failure' exception if
the password is incorrect.
import java.util.Scanner;
AuthenticationFailure(){
super("AuthenticationFailure");
}
}
String pass="UEMKCSEJAVA";
Scanner sc=new Scanner(System.in);
21. Write a program to input name and age of a person and throw a user-defined exception, if the entered
age is negative.
import java.util.Scanner;
NegAgeException(){
super("Age should'nt be negetive");
}
}
if(age<0)
try {
throw new NegAgeException();
} catch (NegAgeException e) {
System.out.print(e);
}
}
}
Enter the name :Soumyadip
Enter the age :
-20
NegAgeException: Age should'nt be negetive
22. Write a program to throw user defined exception if the given number is not positive.
import java.util.Scanner;
NotPositiveException(){
super("Age should'nt be negetive");
}
}
if(age<0)
try {
throw new NotPositiveException();
} catch (NotPositiveException e) {
System.out.print(e);
}
}
}
Enter a number :
-1
NotPositive_Exception: Number should'nt be negetive
23. Write a program to throw a user-defined exception "String Mismatch Exception", if two strings are not
equal (ignore the case).
import java.util.Scanner;
24. Design a stack class. Provide your own stack exceptions namely push exception and pop exception,
which throw exceptions when the stack is full and when the stack is empty respectively. Show the usage
of these exceptions in handling a stack object in the main.
public StackException()
{
super("Stack size exception");
}
}
class Stack_{
else
{
top--;
try {
throw new StackException();
} catch (StackException e) {
System.out.println(e);
}
}
}
static void pop()
{
if(top>=0)
System.out.println(arr[top--]+" Popped");
else
{
top++;
try {
throw new StackException();
} catch (StackException e) {
System.out.println(e);
}
}
}
}
public class Stack_Exception {
}
}
10 pushed
20 pushed
30 pushed
40 pushed
50 pushed
StackException: Stack size exception
50 Popped
40 Popped
30 Popped
20 Popped
10 Popped
StackException: Stack size exception
25. Write an application that displays a series of at least five student ID numbers (that you have stored in
an array) and asks the user to enter a numeric test score for the student. Create a ScoreException class,
and throw a ScoreException for the class if the user does not enter a valid score (zero to 100). Catch the
ScoreException and then display an appropriate message. In addition, store a 0 for the student¡¦s score.
At the end of the application, display all the student IDs and scores.
import java.util.Scanner;
ScoreException (){
super("Invaid Score");
}
}
for(int i=0;i<enroll.length;i++)
{
System.out.println("Enrollment no:"+enroll[i]+" Marks:"+marks[i]);
}
}
}
width=200
height=200>
</applet>
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
Button b1,b2;
b1=new Button("RED");
add(b1);
b1.addActionListener(this);
b2=new Button("GREEN");
add(b2);
b2.addActionListener(this);
if(e1.getSource()==b1)
{
setBackground(Color.red);
if(e1.getSource()==b2)
setBackground(Color.green);
2. Design a Java applet that will display “Hello Applet” message in the applet window and set the
background and foreground colour
/*
</applet>
*/
import java.applet.*;
import java.awt.Color;
import java.awt.*;
setBackground(Color.cyan);
setForeground(Color.red);
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.*;
public class AppletLifeCycle extends Applet
{
public void init()
{
setBackground(Color.CYAN);
System.out.println("init() called");
}
public void start(){ System.out.println("Start() called"); }
public void paint(Graphics g){ System.out.println("Paint(() called"); }
a. Rectangle
b. Square
c. Circle.
Import java.awt.*;
import java.applet.Applet;
{
// Rectangle
g.drawRect(10,10,50,100);
// Square
g.drawRect(100,100,50,50);
// Circle
g.drawOval(150, 50, 90, 90);