0% found this document useful (0 votes)
79 views93 pages

SADGVD

The document contains examples of simple Java programs including displaying a welcome message, swapping two numbers, calculating the area and perimeter of shapes, checking voter eligibility, and calculating the sum of natural numbers. It also includes examples of generating electricity bills and implementing currency, distance, and time converters using packages.

Uploaded by

rajshankartamil
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)
79 views93 pages

SADGVD

The document contains examples of simple Java programs including displaying a welcome message, swapping two numbers, calculating the area and perimeter of shapes, checking voter eligibility, and calculating the sum of natural numbers. It also includes examples of generating electricity bills and implementing currency, distance, and time converters using packages.

Uploaded by

rajshankartamil
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/ 93

EX NO:1(a) SIMPLE JAVA PROGRAM-TO DIPLAY THE

MESSAGE AS WELCOME USER NAME

Aim:
To write a program to understand input output constructs in
Java.
ALGORITHM:

1. Import necessary packages and relevant classes.


2. Defile a class as Welcome
3. Define a main method
4. Create a Scanner object for getting input.
5. Getting String as input and store it into user.
6. To display the message as Welcome user.
Program:
import java.lang.*;
import java.util.*;
class Welcome
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
System.out.println("Enter your name");
String s = obj.nextLine();
System.out.println("WELCOME " + s);
}
}

OUTPUT:

RESULT:
Thus the simple java program to display the message as
welcome user was implemented and verified.
EX NO:1(b)
SWAPPING OF TWO NUMBERS

Aim:
To write a program to perform swapping of two numbers

aLGORITHM:
1. Import necessary packages and relevant classes.
2. Define a, b and temp as member
3. Read input value a and b from the user using getInput()
method.
4. Swap two numbers using swap method.
5. Print a and b value using display() method.

Program:
import java.util.Scanner;
public class Swapping
{int num1,num2, temp;
void getInput(){
Scanner obj=new Scanner(System.in);
System.out.println("Enter the number 1:");
num1=obj.nextInt();
System.out.println("Enter the number 2:");
num2=obj.nextInt();
}
void display(){
System.out.println(" Number 1 value is: "+num1);
System.out.println(" Number 2 value is: "+num2);
}
void swap(){ temp =num1;
num1=num2;
num2=temp;
}
public static void main(String args[])
{Swapping s=new Swapping();
s.getInput();
System.out.println("Before Swapping");
s.display();
s.swap(); //to perform swapping
System.out.println("After Swapping");
s.display();
}
}

Output:

Result:
Thus the java program to swap the two number was executed
and verified successfully
EX NO:1(c) CALCULATE PERIMETER AREA AND VOLUME
OF ANY ONE OF THE SHAPE
Aim:
To write a java program to calculate perimeter, Area and
volume of any one of the shape.

ALGORITHM:
1. Import necessary packages and relevant classes.
2. Define side as member.
3. Read input value of side using getInput() method.
4. Calculate the area of square using areaSquare() method.
5. Determine the perimeter of square using perimeterSquare() method.

PROGRAM:
import java.util.Scanner;
public class Shape {
int side;
void getInput(){
System.out.println("Enter the side of Square object:");
Scanner obj=new Scanner(System.in);
side=obj.nextInt();
}
void areaSquare()
{
System.out.println("The area of Square Object is:"+side*side);
}
void perimeterSquare()
{
System.out.println("The perimeter of Square Object is:"+4*side);
}
void cube()
{
System.out.println("The volume of cube is:"+side*side*side);
}
public static void main(String args[])
{Shape e=new Shape();
e.getInput();
e.areaSquare();
e.perimeterSquare();
e.cube();
}
}
OUTPUT:

RESULT:
Thus the java program to calculate the area, perimeter and volume of
any one of the shape was executed and verified successfully.

EX NO:1(d)
ELIGIBILITY FOR VOTING OR NOT

AIM:
To write a java program to check whether the person is eligible to
vote or not.

ALGORITHM:
1. Get details of the voter using getVoterDetails() .
2. Check whether the person is eligible to vote or not using
checkEligible() i.e. age >= 18 person is eligible otherwise not eligible.

PROGRAM:
import java.util.Scanner;
public class VoterDemo
{ int age;
String name;
void getVoterDetails()
{ Scanner obj=new Scanner(System.in);
System.out.println("Enter the Person Name:");
name=obj.nextLine();
System.out.println("Enter the Person Age:");
age=obj.nextInt();
}
void checkEligible(){
if(age >=18 )
System.out.println(name+" is eligible to Vote");
else
System.out.println(name+" is not eligible to Vote");
}
public static void main(String args[])
{VoterDemo v=new VoterDemo();
v.getVoterDetails();
v.checkEligible();
}
}

OUTPUT:
RESULT:
Thus the java program to check whether the person is eligible to vote
or not was implemented and verified successfully.
EX NO:1(e)
SUM OF NATURAL NUMBERS UPTO THE LIMIT
AIM:
To write a java program to find the sum of first n natural numbers.

ALGORITHM:
1. read n value using Scanner object.
2. find sum of first n natural numbers using calculate().

PROGRAM:
import java.util.Scanner;
public class SumFirstN
{
int calculate(int n)
{
int sum=0;
for(int i=1;i<=n;i++)
sum+=i;
return sum;
}
public static void main(String args[])
{ Scanner obj=new Scanner(System.in);
System.out.println("Enter the Limit (N):");
int n=obj.nextInt();
SumFirstN s=new SumFirstN();
System.out.println("The sum of First N Natural number
is:"+s.calculate(n));
}
}

OUTPUT:
RESULT:
Thus the java program to print the sum of first n natural numbers
was implemented and verified successfully.
EX NO:2
ELECTRICITY BILL CALCULATION

AIM:
To Develop a Java application to generate Electricity bill. Create a
class with the following members: Consumer no., consumer name,
previous month reading, current month reading, type of EB connection
(i.e domestic or commercial). Compute the bill amount using the
following tariff.
a. If the type of the EB connection is domestic, calculate the
amount to be paid as follows:
➢ First 100 units - Rs. 1 per unit
➢ 101-200 units - Rs. 2.50 per unit
➢ 201 -500 units - Rs. 4 per unit
➢ 501 units - Rs. 6 per unit
b. If the type of the EB connection is commercial, calculate the
amount to be paid as follows:
➢ First 100 units - Rs. 2 per unit
➢ 101-200 units - Rs. 4.50 per unit
➢ 201 -500 units - Rs. 6 per unit
➢ 501 units - Rs. 7 per unit
ALGORITHM:
1. Declare the members of the customer
2. Read the customer details using getCustomerDetails()
3. Calculate EB Bill by calling EbillCal()
4. Generate report of EB Bill Statement by calling display()

PROGRAM:
import java.util.Scanner;

public class EBbill

int EBNumber;

String customerName;

int previousMonthReading;

int currentMonthReading;

int numberOfUnitsConsumed;

double charge;

int typeEBConnection;

void getCustomerDetails()

Scanner obj=new Scanner(System.in);

System.out.println("Enter the Customer Name:");

customerName=obj.nextLine();

System.out.println("Enter the Customer EB Number:");


EBNumber=obj.nextInt();

System.out.println("Enter the previous month EB reading");

previousMonthReading=obj.nextInt();

System.out.println("Enter the Current month EB reading");

currentMonthReading=obj.nextInt();

System.out.println("Enter the type of EB Connection (Domestic -1 / Commercial -


2 )");

typeEBConnection=obj.nextInt();

void eBillCal()

numberOfUnitsConsumed=currentMonthReading-previousMonthReading;

if(typeEBConnection==1)

if(numberOfUnitsConsumed < 101)

charge=numberOfUnitsConsumed*1;

else if(numberOfUnitsConsumed > 100 && numberOfUnitsConsumed < 201)

charge=100+(numberOfUnitsConsumed-100)*2.5;

else if(numberOfUnitsConsumed>200 && numberOfUnitsConsumed < 501)

charge=100+100*2.5+(numberOfUnitsConsumed-200)*4;

else

charge=100+100*2.5+300*4+(numberOfUnitsConsumed-500)*6;

}
else

if(numberOfUnitsConsumed < 101)

charge=numberOfUnitsConsumed*2;

else if(numberOfUnitsConsumed > 100 && numberOfUnitsConsumed < 201)

charge=100+(numberOfUnitsConsumed-100)*4.5;

else if(numberOfUnitsConsumed>200 && numberOfUnitsConsumed < 501)

charge=100+100*4.5+(numberOfUnitsConsumed-200)*6;

else

charge=100+100*2.5+300*4+(numberOfUnitsConsumed-500)*7;

void display()

String con=(typeEBConnection==1)?"Domestic":"Commercial";

System.out.println("------------------EB Bill Details----------------------- ");

System.out.println(" ");

System.out.println("Customer Name :"+customerName);

System.out.println("Customer EB Number :"+EBNumber);

System.out.println("Previous Month Reading :"+previousMonthReading);

System.out.println("Current Month Reading :"+currentMonthReading);

System.out.println("Number of Units Consumed :"+numberOfUnitsConsumed);

System.out.println("Type of EB Connection :"+con);


System.out.println("EB Charge :"+charge);

System.out.println(" ");

public static void main(String[] args)

EBbill e=new EBbill();

e.getCustomerDetails();

e.eBillCal();

e.display();

OUTPUT:(1)
OUTPUT:(2)

RESULT:
Thus the java program to generate EB Bill of the customer was
implemented and verified successfully.
EX NO:3
USER DEFINED PACKAGE WITH CLASSES

AIM:
To develop a java application to implement currency converter (Dollar to
INR, EURO to INR, Yen to INR and vice versa), distance converter (meter to KM,
miles to KM and vice versa) , time converter (hours to minutes, seconds and vice
versa) using packages.

ALGORITHM:

1. Define a package “packex” that contains CurrencyDEY, Distance and Time


Conversion Classes and necessary methods for conversion.
2. DEMOCDT Class imports CurrencyDEY, Distance and TimeCoversion
class from packex.
3. DEMOCDT declare necessary members, getCurrencyInput(),
conCurrencey(),getDistanceInput(),conDistance(), getTimeInput() and
conTime();
4. To invoke CurrenceyDEY,Distance and TimeConversion classes call
respective methods.
5. Create an object of DEMOCDT and call methods.

PROGRAM:
//Currency class

package packex;

public class CurrencyDEY

public double dolToRup(double dollar)


{return dollar*75;

public double rupToDol(double rupee)

{return rupee/75;

public double euroToRup(double euro)

{return euro*85;

public double rupToEuro(double rupee)

{return rupee/85;

public double yenToRup(double yen)

{return yen*0.6;

public double rupToYen(double rupee)

{return rupee/0.6;

//Distance class

package packex;

public class Distance

public double kmToMeter(double kilometer)


{return kilometer*1000;

public String meterToKM(int meter)

return meter/1000 + "KM "+ meter%1000+"Meter(s)";

public double milesToKM(double miles)

return miles*1.60;

public double kmToMiles(double kilometer)

return kilometer*0.62;

//TIME CLASS

package packex;

public class TimeConversion

public int hrsToMins(int h)

{return h*60;

public int hrsToSecs(int h)


{return hrsToMins(h)*60;

public int hrsMinsSecsToSecs(int h,int m,int s)

{return h*3600+m*60+s;

public String minsToHrs(int m)

return m/60 +"Hour(s)"+ m%60+"Minute(s)";

public String secsToHrs(int s)

{int h=s/3600;

int m=(s-(h*3600))/60;

int sec=(s-(h*3600)-(m*60))%60;

return h+"Hour(s)"+m+"Minute(s)"+sec+"Second(s)";

}
//Main Class

import packex.CurrencyDEY;

import packex.TimeConversion;

import packex.Distance;

import java.util.Scanner;

public class DEMOCDT {

double dollar,rupee,yen,euro,km,miles;
int hours,minutes,seconds,meter;

CurrencyDEY c=new CurrencyDEY();

Distance d=new Distance();

Scanner obj=new Scanner(System.in);

void getCurrencyInput(){

System.out.println("Enter the dollor:");

dollar=obj.nextDouble();

System.out.println("Enter the euro:");

euro=obj.nextDouble();

System.out.println("Enter the yen:");

yen=obj.nextDouble();

System.out.println("Enter the rupee:");

rupee=obj.nextDouble();

void conCurrency(){

System.out.println("Dollar to Rupee:"+Math.ceil(c.dolToRup(dollar)));

System.out.println("Euro to Rupee :"+Math.ceil(c.euroToRup(euro)));

System.out.println("Yen to Rupee :"+Math.ceil(c.yenToRup(yen)));

System.out.println("Rupee to Dollar:"+Math.ceil(c.rupToDol(rupee)));

System.out.println("Rupee to Euro :"+Math.ceil(c.rupToEuro(rupee)));

System.out.println("Rupee to Yen :"+Math.ceil(c.rupToYen(rupee)));

System.out.println("Yen to Rupee :"+Math.ceil(c.yenToRup(yen)));

}
void getDistanceInput()

{ System.out.println("Enter the kilometer:");

km=obj.nextDouble();

System.out.println("Enter the meter:");

meter=obj.nextInt();

System.out.println("Enter the miles:");

miles=obj.nextDouble();

void conDistance(){

System.out.println("Kilo-meter to meters:"+d.kmToMeter(km));

System.out.println("Meters to Kilo-meters:"+d.meterToKM(meter));

System.out.println("Miles to Kilometers:"+d.milesToKM(miles));

System.out.println("Kilometer to Miles:"+d.kmToMiles(km));

void getTimeInput()

{ System.out.println("Enter the hours");

hours=obj.nextInt();

System.out.println("Enter the minutes");

minutes=obj.nextInt();

System.out.println("Enter the seconds");

seconds=obj.nextInt();

TimeConversion t=new TimeConversion();


void conTime()

if(minutes<=60 && seconds <=60)

System.out.println("Hours, Minutes & Seconds to


Seconds:"+t.hrsMinsSecsToSecs(hours, minutes, seconds));

else{

System.out.println("Hours to Minutes:"+t.hrsToMins(hours));

System.out.println("Hours to Seconds:"+t.hrsToSecs(hours));

System.out.println("Minutes to Hours:"+t.minsToHrs(minutes));

System.out.println("Seconds to Hours:"+t.secsToHrs(seconds));

public static void main(String args[])

DEMOCDT obj=new DEMOCDT();

obj.getCurrencyInput();

obj.conCurrency();

obj.getDistanceInput();

obj.conDistance();

obj.getTimeInput();

obj.conTime();

}
OUTPUT:

RESULT:

Thus the java program to import user defined package classes and
operations were implemented and Verified successfully.
EX NO:4
STRING OPERATIONS USING ARRAYLIST

AIM:
1. To write a program to perform string operations using ArrayList. Write
functions for the following

a. Append - add at end

b. Insert – add at particular index

c. Search

d. List all string starts with given letter

ALGORITHM:

1. Create Class StringOperation using ArrayList as member.

2. To read the ArrayList elements using getDetails()

3. To perform various ArrayList- String Operations using the following


methods

a. getDetails()

b. appendAtEnd()

c. insert()

d. search()
PROGRAM:
import java.io.*;

import java.util.*;

public class StringOperationArrayList

{ ArrayList<String> al = new ArrayList<String>();

static Scanner obj=new Scanner(System.in);

void getDetails()

System.out.println("Enter the Number of players:");

int n=obj.nextInt();

//add players to the ArrayList

System.out.println("Enter the Player one by one:");

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

al.add(obj.next());

System.out.println(al);

void insert()

//insert Player at a specific index

System.out.println("What is Position of new player is to be inserted:");

int pos=obj.nextInt();

System.out.println("Enter the new player name");

String newPlayerName=obj.next();
al.add(pos,newPlayerName);

System.out.println(al);

void search()

//Search the player

System.out.println("Enter the player to be searched:");

String search=obj.next();

String info=al.contains(search)? "Yes, is found":"No, is not Found";

System.out.println("Does list contains Player? "+info );

void starts()

//List the player startswith

System.out.println("List the player names startswith:");

String s=obj.next();

System.out.println("List of Player startswith:"+s);

for(int i=0;i<al.size();i++)

if( al.get(i).startsWith(s)) System.out.println(al.get(i));

void appendAtEnd()

//Add Player at the End


System.out.println("Add the Player name at the end of List:");

al.add(obj.next());

System.out.println(al);

public static void main(String arg[]){

StringOperationArrayList soa = new StringOperationArrayList();

soa.getDetails();

int choice;

while(true){

System.out.println("Menu");

System.out.println("1.Append at the End");

System.out.println("2.Insert at the Particular Index");

System.out.println("3.Search");

System.out.println("4.List all the Players startwith given letter");

System.out.println("5.Exit");

System.out.println("Enter your choice:");

choice=obj.nextInt();

switch(choice){

case 1:

soa.appendAtEnd();

break;

case 2:

soa.insert();
break;

case 3:

soa.search();

break;

case 4:

soa.starts();

break;

case 5:

break;

default:

System.out.println("Enter the valid choice try it once again:");

if (choice==5)

break;

OUTPUt:
RESULT:
Thus the java program to perform various string operations using ArrayList
was implemented and verified successfully.
EX NO:5 EMPLOYEE SALARY CLACULATION UJSING
INHERITANCE CONCEPTS

AIM:
To develop a java application with Employee class with Emp_name,
Emp_id, Address, Mail_id, Mobile_no as members. Inherit the classes,
Programmer, Assistant Professor, Associate Professor and Professor from
employee class and Generate pay slips for the employees with their gross and net
salary with respected to given statements below.

Designation Basic pay %BP %BP %BP %BP as


(BP) As As as Staff club
DA HRA PF

Programmer 15000- 97 10 12 1
20000
Assistant 20001- 120 20 12 5
professor 30000
Associate 30001- 130 30 12 10
Professor 40000

Professor >40000 140 40 12 15

ALGORITHM:
1. Create a base class Employee, necessary members and methods to read / display
the employee information.
2. Create subclasses Programmer, AssistantProfessor, AssociateProfessor and
Professor derived from Employee class and overload and override methods
like(getEmployeeDetails(basicPay) and display(). in addition cal() method which is
used to salary calculation based on employee designation with respected to
problem statements.

PROGRAM:
import java.util.Scanner;

public class EmployeeSalaryCalc

public static void main(String args[])

Scanner obj=new Scanner(System.in);

Programmer p=new Programmer();

System.out.println("Enter the basic pay of Programmer");

p.getEmployeeDetails(obj.nextDouble());

p.cal();

AssistantProfessor ap=new AssistantProfessor();

System.out.println("Enter the basic pay of Assistant Professor");

ap.getEmployeeDetails(obj.nextDouble());

ap.cal();

AssociateProfessor asp=new AssociateProfessor();

System.out.println("Enter the basic pay of Associate Professor");

asp.getEmployeeDetails(obj.nextDouble());

asp.cal();
Professor prof=new Professor();

System.out.println("Enter the basic pay of Professor");

prof.getEmployeeDetails(obj.nextDouble()); prof.cal();

class Employee

String employeeName;

int employeeID;

String address;

String mailID;

long mobileNumber;

double da,hra,pf,sc,ns,gs;

Scanner obj=new Scanner(System.in);

void getEmployeeDetails()

System.out.println("Enter the Employee Name:");

employeeName=obj.nextLine();

System.out.println("Enter the Employee Address:");

address=obj.nextLine();

System.out.println("Enter the Employee Mail ID:");

mailID=obj.nextLine();

System.out.println("Enter the Employee ID:");


employeeID=obj.nextInt();

System.out.println("Enter the Employee Mobile Number:");

mobileNumber=obj.nextLong();

void display()

System.out.println("Employee Name :"+employeeName);

System.out.println("Employee ID :"+employeeID);

System.out.println("Employee Address :"+address);

System.out.println("Employee Mail ID :"+mailID);

System.out.println("Employee Mobile Number:"+mobileNumber);

class Programmer extends Employee

{double basicPay;

public double getBasicPay()

{return basicPay;

public void setBasicPay(double basicPay)

{this.basicPay = basicPay;

void getEmployeeDetails(double bp)

{
super.getEmployeeDetails();

setBasicPay(bp);

void cal()

{ da=getBasicPay()*97/100.0;

hra=getBasicPay()*10/100.0;

pf=getBasicPay()*12/100.0;

sc=getBasicPay()*1/100.0;

gs=getBasicPay()+da+hra+pf+sc;

ns=gs-pf-sc;

display();

void display()

{ super.display();

System.out.println("Employee Gross Salary:"+gs);

System.out.println("Employee Net Salary :"+ns);

class AssistantProfessor extends Employee

{double basicPay;

public double getBasicPay()

{return basicPay;

}
public void setBasicPay(double basicPay)

{this.basicPay = basicPay;

void getEmployeeDetails(double

bp){super.getEmployeeDetails();

setBasicPay(bp);

void cal()

{ da=getBasicPay()*110/100.0;

hra=getBasicPay()*20/100.0;

pf=getBasicPay()*12/100.0;

sc=getBasicPay()*5/100.0;

gs=getBasicPay()+da+hra+pf+sc;

ns=gs-pf-sc;

display();

void display()

{ super.display();

System.out.println("Employee Gross Salary:"+gs);

System.out.println("Employee Net Salary :"+ns);

class AssociateProfessor extends Employee


{double basicPay;

public double getBasicPay()

{return basicPay;

public void setBasicPay(double basicPay)

{this.basicPay = basicPay;

void getEmployeeDetails(double bp)

{super.getEmployeeDetails();

setBasicPay(bp);

void cal()

{ da=getBasicPay()*130/100.0;

hra=getBasicPay()*30/100.0;

pf=getBasicPay()*12/100.0;

sc=getBasicPay()*10/100.0;

gs=getBasicPay()+da+hra+pf+sc;

ns=gs-pf-sc;

display();

void display()

{ super.display();

System.out.println("Employee Gross Salary:"+gs);


System.out.println("Employee Net Salary :"+ns);

class Professor extends Employee

double basicPay;

public double getBasicPay()

{return basicPay;

public void setBasicPay(double basicPay)

{this.basicPay = basicPay;

void getEmployeeDetails(double bp)

{super.getEmployeeDetails();

setBasicPay(bp);

void cal(){

da=getBasicPay()*140/100.0;

hra=getBasicPay()*40/100.0;

pf=getBasicPay()*12/100.0;

sc=getBasicPay()*15/100.0;

gs=getBasicPay()+da+hra+pf+sc;

ns=gs-pf-sc;
display();

void display()

{ super.display();

System.out.println("Employee Gross Salary:"+gs);

System.out.println("Employee Net Salary :"+ns);

}
OUTPUT:
RESULT:
Thus the java program to calculate the employee salary using inheritance
concepts was implemented and verified successfully.
EX NO:6
JAVA INHERITANCE FOR ADT STACK

AIM:
To Design a Java interface for ADT Stack. Implement this interface using
array. Provide necessary exception handling in both the implementation.

ALGORITHM:
1. Declare a stack interface and necessary methods declaration.
2. Define the user defined exception classes to handle the stack overflow and
stack underflow.
3. Create a MainClass to implements all the interface methods and display
method.

PROGRAM:
import java.util.Scanner;

interface Stack

void push(int data);

void pop();

boolean isEmpty();

boolean isFull();

class StackIsOverflow extends Exception

{public StackIsOverflow(String s)
{

super(s);

class StackIsUnderflow extends Exception

{public StackIsUnderflow(String s)

super(s);

public class StackConcepts implements

Stack{int top=-1;

int elements[]=new int[5];

public Boolean isEmpty()

{if (top==-1)

return true;

else

return false;

public boolean isFull()

{ if(top==elements.length-1)

return true;

else
return false;

public void push(int data)

{try{

if(!isFull())

elements[++top]=data;

else

throw new StackIsOverflow(" Stack overflow ");

catch(StackIsOverflow e)

{ System.out.println("Excepion:"+e);

public void pop()

{try

if(!isEmpty())

System.out.println("The popped element:"+elements[top--]);

else

throw new StackIsUnderflow("Stack is UnderFlow");

catch(StackIsUnderflow e)

{ System.out.println("UserDefined Exception:"+e);
}

void display()

System.out.println("Stack Elements are...");

for (int i=0;i<=top;i++)

System.out.println(elements[i]);

public static void main(String args[])

StackConcepts c=new StackConcepts();

Scanner obj=new Scanner(System.in);

int choice;

while(true)

{ System.out.println("Menu");

System.out.println("1.Push");

System.out.println("2.Pop");

System.out.println("3.Display");

System.out.println("4.Exit");

System.out.println("Enter your choice:");

choice=obj.nextInt();

switch(choice)

{
case 1:

System.out.println("Enter the data to be pushed");

c.push(obj.nextInt());

break;

case 2:

c.pop();

break;

case 3:

c.display();

break;

case 4:

break;

default:

System.out.println("Enter the valid choice try it once again:");

if (choice==4)

break;

}
OUTPUT:
RESULT:
Thus the program to design a Java interface for ADT Stack. Implement this
interface using array. Provide necessary exception handling in both the
implementations were implemented and verified successfully.
EX NO:7
JAVA INHERITANCE FOR ADT QUEUE

AIM:
To design a java interface for ADT Queue. Implement this interface using
array. Provide necessary exception handling in both the implementations.

ALGORITHM:

1. Declare a queue interface and necessary methods declaration.


2. Define the user defined exception classes to handle the queue overflow and
queue underflow.
3. Create a MainClass to implements all the interface methods and display
method.

PROGRAM:

import java.util.Scanner;

interface Queue1

void dequeue();

boolean isQueueEmpty();

boolean isQueueFull();

void enqueue(int item);

class QueueIsFull extends Exception


{

QueueIsFull(String s)

super(s);

class QueueIsEmpty extends Exception

QueueIsEmpty(String s)

super(s);

public class QueueImpl implements Queue1

private int capacity;

int queueArr[];

int front =0;

int rear = -1;

public QueueImpl(int queueSize)

this.capacity =queueSize;

queueArr = new int[this.capacity];


}

public boolean

isQueueFull()

boolean status = false;

if (rear > capacity- 2)

status = true;

return status;

public boolean isQueueEmpty()

boolean status = false;

if (rear <0 || front >rear)

status = true;

return status;

public void enqueue(int item)

try
{

if (isQueueFull())

throw new QueueIsFull("Overflow ! Unable to add element: "+item);

else

rear++; queueArr[rear] = item;

System.out.println("Element " + item+ " is pushed to Queue !");

catch(QueueIsFull e)

System.out.println(e.getMessage());

public void dequeue()

try

if (isQueueEmpty())

throw new QueueIsEmpty("Underflow ! Unable to remove element from Queue");


}

else

System.out.println("Pop operation done ! removed: "+queueArr[front++]);

catch(QueueIsEmpty e)

System.out.println(e);

void display()

if(!isQueueEmpty())

for (int i=front; rear<capacity && i<=rear;i++)

System.out.println(queueArr[i]);

else

System.out.println("Queue is Empty or Front pointer cross the Rear Pointer");

}
public static void main(String args[])

System.out.println("Enter the Queue capacity");

Scanner obj=new Scanner(System.in);

QueueImpl queue = new QueueImpl(obj.nextInt());

int choice;

while(true)

System.out.println("Menu");

System.out.println("1.Enqueue");

System.out.println("2.Dequeue");

System.out.println("3.Display");

System.out.println("4.Exit");

System.out.println("Enter your choice:");

choice=obj.nextInt();

switch(choice)

case 1:

System.out.println("Enter the data to be enqueued:");

queue.enqueue(obj.nextInt());

break;

case 2:

queue.dequeue();
break;

case 3:

System.out.println("Queue Elements are...");

queue.display();

break;

case 4: break;

default: System.out.println("Enter the valid choice try it once again:");

if (choice==4)break;

OUTPUT:
RESULT:
Thus the java program to design a java interface for ADT queue was
implemented and verified successfully.
EX NO:8
ABSTRACT CLASS

AIM:
To write a Java Program to create an abstract class named Shape that contains
two integers and an empty method named print Area(). Provide three classes
named Rectangle, Triangle and Circle such that each one of the classes extends the
class Shape. Each one of the classes contains only the method print Area () that
prints the area of the given shape.

ALGORITHM:
1. Create a class ShapeDemo with necessary members and abstract method
printArea()

2. Create sub classes Rectangle and Triangle derived from ShapeDemo and
override the printArea().

PROGRAM:
import java.util.Scanner;

public class AbstractDemo

public static void main(String args[])

Scanner obj=new Scanner(System.in);


System.out.println("Enter the length and breadth of Rectangle class:");

Rectangle r=new Rectangle(obj.nextInt(), obj.nextInt());

r.printArea();

System.out.println("Enter the base and height of Triangle class:");

Triangle t=new Triangle(obj.nextInt(), obj.nextInt());

t.printArea();

abstract class ShapeDemo

int length, breadth;

ShapeDemo(int l, int b)

length=l;

breadth=b;

abstract void printArea();

class Rectangle extends ShapeDemo

Rectangle(int l, int b)

super(l,b);
}

void printArea()

System.out.println("The Area of Rectangle is:"+length*breadth);

class Triangle extends ShapeDemo

Triangle(int l, int b)

super(l,b);

@Override

void printArea()

System.out.println("The Area of Triangle is:"+0.5*length*breadth);

}
OUTPUT:

RESULT:
Thus the java program to demonstrate Abstract Class was implemented and
verified successfully.
EX NO:9
DISPLAY FILE INFORMATION

AIM:
To write a Java program that reads a file name from the user, displays
information about whether the file exists, whether the file is readable, or writable,
the type of file and the length of the file in bytes.

ALGORITHM:

1. Create a class FileInfo with necessary members

2. Read the file name using getFile() method.

3. Display the details of file using showDetails() method.

PROGRAM:
import java.util.Scanner;

import java.io.File;

public class FileInfo

String name;

File f1;

void getFile()

{
Scanner input=new Scanner(System.in);

System.out.println("Enter the file name:");

name=input.nextLine();

f1=new File(name);

void showDetails(){

System.out.println("File Name:"+f1.getName());

System.out.println("Path:"+f1.getPath());

System.out.println("Abs Path:"+f1.getAbsolutePath());

System.out.println("This file is:"+(f1.exists()?"Exists":"Does not exists"));

System.out.println("Is Readable:"+f1.canRead());

System.out.println("IS Writable:"+f1.canWrite());

System.out.println("Type of File:"+name.substring(name.lastIndexOf(".") + 1));

System.out.println("File Size:"+f1.length()+"bytes");

public static void main(String args[])

FileInfo fi=new FileInfo();

fi.getFile();

fi.showDetails();

}
OUTPUT:

RESULT:
Thus the java program to display the file information was implemented and
verified successfully.
EX NO:10
MULTITHREADING

AIM:
To write a java program that implements a multi-threaded application that has
three threads. First thread generates a random integer every 1 second and if the
value is even, second thread computes the square of the number and prints. If the
value is odd, the third thread will print the value of cube of the number.

ALORITHM:
1. Create Master thread class as Thread1 and two slave threads

2. Master Thread generate random number every 1 seconds based on the value is
even it invoke Second Thread - prints the square of the number otherwise Third
Thread – prints the cube of the number.

PROGRAM:

import java.util.Scanner;

import java.util.Random;

public class MultiThreadDemo

public static void main(String args[])

Thread t1=new Thread(new Thread1());


t1.start();

class Thread1 implements Runnable

Scanner obj=new Scanner(System.in);

Random r=new Random();

public void run()

try

System.out.println("How Many Random number to be generated:");

int n=obj.nextInt();

for(int i=1;i<=n;i++)

int no=r.nextInt(100);

if(no%2==0)

Thread2 t2=new Thread2(no);

t2.start();

else

{
Thread3 t3=new Thread3(no);

t3.start();

Thread.sleep(1000);

catch(Exception e)

System.out.println(e);

class Thread2 extends Thread

int n1;

Thread2(int n)

n1=n;

public void run()

System.out.println("Print the Square of numbers is:"+Math.pow(n1,2));

}
}

class Thread3 extends Thread

int n1;

Thread3(int n)

n1=n;

public void run()

System.out.println("Print the Cube root of numbers is:"+Math.pow(n1,3));

OUTPUT:
RESULT:
Thus the java program to demonstrate the multithreading concept was
implemented and verified successfully.
EX NO:11 FIND MAX ELEMENT USING GENERIC
FUNCTION
AIM:
To write a java program to find max element using generic function.

ALGORITHM:

1. Create a class as GenericDemo and define a generic method as max(collection)

2. Create a GenericDemo class object and invoke generic method max(collection)


with respected to collection it returns the max element.

PROGRAM:
import java.util.Scanner;

public class GenericDemo {

public static <E extends Comparable<E> > E max(E[] list)

E max = list[0];

for(int i = 1; i < list.length; i++)

if(list[i].compareTo(max) > 0 )

max = list[i];

return max;
}

public static void main(String args[])

Integer []a={1,5,3,15};

Double []b={.5,67.8,3.8,0.01};

GenericDemo g=new GenericDemo();

System.out.println("Find the max number in Integer list is:"+g.max(a));

System.out.println("Find the max number in Double list is:"+g.max(b));

OUTPUT:
RESULT:
Thus the java program to find the max elements using Generic Function was
implemented and verified successfully.

EX NO:12
CALCULATION USING EVENT HANDLING

AIM:
To write a java program to perform various calculator operations using event
handling mechanism.
ALGORITHM:
1. Create a Calculator Frame class with necessary panel, buttons and textfield

2. Arrange the panel, button and textfield into Calcultor Frame using
BorderLayout/ Grid Layout .

3. Add action listener to all button objects.

4. Based on the button click that performs required operation.

PROGRAM:
import java.util.Scanner;

import java.awt.BorderLayout;

import java.awt.GridLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.Reader;

import javax.script.ScriptEngine;

import javax.script.ScriptEngineFactory;

import javax.script.ScriptEngineManager;

import javax.script.ScriptException;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JTextField;
public class Cal extends javax.swing.JFrame implements ActionListener

JButton b[]=new JButton[21];

JTextField io=new JTextField("");

public Cal()

setLayout(new BorderLayout());

add(io,BorderLayout.NORTH);

for(int i=0;i<10;i++)

b[i]=new JButton(""+i);

b[10]=new JButton("+");

b[11]=new JButton("-");

b[12]=new JButton("*");

b[13]=new JButton("/");

b[14]=new JButton("%");

b[15]=new JButton("(");

b[16]=new JButton(")");

b[17]=new JButton(".");

b[18]=new JButton("back");

b[19]=new JButton("clr");

b[20]=new JButton("=");

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

for(int i=0;i<20;i++)
p.add(b[i]);

add(p,BorderLayout.CENTER);

add(b[20],BorderLayout.SOUTH);

setSize(600,600);

for(int i=0;i<21;i++)

b[i].addActionListener(this);

public static void main(String args[])

java.awt.EventQueue.invokeLater(new Runnable()

public void run()

Cal c=new Cal();

c.setVisible(true);

c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

c.show();

});

@Override

public void actionPerformed(ActionEvent e)

{
Object src= e.getSource();

try{

if(src==b[0]||src==b[1]||src==b[2]||src==b[3]||src==b[4]||src==b[5]||src==b[6]||src=
=b[7]||src==b[8]||src==b[9]||src==b[10]||src==b[11]||src==b[12]||src==b[13]||src==
b[14]||src==b[15]||src==b[16]||src==b[17])

io.setText(io.getText()+e.getActionCommand());

else if(src==b[18])

io.setText(io.getText().substring(0, io.getText().length()-1));

else if(src==b[19])

io.setText("");

else if(src==b[20])

ScriptEngine runtime = new


ScriptEngineManager().getEngineByName("javascript");

if(io.getText().contains(".") || io.getText().contains("/"))

Double r=(Double)runtime.eval(io.getText().toString());

io.setText(String.valueOf(r));

else

Integer r=(Integer)runtime.eval(io.getText().toString());

io.setText(String.valueOf(r));

}
}

catch(Exception er)

io.setText(er.toString());

OUTPUT:
RESULT:
Thus the java program to find the max elements to using Generic Functions
was implemented and verified successfully.

EX NO:13
MARKSHEET CALCULATION

Aim:
To write a java file to get 5 subjects marks as input and calculate total and
percentage and write it to a file.

ALGORITHM:
1. Declare necessary variables

2. Use JOptionPane to create dialog boxes in GUI and get input.

3. Calculate Total marks and percentage.

4. Output the calculate details in a message dialog box.

5. Append the details to a existing file or create a new file.

Program:
import javax.swing.JOptionPane;

import java.io.*;

class Marksheet{

public static void main(String[]args) throws Exception

String filename = "StudentDetails.txt";

String info = "";

BufferedWriter bw = new BufferedWriter(new FileWriter(filename,true));

PrintWriter out = new PrintWriter(bw);

String firstname = JOptionPane.showInputDialog("Enter Your First Name :");

String regno = JOptionPane.showInputDialog("Enter Your Register Number: ");

String a = JOptionPane.showInputDialog("Enter OOPS Marks");


int OOPS = Integer.parseInt(a);

String b = JOptionPane.showInputDialog("Enter DPSD Marks");

int DPSD = Integer.parseInt(b);

String c = JOptionPane.showInputDialog("Enter DS Marks");

int DS = Integer.parseInt(c);

String d = JOptionPane.showInputDialog("Enter CE Marks");

int CE = Integer.parseInt(d);

String e = JOptionPane.showInputDialog("Enter DM Marks");

int DM = Integer.parseInt(e);

int total = 500;

int obtained = OOPS + DPSD + CE + DS + DM;

int percentage = obtained * 100 / total;

if(OOPS >39 && DPSD >39 && DS >39 && CE >39 && DM >39 &&
(percentage <100 && percentage >=80)) {

info = " Name :"+firstname +"\n Register Number :"+ regno +"\n Total Marks :" +
total +"\n Obtained Marks : " + obtained +"\n Percentage : " + percentage +"%" +

"\n You Are Pass" + "\n You Got A Grade\n\n";

JOptionPane.showMessageDialog(null,info);

if(OOPS >39 && DPSD >39 && DS >39 && CE >39 && DM >39 &&
(percentage <80 && percentage >=70)) {

info = " Name :"+firstname +"\n Register Number :"+ regno +"\n Total Marks :" +
total +"\n Obtained Marks : " + obtained +"\n Percentage : " + percentage +"%" +
"\n You Are Pass" + "\n You Got A Grade\n\n" ;

JOptionPane.showMessageDialog(null, info);

if(OOPS >39 && DPSD >39 && DS >39 && CE >39 && DM >39 &&
(percentage <70 && percentage >=60))

info = " Name :"+firstname +"\n Register Number :"+ regno +"\n Total Marks :" +
total +"\n Obtained Marks : " + obtained +"\n Percentage : " + percentage +"%" +

"\n You Are Pass" + "\n You Got B Grade\n\n";

JOptionPane.showMessageDialog(null,info );

if(OOPS >39 && DPSD >39 && DS >39 && CE >39 && DM >39 &&
(percentage <60 && percentage >=50))

info = " Name :"+firstname +"\n Register Number :"+ regno +"\n Total Marks :" +
total +"\n Obtained Marks : " + obtained +"\n Percentage : " + percentage +"%" +

"\n You Are Pass" + "\n You Got C Grade\n\n";

JOptionPane.showMessageDialog(null,info );

if(OOPS >39 && DPSD >39 && DS >39 && CE >39 && DM >39 &&
(percentage <50 && percentage >=40))

info = " Name :"+firstname +"\n Register Number :"+ regno +"\n Total Marks :" +
total +"\n Obtained Marks : " + obtained +"\n Percentage : " + percentage +"%"
+"\n You Passed" + "\n You Got D Grade\n\n";
JOptionPane.showMessageDialog(null, info);

if(OOPS <40 || DPSD <40 || DS <40 || CE <40 || DM <40 || percentage < 40) {

info = " Name :"+firstname +"\n Register Number :"+ regno +"\n Total Marks :" +
total +"\n Obtained Marks : " + obtained +"\n Percentage : " + percentage +"%" +

"\n You Failed\n\n";

JOptionPane.showMessageDialog(null,info );

out.write(info);

out.close();

OUTPUT:
RESULT:
Thus the java program to get input from GUI and calculate marks percentage
and show the output in a message box and write the details to a file.

You might also like