0% found this document useful (0 votes)
111 views

OOP Lab Manual - A7603 - II Year - 2 Semester - CSM

The document discusses two programming concepts - packages and interfaces in Java. It provides examples to create a package called Measure that contains a Converter class with methods to convert between different units of measurement. It also shows how to create an interface called Student with methods for grade and attendance, and implements this interface in PGStudent and UGStudent classes.

Uploaded by

bharath chandra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views

OOP Lab Manual - A7603 - II Year - 2 Semester - CSM

The document discusses two programming concepts - packages and interfaces in Java. It provides examples to create a package called Measure that contains a Converter class with methods to convert between different units of measurement. It also shows how to create an interface called Student with methods for grade and attendance, and implements this interface in PGStudent and UGStudent classes.

Uploaded by

bharath chandra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

WEEK-6

Objective:After the completion of the practice session, the


student will be able toimplement Packages and Interfaces.

a) Create a Package Measure; in which store a class named Convertor


that contains methods to convert mm to cm, cm to m and m to km.
Define a class Need_Convertor that imports the Convertor class,
now store Need_Convertor outside the package Measure. Perform
path settings accordingly.
package Measure;
public class Converter
{
public float mmtom(float mm)
{
float m=(mm/1000);
return m;
}
public float cmtom(float cm)
{
float m=(cm/100);
return m;
}
public float mtokm(float m)
{
float km=(m/1000);
return km;
}
}

import Measure.*;
public class NeedConverter
{
public static void main(String args[])
{
Converter c=new Converter();
System.out.println(" mm to m is "+c.mmtom(100));
System.out.println(" cm to m is "+c.cmtom(1000));
System.out.println(" m to km is "+c.mtokm(3000));
}
}
Output:

b) Write a Java program that implements an interface Student which


has two methods displayGrade() and attendance(). Implement two
classes PG_Student and UG_Student with necessary inputs of data.

interface Student
{
void displayGrade();
void attendence();
}

class PGStudent implements Student


{
String name;
int rollno;
String grade;
double att;
PGStudent(String n , int r , String g , double a)
{
name = n;
rollno=r;
grade=g;
att = a;
}

public void display()


{
System.out.println("The PG Student data is ");
System.out.println(" Name : " +name +" : "+ "Rollno " + rollno);
}
public void displayGrade()
{
System.out.println("The Grade of PG Student is " +grade);
}

public void attendence()


{
System.out.println("The attendence of PG Student is " +att);
}

}
class UGStudent implements Student
{
String name;
int rollno;
String grade;
double att;

UGStudent(String n , int r , String g , double a)


{
name = n;
rollno=r;
grade=g;
att = a;
}

public void display()


{
System.out.println("The UG Student data is ");
System.out.println(" Name : " +name +" : "+ "Rollno " + rollno);
}

public void displayGrade()


{
System.out.println("The Grade of UG Student is :" +grade);
}

public void attendence()


{
System.out.println("The attendence of UG Student is : " +att);
}
}
public class IntDemo
{
public static void main(String args[])
{
PGStudent s = new PGStudent("Harsha", 1101, "A",78.5);
s.display();
s.attendence();
s.displayGrade();

UGStudent u = new UGStudent("Varsha",5101,"B",68.5);


u.display();
u.attendence();
u.displayGrade();

}
}

Output:
WEEK-7
Objective: After the completion of the practice session, the
student will be able toimplement Exception Handling .
a) Creates a user interface to perform integer divisions. The user
enters two numbers in the text fields, Num1 and Num2. The
division of Num1 andNum2 is displayed in the Result field when the
Div- id button is clicked. If Num1 or Num2 were not an integer, the
program would throw a NumberFormatException. If Num2 is Zero,
the program would throw an ArithmeticException. Display the
exception in a message dialog box.
import java.util.*;
public class ExcepDemo1
{
public static void main (String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number num1");
String s1 = sc.next();
System.out.println("Enter the number2");
String s2=sc.next();
try
{
int num1 = Integer.parseInt(s1);
int num2 = Integer.parseInt(s2);
System.out.println("num1 is " +num1);
System.out.println("num2 is " +num2);
if(num2 ==0)
throw new ArithmeticException ("Division Error");

int res = num1/num2;


System.out.println("The result is " +res);
}
catch(NumberFormatException e)
{
System.out.println("The numbers must be numeric data");
System.out.println("Exception " +e);
}

catch(ArithmeticException e)
{
System.out.println("num2 must not be zero");
System.out.println("Exception" +e);
}
finally
{
System.out.println("Finally block is executed");
}
System.out.println("Remaining statements");
}
}
Output:
b) In the CustomExceptionTest class, the age is expected to be
a positive number. It would throw the user defined
exception NegativeAgeException if the age is assigned a
negative number.

class NegativeAgeException extends Exception


{
NegativeAgeException(String s)
{
super(s);
}

public String toString()


{
return "Age Exception";
}
}

public class ExcepDemo2


{
static void validate(int age) throws NegativeAgeException
{
if(age<0)
throw new NegativeAgeException(" not valid "+age);
else
System.out.println(" welcome to the world " +age);
}
public static void main(String args[])
{
try{
validate(23);
validate(17);
validate(-12);
validate(25); // Not Executed
}
catch(Exception m)
{
System.out.println("Exception occured: No Negative Age");
System.out.println("--- " + m + "---"); // Description of Message
}
finally {
System.out.println("Finally block executed");
}
System.out.println("rest of the code...");
}
}

Output:
WEEK-8
Objective: After the completion of the practice session, the
student will be able todevelop applications on Multithreaded
Programming and thread synchronization.
a) Create a multithreaded java program by creating a subclass of
Thread and then creating, initializing, and staring two Thread
objects from your class. The threads will execute concurrently
and display “Java is object oriented” in console window.
class NewThread extends Thread
{
NewThread(String name)
{
super(name);
//start();
}

public void run()


{
try
{
for(int i=1;i<=4;i++ )
{
System.out.println("Java is object oriented" + getName());
sleep(1000);
}
}
catch (InterruptedException ie)
{
System.out.println("Child Thread - Exception caught");
}
}
}
public class ThreadDemo
{
public static void main(String args[])
{
NewThread t1 = new NewThread("First");
NewThread t2 = new NewThread("Second");

t1.start();
t2.start();
System.out.println("Main
Program");
}
}
b) Implement the concept of producer consumer problem using
thread synchronization.

class Buffer
{
int item;
boolean produced = false;
synchronized void produce(int x)
{
if(produced)
{
try{
wait();
}
catch(InterruptedException ie)
{
System.out.println("Exception Caught");
}
}

item =x;
System.out.println("Producer - Produced-->" +item);
produced =true;
notify();
}

synchronized int consume()


{
if(!produced)
{
try{
wait();
}
catch(InterruptedException ie)
{
System.out.println("Exception Caught " +ie);
}
}

System.out.println("Consumer - Consumed " +item);


produced = false;
notify();
return item;
}
}

class Producer extends Thread


{

Buffer b;
Producer( Buffer b)
{
this.b = b;
start();
}

public void run()


{
b.produce(10);
b.produce(20);
b.produce(30);
b.produce(40);
b.produce(50);

}
}

class Consumer extends Thread


{
Buffer b;

Consumer(Buffer b)
{
this.b = b;
start();
}
public void run()
{

b.consume();
b.consume();
b.consume();
b.consume();

}
}

public class PCDemo


{
public static void main(String args[])
{
Buffer b = new Buffer(); //Synchronized Object
new Producer(b);
new Consumer(b);
}
}
Output:
WEEK-9
Objective: After the completion of the practice session, the
student will be able toimplement Collection Frameworks to
retrieve data.
a) Use an ArrayList to manage Employee objects for insertion,
display and remove.

import java.util.*;
class Employee
{
int eid;
String ename;
double sal;

public Employee(int x, String y, double z)


{
eid=x;
ename=y;
sal = z;
}
}

public class EmpArrayList


{
public static void main(String[] args)
{
ArrayList<Employee> list =new ArrayList<Employee>();
//Creating Employees
Employ e1=new Employee(101,"A.Harsha",75000.50);
Employee e2=new Employee(102,"B.Varsha",85000.50);
Employee e3=new Employee(103,"C.Sirisha",95000.50);
Employee e4=new Employee(104,"D.Sandeep",195000.50);
//Adding Employees to list
list.add(e1);
list.add(e2);
list.add(e3);
list.add(e4);

//Displaying Number of Employees


System.out.println("\n The number of employees is ->" +list.size());

//Displaying Details of Employees


System.out.println("\n The employess data is \n");
for(Employee e:list)
{
System.out.println(e.eid+":"+e.ename+":"+e.sal);
System.out.println();
}
//Deleting an Employee
list.remove(2);
System.out.println("\n After removing number of employees are ->" + list.size());
//Displaying Details of Employees
System.out.println("\n The employess data after removing is \n");
for(Employee e:list)
{
System.out.println(e.eid+":"+e.ename+":"+e.sal);
System.out.println();
}
}
}
Output:
b) Use HashSet methods to perform operations on collection of
data.

import java.util.*;
class HashDemo
{
public static void main(String args[])
{
//Creating HashSet
HashSet<String> set=new HashSet<String>();

//Adding Elements to HashSet - ignores duplicates


set.add("hyderabad");
set.add("hyderabad");
set.add("bangalore");
set.add("chennai");
set.add("kolkata");
set.add("kolkata");
set.add("pune");

Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}

//Removing specific element from HashSet


set.remove("hyderabad");
//Displaying set
System.out.println("\n The list after remove ->" +set);

//adding another set


HashSet<String> set1=new HashSet<String>();
set1.add("Panjab");
set1.add("Delhi");
set.addAll(set1);
System.out.println("\n Updated List is -> "+set);
//removing new set from list
set.removeAll(set1);
System.out.println("\n Updated List is -> "+set);
//Removing all the elements available in the set
set.clear();
System.out.println("\n After clear the set is -> "+set);

}
}
Output:
WEEK-10
Objective: After the completion of the practice session, the student
will be able to implement Collection Frameworks to retrieve data.
a) Implement MouseListener and MouseMotionListener.

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

public class MouseDemo extends Frame implements


MouseListener,MouseMotionListener
{

int x=0, y=0;


String msg= "";

MouseDemo(String title)
{
super(title);
addMouseListener(this);
addMouseMotionListener(this);
setSize(500,500);
setVisible(true);
//window close
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
}
} );

public void mouseClicked(MouseEvent e)


{

msg= "MouseClicked";
x = e.getX();
y = e.getY();
repaint();
}

public void mousePressed(MouseEvent e)


{
msg= "MousePressed";
x = e.getX();
y = e.getY();
repaint();

public void mouseReleased(MouseEvent e)


{
msg = "MouseReleased";
x = e.getX();
y = e.getY();
repaint();

public void mouseEntered(MouseEvent e)


{
msg= "MouseEntered";
x = e.getX();
y = e.getY();
repaint();

public void mouseExited(MouseEvent e)


{
msg= "MouseExited";
x = e.getX();
y = e.getY();
repaint();
}

public void mouseMoved(MouseEvent e)


{
msg= "*";
x = e.getX();
y = e.getY();
repaint();
}

public void mouseDragged(MouseEvent e)


{
msg= "#";
x = e.getX();
y = e.getY();
repaint();
}

public void paint(Graphics g)


{
g.drawString(msg + " at " + x + "," + y, 100,50);
}

public static void main(String[] args)


{

MouseDemo f = new MouseDemo("Mouse Events Handling");


}

Output:

b) Implement KeyListener to handle key events.

import java.awt.*;
import java.awt.event.*;
public class KeyDemo extends Frame implements KeyListener
{
Label l;
TextArea area;
KeyDemo()
{
l=new Label();
l.setBounds(20,50,100,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);

add(l);add(area);
setSize(400,400);
setLayout(null);
setVisible(true);

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
}
});
}

public void keyPressed(KeyEvent e)


{
l.setText("Key Pressed");
}
public void keyReleased(KeyEvent e)
{
l.setText("Key Released");
}

public void keyTyped(KeyEvent e)


{
l.setText("Key Typed");
}

public static void main(String[] args)


{
new KeyDemo();
}
}

Output:
WEEK-11
Objective: After the completion of the practice session, the student
will be able to Develop GUI applications using AWT.

a) Create a Simple login window to validate a user with name and


password.
import java.awt.*;
import java.awt.event.*;
public class LoginDemo extends Frame implements ActionListener
{
Label l1,l2,l3;
TextField t1,t2;
Button b1;
LoginDemo(String name)
{
super(name);
l1=new Label("User Name");
l1.setBounds(20,50,100,20);
//x,y -> top left point , width,height are dimensions
l2=new Label("Password");
l2.setBounds(20,100,100,20);

t1= new TextField();


t1.setBounds(130,50,100,20);

t2= new TextField();


t2.setBounds(130,100,100,20);
t2.setEchoChar('*');

b1= new Button("login");


b1.setBounds(80,150,80,20);

l3 = new Label("->");
l3.setBounds(80,200,200,20);
add(l1);add(t1);
add(l2);add(t2);
add(b1);add(l3);

b1.addActionListener(this);
setSize(400,400);
setLayout(null);
setVisible(true);

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
}});

public void actionPerformed(ActionEvent e)


{
String uname = t1.getText();
String pwd = t2.getText();

if(uname.equals("vce") && pwd.equals("root"))


l3.setText("Welcome to VCE");
else
l3.setText("Invalid Username or Password");
}

public static void main(String[] args)


{
new LoginDemo("Login Window");
}
}

Output:
b) Using Grid Layout design a Simple calculator with
appropriate event handling.

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

//<applet code = "CalsiDemo.class" width = 350 height = 350></applet>

public class CalsiDemo extends Applet implements ActionListener


{
TextField t1;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;
Button add,sub,mul,div, eql,clr,rem;
String msg="",tmp;
int a, b;
public void init()
{
Color c1 = new Color(100,250,100);
setBackground(c1);

GridLayout gl= new GridLayout(5,4,8,8);


setLayout(gl);
t1=new TextField();
b1=new Button("1");
b2=new Button("2");
b3=new Button("3");
b4=new Button("4");
b5=new Button("5");
b6=new Button("6");
b7=new Button("7");
b8=new Button("8");
b9=new Button("9");
b0=new Button("0");
add=new Button("+");
sub=new Button("-");
div=new Button("/");
mul=new Button("*");
eql=new Button("=");
clr = new Button("C");
rem = new Button("%");

add(b7);
add(b8);
add(b9);
add(t1);
add(b4);
add(b5);
add(b6);
add(mul);

add(b1);
add(b2);
add(b3);
add(sub);
add(b0);
add(eql);
add(add);
add(div);
//t1.setBounds(30,30,200,40);
add(clr);
add(rem);

b0.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
div.addActionListener(this);
mul.addActionListener(this);
add.addActionListener(this);
sub.addActionListener(this);
eql.addActionListener(this);
clr.addActionListener(this);
rem.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
String str = ae.getActionCommand();
if(str.equals("+")||str.equals("-")||str.equals("*")||str.equals("/") ||
str.equals("%"))
{
String str1 = t1.getText();
tmp=str;
a = Integer.parseInt(str1);
msg="";
}
else if(str.equals("="))
{
String str2 = t1.getText();
b = Integer.parseInt(str2);
int sum=0;
if(tmp=="+")
sum=a+b;
else if(tmp=="-")
sum=a-b;
else if(tmp=="*")
sum=a*b;
else if(tmp=="/")
sum=a/b;
else if(tmp=="%")
sum=a%b;
else
sum=0;
//String s=String.valueOf(sum); //Converts value to string
t1.setText(""+sum);
msg="";
}
else if(str=="C")
{
t1.setText("");
}
else
{
msg+=str;
t1.setText(""+msg);
}
}

Output:
WEEK-12
Objective: After the completion of the practice session, the student will be
able to Develop GUI applications using Swing Controls.

a) Create a user interface to insert employee details, Display the data


in Text area.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;

public class EmpDemo implements ActionListener


{
String data="EMP:" ;
JFrame jf;
JPanel jp;
JLabel l1,l2,l3,l4,l5,l6;
JTextField t1,t2,t3;
JRadioButton r1,r2;
ButtonGroup bg;
JComboBox jc;
JCheckBox c1,c2,c3;
JButton b1;
JTextArea ta1;
String cities[] = {"HYD", "BNGL","PUNE","DELHI"};

EmpDemo( )
{
jf = new JFrame( ); //Top or High Level Window
jf.setSize(300,300);
jf.setTitle("Demo");
jp = new JPanel(); // lower or second level window

l1 = new JLabel("EMP-ID");

l2 = new JLabel("EMP-NAME");

l3 = new JLabel("Designation");

l4 = new JLabel("Gender");

l5 = new JLabel("CITY");

l6= new JLabel("COMPANY");


t1= new JTextField(30);

t2= new JTextField(30);

t3= new JTextField(30);

r1= new JRadioButton("Male");

r2= new JRadioButton("FeMale");

bg = new ButtonGroup();

bg.add(r1);
bg.add(r2);

jc = new JComboBox(cities);

c1= new JCheckBox("Apple");

c2= new JCheckBox("Google");

c3= new JCheckBox("Microsoft");

b1 = new JButton("Submit");

ta1 = new JTextArea(30,10);

jf.setLayout(new GridLayout(5,4));

jp.add(l1); jp.add(t1);
jp.add(l2); jp.add(t2);
jp.add(l3); jp.add(t3);
jp.add(l4); jp.add(r1);jp.add(r2);
jp.add(l5); jp.add(jc);

jp.add(l6); jp.add(c1); jp.add(c2); jp.add(c3);


jp.add(b1); jp.add(ta1);

jf.add(jp);
jf.setSize(1000,600);
jf.setVisible(true);
b1.addActionListener (this);
}

public void actionPerformed(ActionEvent e)


{
data= data + t1.getText() + ":";
data= data + t2.getText() + ":";
data= data + t3.getText() + ":";

if(r1.isSelected())
data= data+ "Male" +";";
else
data= data+ "FeMale" +";";

String str = (String) jc.getSelectedItem();

data = data + str + ":";

if(c1.isSelected())
data= data + c1.getText();
else if(c2.isSelected())
data=data +c2.getText();
else
data=data+c3.getText();

ta1.setText(data);

}
public static void main(String args[])
{
new EmpDemo();
}
}

Output:
b) Create a JTable to display various fields of Student data like
RollNo, Name, Branch ,Year, Percentage etc.

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
/* import javax.swing.*/

public class JStudent


{

JFrame f;
JTable j;

JStudent()
{

f = new JFrame();

f.setTitle("JTable Example");

String[][] data = {
{ "101", "Rajesh", "CSE","II","78.5"},
{ "102", "Harsha", "CSE","II","87.5"},
{ "103", "Varsha", "CSE","II","65.5"},
{ "104", "Kiran", "IT","II","75.5"},
{ "105", "Karan", "IT","II","87.5"},
};

// Column Names
String[] head = { "RollNo", "Name", "Department","Branch" , "Percentage"};

// Initializing the JTable


j = new JTable(data, head);
j.setBounds(30, 40, 200, 300);

// adding it to JScrollPane
JScrollPane sp = new JScrollPane(j);
f.add(sp);
f.setSize(500, 200);

f.setVisible(true);
}

public static void main(String[] args)


{
new JStudent();
}
}

Output:

You might also like