Java Practical File Ques 1-7
Java Practical File Ques 1-7
ASSIGNMENT */
NAME – Aditi Singh
COLLEGE ROLL NUMBER - 20570020
UNIVERSITY ROLL NUMBER -20033570013
COLLEGE NAME- KALINDI COLLEGE
SUBMITTED TO – Dr. Nidhi Arora Mam
SUBMITTED ON- 12 JUNE,2021
INDEX
SERIAL
QUESTION
NO .
1. Design a class Complex having a real part (x) and an imaginary part
(y). Provide methods to perform the following on complex
numbers:
a) Add two complex numbers.
b) Multiply two complex numbers.
c) toString() method to display complex numbers in the form: x + i y
2. Create a class TwoDim which contains private members as x and y
coordinates in package P1. Define the default constructor, a
parameterized constructor and override toString() method to
display the co-ordinates. Now reuse this class and in package P2
create another class ThreeDim, adding a new dimension as z as ist
private member. Define the constructors for the subclass and
override toString() method in the subclass also. Write appropriate
methods to show dynamic method dispatch. The main() function
should be in a package P.
3. Define an abstract class Shape in package P1. Inherit two more
classes: Rectangle in package P2 and Circle in package P3. Write a
program to ask the user for the type of shape and then using the
concept of dynamic method dispatch, display the area of the
appropriate subclass. Also write appropriate methods to read the
data. The main() function should not be in any package.
4. Create an exception subclass UnderAge, which prints “Under Age”
along with the age value when an object of UnderAge class is
printed in the catch statement. Write a class exceptionDemo in
which the method test() throws UnderAge exception if the
variable age passed to it as argument is less than 18. Write main()
method also to show working of the program.
5. Write a program to implement stack. Use exception handling to
manage underflow and overflow conditions.
6. Write a program that copies content of one file to another. Pass
the names of the files through command-line arguments.
7. Write a program to read a file and display only those lines that
have the first two characters as ‘//’ (Use try with resources).
8. Write a program to create a frame using AWT. Implement
mouseClicked( ), mouseEntered( ) and mouseExited( ) events.
Frame should become visible when mouse enters it.
9. Using AWT, write a program to display a string in frame window
with pink color as background.
10. Using AWT, write a program to create two buttons named “Red”
and “Blue”. When a button is pressed the background color should
be set to the color named by the button’s label.
11. Using AWT, write a program which responds to KEY_TYPED event
and updates the status window with message (“Typed character is:
X”). Use adapter class for other two events.
12. Using AWT, write a program to create two buttons labelled ‘A’ and
‘B’. When button ‘A’ is pressed, it displays your personal
information (Name, Course, Roll No, College) and when button ‘B’
is pressed, it displays your CGPA in previous semester.
13. Rewrite all the above GUI programs using Swing.
Ques 1: Design a class Complex having a real part (x)
and an imaginary part (y). Provide methods to perform
the following on complex numbers:
a) Add two complex numbers.
b) Multiply two complex numbers.
c) toString() method to display complex numbers in the
form: x + i y
CODE
import java.io.*;
class Complex
{
private int x;
private int y;
Complex(int real, int img)
{
x=real;
y=img;
}
Complex Add(Complex o1)
{
Complex temp=new Complex(0,0);
temp.x=this.x+o1.x;
temp.y=this.y+o1.y;
return temp;
}
Complex Multiply(Complex o1)
{
Complex temp= new Complex(0,0);
temp.x=(this.x*o1.x)-(this.y*o1.y);
temp.y=(this.x*o1.y)+(this.y*o1.x);
return temp;
}
public String toString()
{
return x+"+"+y+"i";
}}
public class Practical_1
{
public static void main(String[] args) throws
IOException
{
System.out.println(args[0]);
BufferedReader sd=new BufferedReader(new
InputStreamReader(System.in));
Complex c1 = new Complex(7,8);
Complex c2 = new Complex(9,10);
Complex c3,c4;
System.out.println("Complex 1: " + c1);
System.out.println("Complex 2: " + c2);
String opinion;
do{
int op;
System.out.println("/*/*...MENU DRIVEN
PROGRAM.....*/*/");
System.out.println("Enter 1 for Addition of
two complex numbers");
System.out.println("Enter 2 for Multiplication
of two complex numbers");
System.out.println("Enter your option:");
op=Integer.parseInt(sd.readLine());
switch (op)
{
case 1:
{
System.out.println("Addition of two
complex numbers:");
c3= c1.Add(c2);
System.out.println(c3);
}break;
case 2:
{
System.out.println("Multiplication of
two complex numbers:");
c4=c1.Multiply(c2);
System.out.println(c4);
}break;
default:
System.out.println("The user has entered
an invalid option");
}
System.out.println("Do you want to
continue(N/Y)");
opinion=sd.readLine();
}
while(opinion.equals("Y"));
}
}
OUTPUT:
ref3=new TwoDim(2,4);
System.out.println("Object with two
dimensions:"+ref3);
ref3.perimeter();
//subclass object
ref3=ref2;
ref3=new ThreeDim(1,5,7);
System.out.println("Object with three
dimensions:"+ref3);
ref3.perimeter();
}
}
OUTPUT:
QUES 3: Define an abstract class Shape in package P1.
Inherit two more classes: Rectangle in package P2 and
Circle in package P3. Write a program to ask the user for
the type of shape and then using the concept of dynamic
method dispatch, display the area of the appropriate
subclass. Also write appropriate methods to read the
data. The main() function should not be in any package.
CODE:
// SHAPE CLASS
package P1;
import java.io.IOException;
public abstract class Shape
{
public abstract void getdata() throws
IOException;
public abstract double area() throws
IOException;
}
// RECTANGLE CLASS
package P2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import P1.*;
public class Rectangle extends Shape
{
private double a;
private double b;
public Rectangle()
{
a=1.1;
b=1.1;
}
public void getdata() throws IOException
{
BufferedReader sd=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the length of the
rectangle:");
a=Double.parseDouble(sd.readLine());
System.out.println("Enter the breadth of
the rectangle:");
b=Double.parseDouble(sd.readLine());
}
public double area() throws IOException
{
getdata();
return(a*b);
}
}
// CIRCLE CLASS
package P3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import P1.*;
// MAIN CLASS
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import P3.*;
import P2.*;
import P1.*;
public class Practical_3 {
static int getshapetype() throws IOException
{
BufferedReader ob=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("/*/*/*... MENU DRIVEN
PROGRAM...*/*/*/");
System.out.println("Enter (1) when the
shape is Rectangle");
System.out.println("Enter (2) when the
shape is Circle");
System.out.println("Enter your choice:");
return Integer.parseInt(ob.readLine());
}
public static void main(String[] args) throws
IOException
{
Shape ref;
BufferedReader ob=new BufferedReader(new
InputStreamReader(System.in));
String opinion;
do{
switch(getshapetype())
{
case 1:
{
// Rectangle rec= new Rectangle();
ref = new Rectangle();
double ar= ref.area();
//ref.getdata();
System.out.println("Area of the
rectangle:" +ar+"sq units");
}break;
case 2:
{
ref= new Circle();
double area1=ref.area();
// ref.getdata();
System.out.println("Area of the
circle:"+ area1+"sq units");
}break;
default:
System.out.println("The user has invalid
option");
}
System.out.println("Do you want to
continue(N/Y)");
opinion=ob.readLine();
}while(opinion.equals("Y"));
}
}
OUTPUT:
CODE:
class UnderAge extends Exception
{
private int age;
UnderAge(int a)
{
age=a;
}
public String toString()
{
return "UnderAge"+" "+age;
}
}
class exceptionDemo {
static void test(int m) throws UnderAge
{
System.out.println("Called test("+m+")");
if(m<18)
throw new UnderAge(m);
System.out.println("The age is greater than
18");
}
public static void main(String[] args)
{
try{
test(23);
test(12);
}
catch(UnderAge e)
{
System.out.println("The person is "+" "
+e);
}
}
}
OUTPUT:
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
class Stack
{
private int top;
private int a[];
Stack(int n)
{
top=-1;
a=new int[n];
}
void push(int x)throws StackException
{
if (top==a.length-1)
throw new StackException("Stack is
overflow:could not push "+x);
else
top++;
a[top]=x;
}
void pop()throws StackException
{
if(top==-1)
throw new StackException("Stack is
underflow:could not pop ");
else
System.out.println(a[top]);
top--;
}
}
System.out.println(e.getMessage());
break;
}
}
System.out.println("Popping integers from
stack....");
while (true)
{
try
{
s1.pop();
}catch(StackException e)
{
System.out.println(e.getMessage());
break;
}
}
}
}
OUTPUT:
QUES 6: Write a program that copies content of one file
to another. Pass the names of the files through
command-line arguments.
CODE:
import java.io.*;
class Practical_6 {
i=fin.read();
if(i!=-1)
fout.write((char)i);
} while(i!=-1);
fin.close();
fout.close();
}
catch(IOException e){
System.out.println("File Error");
}
}
OUTPUT:
READ FILE:
FIRST.TXT
// My name is Aditi Singh. I
study in kalindi college. Hello
My name is Reema Narayan.
WRITE FILE:
COPYFILE.TXT
// My name is Aditi Singh. I
study in kalindi college. Hello
My name is Reema Narayan.
QUES 7: Write a program to read a file and display
only those lines that have the first two characters as ‘//’
(Use try with resources).
CODE:
import java.io.*;
try(BufferedReader br=new
BufferedReader(new FileReader(args[0])))
{
String line=br.readLine();
while(line!=null)
{
if(line.length()>0)
{
if(line.charAt(0)=='/' &&
line.charAt(0)=='/')
{
System.out.println(line);
}
}
line=br.readLine();
}
} catch(IOException e){
System.out.println("Error Opening
Files" + e);
}
}
OUTPUT:
READ FILE:
//FIRST.TXT
// My name is Aditi Singh.
I study in kalindi college.
Hello My name is Reema
Narayan.
QUES 8: Write a program to create
a frame using AWT. Implement
mouseClicked( ), mouseEntered( )
and mouseExited( ) events. Frame
should become visible when
mouse enters it.
CODE:
import java.awt.*;
import java.awt.event.*;
// MOUSE EXITED
// MOUSE ENTERED
QUES 9: Using AWT, write a
program to display a string in
frame window with pink color as
background.
CODE:
import java.awt.event.*;
import java.awt.*;
public class Practical_9 extends Frame
{
public Practical_9 ()
{
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
setSize(500,800);
setBackground(Color.PINK);
setForeground(Color.magenta);
setVisible(true);
}
public void paint(Graphics g)
{
g.drawString( "Hello my name is Aditi Singh",20
,50);
}
public static void main(String args[])
{
Practical_9 ob= new Practical_9();
ob.setTitle("PRACTICAL 9");
ob.setVisible(true);
}
}
OUTPUT:
QUES 10: Using AWT, write a
program to create two buttons
named “Red” and “Blue”. When a
button is pressed the background
color should be set to the color
named by the button’s label.
CODE:
import java.awt.*;
import java.awt.event.*;
public class Practical_10 extends Frame implements
ActionListener {
Button red,blue;
public Practical_10()
{
setLayout(new FlowLayout());
red=new Button("RED");
blue= new Button("BLUE");
add(red);
add(blue);
red.addActionListener(this);
blue.addActionListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("RED"))
{
//msg="You pressed Red";
setBackground(Color.RED); }
else
{
// msg="You pressed Blue";
setBackground(Color.BLUE); }
repaint();
}
public void paint(Graphics p)
{
/*p.drawString("Hello", 100, 500);
p.drawString("myself",100,500);
p.drawString("Aditi",100,500);*/
OUTPUT:
// BLUE BUTTON
// RED BUTTON
QUES 11: Using AWT, write a
program which responds to
KEY_TYPED event and updates the
status window with message
(“Typed character is: X”). Use
adapter class for other two
events.
CODE:
import java.awt.*;
import java.awt.event.*;
public class Practical_11 extends Frame {
String msg=" ";
String keystate=" ";
public Practical_11()
{
addKeyListener(new MyKeyAdapter (this));
addWindowListener(new MyWindowAdapter ());
}
public void paint(Graphics g)
{
g.drawString(msg,100,100);
g.drawString(keystate,300,300);
}
public static void main(String args[])
{
Practical_11 pq=new Practical_11();
pq.setSize(new Dimension(300,300));
pq.setTitle("PRACTICAL QUESTION 11");
pq.setVisible(true);
}
}
class MyKeyAdapter extends KeyAdapter
{
Practical_11 ref;
public MyKeyAdapter(Practical_11 ref)
{
this.ref=ref;
}
public void keyTyped(KeyEvent ke)
{
ref. msg=ref.msg+ke.getKeyChar();
ref.keystate="(Typed character is:X)";
ref.setBackground(Color.PINK);
ref.repaint();
}
}
class MyWindowAdapter extends WindowAdapter{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
OUTPUT:
// KEY_TYPED
QUES 12: Using AWT, write a
program to create two buttons
labelled ‘A’ and ‘B’. When button
‘A’ is pressed, it displays your
personal information (Name,
Course, Roll No, College) and
when button ‘B’ is pressed, it
displays your CGPA in previous
semester.
CODE:
import java.awt.*;
import java.awt.event.*;
public class Practical_12 extends Frame implements
ActionListener {
Button a,b;
Label l1,l2,l3,l4,l5;
public Practical_12()
{
setLayout(new FlowLayout());
// CREATE BUTTONS
a=new Button("A");
b= new Button("B");
// CREATE LABELS
l1=new Label("Name: Aditi Singh");
l2=new Label("Roll Number:20570020");
a.addActionListener(this);
b.addActionListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("A"))
{
remove(l5);
l1.setBounds(100,50,150,20);
l1.setBackground(Color.RED);
l2.setBounds(100,100,250,20);
l2.setBackground(Color.GREEN);
l3.setBounds(100,150,350,20);
l3.setBackground(Color.MAGENTA);
l4.setBounds(100,200,450,20);
l4.setBackground(Color.orange);
remove(l5);
add(l1);
add(l2);
add(l3);
add(l4);
else
{
l5.setBounds(100,250,500,20);
l5.setBackground(Color.pink);
remove(l1);
remove(l2);
remove(l3);
remove(l4);
add(l5);
}
repaint();
}
public void paint(Graphics p)
{
p.drawString("HELLO WORLD",20,100);
OUTPUT:
// WHEN A BUTTON IS PRESSED
// WHEN B BUTTON IS PRESSED
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CL
OSE);
jfrm.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
jlab.setText("CLICK RECEIVED");
jfrm.getContentPane().setBackground(Color.R
ED);
jfrm.getContentPane().setForeground(Color.M
AGENTA);
jfrm.repaint();
}
public void mouseEntered(MouseEvent me)
{
mouseX=300;
mouseY=300;
jlab.setText("MOUSE ENTERED");
jfrm.getContentPane(). setBackground(Color.G
REEN);
jfrm.getContentPane().setForeground(Color.P
INK);
jfrm.repaint();
}
public void mouseExited(MouseEvent me)
{
mouseX=300;
mouseY=300;
jlab.setText("MOUSE EXITED");
jfrm.getContentPane().setBackground(Color.c
yan);
jfrm.getContentPane().setForeground(Color.B
LUE);
jfrm.repaint();
}
});
jfrm.add(jlab);
jfrm.setVisible(true);
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawString(msg,mouseX,mouseY);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new Swing8();
}
});
}
}
OUTPUT:
//MOUSE ENTERED
//MOUSE EXITED
//MOUSE CLICKED
import java.awt.*;
import javax.swing.*;
class Swing9 {
Swing9()
{
JFrame j=new JFrame("PRACTICAL QUESTION 9 USING SWI
NG OPERATION");
j.setSize(200,200);
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE
);
JLabel jb= new JLabel("HELLO WORLD");
j.add(jb);
j.getContentPane().setBackground(Color.pink);
j.setVisible(true);
}
public static void main(String args[])
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new Swing9();
}
});
}
}
OUTPUT:
QUESTION 10(USING SWING)
CODE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Swing10 {
JLabel jb;
Swing10()
{
JFrame jf=new JFrame("PRACTICAL QUESTION 10
USING SWING OPERATION");
jf.setSize(500,500);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_
CLOSE);
JButton Red=new JButton("RED");
JButton Blue=new JButton("BLUE");
Red.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent ae)
{
jf.getContentPane().setBackground(Color.RED
);
}
});
Blue.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent ae)
{
jf.getContentPane().setBackground(Color.BLU
E);
}
});
Red.setBounds(50,100,95,30);
Blue.setBounds(100,150,95,30);
jf.add(Red);
jf.add(Blue);
JLabel l=new JLabel("PRESS A BUTTON");
jf.add(l);
jf.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new Swing10();
}
});
}
}
OUTPUT:
//WHEN RED BUTTON IS PRESSED
//WHEN BLUE BUTTON IS PRESSED
QUESTION 11(USING SWING)
CODE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Swing11 extends JFrame {
String msg = "";
String keystate = "";
Swing11() {
setTitle("Swing11 Frame ");
setSize(500, 500);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLO
SE);
addKeyListener(new Myclass(this));
addKeyListener(new Myclass(this));
addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent ke) {
keystate="Typed Character is:";
msg = msg + ke.getKeyChar();
getContentPane().setBackground(Colo
r.PINK);
repaint();
}
});
setVisible(true);
}
public Myclass(Swing11 a) {
this.a = a;
}
// CREATE BUTTONS
a=new JButton("A");
b= new JButton("B");
// CREATE LABELS
l1=new JLabel("Name: Aditi Singh");
a.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent ae)
{
str=" A is Pressed";
l1.setBounds(100,50,150,20);
l2.setBounds(100,100,250,20);
l3.setBounds(100,150,350,20);
l4.setBounds(100,200,450,20);
remove(l5);
add(l1);
add(l2);
add(l3);
add(l4);
getContentPane(). setBackground(Color.magenta);
repaint();
}
});
{
}
b.addActionListener(new ActionListener ()
{
public void actionPerformed(ActionEvent ae)
{
str=" B is Pressed";
l5.setBounds(100,250,500,20);
remove(l1);
remove(l2);
remove(l3);
remove(l4);
add(l5);
getContentPane().setBackground(Color.pink);
repaint();
}
});
add(a);
add(b);
JLabel jb=new JLabel("PRESS A BUTTON",JLabel.CENTER
);
add(jb);
setVisible(true);
}
public void paint(Graphics p)
{
super.paint(p);
p.drawString(str,30,90);
OUTPUT:
//WHEN A BUTTON IS PRESSED