Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

JAVA

Core Java
Slip 1_1: Create abstract class shape. Drive three classes sphere. Cone and cylinder from it.
Calculate Area and volume of all ( use method overriding)

import java.io.*;
abstract class Shape
{
double r,h;
Shape(double r, double h)
{
this.r = r;
this.h = h;
}
abstract double calcArea();
abstract double calcVolume();
}
class Sphere extends Shape
{
Sphere(double r)
{
super(r,0);
}
double calcArea()
{
return 4*3.14*r*r;
}
double calcVolume()
{
return 4*3.14*Math.pow(r,3)/3;
}
}
class Cone extends Shape
{
Cone(double r, double h)
{
super(r,h);
}
double calcArea()
{
return 3.14*r*(r+Math.sqrt(r*r+h*h));
}
double calcVolume()
{

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 1


return 3.14*r*r*h/3;
}
}
class Cylinder extends Shape
{
Cylinder(double r, double h)
{
super(r,h);
}
double calcArea()
{
return 2*3.14*r*(h+r);
}
double calcVolume()
{
return 3.14*r*r*h;
}
}
class Slip1_1
{
public static void main(String args[])throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Shape s=null;
double r=0,h=0;
int ch;
do
{
System.out.print("1.Sphere"+"\n2.Cone"+"\n3.Cylinder"+
"\n4.Exit "+"\nEnter your choice : ");
ch = Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
System.out.print("Enter radius of sphere:");
r = Double.parseDouble(br.readLine());
s = new Sphere(r);
break;
case 2:
System.out.print("Enter radius of cone:");
r = Double.parseDouble(br.readLine());
System.out.print("Enter height of
cone:");
h = Double.parseDouble(br.readLine());
s = new Cone(r,h);
break;

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 2


case 3:
System.out.print("Enter radius of cylinder:");
r = Double.parseDouble(br.readLine());
System.out.print("Enter height of
cylinder:");
h = Double.parseDouble(br.readLine());
s = new Cylinder(r,h);
break;
case 4:
System.exit(0);
}
System.out.println("Area = "+s.calcArea()+
"\nVolume = "+s.calcVolume());
}while(ch!=4);
}
}

Slip 2_1: Write a menu driven program to perform the following operations on a set of integers
as shown in the following fig. the load operation should generate 10 random integer(2 digit) and
display the number on screen. The save operation should save the number to a file”number.txt”.
The short menu provides various operations and the result is displayed on the screen.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;

class Slip2_1 extends JFrame implements ActionListener


{
JMenu m1,m2;
JMenuBar mb;
JMenuItem m[];

JLabel l;
JTextField t;
JPanel p;

StringBuffer ss=new StringBuffer();

int n;
int arr[]=new int [20];
Slip2_1()
{
p=new JPanel();
mb=new JMenuBar();
m1=new JMenu("Operation");

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 3


m2=new JMenu("Sort");

l=new JLabel("Numbers");
t=new JTextField(20);

String str[]={"Load","Save","Exit","Ascending","Descending"};
m=new JMenuItem[str.length];
for(int i=0;i<str.length;i++)
{
m[i]=new JMenuItem(str[i]);
m[i].addActionListener(this);
}
p.add(l);
p.add(t);

mb.add(m1);
mb.add(m2);

m1.add(m[0]);
m1.add(m[1]);
m1.addSeparator();
m1.add(m[2]);

m2.add(m[3]);
m2.add(m[4]);

setLayout(new BorderLayout());
add(mb,BorderLayout.NORTH);
add(p,BorderLayout.CENTER);
setSize(300,150);
setVisible(true);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}
void sortasc()
{
for(int i=0;i<n;i++)
for(int j=0;j<n-1;j++)
{
if(arr[j]>arr[j+1])
{
int t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
}

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 4


}
StringBuffer s5=new StringBuffer();
for(int i=0;i<n;i++)
{
s5.append(new Integer(arr[i]).toString());
s5.append(" ");
}
t.setText(new String(s5));
}

void sortdesc()
{
for(int i=0;i<n;i++)
for(int j=0;j<n-1;j++)
{
if(arr[j]<arr[j+1])
{
int t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
}
}
StringBuffer s5=new StringBuffer();
for(int i=0;i<n;i++)
{
s5.append(new Integer(arr[i]).toString());
s5.append(" ");
}
t.setText(new String(s5));
}

public void actionPerformed(ActionEvent e)


{
String s=e.getActionCommand(); //return the name of menu
if(s.equals("Exit"))
System.exit(0);
else if(s.equals("Load"))
{
if(arr[0]==0)
{
int i=0;
try
{
BufferedReader r=new BufferedReader(new
FileReader("new.txt"));
String s1=r.readLine();

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 5


while(s1!=null)
{
ss.append(s1);
ss.append(" ");
arr[i]=Integer.parseInt(s1);
n=++i;
s1=r.readLine();
}
}
catch(Exception eee)
{ }
t.setText(new String(ss));
}
}
else if(s.equals("Save"))
{
char ch;
String sss = t.getText();
try
{
FileOutputStream br1 = new FileOutputStream("new.txt");
for(int i=0;i<sss.length();i++)
{
ch=sss.charAt(i);
if(ch == ' ')
br1.write('\n');
else
br1.write(ch);
}
br1.close();}
catch(Exception eee)
{}
}
else if(s.equals("Ascending"))
{
sortasc();
}
else if(s.equals("Descending"))
{
sortdesc();
}
}
public static void main(String arg[])
{
Slip2_1 c =new Slip2_1();
}

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 6


}

Slip 3_1: Define a class MyDate( Day,Month,year) with method to accept and display a MyDate
object. Accept date as dd, mm, yyyy. Throw user defined exception “InvalidDateExeption” if the
date is invalid.
a. 12 15 2015
b. 31 6 1990
c. 29 2 2015

import java .io.*;


class InvalidDateException extends Exception
{
}
class MyDate
{
int day,mon,yr;

void accept(int d,int m,int y)


{
day=d;
mon=m;
yr=y;
}

void display()
{
System.out.println("Date is valid : "+day+"/"+mon+"/"+yr);
}
}
class Slip3_1
{
public static void main(String arg[]) throws Exception
{
System.out.println("Enter Date : dd mm yyyy ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int day=Integer.parseInt(br.readLine());
int mon=Integer.parseInt(br.readLine());
int yr=Integer.parseInt(br.readLine());

int flag=0;
try
{

if(mon<=0 || mon>12)

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 7


throw new InvalidDateException();
else
{
if(mon==1 || mon==3 || mon==5 || mon==7 ||
mon==8 || mon==10 || mon == 12)
{
if(day>=1 && day <=31)
flag=1;
else
throw new InvalidDateException();
}
else if (mon==2)
{
if(yr%4==0)
{
if(day>=1 && day<=29)
flag=1;
else throw new
InvalidDateException();
}
else
{
if(day>=1 && day<=28)
flag=1;
else throw new
InvalidDateException();
}
}
else
{
if(mon==4 || mon == 6 || mon== 9 ||
mon==11)
{
if(day>=1 && day <=30)
flag=1;
else throw new
InvalidDateException();
}
}
}
if(flag== 1)
{
MyDate dt = new MyDate();
dt.accept(day,mon,yr);
dt.display();
}

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 8


}
catch (InvalidDateException mm)
{
System.out.println("Invalid Date");
}

}
}

Slip 4_1: Write a menu driven program to perform the following operations on a set of integers
as shown in the following figure. A load operation should generate 10 random integers (2 digit)
and display the no on screen. The save operation should save the no to a file “number.txt”. The
short menu provides various operations and the result is displayed on the screen.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;

class Slip4_1 extends JFrame implements ActionListener


{
JMenu m1,m2;
JMenuBar mb;
JMenuItem m[];

JLabel l;
JTextField t;
JPanel p;

StringBuffer ss=new StringBuffer();

int n;
int arr[]=new int [20];
Slip4_1()
{
p=new JPanel();
mb=new JMenuBar();
m1=new JMenu("Operation");
m2=new JMenu("Compute");

l=new JLabel("Numbers");
t=new JTextField(20);

String str[]={"Load","Save","Exit","Sum","Average"};
m=new JMenuItem[str.length];
for(int i=0;i<str.length;i++)

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 9


{
m[i]=new JMenuItem(str[i]);
m[i].addActionListener(this);
}
p.add(l);
p.add(t);

mb.add(m1);
mb.add(m2);

m1.add(m[0]);
m1.add(m[1]);
m1.addSeparator();
m1.add(m[2]);

m2.add(m[3]);
m2.add(m[4]);

setLayout(new BorderLayout());
add(mb,BorderLayout.NORTH);
add(p,BorderLayout.CENTER);
setSize(300,150);
setVisible(true);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}
/*void sortasc()
{
for(int i=0;i<n;i++)
for(int j=0;j<n-1;j++)
{
if(arr[j]>arr[j+1])
{
int t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
}
}
StringBuffer s5=new StringBuffer();
for(int i=0;i<n;i++)
{
s5.append(new Integer(arr[i]).toString());
s5.append(" ");
}
t.setText(new String(s5));

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 10


}

void sortdesc()
{
for(int i=0;i<n;i++)
for(int j=0;j<n-1;j++)
{
if(arr[j]<arr[j+1])
{
int t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
}
}
StringBuffer s5=new StringBuffer();
for(int i=0;i<n;i++)
{
s5.append(new Integer(arr[i]).toString());
s5.append(" ");
}
t.setText(new String(s5));
}*/
public int givesum()
{
int sum=0;
for(int i=0;i<n;i++)
{
sum=sum+arr[i];
}
return sum;
}

public double giveavg()


{
int sum=0;
for(int i=0;i<n;i++)
{
sum=sum+arr[i];
}
return sum/n;
}

public void actionPerformed(ActionEvent e)


{
String s=e.getActionCommand(); //return the name of menu
if(s.equals("Exit"))

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 11


System.exit(0);
else if(s.equals("Load"))
{
if(arr[0]==0)
{
int i=0;
try
{
BufferedReader r=new BufferedReader(new
FileReader("new.txt"));
String s1=r.readLine();
while(s1!=null)
{
ss.append(s1);
ss.append(" ");
arr[i]=Integer.parseInt(s1);
n=++i;
s1=r.readLine();
}
}
catch(Exception eee)
{ }
t.setText(new String(ss));
}
}
else if(s.equals("Save"))
{
char ch;
String sss = t.getText();
try
{
FileOutputStream br1 = new FileOutputStream("new.txt");
for(int i=0;i<sss.length();i++)
{
ch=sss.charAt(i);
if(ch == ' ')
br1.write('\n');
else
br1.write(ch);
}
br1.close();}
catch(Exception eee)
{}
}
else if(s.equals("Sum"))
{

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 12


t.setText(new Integer(givesum()).toString());
}
else if(s.equals("Average"))
{
t.setText(new Double(giveavg()).toString());
}
}

public static void main(String arg[])

Slip4_1 ob = new Slip4_1();


}
}

Slip 5_1: Define a class saving account (acno, name, balance) .define appropriate and operation
withdraw(), deposit(), and viewbalance(). The minimum balance must be 500. Create an object
and perform operation. Raise user defined “InsufficientFundException” when balance is not
sufficient for withdraw operation.

import java.io.*;

class InsufficientFundsException extends Exception


{
}

class SavingAccount
{
int ano;
String name;
float bal;
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
SavingAccount(int a,String nm,float b)
{
ano=a;
name=nm;
bal=b;
}

void withdraw() throws Exception


{
System.out.println("Enter amount to be withdraw ");
float amt=Integer.parseInt(br.readLine());
try
{

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 13


if(amt>bal || bal<500 )
throw new InsufficientFundsException();
else
{
bal=bal-amt;
System.out.println("Withdarawl amt successfully ....");
}
}
catch(InsufficientFundsException ob)
{
System.out.println("Insufficient Balance");
}
}
void deposit() throws Exception
{
System.out.println("Enter amount to be withdraw ");
float amt=Integer.parseInt(br.readLine());
bal=bal+amt;
System.out.println("Deposit amt successfully ....");
}
void viewBalance()
{
System.out.println("Balance "+bal);
}
}

class Slip5_1
{
public static void main(String ar[]) throws Exception
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Account no:");
int a =Integer.parseInt(br.readLine());
System.out.println("Enter Name:");
String nm=br.readLine();
System.out.println("Enter Balance:");
float b =Float.parseFloat(br.readLine());
SavingAccount sa = new SavingAccount(a,nm,b);
do
{
System.out.println(" \n 1.Deposit \n 2.Withdraw \n 3.Check Balance \n
4.Exit ");
System.out.println("Enter your choice :");

int ch=Integer.parseInt(br.readLine());
switch(ch)

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 14


{
case 1 : sa.deposit();
break;
case 2 sa.withdraw();
break;
case 3 : sa.viewBalance();
break;
case 0 : System.exit(1);

}
}while(true);
}
}

Slip 6_1: Write a program to accept a decimal number in the Textfield. After clicking calculate
button, program should display the binary, octal, hexadecimal equivalent for the entered decimal
number.

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

public class Slip6_1 extends Frame implements ActionListener


{
Label labelD, labelB, labelO,labelH;
TextField txtNo, txtB, txtO,txtH;
Button cal ,clear;
Panel p;

public Slip6_1()
{
labelD= new Label("Decimal No:");
labelB = new Label("Binary No : ");
labelO = new Label("Octal No :");
labelH = new Label("Hexadecimal No :");

txtNo = new TextField(10);


txtB = new TextField(10);
txtO = new TextField(10);
txtH = new TextField(10);

cal = new Button("Calculate");


clear = new Button("Clear");

p = new Panel();
p.setLayout(new GrideLayout(5,2));
p.add(labelD);

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 15


p.add(txtNo);
p.add(labelB);
p.add(txtB);
p.add(labelO);
p.add(txtO);
p.add(labelH);
p.add(txtH);
p.add(cal);
p.add(clear);

setLayout(new FlowLayout());
add(p);
setTitle("Binary Calculator");
setSize(300,300);
setVisible(true);

cal.addActionListener(this);
clear.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
Button btn = (Button)ae.getSource();
if(btn == cal)
{
int n = Integer.parseInt(txtNo.getText());
txtB.setText(Integer.toBinaryString(n));
txtO.setText(Integer.toOctalString(n));
txtH.setText(Integer.toHexString(n));
}

if(btn == clear)
{
txtNo.setText("");
txtB.setText("");
txtO.setText("");
txtH.setText("");
}
}

public static void main(String args[])


{
new Slip6_1();
}
}

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 16


Slip 7_1: Create a package series having two different classes to print the following series.
a. Prime number
b. Squares of numbers
Write a program to generate ‘n’ terms of the above series.

Prime.java

package Series;
public class Prime
{
public void prime_range(int no)
{
for(int i=1;i<=no;i++)
{
int flag=0;
for(int j=2;j<=i/2;j++)
{
if(i%j==0)
{ flag=1;
break;
}
}
if(flag==0)
System.out.println(i+" ");
}
}

Squar.java

package Series;
public class Square
{
public void square_range(int no)
{
for(int i=1;i<=no;i++)
{
System.out.println(i+" = "+(i*i));
}
}
}
import Series.Prime;
import Series.Square;

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 17


import java.io.*;

class Slip7_1
{
public static void main(String a[]) throws IOException
{
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter no :");
int no = Integer.parseInt(br.readLine());
Prime p = new Prime();
System.out.println("Prime no upto given nos are : ");
p.prime_range(no);

Square s = new Square();


System.out.println("Sqaure upto given nos are : ");
s.square_range(no);

}
}

Slip 8_1: Write a program to create the following GUI and apply the change to text in the
TextField.

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

class Font1 extends JFrame implements ItemListener


{
JLabel font, style, size;
JComboBox fontcb, sizecb;
JCheckBox bold, italic;
JTextField t;
JPanel p1, p2;
Font1()
{ p1 = new JPanel();
p2 = new JPanel();
font = new JLabel("Font");
style = new JLabel("Style");

fontcb = new JComboBox();


fontcb.addItem("Arial");
fontcb.addItem("Sans");

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 18


fontcb.addItem("Monospace");

bold = new JCheckBox("Bold");


size = new JLabel("Size");
italic = new JCheckBox("Italic");

sizecb = new JComboBox();


sizecb.addItem("10");
sizecb.addItem("12");
sizecb.addItem("16");
t = new JTextField(10);

p1.setLayout(new GridLayout(4,2));
p1.add(font);
p1.add(style);
p1.add(fontcb);
p1.add(bold);
p1.add(size);
p1.add(italic);
p1.add(sizecb);

p2.setLayout(new FlowLayout());
p2.add(t);

bold.addItemListener(this);
italic.addItemListener(this);
fontcb.addItemListener(this);
sizecb.addItemListener(this);

setLayout(new BorderLayout());
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.CENTER);

setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void itemStateChanged(ItemEvent ie)
{
String f = (String)fontcb.getSelectedItem();
System.out.println("font = "+f);
t.setFont(new Font(f,Font.BOLD,10));
String no =(String)sizecb.getSelectedItem();
int num=Integer.parseInt(no);

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 19


if(bold.isSelected())
{
t.setFont(new Font(f,Font.BOLD,num));
}
if(italic.isSelected())
{
t.setFont(new Font(f,Font.ITALIC,num));
}

}
public static void main(String args[])
{
Font1 f1 = new Font1();
}
}

Slip9_1 & Slip19_1: Create an applet which display a message in the center of the screen. The
message indicates the events taking place on the applet window. Handle events like mouse click,
mouse moves, mouse dragged, mouse pressed. The message should update each time an event
occurs. The message should give details of the event such as which mouse button was pressed (
hint: use repaint(), mouselistener, MouseMotionListener)

import java.awt.*;
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
/*
<applet code="MouseApplet.java" width=1500 height=800>
</applet>
*/
public class MouseApplet extends Applet
{
JPanel p;
JTextField t;
String msg;
public void init()
{
t=new JTextField(20);
add(t);
addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
msg="Mouse Clicked : X = "+me.getX() + " Y = "+me.getY();

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 20


t.setText(msg);
}
});
addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseMoved(MouseEvent me)
{
msg="Mouse Moved : X = "+me.getX() +" Y = "+me.getY();
t.setText(msg);
}
});
}
}

Slip 10_1: Write a program to implement simple arithmetic calculator. Perform appropriate
validations.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Slip10_1 extends JFrame implements ActionListener


{
String msg=" ";
int v1,v2,result;
JTextField t;
JButton b[]=new JButton[10];
JButton add,sub,mul,div,clear,equals;
char choice;
JPanel p,p1;
Slip10_1()
{
setLayout(new BorderLayout());
p =new JPanel();
t=new JTextField(20);
p.add(t);

p1=new JPanel();
p1.setLayout(new GridLayout(5,4));
for(int i=0;i<10;i++)
{
b[i]=new JButton(""+i);
}
equals=new JButton("=");
add=new JButton("+");
sub=new JButton("-");

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 21


mul=new JButton("*");
div=new JButton("/");
clear=new JButton("C");

for(int i=0;i<10;i++)
{
p1.add(b[i]);
}

p1.add(equals);
p1.add(add);
p1.add(sub);
p1.add(mul);
p1.add(div);
p1.add(clear);

for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
}
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
clear.addActionListener(this);
equals.addActionListener(this);

add(p,BorderLayout.NORTH);
add(p1);
setVisible(true);
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

public void actionPerformed(ActionEvent ae)


{
String str = ae.getActionCommand();
char ch = str.charAt(0);
if ( Character.isDigit(ch))
t.setText(t.getText()+str);
else
if(str.equals("+"))
{
v1=Integer.parseInt(t.getText());
choice='+';

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 22


t.setText("");
}
else if(str.equals("-"))
{
v1=Integer.parseInt(t.getText());
choice='-';
t.setText("");
}
else if(str.equals("*"))
{
v1=Integer.parseInt(t.getText());
choice='*';
t.setText("");
}
else if(str.equals("/"))
{
v1=Integer.parseInt(t.getText());
choice='/';
t.setText("");
}

if(str.equals("="))
{
v2=Integer.parseInt(t.getText());
if(choice=='+')
result=v1+v2;
else if(choice=='-')
result=v1-v2;
else if(choice=='*')
result=v1*v2;
else if(choice=='/')
result=v1/v2;

t.setText(""+result);
}
if(str.equals("C"))
{
t.setText("");
}
}
public static void main(String a[])
{
Slip10_1 ob = new Slip10_1();
}
}

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 23


Slip 11_1: write a program to accept a string as command line argument and check whether it is
a file or directory. Also perform operations as follows.
a. If it is a directory, list the name of text files. Also, display a count showing the number of
files in the directory.
b. If it is a file display various details of that file.

import java.io.*;

class Slip11_1
{
public static void main(String a[])
{

String fname=a[0];
File f = new File(fname);
int num=0;
if(f.isDirectory())
{
System.out.println("Given file "+fname+"is directory :");
System.out.println("List of files are : ");
String s[] = f.list();
for(int i=0; i<s.length; i++)
{
File f1 = new File(fname, s[i]);

if(f1.isFile())
{
num++;
System.out.println(s[i]); //file name in directory
}
else System.out.println("\n"+s[i]+" is a sub directory");
}
System.out.println("\nNumber of files are: "+num);
}
else
{
if(f.exists())
{
System.out.println("\n"+fname+" is a File");
System.out.println("Details of "+fname+" are : ");
System.out.println("Path of file is "+f.getPath());
System.out.println("Absolute Path of file is
"+f.getAbsolutePath());
System.out.println("Size of file is "+f.length());
}
else System.out.println(fname+" file is not present ");

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 24


}
}
}

Slip 12_1: Create the following GUI screen using appropriate layout manager. Accept the name,
class, hobbies from the user and display the selected options in a text box.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class Slip12_1 extends JFrame implements ActionListener


{
JLabel l1,l2,l3;
JButton b;
JRadioButton r1,r2,r3;
JCheckBox c1,c2,c3;
JTextField t1,t2;
ButtonGroup b1;
JPanel p1,p2;
static int cnt;
private StringBuffer s1=new StringBuffer();

Slip12_1()
{

b1=new ButtonGroup();
p1=new JPanel();
p2=new JPanel();
b=new JButton("Clear");
b.addActionListener(this);

r1=new JRadioButton("FY");
r2=new JRadioButton("SY");
r3=new JRadioButton("TY");

b1.add(r1);
b1.add(r2);
b1.add(r3);
r1.addActionListener(this);
r2.addActionListener(this);
r3.addActionListener(this);

c1=new JCheckBox("Music");
c2=new JCheckBox("Dance");
c3=new JCheckBox("Sports");

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 25


c1.addActionListener(this);
c2.addActionListener(this);
c3.addActionListener(this);

l1=new JLabel("Your Name");


l2=new JLabel("Your Class");
l3=new JLabel("Your Hobbies");
t1=new JTextField(20);
t2=new JTextField(30);

p1.setLayout(new GridLayout(5,2));
p1.add(l1);p1.add(t1);
p1.add(l2);p1.add(l3);
p1.add(r1);p1.add(c1);
p1.add(r2); p1.add(c2);
p1.add(r3);p1.add(c3);

p2.setLayout(new FlowLayout());
p2.add(b);
p2.add(t2);

setLayout(new BorderLayout());
add(p1,BorderLayout.NORTH);
add(p2,BorderLayout.EAST);

setSize(400,200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void actionPerformed(ActionEvent e)


{

if(e.getSource()==r1)
{
cnt++;
if(cnt==1)
{
String s =t1.getText();
s1.append("Name = ");
s1.append(s);
}
s1.append(" Class = FY");
}
else if(e.getSource()==r2)

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 26


{
cnt++;
if(cnt==1)
{
String s =t1.getText();
s1.append("Name = ");
s1.append(s);
}
s1.append(" Class = SY");
}
else if(e.getSource()==r3)
{
cnt++;
if(cnt==1)
{
String s =t1.getText();
s1.append("Name = ");
s1.append(s);
}
s1.append(" Class = TY");
}

else if(e.getSource()==c1)
{
s1.append(" Hobbies = Music");
}
else if(e.getSource()==c2)
{
s1.append(" Hobbies = Dance");
}
else if(e.getSource()==c3)
{
s1.append(" Hobbies = Sports");
}

t2.setText(new String(s1));
// t2.setText(s2);

if(e.getSource()==b)
{
t2.setText(" ");
t1.setText(" ");
}

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 27


public static void main(String arg[])
{
Slip12_1 s=new Slip12_1();

}
}

Slip 13_1: Write a program to accept a string as command line argument and check whether it is
a file or directory. Also perform operation as follows:
a. If it is a directory, delete all text file in that directory. Confirm delete operation from user
before deleting text file. Also, display a count showing the number of files deleted, if any, from
the directory.
b. If it is a file display various details of that file.

import java.io.*;

class Slip13_1
{
public static void main(String a[]) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String fname=a[0];

File f = new File(fname);


int num=0;
if(f.isDirectory())
{
System.out.println("Contents of directory :"+fname);

String s[] = f.list();


for(int i=0; i<s.length; i++)
{
File f1 = new File(fname, s[i]);

if(f1.isFile())
{

System.out.println(s[i]+" is a file");

if(s[i].endsWith("txt"))
{
System.out.println("\nDo you want to delete the file
with extension "+s[i]+" ?\n1:YES 2:NO");

int ch = Integer.parseInt(br.readLine());

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 28


if(ch==1)
{
f1.delete();
System.out.println("File has been deleted");
num++;
}
}
}
else
System.out.println("\n"+s[i]+" is a sub directory");
}
System.out.println("\nNumber of Deleted files are: "+num);
}
else
{if(f.exists())
{
System.out.println("\n"+fname+" is a File");
System.out.println("Details of "+fname+" are : ");
System.out.println("Path of file is "+f.getPath());
System.out.println("Absolute Path of file is
"+f.getAbsolutePath());
System.out.println("Size of file is "+f.length());
}
else System.out.println(fname+" file is not present ");

}
}
}

Slip 14_1: Write a menu driven program to perform the following operations on a text file
“phone.txt” which contain name and phone number pairs. The menu should have options:
a. Search name and display phone number
b. Add new name-phone number pair.

import java.io.*;
import java.util.*;

class phone
{
String name,phno;
phone (String nm,String ph)
{
name = nm;
phno=ph;
}

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 29


public String toString ()
{
String s = name + " " + phno ;
return (s);
}

public static void search(phone[] arr,int n)throws IOException


{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
for(int i=0;i<n;i++)
{
if(arr[i].name.equals(s))
{
System.out.println(arr[i].toString());
return;
}
}
System.out.println("No Records Found");
}
}

class Slip14_1
{
public static void main (String args[]) throws IOException
{
String s, space = " ";
int i;

File f = new File ("phone.dat");


RandomAccessFile rf = new RandomAccessFile (f, "rw");

BufferedReader b = new BufferedReader (new InputStreamReader (System.in));


System.out.println ("Enter no.of Customer");
int ch,n;
n = Integer.parseInt (b.readLine ());

System.out.println ("Enter Records:\n <name><phone no> :");

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


{
s = b.readLine () + "\n";
rf.writeBytes(s);
}
rf.close ();
RandomAccessFile rf1 = new RandomAccessFile (f, "r");

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 30


phone p[] = new phone[n];

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


{
s = rf1.readLine ();
StringTokenizer t = new StringTokenizer (s, space);
String sn = new String (t.nextToken ());
String sp = new String (t.nextToken ());
p[i] = new phone(sn,sp);

do
{
System.out.println("Menu :\n"+"1:Search for a phone no by
name\n"+"2:Add a new Record \n"+"3:Exit\n"+"Enter your Choice :" );
ch=Integer.parseInt(b.readLine());

switch (ch)
{
case 1:
System.out.println ("Enter name to be searched");
phone.search (p,n);
break;
case 2:
rf = new RandomAccessFile (f, "rw");
System.out.println ("Enter Records:\n <name><phone no>
:");

String s1 = b.readLine () + "\n";


rf.writeBytes(s1);
rf.close();
rf1 = new RandomAccessFile (f, "r");

s = rf1.readLine ();
StringTokenizer t = new StringTokenizer (s, space);
String sn = new String (t.nextToken ());
String sp = new String (t.nextToken ());
phone p1 = new phone(sn,sp);
System.out.println(" Records are ");

for(i=0;i<n;i++)
System.out.println(p[i].toString());
System.out.println(p1.toString());

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 31


break;
case 3 :System.exit(0);

}
}while(ch!=3);
}
}

Slip 15_1: Write a program to read item information( id, name, price, qty) from the file
‘item.dat’. write a menu driven program to perform the following operations using random
access file:
a. Search for a specific item by name
b. Find costliest item
c. Display all items and total cost.

import java.io.*;
import java.util.*;
class item
{
String name,id;
int qty;
double price,total;

item(String i,String n,String p,String q)


{
name=n;
id=i;
qty=Integer.parseInt(q);
price=Double.parseDouble(p);
total=qty*price;
}

public String toString()


{

String s=name+" "+id+" "+qty+" "+price+" "+total;


return(s);
}
public static void search(item[] arr,int n)throws IOException
{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));


String s=br.readLine();
for(int i=0;i<n;i++)
{
if(arr[i].name.equals(s)){

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 32


System.out.println(arr[i].toString());return;}

}
System.out.println("No Records Found");
}

public static void search_cost(item[] arr,int n)


{

double max=0;int c=0;

for(int i=0;i<n;i++)
{
if(arr[i].price > max){
c=i;
}
}
System.out.println(arr[c].toString());
}

}
class Slip15_1
{
public static void main(String[] args)throws IOException
{
String s,space=" ";
int ch,i;
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter no. of records");


int n=Integer.parseInt(b.readLine());

System.out.println("Enter Records:\n<id><name><price><qty> :");

File f = new File ("item.dat");


RandomAccessFile rf = new RandomAccessFile (f, "rw");

for( i=0;i<n;i++)
{
s=b.readLine()+"\n";
rf.writeBytes(s);
}
rf.close();

item it[]=new item[20];


RandomAccessFile rf1 = new RandomAccessFile (f, "r");

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 33


for(i=0;i<n;i++)
{
s=rf1.readLine();
StringTokenizer t = new StringTokenizer(s,space);
String id=new String(t.nextToken());
String pname=new String(t.nextToken());
String price=new String(t.nextToken());
String qty=new String(t.nextToken());
it[i]=new item(id,pname,price,qty);

do {
System.out.println("Menu :\n"+"1:Search for a item by name\n"+"2:Find
costliest item\n"+"3:Display all items and total cost\n4:Exit\n"+"Choice :" );
ch=Integer.parseInt(b.readLine());

switch (ch) {
case 1: System.out.println("Enter item name to be searched:");
item.search(it,n);
break;
case 2: System.out.println("Costliest Item :");
item.search_cost(it,n);
break;
case 3: for(i=0;i<n;i++)
System.out.println(it[i].toString());
break;
case 4: break;
default:System.out.println("Invalid Option");
}

}while(ch!=4);
}
}

Slip 16_1: Define a class cricket player(name, no_ofinings, no_of_times_notout, total_runs,


bat_avg).create an array of ‘n’ player objects. Calculate the batting average for each player using
a static method avg(). Handle appropriate exception while calculating average. Difine static
method ‘sortPlayer’ which sorts the array on the basis of average. Display the player details in
sorted order.

import java.io.*;
class Inning_Invalid extends Exception
{}
class CricketPlayer
{

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 34


int no_of_in,runs,bat_avg;
String name;
int not_out;

CricketPlayer(){}
CricketPlayer(String n,int no,int n_out,int r)
{
name=n;
no_of_in=no;
not_out=n_out;
runs=r;
}

void cal_avg()
{
try
{
if(no_of_in==0)
throw new Inning_Invalid();
bat_avg=runs/no_of_in;
}
catch(Inning_Invalid ob)
{
System.out.println("no of inning can not be zero");
runs=0;
bat_avg=0;
}
}
void display()
{
System.out.println(name+"\t"+no_of_in+"\t"+not_out+"\t"+runs+"\t"+bat_avg);
}
float getavg()
{
return bat_avg;
}

public static void sortPlayer(CricketPlayer c[],int n)


{
for(int i=n-1;i>=0;i--)
{
for(int j=0;j<i;j++)
{
if(c[j].getavg()>c[j+1].getavg())
{

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 35


CricketPlayer t=c[j];
c[j]=c[j+1];
c[j+1]=t;
}
}
}
for(int i=0;i<n;i++)
c[i].display();

}
}
class Slip16_1
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter no. of Player:");
int n=Integer.parseInt(br.readLine());
CricketPlayer cp[]=new CricketPlayer[n];
for(int i=0;i<n;i++)
{
System.out.print("Enter Name:");
String name=br.readLine();

System.out.print("Enter no of innings:");
int in=Integer.parseInt(br.readLine());

System.out.print("Enter no of times not out:");


int ot=Integer.parseInt(br.readLine());

System.out.print("Enter total runs:");


int r=Integer.parseInt(br.readLine());
cp[i]=new CricketPlayer(name,in,ot,r);
cp[i].cal_avg();
}
System.out.println("===============================");
for(int i=0;i<n;i++)
cp[i].display();

CricketPlayer.sortPlayer(cp,n);
}
}

Slip 17_1: Define an abstract class “staff” with members name and address. Define two
subclasses off this class- ‘Full Timestaff’ (department, salary) and part time staff

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 36


(number_of_hours_, rate_per_hour). defineappropriate constructors.create ‘n’ object which could
be of either FullTimeStaff or ParttimeStaff class by asking the users choice. Display details of all
“FulTimeStaff” objects and all “PartTimeStaff” objects.

import java.io.*;
abstract class Staff
{
String name,address;

public Staff(String name,String address)


{
this.name=name;
this.address=address;
}
abstract public void display();
}

class FullTime extends Staff


{
String department;
double salary;

public FullTime(String name,String address,String department,double salary)


{
super(name,address);
this.department=department;
this.salary=salary;
}
public void display()
{
System.out.println("Name:"+name);
System.out.println("Address:"+address);
System.out.println("Department:"+department);
System.out.println("Salary:"+salary);
}

}
class PartTime extends Staff
{
int noofhrs;
double rate;

public PartTime(String name,String address,int noofhrs,double rate)


{
super(name,address);
this.noofhrs=noofhrs;

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 37


this.rate=rate;
}
public void display()
{
System.out.println("Name:"+name);
System.out.println("Address:"+address);
System.out.println("Number of hours:"+noofhrs);
System.out.println("Rate per hour:"+rate);
}
}

class Slip17_1
{

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


{
int ch=0,n=0,noofhrs;
String name,address,department;
double salary,rate;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
do
{

System.out.println("\n1:Full Time \n2:Part Time \n3:Exit");


System.out.println("Enter your choice:");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
System.out.println("Enter how many staff members:");
n=Integer.parseInt(br.readLine());
FullTime F[]=new FullTime[n];
for(int i=0;i<n;i++)
{
System.out.println("Enter name:");
name=br.readLine();
System.out.println("Enter Address:");
address=br.readLine();
System.out.println("Enter Department:");
department=br.readLine();
System.out.println("Enter Salary:");
salary=Double.parseDouble(br.readLine());
F[i]=new
FullTime(name,address,department,salary);
}
System.out.println("Full Time details:");

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 38


System.out.println("========================");
for(int i=0;i<n;i++)
F[i].display();
break;

case 2:
System.out.println("Enter how many staff members:");
n=Integer.parseInt(br.readLine());
PartTime obj[]=new PartTime[n];
for(int i=0;i<n;i++)
{
System.out.println("Enter name:");
name=br.readLine();
System.out.println("Enter Address:");
address=br.readLine();
System.out.println("Enter no of hrs:");
noofhrs=Integer.parseInt(br.readLine());
System.out.println("Enter rate:");
rate=Double.parseDouble(br.readLine());
obj[i]=new PartTime(name,address,noofhrs,rate);
}
System.out.println("Part Time details:");
System.out.println("========================");
for(int i=0;i<n;i++)
obj[i].display();
break;

case 3:break;

default:
System.out.println(" invalid input ");
break;
}

}while(ch!=3);
}
}

Slip 18_1 : Define a class MyNumber having one private int no member. Write a default
constructor to initialize it to 0 and another constructor to initialize it to a value (Use this). Write
methods isNegative, isPositive, isZero, isOdd, isEven.
Create an object in main.Use command line arguments to pass a value to the object and perform
the above tests.

class MyNumber
{

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 39


int no;
MyNumber()
{no=0;}
MyNumber(int no)
{
this.no=no;
}

void isNegative()
{
if(no<0)
System.out.println("Given number is negative.\n ");
}

void isPositive()
{
if(no>0)
System.out.println("Given number is positive..\n");

void isZero()
{
if(no==0)
System.out.println("Given number is negative..\n ");

void isOdd()
{
if((no%2)==1)
System.out.println("Given number is Odd..\n ");

void isEven()
{
if((no%2)==0)
System.out.println("Given number is Even.\n ");
}
}

class Slip18_1
{
public static void main(String args[])
{

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 40


int num=Integer.parseInt(args[0]);

MyNumber ob=new MyNumber(num);


ob.isNegative();
ob.isPositive();
ob.isZero();
ob.isOdd();
ob.isEven();
}
}

Slip 20_1: Write a program to create package “TY” which has a class TYmarks( computer total,
maths total, electronics total). Create another package “TY” which has a class TYmarks (Theory,
Practical). Create “n” object of student class having roll number, name, SY Marks and TY
Marks. Add the Marks of SY and TY computer subject and calculate grade (‘A’ for>=70,’B’
for>=60,’C’ for >=50, “Pass Class” for >=40 else “Fail”) and display the result of the student in
proper format.

package SY;

public class SYMarks


{
int ct,mt,et;
public SYMarks(int ct,int mt,int et)
{
this.ct=ct;
this.mt=mt;
this.et=et;
}
public void display()
{
System.out.println("\nMarks are;");
System.out.println("Computer\tMaths\tElectronics");
System.out.println(ct+"\t"+mt+"\t"+et);
}
}

package TY;

public class TYMarks


{
int Theory,Practicals;
public TYMarks(int Theory,int Practicals)
{
this.Theory=Theory;

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 41


this.Practicals=Practicals;
}
public void display()
{
System.out.println("\nMarks are:");
System.out.println("Theory\tPracticals");
System.out.println(Theory+"\t"+Practicals);
}
}

/* slip 20_1 */
import SY.SYMarks;
import TY.TYMarks;
import java.io.*;

class Slip20_1
{
int rollno;
int ComputerTotal, MathsTotal, ElecTotal, Theory, Practicals,total;
String name;
static BufferedReader br =new BufferedReader(new InputStreamReader(System.in));

public Slip20_1()
{}

public Slip20_1(int rollno,String name) throws Exception


{
this.rollno = rollno;
this.name = name;

System.out.println("Enter SY marks: ");

System.out.println("\nEnter computer marks");


ComputerTotal = Integer.parseInt(br.readLine());

while((ComputerTotal<0 || ComputerTotal>100))
{
System.out.println("Invalid marks.....");

System.out.println("Please ReEnter the marks: ");


ComputerTotal = Integer.parseInt(br.readLine());
}

System.out.println("Enter maths marks");

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 42


MathsTotal=Integer.parseInt(br.readLine());

while((MathsTotal<0 || MathsTotal>100))
{
System.out.println("Invalid marks.....");

System.out.println("Please Reenter the marks: ");


MathsTotal=Integer.parseInt(br.readLine());
}

System.out.println("Enter electronics marks");


ElecTotal = Integer.parseInt(br.readLine());

while((ElecTotal<0 || ElecTotal>100))
{
System.out.println("Invalid marks.....");

System.out.println("Please Reenter the marks: ");


ElecTotal = Integer.parseInt(br.readLine());
}

SYMarks sy = new SYMarks(ComputerTotal, MathsTotal, ElecTotal);

System.out.print("Enter TY marks: ");

System.out.print("Enter theory marks ");


Theory = Integer.parseInt(br.readLine());

while((Theory<0 || Theory>100))
{
System.out.println("Invalid marks.....");
System.out.println("Please Reenter the marks: ");
Theory = Integer.parseInt(br.readLine());
}

System.out.print("Enter practicals marks ");


Practicals = Integer.parseInt(br.readLine());

while((Practicals<0 || Practicals>100))
{
System.out.println("Invalid marks.....");

System.out.println("Please Reenter the marks: ");


Practicals = Integer.parseInt(br.readLine());
}

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 43


TYMarks ty = new TYMarks(Theory, Practicals);

}
public void CalculateGrade()
{
double percentage;

total = (ComputerTotal+ MathsTotal + ElecTotal + Theory + Practicals);


percentage=total/5;
System.out.println("Total Marks : \t"+total);
if(percentage >= 70)
System.out.println("Grade:A");

else if(percentage >= 60)


System.out.println("Grade:B");

else if(percentage >= 50)


System.out.println("Grade:C");

else if(percentage >= 40)


System.out.println("Grade:PASS");
else
System.out.println("Grade:FAIL");
System.out.println("=============================");
}

public void display()


{
System.out.println("Name of Student : "+name);
System.out.println("Computer Total : "+ ComputerTotal+"\nMaths Total :
"+MathsTotal+"\nElectronic Total : \t"+ElecTotal);
System.out.println("Theory Mark : "+Theory+"\nPractical Mark : "+Practicals);

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


{

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


int no=Integer.parseInt(br.readLine());

Slip20_1 ob[]=new Slip20_1[no];

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


{

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 44


System.out.println("Enter roll no: ");
int r = Integer.parseInt(br.readLine());

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


String nm = br.readLine();

ob[i] = new Slip20_1(r,nm);


}
for(int i=0; i<no; i++)
{
ob[i].display();
ob[i].CalculateGrade();
}

//st.getdata();
}
}

Slip 21_1: Define a student class ( roll number, name, percentage). Define a default and
parameterized constructor. keep a count of object created. Create object using parameterized
constructor and display the object count after each object is created. ( use static member and
method). Also display the content of each object. Modify program to create “n” object of the
student class. Accept details for each object. Define static method “shortStudent” which shorts
the array on the basis Of percentage.

import java.io.*;
class Student
{
int rollno;
String name;
float per;
static int count;

Student(){}
Student(String n,float p)
{
count++;
rollno=count;
name=n;
per=p;

void display()
{

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 45


System.out.println(rollno+"\t"+name+"\t"+per);
}
float getper()
{
return per;
}
static void counter()
{
System.out.println(count+" object is created");
}
public static void sortStudent(Student s[],int n)
{
for(int i=n-1;i>=0;i--)
{
for(int j=0;j<i;j++)
{
if(s[j].getper()>s[j+1].getper())
{
Student t=s[j];
s[j]=s[j+1];
s[j+1]=t;
}
}
}
for(int i=0;i<n;i++)
s[i].display();

}
}
class Slip21_1
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter no. of Student:");
int n=Integer.parseInt(br.readLine());
Student p[]=new Student[n];
for(int i=0;i<n;i++)
{
System.out.print("Enter Name:");
String name=br.readLine();
System.out.print("Enter percentage:");
float per=Float.parseFloat(br.readLine());
p[i]=new Student(name,per);
p[i].counter();
}

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 46


Student.sortStudent(p,Student.count);
}
}

Slip 22_1: Write a menu driven program to perform following operations. Accept operation
accept the two number using input dialog box. GCD will compute the GCD of two numbers and
display in the message box and power operation will calculate the value of an and display it in
message box where “a” and “n” are two inputted values.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;

class Slip22_1 extends JFrame implements ActionListener


{
JMenu m1,m2;
JMenuBar mb;
JMenuItem m[];

StringBuffer ss=new StringBuffer();

int n;
int arr[]=new int [20];

int n1,n2,gcd,pow;
public Slip22_1()
{
mb=new JMenuBar();

m1=new JMenu("Operation");
m2=new JMenu("Compute");

String str[]={"Accept","Exit","GCD","Power"};
m=new JMenuItem[str.length];
for(int i=0;i<str.length;i++)
{
m[i]=new JMenuItem(str[i]);
m[i].addActionListener(this);
}

mb.add(m1);
mb.add(m2);

m1.add(m[0]);
m1.add(m[1]);

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 47


m2.add(m[2]);
m2.add(m[3]);

setLayout(new BorderLayout());
add(mb,BorderLayout.NORTH);
setSize(300,150);
setVisible(true);
setLocation(500,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

} // constructor
public void actionPerformed(ActionEvent e)
{
String s=e.getActionCommand(); //return the name of menu
if(s.equals("Exit"))
System.exit(0);
if(s.equals("Accept"))
{
n1=Integer.parseInt(JOptionPane.showInputDialog("Enter 1st no for
Number"));
n2=Integer.parseInt(JOptionPane.showInputDialog("Enter 2nd no for
Number"));
}
if(s.equals("GCD"))
{
int min;
if(n1>=n2)
min=n1;
else min=n2;
for(int i=1;i<=min;i++)
{
if(n1%i==0 && n2%i==0)
gcd=i;
}
JOptionPane.showMessageDialog(null,"GCD = "+gcd);
}
if(s.equals("Power"))
{
pow=1;

for(int i=1;i<=n2;i++)
{
pow=pow*n1;
}
JOptionPane.showMessageDialog(null,"Power = "+pow);

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 48


}
}
public static void main(String a[])
{
new Slip22_1();
}
}

Slip 23_1: Create an interface”CreditCardInterface” with methods:


viewcreditamount(),PayCard(). Create a class “silverCardCustomer”(name, cardnumber)(16
digit), creditamount-initialized to 0, credit limit set to 50,000) which implement above interface.
Inherit class GoldCardCustomer from SilverCardCustomer having same method but creditLimit
of 1,00,000. Create an object of each class and perform operations. Display appropriate message
for success or failure of transaction. ( use method overriding)
a. useCard() method increase the credit amount by a specific amount upto creditLimit.
b. payCredit() reduces the credit Amount by a specific amount.
c. increaseLimit() increase the credit limit for GoldCardCustomer (only 3 times, not mor than
5000 rupees each time.)

import java.io.*;
interface CreditCard
{
void viewCreditAmount();
void increaseLimit()throws IOException;
void useCard()throws IOException ;
void payCard()throws IOException;
}

class SliverCardCustomer implements CreditCard


{
String name;
int card_no ;
double creditAmount;
double creaditLimit;
static int cnt;
BufferedReader br=new BufferedReader(new BufferedReader(new
InputStreamReader(System.in)));

SliverCardCustomer()
{
name="Noname" ;
card_no=0;
creditAmount=0;
creaditLimit=50000;
}

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 49


public void viewCreditAmount()
{
System.out.println("Your amount is : "+creditAmount) ;
}

public void getdata()throws IOException


{
System.out.println("Enter the name : ");
String name=(br.readLine());
System.out.println("Enter the card number :");
card_no=Integer.parseInt(br.readLine());
System.out.println("Enter Credit amount : ");
creditAmount=Double.parseDouble(br.readLine());
}

public void payCard()throws IOException


{
System.out.println("Enter amount to be pay");
double pay=Double.parseDouble(br.readLine()) ;
creditAmount=creditAmount+pay;
System.out.println("Balance is paid");
}
public void useCard()throws IOException
{

System.out.println("Enter amount : ");


double amount=Double.parseDouble(br.readLine());
if(amount<creditAmount)
{
creditAmount=creditAmount-amount;
viewCreditAmount();
System.out.println("Thanks for using the service") ;
}
else System.out.println("\nerror!");
}

public void increaseLimit()throws IOException


{
cnt++;
if(cnt<=3)
{
System.out.println("Enter amount limit to increse : ");
double amt=Double.parseDouble(br.readLine());
if(amt<=2500)
{

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 50


creaditLimit=creaditLimit+amt;
System.out.println("Amount limit to increse Successfully : ");
}
System.out.println("You can't increse creadit amount more than 2500 at a
time ");

}
else
System.out.println("You can't increse limit more than 3 times ");
}
}//end of class

class GoldCardCustomer extends SliverCardCustomer


{
static int cnt;
public void increaseLimit()throws IOException
{
cnt++;
if(cnt<=3)
{
System.out.println("Enter amount limit to increse : ");
double amt=Double.parseDouble(br.readLine());
if(amt<=5000)
{
creaditLimit=creaditLimit+amt;
System.out.println("Amount limit to increse Successfully : ");
}
System.out.println("You can't increse creadit amount more than 2500 at a
time ");

}
else
System.out.println("You can't increse limit more than 3 times ");
}

}
class Slip23_1
{
public static void main(String args[])throws IOException
{
int ch ;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the info for silver card holder : ");


SliverCardCustomer sc=new SliverCardCustomer();
sc.getdata();

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 51


System.out.println("Enter the info for Gold card holder : ");
GoldCardCustomer gc=new GoldCardCustomer();
gc.getdata();
do
{
System.out.println("1.Use silver card \n2.Pay credit for Silver
card\n3.Increse limit for silver card ") ;
System.out.println("4.Use Gold card \n5.Pay credit for Gold
card\n6.Increse limit for Gold card ") ;

System.out.println("0. exit") ;
System.out.println("Enter your choice : ") ;
ch=Integer.parseInt(br.readLine());

switch(ch)
{
case 1: sc.useCard();
break;
case 2:sc.payCard();
break ;
case 3:sc.increaseLimit();
break;
case 4:gc.useCard();
break;
case 5:gc.payCard();
break ;
case 6:gc.increaseLimit();
break;

case 0 :break;
}
}while(ch!=0);
}
}

Slip 24_1: Create a class to create a super class vehicle having members company and price.
Drive two different classes LightMotorVehicle(mileage) and heavyMoterVehicle
(Capacity_in_tons). Accept the information for ‘n’ vehicle and .display the information in
appropriate form while taking data, ask user about the type of vehicle first.

import java.io.*;
class Vehicle
{
String cname;
float price;

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 52


void accept() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter vehicle information");

System.out.println("Enter Company name : ");


cname= br.readLine();
System.out.println("Enter price : ");
price = Float.parseFloat(br.readLine());
}

void display()
{
System.out.println("Company Name : "+cname+"\nPrice : "+price);
}

class LightMotorVehicle extends Vehicle


{
int mileage;

void accept() throws IOException


{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

super.accept();

System.out.println("Enter mileage : ");


mileage = Integer.parseInt(br.readLine());
}

void display()
{
super.display();
System.out.println("\nMileage : "+mileage);
}

class HeavyMotorVehicle extends Vehicle


{
int capacity;

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 53


void accept() throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

super.accept();

System.out.println("Enter capacity in tones : ");


capacity = Integer.parseInt(br.readLine());
}

void display()
{
super.display();
System.out.println("\nCapacity int tones : "+capacity);
}

class Slip24_1
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter type of vehicle \n1. for light motor vehicle \n2. for
heavy motor vehicle ");
int ch = Integer.parseInt(br.readLine());
int no;
switch(ch)
{
case 1 :System.out.println("Enter no of light motor");
no = Integer.parseInt(br.readLine());
LightMotorVehicle lv[] = new LightMotorVehicle[no];

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


{
lv[i] = new LightMotorVehicle();
lv[i].accept();
}
System.out.println("Information of light motor are");
System.out.println("=======================");
for(int i = 0 ; i < no; i++)
{
//lv[i] = new LightMotorVehicle();
lv[i].display();
}

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 54


break;
case 2 :System.out.println("Enter no of heavy motor");
no = Integer.parseInt(br.readLine());
HeavyMotorVehicle hv[] = new HeavyMotorVehicle[no];

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


{
hv[i] = new HeavyMotorVehicle();
hv[i].accept();
}
System.out.println("Information of heavy motor are");
System.out.println("=======================");
for(int i = 0 ; i < no; i++)
{
//lv[i] = new LightMotorVehicle();
hv[i].display();
}
break;
//calculate_salary(mn,no);
}
}
}

Slip 25_1: Define a class employee having members –id, name, department, salary. Define
default and parameterized constructors. Create a subclass called manager with private member
bonus. Define methods accept and display in both the classes. Create “n” objects of the manager
class and display the details of the manager having the maximum total salary (salary+bonus).

import java.io.*;
class Employee
{
private int id;
private String name, department;
private float salary;

Employee()
{
id = 1;
name = "nived";
department = "bcs";
salary = 20000;
}

Employee(int id, String name, String department, float salary)


{
this.id = id;

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 55


this.name = name;
this.department = department;
this.salary = salary;
}

void accept() throws IOException


{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter employee information: id, name, department, salary");

id = Integer.parseInt(br.readLine());
name= br.readLine();
department = br.readLine();
salary = Float.parseFloat(br.readLine());
}

void display()
{
System.out.println("\nId : "+id+"\nName : "+name+"\nDepartment :
"+department+"\nSalary : "+salary);
}

float getsalary()
{
return salary;
}
}

class Manager extends Employee


{
private float bonus;

Manager()
{
super();
}

Manager(int id, String name, String department, float salary, float bonus)
{
super(id, name, department, salary);
this.bonus = bonus;
}

void accept() throws IOException


{

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 56


BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

super.accept();

System.out.println("Enter bonus : ");


bonus = Float.parseFloat(br.readLine());
}

void display()
{
super.display();
System.out.println("\nBonus : "+bonus);
}

float getbonus()
{ return bonus;
}
}

class Slip25_1
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter Number Of Employees: ");


int no = Integer.parseInt(br.readLine());

Manager mn[] = new Manager[no];


for(int i = 0 ; i < no; i++)
{
mn[i] = new Manager();
mn[i].accept();
}

calculate_salary(mn,no);
}

static void calculate_salary(Manager mn[],int n)


{
int index = 0;
float sal[] = new float[n];

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


{
sal[i] = mn[i].getsalary() + mn[i].getbonus();

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 57


}

float max = 0;
for(int i = 0; i<n; i++)
{
if(sal[i] > max)
{
max = sal[i];
index = i;
}
}
System.out.println("Employee with max salary is: ");
mn[index].display();
}
}

AHIRE CLASSES,BARAMATI (9960703408/8788100181) Page 58

You might also like