You are on page 1of 64

CHRIST COLLEGE, PUNE

T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018


Lab Course-( Java)

Slip no :1
Write a java program to read the characters from a file, if a character is
alphabet then reverse its case, if not then display its category on the Screen.
(whether it is Digit or Space)
CODE:
import java.io.*;
class Slip1
{
public static void main(String args[]) throws IOException
{
FileInputStream fin=new FileInputStream("fruits.txt");
int i=0;
while((i=fin.read())!=-1)
{
if(Character.isDigit((char)i))
{
System.out.println("It is a number");
}
else if(i==32)
{
System.out.println("It is a space");
}
else if(Character.isLowerCase((char)i))
{
System.out.println(Character.toUpperCase((char)i)
);

}
else
{
System.out.println(Character.toLowerCase((char)i)
);
}
}
fin.close();
}

}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

OUTPUT:
D:\docs>javac Slip1.j
D:\docs>java Slip1
It is a number
It is a space
A
P
P
L
E
It is a number
It is a space
B
A
N
A
N
A
It is a number
It is a space
G
R
A
P
E
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No:2
Write a java program to accept n names of cites from user and display them
in descending order.
CODE:
import java.io.*;
class Descending
{
String[] desc(int n, String city[])
{
for(int i=0;i<n;++i)
{
for(int j=i+1;j<n;++j)
{
int c=city[i].compareTo(city[j]);
if(c<0)
{
String str=city[i];
city[i]=city[j];
city[j]=str;
}
}
}
return(city);
}
public static void main(String args[]) throws IOException
{
int n;
Descending d=new Descending();
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the no. of cities");
n=Integer.parseInt(br.readLine());
String city[]=new String[n];
System.out.println("Enter the names of the cities: ");
for(int i=0;i<n;++i)
{
city[i]=br.readLine();
}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

city=d.desc(n,city);
System.out.println("The cities in descending order are: ");
for(int i=0;i<n;++i)
{
System.out.println(city[i]);
}
}
}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No:3

Write a java program to accept the details of ‘n’ employees (EName ,Salary)
from the user, store them into the Hashtable and displays the Employee
Names having maximum Salary.
CODE:
import java.util.*;
import java.io.*;
class HashTableDemo
{
static BufferedReader br=new BufferedReader (new
InputStreamReader(System.in));
public static void main(String args[])
{
try
{
System.out.print("Enter no of Records:");
int n=Integer.parseInt(br.readLine());
Hashtable<String,Float> hashtable=new
Hashtable<String,Float>();
for(int i=1; i<=n; i++)
{
System.out.println("Enter the name of
Employee :"+i+":");
String name=br.readLine();
System.out.println("Enter Salary of Employee:"+ i +":");
float Salary=Float.parseFloat(br.readLine());
hashtable.put(name,Salary);
}
System.out.println("Name \t Percentage");
Enumeration keys=hashtable.keys();
float max=0;

while(keys.hasMoreElements())
{
String key=(String) keys.nextElement();

float value =Float.valueOf(hashtable.get(key).toString());


CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

System.out.println(key+"\t" + value);
if(max<value)
max=value;
}

System.out.println("Maximum salary=" +max);

for(Map.Entry m:hashtable.entrySet())
{
float sal=Float.valueOf((m.getValue()).toString());

if(max == sal)
{

System.out.println("Employee name having maximum salary


"+m.getKey());
}
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

OUTPUT:
D:\docs\slip 3>javac HashTableDemo.java

D:\docs\slip 3>java HashTableDemo


Enter no of Records:5
Enter the name of Employee :1:
fiona
Enter Salary of Employee:1:
50000
Enter the name of Employee :2:
prabhu
Enter Salary of Employee:2:
65000
Enter the name of Employee :3:
vaishali
Enter Salary of Employee:3:
20000
Enter the name of Employee :4:
jenni
Enter Salary of Employee:4:
23000
Enter the name of Employee :5:
ankita
Enter Salary of Employee:5:
20000
Name Percentage
ankita 20000.0
prabhu 65000.0
jenni 23000.0
vaishali 20000.0
fiona 50000.0
Maximum salary=65000.0
Employee name having maximum salary prabhu
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No :4
Design a screen in Java to handle the Mouse Events such as
MOUSE_MOVED and MOUSE_CLICK and display the position of the
Mouse_Click in a TextField.
import java.awt.*;
import java.awt.event.*;

public class Ass21 extends Frame


{
TextField statusBar;
public static void main(String []args)
{
new Ass21().show();
}

public Ass21()
{
addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
statusBar.setText("Clicked at (" + e.getX() + "," +
e.getY() + ")");
repaint();
}
public void mouseEntered(MouseEvent e)
{
statusBar.setText("Entered at (" + e.getX() + "," +
e.getY() + ")");
repaint();
} });
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
setLayout(new FlowLayout());
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

setSize(275,300);
setTitle("Mouse Click Position");
statusBar = new TextField(20);
add(statusBar);
setVisible(true);
}
}

OUTPUT:
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No:5
Define a class Student with attributes rollno and name. Define default and
parameterized constructor. Override the toString() method. Keep the count of
Objects created. Create objects using parameterized constructor and Display
the object count after each object is created.

import java.io.*;
class Student
{
int rno;
static int count=0;
String nm;
Student() throws IOException
{

rno=55;
nm="Fiona";
}
Student(int rno,String nm)
{
System.out.println("This is object no:"+(++count));
this.rno=rno;
this.nm=nm;
}
public String toString()
{
String str="Roll no: "+rno+"name: "+nm;
return(str);
}
public static void main(String args[]) throws IOException
{
int rno;
String nm;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
Student st[]=new Student[5];
for(int i=0;i<5;++i)
{
System.out.println("Enter the details: ");
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

rno=Integer.parseInt(br.readLine());
nm=br.readLine();
st[i]=new Student(rno,nm);

}
for(int i=0;i<5;++i)
{
System.out.println(st[i]);

}
}
}
OUTPUT:
D:\docs\slip5>javac Student
D:\docs\slip5>java Student
Enter the details:
1
fiona
This is object no:1
Enter the details:
2
prabhu
This is object no:2
Enter the details:
3
vaishali
This is object no:3
Enter the details:
4
jenni
This is object no:4

Roll no: 1name: fiona


Roll no: 2name: prabhu
Roll no: 3name: vaishali
Roll no: 4name: jenni
Roll no: 5name: ashsih
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No:6
Create a calculator with functionality in an Applet.

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

class Calculatorpanel extends JApplet implements ActionListener


{

public Calculatorpanel()
{
setLayout(new BorderLayout());
display = new JTextField("0");
display.setEditable(false);
add(display, "North");
JPanel p = new JPanel();
p.setLayout(new GridLayout(4, 4));
String buttons = "789/456*123-0.=+";
for (int i = 0; i < buttons.length(); i++)
{
addButton(p, buttons.substring(i, i + 1));
}
add(p, "Center");
}

private void addButton(Container c, String s) {


JButton b = new JButton(s);
c.add(b);
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

b.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
String s = ae.getActionCommand();
if ('0' < s.charAt(0) && s.charAt(0) <= '9' || s.equals("."))
{
if (start)
{
display.setText(s);
} else
{
display.setText(display.getText() + s);
}
start = false;
} else
{
if (start)
{
if (s.equals("="))
{
display.setText(s);
start = false;
} else
{
op = s;
}
} else
{
double x = Double.parseDouble(display.getText());
Calculate(x);
op = s;
start = true;
}
}
}

public void Calculate(double n)


CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

{
if (op.equals("+"))
{
arg += n;
} else if (op.equals("-"))
{
arg -= n;
} else if (op.equals("*"))
{
arg *= n;
} else if (op.equals("/"))
{
arg /= n;
} else if (op.equals("="))
{
arg = n;
}
display.setText(" " + arg);

}
private JTextField display;
private double arg = 0;
private String op = "=";
private boolean start = true;
}

public class CalculatorApplet extends JApplet


{

public void init()


{
Container ContentPane = getContentPane();
ContentPane.add(new Calculatorpanel());
}
}
/*<applet CODE="CalculatorApplet.class" width="300" height="300"></applet>
*/
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No :7
Write a java program to display “Hello Java” with settings Font- Georgia,
Foreground color- Red, background color – Blue on the Frame.
import java.awt.*;
import java.awt.event.*;
class FrameDemo extends Frame
{
FrameDemo()
{
Font fo =new Font("Georgia",Font.BOLD,10);
Label l =new Label("Hello Java");
l.setBackground(Color.RED);
l.setForeground(Color.BLUE);
l.setFont(fo);
Panel p =new Panel();
p.add(l);
Frame f =new Frame("Hello Java");
f.setVisible(true);
f.setSize(200,200);
f.add(p);
}
public static void main(String args[])
{
FrameDemo fd =new FrameDemo();
}
}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No :8
Write a java program to design a following GUI (Use Swing).

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

class Slip8 extends JFrame


{
JLabel l1,l2,l3,l4,l5,l6;
JTextField t1,t2,t3;
JTextArea t;
JPanel p,p1,p2,p3;
ButtonGroup bg;
JRadioButton m,f;
JCheckBox c1,c2,c3;
JButton b1,b2;
Slip8()
{
p =new JPanel();
p1=new JPanel();
l1=new JLabel("First Name ");
l2=new JLabel("last Name ");
l3=new JLabel("Address ");
l4=new JLabel("mobile No ");

t1=new JTextField(10);
t2=new JTextField(10);
t3=new JTextField(10);
t=new JTextArea(2,10);
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

p.add(l1); p.add(t1);
p.add(l2); p.add(t2);
p.add(l3); p.add(t);
p.add(l4); p.add(t3);
p.setLayout(new GridLayout(4,2));
add(p);

l5=new JLabel("Gender ");


m = new JRadioButton("male");
f = new JRadioButton("female");

bg = new ButtonGroup();
bg.add(m);
bg.add(f);
p1.add(l5);
p1.add(m);
p1.add(f);
p1.setLayout(new GridLayout(1,3));

p2=new JPanel();
l6=new JLabel("Your Interests ");
c1=new JCheckBox("Computer");
c2=new JCheckBox("Sports");
c3=new JCheckBox("Music");

p2.add(l6);
p2.add(c1);
p2.add(c2);
p2.add(c3);
p2.setLayout(new GridLayout(1,4));

p3=new JPanel();
b1=new JButton("submit");
b2=new JButton("clear");
p3.add(b1);
p3.add(b2);

add(p);
add(p1);
add(p2);
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

add(p3);
setSize(300,400);
setLayout(new FlowLayout(FlowLayout.LEFT));
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String a[])
{
new Slip8();
}
}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No:9
Write a java program to display the contents of a file in reverse order.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Main


{
public static void main(String[] args) throws FileNotFoundException, IOException
{
Scanner scanner = new Scanner(new File("D:/test.txt")).useDelimiter("\\Z");
String contents = scanner.next();
System.out.println("Original String : " + contents);
contents = new StringBuffer(contents).reverse().toString();
System.out.println("Reversed String : " + contents);
FileWriter fstream = new FileWriter("D:/test.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(contents);
out.close();
}
}

Output :
Original String : subin suresh
Reversed String : hserus nibus

Slip No:10
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Write an applet application in Java for designing Temple.

import java.applet.Applet;
import java.awt.Graphics;
public class Temple extends Applet
{
public void paint(Graphics g)
{
g.drawRect(100,100,60,100);
g.drawLine(100,100,130,50);
g.drawLine(130,50,162,100);
g.drawRect(120,140,20,60);
g.drawLine(130,50,130,10);
g.drawRect(130,10,30,20);
}
}
/* <applet code="Temple.class" height=1000 width=1000> </applet>*/
OUTPUT:
D:\docs\slip10>javac Temple.java
D:\docs\slip10>appletviewer Temple.java

Slip No :11
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Write a java program to accept Employee name from the user and check
whether it is valid or not. If it is not valid then throw user defined Exception
“Name is Invalid” otherwise display it.
CODE:
import java.io.*;
class NameException extends Exception
{
NameException()
{
super();
}
}
class Employeee
{
String nm;
Employeee() throws IOException
{
System.out.println("Enter the name: ");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
nm=br.readLine();
}
void check()
{
try
{
char c[]=nm.toCharArray();
for(int i=0;i<nm.length();++i)
{
if(Character.isDigit(c[i]))
{
throw new NameException();
}
}
}
catch(NameException ne)
{
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

System.out.println("Invalid Name\nInvalid Name Exception


Handled");
}
}
public static void main(String args[]) throws IOException
{
Employeee e=new Employeee();
e.check();
}
}
OUTPUT:
D:\docs\slip11>javac Employeee.jav
D:\docs\slip11>java Employeee
Enter the name:
fiona
D:\docs\slip11>java Employeee
Enter the name:
fio45
Invalid Name
Invalid Name Exception Handled
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No:12
Write a java program to accept list of file names through command line and
delete the files having extension “.txt”. Display the details of remaining files
such as FileName and size.

import java.io.*;

class DeleteFileDemo
{
public static void main(String args[])throws IOException
{

BufferedReader br =new BufferedReader(new


InputStreamReader(System.in));

String name =args[0];


File file =new File(name);

if(file.isFile())
{

System.out.println(name+"is file");

}
if(file.isDirectory())
{
System.out.println(name +"is directory");
String names[] =file.list();
int count=0;
for(int i=0;i<names.length;i++)
{

File f =new File(name+"/"+names[i]);


if(f.isFile())
{
System.out.println(names[i]+"\t"+f.length());
if(names[i].endsWith(".txt"))
{
System.out.println("Delete the file Y/N ?");
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

String ch =br.readLine();
if(ch.equals("Y"))
{
f.delete();
}

}
count++;
}
}

System.out.println("Total Files"+count);

}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No:13
Write a java program to copy the contents of one file into the another file,
while copying change the case of alphabets and replace all the digits by ‘*’ in
target file.
CODE:

import java.io.*;
class FileHandling
{
public static void main(String args[]) throws IOException
{
FileInputStream fin=new FileInputStream("fruits.txt");
FileOutputStream fout=new FileOutputStream("copied.txt");
int i=0;
while((i=fin.read())!=-1)
{
if(i>=65 && i<=90)
{
i=i+32;
}
else if(i>=97 && i<=123)
{
i=i-32;
}
else if(Character.isDigit(i))
{
i='*';
}
fout.write((byte)i);
}
fout.close();
fin.close();

}
}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

OUTPUT:
D:\docs\slip13>javac FileHandling.java

D:\docs\slip13>java FileHandling
Fruits.txt:
1. Apple
2. Mango
3. Grapes
4. Chicku

copied.txt
*. aPPLE
*. mANGO
*. gRAPES
*. cHICKU
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No:14
Write a Java program which will create a frame if we try to close it, it should
change it’s color and it remains visible on the screen(Use swing).
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
class SFrame extends JFrame
{
JPanel p = new JPanel();
SFrame()
{
setVisible(true);
setSize(400,400);
setTitle("Swing Background");
add(p);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{
p.setBackground(Color.BLACK);
JOptionPane.showMessageDialog(null,"","Close",JOptionPane.
INFORMATION_MESSAGE);
} });
}
public static void main(String args[])
{ new SFrame().show();
}
}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No:15
Define an abstract class Shape with abstract methods area() and volume().
Write a java program to calculate area and volume of Cone and Cylinder.
CODE:
abstract class Shape
{
abstract void area();
abstract void volume();
}
class Cone extends Shape
{
float r,l;
Cone(float r,float l)
{
this.r=r;
this.l=l;
}
void area()
{
double a=3.14*r*(l+r);
System.out.println("Area Of Cone is: "+a);
}
void volume()
{
double v=(3.14*r*r*l)/3;
System.out.println("Volume Of Cone is: "+v);
}
}
class Cylinder extends Shape
{
Float r,h;
Cylinder(float r,float h)
{
this.r=r;
this.h=h;
}
void area()
{
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

double a=3.14*r*r*h;
System.out.println("Area Of Cylinder is: "+a);
}
void volume()
{
double v=2*3.14*r*(r+h);
System.out.println("Volume Of Cylinder is: "+v);
}
}
class Slip15
{
public static void main(String args[])
{
Cylinder cy=new Cylinder(2,3);
Cone cn=new Cone(3,4);
cy.area();
cy.volume();
cn.area();
cn.volume();
}
}
OUTPUT:
D:\docs>javac Slip15.java

D:\docs>java Slip15
Area Of Cylinder is: 37.68
Volume Of Cylinder is: 62.800000000000004
Area Of Cone is: 65.94
Volume Of Cone is: 37.68
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No:16
Write an application in Java using Awt to display 4 X 4 squares on the screen.
One of the block will be active with black color. All other blocks should be
filled with blue color. Provide command buttons as follows to move the active
cell. The active cell should be changed only if it is within the boundary of the
squares otherwise give the beep.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Ass18 extends JFrame implements ActionListener
{
JButton moveBtns[]=new JButton[4];
JPanel gridPanels[]=new JPanel[16];
String icons[]={"Left","Up","Right","Down"};
int cnt=1;
public Ass18()
{
setLayout(new GridLayout(5,4));
for(int i=0;i<16;i++)
{
gridPanels[i]=new JPanel();
add(gridPanels[i]);
gridPanels[i].setBorder(BorderFactory.createLineBorder(Color.black,
1));
gridPanels[i].setBackground(Color.blue);
}
gridPanels[0].setBackground(Color.black);
for(int i=0;i<4;i++)
{
moveBtns[i]=new JButton(icons[i]);
add(moveBtns[i]);
moveBtns[i].addActionListener(this);
}

setSize(300,300);
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

setVisible(true);
setTitle("Grid Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
JButton btn=(JButton) e.getSource();
gridPanels[cnt-1].setBackground(Color.blue);
if(btn==moveBtns[0])
{
if(cnt%4!=1)
cnt--;
}
if(btn==moveBtns[1])
{
if(cnt>4)
cnt=cnt-4;
}
if(btn==moveBtns[2])
{
if(cnt%4!=0)
cnt++;
}
if(btn==moveBtns[3])
{
if(cnt<13)
cnt=cnt+4;
}
gridPanels[cnt-1].setBackground(Color.black);
}

public static void main(String args[])


{
new Ass18().show();
}
}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Output:
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip NO:17
Write a Java program to design a screen using Awt that will take a user name
and password. If the user name and password are not same, raise an
Exception with appropriate message. User can have 3 login chances only. Use
clear button to clear the TextFields

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

class InvalidPasswordException extends Exception


{
}

public class Ass20 extends JFrame implements ActionListener


{
JLabel name, pass;
JTextField nameText;
JPasswordField passText;
JButton login, end;
static int attempt=0;

public Ass20()
{
name = new JLabel("Name:",JLabel.RIGHT);
pass = new JLabel("Password:",JLabel.RIGHT);

nameText = new JTextField(20);


passText = new JPasswordField(20);

login = new JButton("Login");


end = new JButton("End");

login.addActionListener(this);
end.addActionListener(this);

setLayout(new GridLayout(3,2));
add(name);
add(nameText);
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

add(pass);
add(passText);
add(login);
add(end);

setTitle("Login Check");
setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public void actionPerformed(ActionEvent ae)


{
JButton btn = (JButton)ae.getSource();
if(btn == end)
{
System.exit(0);
}
if(btn == login)
{
try
{
String user = nameText.getText();
String pass = new String(passText.getPassword());
if(user.compareTo(pass)==0)
{
JOptionPane.showMessageDialog(null,"Login
Successful","Login",JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
else
{
throw new InvalidPasswordException();
}
}
catch(Exception e)
{
attempt++;
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

JOptionPane.showMessageDialog(null,"Login
Failed","Login",JOptionPane.ERROR_MESSAGE);
nameText.setText("");
passText.setText("");
nameText.requestFocus();
if(attempt == 3)
{
JOptionPane.showMessageDialog(null,"3 Attempts
Over","Login",JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
}
}

public static void main(String args[])


{
new Ass20();
}
}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip NO:18
Write a java program that displays the number of characters, lines & words
from a file.
import java.io.*;
class CountDemo
{
public static void main(String args[]) throws IOException
{
FileInputStream fin=new FileInputStream(args[0]);
int charc=0,wordc=0,linec=0,i;
while((i=fin.read())!=-1)
{
charc++;
if(i==13 || i==32)
{
wordc++;
}
if(i==13)
{
linec++;
}
}
System.out.println("The no. of characters are: "+charc);
System.out.println("The no. of words are: "+ wordc);
System.out.println("The no.of lines are: "+linec);
}
}
OUTPUT:
D:\docs\slip18>javac CountDemo.java
D:\docs\slip18>java CountDemo name.txt
The no. of characters are: 24
The no. of words are: 2
The no.of lines are: 2
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No:19
Write a java program to accept a number from the user, if number is zero
then throw user defined Exception “Number is 0” otherwise calculate the sum
of first and last digit of a given number (Use static keyword).

import java.io.*;
class NumberException extends Exception
{
NumberException()
{
super();
}
}
class SumOfFirstnLast
{
int no;
SumOfFirstnLast() throws IOException
{
System.out.println("Enter the no.: ");
BufferedReader br= new BufferedReader(new
InputStreamReader(System.in));
no=Integer.parseInt(br.readLine());
}
void sum()
{
try
{
if(no==0)
{
throw new NumberException();
}
else
{
int n=no;
int f=n%10;
while(n>=10)
{
n=n/10;
}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

n=f+n;
System.out.println("The sum of first and last digit is:
"+n);
}
}
catch(NumberException ne)
{
System.out.println("Number is Zero");
}
}
public static void main(String args[]) throws IOException
{
SumOfFirstnLast s=new SumOfFirstnLast();
s.sum();
}
}
OUTPUT:
D:\docs\slip19>javac SumOfFirstnLast.java

D:\docs\slip19>java SumOfFirstnLast
Enter the no.:
45
The sum of first and last digit is: 9

D:\docs\slip19>java SumOfFirstnLast
Enter the no.:
0
Number is Zero
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip NO:20
Write a package for Games in Java, which have two classes Indoor and
Outdoor. Use a function display () to generate the list of players for the
specific games. (Use Parameterized constructor, finalize() method and Array
Of Objects)

Indoor.java

package Games;

public class Indoor


{
String player;
public Indoor(String p)
{

player =p;
}
public void display()
{
System.out.println("Player name"+player);
}
protected void finalize()
{
System.out.println("Terminating class Indoor");
}

package Games;

public class Outdoor


{
String player;
public Outdoor(String p)
{

player =p;
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

}
public void display()
{
System.out.println("Player name"+player);
}
protected void finalize()
{
System.out.println("Terminating class Outdoor");
}

package TestGames;
import java.io.*;
import Games.*;

class TestGamesDemo
{

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


{

BufferedReader br =new BufferedReader(new


InputStreamReader(System.in));

Indoor in[] =new Indoor[5];


System.out.println("Enter Palyer name for Indoor Games");
for(int i=0;i<5;i++)
{
String name=br.readLine();
in[i]=new Indoor(name);
}

Outdoor out[] =new Outdoor[5];


System.out.println("Enter player names for Outdoor games");
for(int i=0;i<5;i++)
{
String name=br.readLine();
out[i]=new Outdoor(name);
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

}
System.out.println("Indoor Player List");
for(int j=0;j<5;j++)
{
in[j].display();
}
System.out.println("Outdoor Player List");
for(int j=0;j<5;j++)
{
out[j].display();
}

}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No:21
Write a Java program to design a screen using Swing that will create four
TextFields. First for the text, second for what to find and third for replace.
Display result in the fourth TextField. Display the count of total no. of
replacements made. The button clear to clear the TextFields.
Find and Replace

Enter Text

Text To Find

Text to Replace

No. Of occurrences

Find Replace Clear

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

public class Ass30 extends JFrame implements ActionListener


{
JLabel textLabel, findLabel, replaceLabel, occurrenceLabel;
JTextArea text;
JTextField findText, replaceText, occurrenceText;
JButton find, replace, exit;
JPanel pan1,pan2;
int occurrences=0,i=0;

public Ass30()
{
textLabel = new JLabel("Enter Text:",JLabel.RIGHT);
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

findLabel = new JLabel("Text to Find:",JLabel.RIGHT);


replaceLabel = new JLabel("Text to Replace:",JLabel.RIGHT);
occurrenceLabel = new JLabel("No.of Occurrences:",JLabel.RIGHT);

text = new JTextArea(1,20);


findText = new JTextField(20);
replaceText = new JTextField(20);
occurrenceText = new JTextField(20);

pan1 = new JPanel();


pan1.setLayout(new GridLayout(4,2));
pan1.add(textLabel);
pan1.add(text);
pan1.add(findLabel);
pan1.add(findText);
pan1.add(replaceLabel);
pan1.add(replaceText);
pan1.add(occurrenceLabel);
pan1.add(occurrenceText);

find = new JButton("Find");


replace = new JButton("Replace");
exit = new JButton("Exit");

find.addActionListener(this);
replace.addActionListener(this);
exit.addActionListener(this);

pan2 = new JPanel();


pan2.setLayout(new FlowLayout());
pan2.add(find);
pan2.add(replace);
pan2.add(exit);

add(pan1,"Center");
add(pan2,"South");

setTitle("Find And Replace");


CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

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

public static void main(String[] args)


{
new Ass30();
}

public void actionPerformed(ActionEvent ae)


{
JButton btn = (JButton)ae.getSource();
if(btn == find)
{
String s = text.getText();
String f = findText.getText();
i = s.indexOf(f);
if(i!=-1)
{
occurrences++;
occurrenceText.setText(Integer.toString(occurrences));
text.select(i,i+f.length());
text.requestFocus();

}
}
if(btn == replace)
{
if(text.getSelectedText().length()!=0)
{
String r = replaceText.getText();
text.replaceSelection(r);
}
}
if(btn == exit)
{
System.exit(0);
}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

}
}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No:22
Define an Interface Shape with abstract method area(). Write a java program
to calculate an area of Circle and Sphere.(use final keyword)
import java.io.*;
interface Shape
{
final float pi=3.14f;
float area(int r);
}
class Circle implements Shape
{
public float area(int r)
{
return(pi*r*r);
}
}
class Sphere implements Shape
{
public float area(int r)
{
return(4*pi*r*r);
}
}
class ShapeDemo
{
public static void main(String arg[])
{
int r;
BufferedReader din=new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.print("Enter radius-");
r=Integer.parseInt(din.readLine());
Circle c1=new Circle();
Sphere s1=new Sphere();
System.out.println("Area of Circle:"+c1.area(r));
System.out.println("Area of Sphere:"+s1.area(r));
}
catch(Exception e)
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

{
System.out.println(e.getMessage());
}
}
}
/*Output
D:\javapro\Ass2>javac ShapeDemo.java

D:\javapro\Ass2>java ShapeDemo
Enter radius-5
Area of Circle:78.5
Area of Sphere:314.0
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No:23
Write a java program to accept the details of n Cricket Players from user
(Player code, name, runs, innings- played and number of times not out). The
program should contain following menus:
-Display average runs of a single player.
-Display average runs of all players. (Use array of objects, Method
overloading and static
keyword)

import java.io.*;

class Player
{
String Name;
int TotalRuns, TimesNotOut, InningsPlayed,pcode;
float Avg;
static BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
void getData()
{
try
{
System.out.println("Enter Player Code: ");
pcode=Integer.parseInt(br.readLine());
System.out.println("Enter Player Name: ");
Name = br.readLine();
System.out.println("Enter Total Runs: ");
TotalRuns = Integer.parseInt(br.readLine());
System.out.println("Enter Times Not Out: ");
TimesNotOut = Integer.parseInt(br.readLine());
System.out.println("Enter Innings Played: ");
InningsPlayed = Integer.parseInt(br.readLine());
}
catch(Exception e)
{
System.out.println(e);
}
}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

void putData()
{
System.out.println(pcode + "\t"+
Name+"\t"+TotalRuns+"\t"+TimesNotOut+"\t"+InningsPlayed+"\t"+Avg);
}

void getAvg()
{
Avg= TotalRuns / (InningsPlayed - TimesNotOut);

}
static void getAvg(Player p[],int n)
{
for (int i=0;i<n;i++)
{
p[i].Avg=p[i].TotalRuns / (p[i].InningsPlayed - p[i].TimesNotOut);
}
for (int i=0;i<n;i++)
{
p[i].putData();
}

}
}

public class Ass1


{
static BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
public static void main(String args[])
{
try
{
System.out.println("Enter No.of Players: ");
int n = Integer.parseInt(br.readLine());
Player p[] = new Player[n];
for(int i=0; i<n; i++)
{
p[i] = new Player();
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

p[i].getData();
}

System.out.println("Player Code For Avg Calculation");


int m=Integer.parseInt(br.readLine());
for(int i=0; i<n; i++)
{
if(p[i].pcode==m)
{
p[i].getAvg();
p[i].putData();
}

}
System.out.println("Average Of All The Players");
Player.getAvg(p,n);
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output:

C:\SlipsJava>javac Ass1.java
C:\SlipsJava>java Ass1
Enter No.of Players:
3
Enter Player Code:
101
Enter Player Name:
Sachin
Enter Total Runs:
10000
Enter Times Not Out:
50
Enter Innings Played:
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

60
Enter Player Code:
102
Enter Player Name:
Dhoni
Enter Total Runs:
8500
Enter Times Not Out:
40
Enter Innings Played:
45
Enter Player Code:
103
Enter Player Name:
Dravid
Enter Total Runs:
5550
Enter Times Not Out:
12
Enter Innings Played:
40
Player Code For Avg Calculation
101
101 Sachin 10000 50 60 1000.0
Average Of All The Players
101 Sachin 10000 50 60 1000.0
102 Dhoni 8500 40 45 1700.0
103 Dravid 5550 12 40 198.0
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No:24
Write a Java Program to accept the details of Employee(Eno, EName,Sal)
from the user and display it on the next Frame. (Use AWT)
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class Emp extends Frame implements ActionListener
{
Label l1,l2,l3,l4,l5,l6;
TextField txt1,txt2,txt3,txt4,txt5,txt6;
Button next,cancel; Panel p1,p2,p3;
Label ll;
Emp()
{
ll=new Label("EMPLOYEE INFORMTION");
l1=new Label("Emp No. : -");
l2=new Label("Name : -");
l3=new Label("Address : -");
l4=new Label("Phone/Mobile No. : -");
l5=new Label("Designation : -");
l6=new Label("Salary : -");

txt1=new TextField(20);
txt2=new TextField(20);
txt3=new TextField(20);
txt4=new TextField(20);
txt5=new TextField(20);
txt6=new TextField(20);
next=new Button("NEXT");
next.addActionListener(this);
cancel=new Button("CANCEL");
cancel.addActionListener(this);

p1=new Panel();
p2=new Panel();
p2.setLayout(new GridLayout(1,2));
p2.add(next); p2.add(cancel);
p3=new Panel(); p3.add(ll);
p1.setLayout(new GridLayout(6,2));
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

p1.add(l1);
p1.add(txt1);
p1.add(l2);

p1.add(txt2);
p1.add(l3);
p1.add(txt3);
p1.add(l4);
p1.add(txt4);
p1.add(l5);
p1.add(txt5);
p1.add(l6);
p1.add(txt6);

//Panel Arrangment
add(p3,BorderLayout.NORTH);
add(p1,BorderLayout.CENTER);
add(p2,BorderLayout.SOUTH);

setVisible(true);
setSize(400,400);
}

public void actionPerformed(ActionEvent ae)

{ if(ae.getSource()==next)
{
new
Empdet(txt1.getText(),txt2.getText(),txt3.getText(),txt4.getText(),txt5.getText(),txt
6.getText ());
}
if(ae.getSource()==cancel)
{ System.exit(0);
}

}
public static void main(String args[])
{
new Emp().show(); } }
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No:25
Define an Employee class with suitable attributes having getSalary() method,
which returns salary withdrawn by a particular employee. Write a class
Manager which extends a class Employee, override the getSalary() method,
which will return salary of manager by adding traveling allowance, house rent
allowance etc.

class Emp
{
int eno;
float bsal,gs,tax,pf,ns,ded,da;
String ename;
Emp(int e,String en,float s)
{
eno=e;
ename=en;
bsal=s;
}
float getSalary()
{
da=bsal*0.10f;
gs=bsal+da;
tax=bsal*0.05f;
pf=bsal*0.04f;
ded=tax+pf;
ns=gs-ded;
return (ns);
}
void disp()
{
System.out.println(eno + " "+ename + " " +ns);
}
}
class Manager extends Emp
{
float hra,ta,mns;
Manager(int e,String en,float s,float hr,float t)
{
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

super(e,en,s);
hra=hr;
ta=t;
}
float getSalary()
{
float f=super.getSalary();
mns=f+hra+ta;
return(mns);
}
}
class Ass9
{
public static void main(String args[])
{
Manager mn=new Manager(1,"satyavan",12500.0f,8200.0f,7420.0f);
float som=mn.getSalary();
System.out.println("Salary Of manager Is \t" + som);
}
}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip NO:26
Write a java Program to accept ‘n’ no’s through the command line and store
all the prime no’s and perfect no’s into the different arrays and display both
the arrays.
import java.io.*;
class Ass13
{
public static void main(String args[])
{
int n=args.length;
int pr[]=new int[n];
int per[]=new int[n];
int k=0,i,j;
int sum=0;
//Prime No
for(i=0;i<n;i++)
{
for(j=2;j<Integer.parseInt(args[i]);j++)
{
if(Integer.parseInt(args[i])%j==0)
break;
}
if(Integer.parseInt(args[i])==j)
pr[k++]=Integer.parseInt(args[i]);
}
System.out.println("Prime Array = ");
for(j=0;j<k;j++)
{
System.out.print(" "+pr[j]);
}
//Perfect No
k=0;
for(i=0;i<n;i++)
{
sum=0;
for(j=1;j<Integer.parseInt(args[i]);j++)
{
if(Integer.parseInt(args[i])%j==0)
{
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

sum=sum+j;
}
}
if(sum==Integer.parseInt(args[i]))
{
per[k++]=sum;
}
}
System.out.println("\nPerfect Array = ");
for(i=0;i<k;i++)
{
System.out.print(" "+per[i]);
}
}
}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip NO:27
Write a java program to accept the details employee (Eno, Ename ,Salary)
and add it into the JTable by clicking on the Button.(Max : 5 Records)
import javax.swing.*;

public class MyTable 

JFrame f;

MyTable()

f=new JFrame();

String data[][]={ {"101","Amit","670000"},

{"102","Jai","780000"},

{"101","Sachin","700000"}};

String column[]={"ID","NAME","SALARY"};

JTable jt=new JTable(data,column);

jt.setBounds(30,40,200,300);

JScrollPane sp=new JScrollPane(jt);

f.add(sp);

f.setSize(300,400);

//  f.setLayout(null);

f.setVisible(true);

}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

public static void main(String[] args)

 {

new MyTable();

}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No:28
Write a java program to read n Students names from user, store them into the
ArrayList collection. The program should not allow duplicate names. Display
the names in Ascending order.

import java.util.*;

public class ArrayListDuplicateDemo


{

public static void main(String args[])


{

ArrayList<Integer> primes = new ArrayList<Integer>();


primes.add(7);
primes.add(11);
primes.add(13);
primes.add(2);
primes.add(3);
primes.add(5);
primes.add(7); //duplicate
System.out.println("list of prime numbers : " + primes);
HashSet<Integer> primesWithoutDuplicates = new
HashSet<Integer>(primes);
primes.clear();
primes.addAll(primesWithoutDuplicates);
System.out.println("list of primes without duplicates : " + primes);
TreeSet<Integer> primesWithoutDuplicates1= new
TreeSet<Integer>(primes);
primes.clear();
primes.addAll(primesWithoutDuplicates1);
System.out.println("list of primes without duplicates : " + primes);

}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No:29

Write a java program to accept n employee names from user, store them into
the LinkedList class and display them by using.
a. Iterator Interface
b.ListIterator Interface
CODE:
import java.util.*;
import java.io.*;
class LinkedListDemo
{
public static void main(String args[])throws IOException
{
LinkedList l1= new LinkedList();
int n;
BufferedReader br= new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter number of employess");
n=Integer.parseInt(br.readLine());
for(int i=0; i<n;i++)
{
System.out.println("Enter name");
String s = new String();
s=br.readLine();
l1.add(s);
}
Iterator it= l1.iterator();
System.out.println("Iterator Interface");
while(it.hasNext())
{
System.out.println(it.next());
}
ListIterator li= l1.listIterator();
System.out.println("Listiterator Interface");
while(li.hasNext())
{
System.out.println(li.next());
}
}
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

}
OUTPUT:
D:\Slip29>javac LinkedListDemo.java
D:\Slip29>java LinkedListDemo
Enter number of employess
3
Enter name
fiona
Enter name
prabhu
Enter name
ankita
Iterator Interface
fiona
prabhu
ankita
Listiterator Interface
fiona
prabhu
ankita
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

Slip No: 30
Write an applet application in Java for smile face.

*/
CODE:
import java.awt.*;
import java.applet.*;

public class FaceApplet extends Applet


{

public void paint(Graphics g)


{
g.drawOval(90, 80, 200, 200);
g.drawOval(130, 120, 45, 45);
g.drawOval(210, 120, 45, 45);
g.drawLine(190, 170, 190, 210);
g.drawArc(160, 200, 60, 50, 0, -180);
g.setColor(Color.black);
g.fillOval(135, 123, 30, 30);
g.fillOval(215, 123, 30, 30);
g.drawOval(40,150,50,50);
g.drawOval(290,150,50,50);
}
}
/*<applet code="FaceApplet.class" height=600 width=600></applet>*/
CHRIST COLLEGE, PUNE
T.Y.B.C.A. (Semester-V) Practical Journal 2017-2018
Lab Course-( Java)

You might also like