JAVApractical VIVEKSINGH
JAVApractical VIVEKSINGH
I Year – II Semester
1
Programming in Java
1:- Design a class Complex having a real part (x) and an imaginary part (y).
Provide methods to perform the following on complex numbers:
Code:-
import java.util.*;
class Complex{
int x,y;
Complex(int a,int b)
{x=a;y=b;
}Complex()
{x=0;y=0;
} int addcomplex(Complex o)
{ int a=(x+o.x);
int b=(y+o.y);
System.out.println("Complex number after addition
is="+a+"+"+b+"i");
return 0; }
int mulcomplex(Complex o)
{ int a=x*o.x-y*o.y;
int b=y*o.x+o.y*x;
return 0; }
2
int tostring()
return 0; }}
class Complexp1{
int x,y=0;
x=sc.nextInt();
y=sc.nextInt();
A.tostring();
x=sc.nextInt();
y=sc.nextInt();
B.tostring();
A.addcomplex(B);
A.mulcomplex(B);
sc.close(); }}
Execution:-
3
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 its
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.
Code:-
package P1;
public class TwoDim{
int x,y;
public TwoDim(){}
public TwoDim(int a,int b)
{ x=a;y=b; }
public String toString()
{ return "The coordinates are : "+x+","+y;
}}
package P2;
import P1.*;
public class ThreeDim extends TwoDim{
int z;
public ThreeDim(){
super(); }
public ThreeDim(int a,int b,int c)
4
{ super(a,b);
z=c;
} public String toString()
{ return super.toString()+","+z;
}}
package P;
import P1.*;
import P2.*;
public class Prac2 {
public static void main(String args[]){
TwoDim a = new TwoDim(2,3);
ThreeDim b = new ThreeDim(3,4,5);
System.out.println(a.toString());
System.out.println(b.toString());
}}
Execution:-
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:-
package P1;
5
public abstract class Shape{
public abstract double getArea();}
package P2;
import P1.Shape;
public class Rectangle extends Shape{
double l,b;
public Rectangle(double len, double br){
l = len;
b = br;}
public double getArea(){
double ar = l*b;
System.out.print("The area of the rectangle is : ");
return ar;}
}
package P3;
import P1.Shape;
public class Circle extends Shape{
double rad;
public Circle(double r){
rad = r;}
public double getArea(){
double ar = (3.14)*rad*rad;
System.out.print("The area of the Circle is : ");
return ar;}}
import P1.Shape;
import P2.Rectangle;
import P3.Circle;
import java.util.*;
6
class Prac3{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
Shape sh;
System.out.println("choose option :\n1 For Rectangle \n2 for Circle \n");
int p;
p = sc.nextInt();
if(p==1)
{int l, b;
System.out.println("enter length and breadth");
l = sc.nextInt();
b = sc.nextInt();
sh = new Rectangle(l,b);
System.out.println(sh.getArea());
}else if(p==2)
{int r;
System.out.print("Enter the radius : ");
r = sc.nextInt();
sh = new Circle(r);
System.out.println(sh.getArea());
}else
{System.out.println("Invalid option");}
sc.close();}}
Execution;-
7
Code:-
import java.util.Scanner;
8
public static void main(String[] args) throws UnderAge {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Age ");
int Age = sc.nextInt();
test(Age);
sc.close();
}}
Execution:-
Code:-
import java.util.*;
class Stack{
int size,stk[],tos;
Stack(int s){
9
size=s;
tos = -1; }
{ if(tos<0) {
for(int i=0;i<tos+1;i++)
{ System.out.println(stk[i]+" "); } } }
{ if(tos==size-1) {
else{ stk[++tos]=element; } }
return stk[tos--]; }
int size;
10
size = sc.nextInt();
char ch='y';
int num = 0;
while(ch=='y'||ch=='Y')
num=sc.nextInt();
switch(num)
{ case 1: try{
stack.push(element); }
break;
case 2: try{
break;
is="+stack.peek());}
11
break;
break; }
ch=sc.next().charAt(0); }
sc.close(); }}
Execution:-
12
13
Code:-
import java.io.*;
class Prac6{
public static void main(String args[]) throws IOException
{ int i;
try(FileInputStream fin=new FileInputStream(args[0]);
FileOutputStream fout=new FileOutputStream(args[1]))
{ do{ i=fin.read();
if(i != -1)
{ fout.write(i); }
}while(i != -1);
}catch(IOException e)
{ System.out.println("I/O error"+e); }
System.out.println("File copied sucessfully."); }}
14
Source file:-
15
Code:-
import java.io.*;
import java.util.Scanner;
public class Practical7 {
public static void main(String args[]) throws IOException
{ try(FileInputStream fin = new FileInputStream("Prac7.txt"))
{ Scanner sc = new Scanner(fin);
while(sc.hasNextLine())
{ String line = sc.nextLine();
if(line.startsWith("//"))
{ System.out.println(line); } }
sc.close(); }
catch(Exception e)
{ System.out.println(e); }
finally{ System.out.println("Reached the end of file."); }}}
Execution:-
16
b) Frame should reduce to its original size when mouse is clicked in it. c)
Close the frame when mouse exits it.
Code:-
Import java.awt.*;
Import java.awt.event.*;
MyFrame(){
addMouseListener(new MyMouseAdapter(this));
addWindowListener(new MyWindowAdapter(this));
setSize(width, height);
setBackground(Color.MAGENTA);
setVisible(true);
D= getSize(); }
Public void paint(Graphics g){
g.drawString(msg, 50, 100); }}
classMyMouseAdapterextendsMouseAdapter{
MyFrame Frame;
MyMouseAdapter(MyFrame Frame){
this.Frame=Frame; }
publicvoidmouseClicked(MouseEvent me){
Frame.msg=" MOUSE CLICKED ";
Frame.setSize(Frame.D);
Frame.repaint(); }
publicvoid mouseEntered(MouseEvent me){
Frame.msg=" MOUSE ENTERED ";
Frame.setSize(Frame.D.height*3,Frame.D.width*3);
Frame.repaint(); }
publicvoidmouseExited(MouseEvent me){
Frame.msg=" MOUSE EXITED ";
Frame.repaint();
System.exit(0); }}
classMyWindowAdapterextendsWindowAdapter{
17
MyFrame Frame;
MyWindowAdapter(MyFrame Frame){
this.Frame=Frame; }
publicvoidwindowClosing(WindowEvent we){
Frame.setVisible(false);
//System.exit(0); }}
class Practical8 {
publicstaticvoidmain(String[] args) {
MyFrame F= newMyFrame(); }}
Execution:-
09:-Using AWT, write a program to display a string in frame window with pink
color as background.
Code:-
Import java.awt.Frame;
Import java.awt.FlowLayout;
Import java.awt.Color;
Import java.awt.TextField;
Import java.awt.event.*;
classMyFrameextendsFrame{
publicMyFrame(){
addWindowListener(newMyWindowAdapter());
setBounds(50,50,400,200);
setVisible(true);
setBackground(Color.PINK);
setLayout(newFlowLayout());
18
TextFieldtf= newTextField("THIS TEXT WILL GET DISPLAYED IN
FRAME");
add(tf); }
classMyWindowAdapterextendsWindowAdapter{
publicvoidwindowClosing(WindowEvent we){
System.exit(0); }}}
publicclass Practical9 {
publicstaticvoidmain(String[] args) {
MyFrameobj= newMyFrame(); } }
Execution:-
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:-
Impor tjava.awt.*;
impor tjava.awt.event.*;
19
addWindowListener(new MyWindowAdapter());
setSize(width, height);
setTitle("Practical- 10");
setLayout(newFlowLayout());
b1=new Button("RED");
b1.addActionListener(this);
b1.setBackground(Color.RED);
add(b1);
b2=new Button("BLUE");
b2.addActionListener(this);
b2.setBackground(Color.BLUE);
add(b2);
setVisible(true); }
Public void paint(Graphics g){
g.drawString(msg, 70, 200);; }
publicvoidactionPerformed(ActionEvent e){
Object source = e.getSource();
if(source == b1){
setBackground(Color.RED);
msg="CLICKED ON RED BUTTON ";
repaint(); }
if(source ==b2){
setBackground(Color.BLUE);
msg="CLICKED ON BLUE BUTTON ";
repaint(); } }}
class Practical10{
public static void main(String[] args) {
MyFrame F= newMyFrame(); }}
20
Execution:-
import java.awt.*;
import java.awt.event.*;
myframek (String s)
{ super(s);
setBackground(Color.cyan);
setForeground(Color.gray);
addKeyListener(new MyKeyAdapterk(this));
addWindowListener((WindowListener)new
MyWindowAdapterk(this));}
21
g.drawString(msg2, 100, 130); } }
{ myframek o1;
int counter=0;
{ o1=o3; }
{ counter++;
if(counter<=20)
o1.msg+=Character.toString(ae.getKeyChar());
else if(counter<=40)
o1.msg1+=Character.toString(ae.getKeyChar());
else
o1.msg2+=Character.toString(ae.getKeyChar());
o1.repaint(); } }
{ o1=o5;}
{ o1.setVisible(false); } }
22
o1.setVisible(true); } }
Execution:-
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.*;
class student
int Rollno;
double cgpa;
{ Name=s;
Course=c;
College=cg;
Rollno=roll;
this.cgpa=cgpa; } }
23
Button b1, b2;
Myframebutton2() {
b1=new Button("A");
b2=new Button("B");
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
addWindowListener(new MyWindowAdapterb2(this)); }
String s=ae.getActionCommand();
msg=" ";
if(s.equals("A"))
else if(s.equals("B"))
repaint();
{ g.drawString(msg,100,100); }}
24
class MyWindowAdapterb2 extends WindowAdapter{
Myframebutton2 o1;
MyWindowAdapterb2(Myframebutton2 o2)
{o1=o2;}
{o1.setVisible(false);}}
o1.setTitle("ButtonEventHndling2");
o1.setSize(new Dimension(400,400));
o1.setVisible(true); } }
Execution:-
25
Code:-
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
{String s="Hello";
{Dimension d;
//JFrame o1;
panel p;
Mouse(){
super("MouseEventHndling swings");
p=new panel();
//setTitle(""); setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); d=getSize();
o1=o2; d=d1;}
26
{Dimension d1; d1=o1.getSize();
o1.setSize(d);}
{o1.setVisible(false);}}
SwingUtilities.invokeLater(new Runnable() {
Execution:-
27
class PanelS extends JPanel{
String s="Hello";
100, 100);}}
PanelS p; FrameS()
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(p);
setVisible(true);}}
SwingUtilities.invokeLater(new Runnable()
{new FrameS();}});}}
Execution:-
28
13.(3)- Source Code:-
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new
FlowLayout()); getContentPane().add(b1);
getContentPane().add(b2); b1.addActionListener(this);
b2.addActionListener(this); setVisible(true);}
{String s=ae.getActionCommand();
if(s.equals("Red"))
getContentPane().setBackground(Color.RED);
if(s.equals("Blue")) getContentPane().setBackground(Color.BLUE);}}
SwingUtilities.invokeLater(new Runnable()
}});}}
Execution:-
29
13.(4)- Source Code:-
g.drawString(msg2, 150,170);
g.drawString(msg3, 150,190);}}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); p1=new
PanelK();
30
add(p1);
MyKeyAdapter(PanelK p3){
p2=p3;}
{counter++;
p2.msg2+=ke.getKeyChar();
else
p2.msg3+=ke.getKeyChar();
p2.repaint(); }}}
SwingUtilities.invokeLater(new Runnable()
Execution:-
31
13.(5)- Source Code:-
32
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p1.setLayout(new FlowLayout());
p1.add(b1);
p1.add(b2);
add(p1); b1.addActionListener(this); b2.addActionListener(this);
setVisible(true);}
public void actionPerformed(ActionEvent ae)
{String s=ae.getActionCommand();
if(s.equals("A")){
p1.msg1="Name="+s1.Name; p1.msg2="Course="+s1.Course;
p1.msg3="College="+s1.College; p1.msg4="Rollno="+s1.Rollno;
p1.repaint();}
else if(s.equals("B"))
{p1.msg1="CGPA="+s1.cgpa; p1.msg2=" ";
p1.msg3=" ";
p1.msg4=" ";
p1.repaint();}}}
ublic class ButtonAandB {
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable(){
public void run()
{new Button();}} );}}
Execution:-
33
34