You are on page 1of 33

OBJECT ORIENTED PROGRAMMING through JAVA

B V RAJU INSTITUTE OF TECHNOLOGY


(UGC Autonomous, NBA and NAAC
Accredited) Vishnupur, Narsapur, Medak, T.S-
502313

Lab Record
of

OBJECT ORIENTED PROGRAMMING through JAVA

Name: _
Roll No: _
Year: Sem:
Branch: Section _
OBJECT ORIENTED PROGRAMMING through JAVA

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CERTIFICATE

Certified that this is a bonafide record of lab work done by

Mr./Ms. bearing Roll No of Year

Semester B. Tech in the

during the academic year 20 - 20

Internal Examiner External Examiner Signature of HOD


OBJECT ORIENTED PROGRAMMING through JAVA

INDEX

Date of Date of Page Signature/


S.No. Name of the Program
Conduct Submission No. Remarks
Write a JAVA program to display default
1
value of all primitive data types of JAVA.
Write a JAVA program to displays the roots of a
2
quadratic equation ax2+bx+c =0.
Write a JAVA program to give the example
3 for this operator. And also use this
keyword
as return statement.
Write a JAVA program to demonstrate static
4
variables, methods, and blocks.
Write a JAVA program to given the example
5
for super keyword.

6 Write a JAVA program that illustrates simple


inheritance.
Write a JAVA program that illustrates
7
multi-level inheritance
Write a JAVA program demonstrating the
8 difference between method overloading and
method overriding.
Write a JAVA program demonstrating the
9 difference between method overloading and
constructor overloading.
Write a JAVA program that describes exception
10
handling mechanism
Write a JAVA program for example of try
11 and catch block. In this check whether the
given array size is negative or not.
Write a JAVA program to illustrate sub
12
class exception precedence over base class.
Write a JAVA program for creation of user defined
13
exception.
OBJECT ORIENTED PROGRAMMING through JAVA

Write a JAVA program to illustrate creation


of threads using runnable class.(start
method start each of the newly created
14
thread. Inside the run method there is sleep
() for suspend the thread for 500
milliseconds).
Write a JAVA program to create a class
MyThread in this class a constructor, call
the base class constructor, using super and
15 starts the thread. The run method of the
class starts after this. It can be observed
that both main thread and created child
thread are executed concurrently.
Write a JAVA program illustrating multiple
16
inheritance using interfaces.
Write a JAVA program to create a package
17 named pl, and implement this package in
ex1 class.
Write a JAVA program that describes the
18
life cycle of an applet.
Write a JAVA program to create a dialog box
19
and menu.
Write a JAVA program to create a grid
20
layout control.
Write a JAVA program to create a border
21
layout control.
Write a JAVA program to create a padding
22
layout control.
Write a JAVA program to create a
23
simple calculator.
Write a JAVA program that displays the x and
24
y position of the cursor movement using
Mouse.
Write a JAVA program that displays number of
25
characters, lines and words in text file.
OBJECT ORIENTED PROGRAMMING through JAVA

1. Write a JAVA program to display default value of all primitive data types of JAVA.

class Test {

int k;
double d;
float f;
boolean istrue;
String p;

public void printValue() {


System.out.println("int default value = "+ k);
System.out.println("double default value = "+ d);
System.out.println("float default value = "+ f);
System.out.println("boolean default value = "+ istrue);
System.out.println("String default value = "+ p);
}
}

public class HelloWorld {


public static void main(String argv[]) {
Test test = new Test();
test.printValue();
}
}

Output:

int default value = 0


double default value = 0.0
float default value = 0.0
boolean default value = false
String default value = null

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING 1


2. Write a JAVA program to displays the roots of a quadratic equation ax2+bx+c =0.
public class Main {

public static void main(String[] args) {

// value a, b, and c
double a = 2.3, b = 4, c = 5.6;
double root1, root2;

// calculate the determinant (b2 - 4ac)


double determinant = b * b - 4 * a * c;

// check if determinant is greater than 0


if (determinant > 0) {

// two real and distinct roots


root1 = (-b + Math.sqrt(determinant)) / (2 * a);
root2 = (-b - Math.sqrt(determinant)) / (2 * a);

System.out.format("root1 = %.2f and root2 = %.2f", root1, root2);


}

// check if determinant is equal to 0


else if (determinant == 0) {

// two real and equal roots


// determinant is equal to 0
// so -b + 0 == -b
root1 = root2 = -b / (2 * a);
System.out.format("root1 = root2 = %.2f;", root1);
}

// if determinant is less than zero


else {

// roots are complex number and distinct


double real = -b / (2 * a);
double imaginary = Math.sqrt(-determinant) / (2 * a);
System.out.format("root1 = %.2f+%.2fi", real, imaginary);
System.out.format("\nroot2 = %.2f-%.2fi", real, imaginary);
}
}
}

Output:
root1 = -0.87+1.30i and root2 = -0.87-1.30i
3. Write a JAVA program to give the example for this operator. And also use this keyword as
return statement.

class Student{

int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}

class TestThis2{
public static void main(String args[]){
Student s1=new
Student(111,"ankit",5000f); Student
s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}

Output:
111 ankit 5000
112 sumit 6000

class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}

Output: Hello java


4. Write a JAVA program to demonstrate static variables, methods, and blocks.

public class Demo {


static int x = 10;
static int y;
static void func(int z) {
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("z = " + z);
}
static {
System.out.println("Running static initialization block.");
y = x + 5;
}
public static void main(String args[]) {
func(8);
}
}

Output:
Running static initialization
block. x = 10
y = 15
z = 8
5. Write a JAVA program to given the example for super keyword.
class Superclass
{
int num = 100;
}
class Subclass extends Superclass
{
int num = 110;
void printNumber()
{
/* Note that instead of writing num we are
* writing super.num in the print statement
* this refers to the num variable of Superclass
*/
System.out.println(super.num);
}
public static void main(String args[]){
Subclass obj= new Subclass();
obj.printNumber();
}
}

Output: 100
6. Write a JAVA program that illustrates simple inheritance.
class Father {
String
familyName;
String houseaddress;
Father() {
familyName = "Programmer";
houseaddress = "Delhi";
}
}
public class Son extends Father {
String name;
Son() {
name = "Xyz";
}
void printdetails() {
System.out.println("Hey my name is " + this.name + " " + this.familyName +
" and I am from " + this.houseaddress);
}
public static void main(String[] args)
{ Son s1 = new Son();
s1.printdetails();
}
}

Output: Hey my name is Xyz Programmer and I am from Delhi


7. Write a JAVA program that illustrates multi-level inheritance

class Father {
String
familyName;
String houseaddress;
Father() {
familyName = "Programmer";
houseaddress = "Delhi";
}
}
class Son extends Father {
Son() {
System.out.println("I am the Son");
System.out.println("My family name is " + this.familyName + " and I am from
" + this.houseaddress);
}
}
class Daughter extends Father {
Daughter() {
System.out.println("I am the Daughter");
System.out.println("My family name is " + this.familyName + " and I am from
" + this.houseaddress);
}
}
class Main {
public static void main(String[] args) {
Son s = new Son();
Daughter d = new Daughter();
}
}

Output:
I am the Son
My family name is Programmer and I am from Delhi
I am the Daughter
My family name is Programmer and I am from Delhi
8. Write a JAVA program demonstrating the difference between method overloading and method
overriding.

Overloading:
class MethodOverloadingEx{
static int add(int a, int b){return a+b;}
static int add(int a, int b, int c){return a+b+c;}

public static void main(String args[]) {


System.out.println(add(4, 6));
System.out.println(add(4, 6, 7));
}
}
Output:
10
17

Overriding
class Dog{
public void bark(){
System.out.println("woof ");
}
}
class Hound extends Dog{
public void sniff(){
System.out.println("sniff ");
}

public void bark(){


System.out.println("bowl");
}
}

public class OverridingTest{


public static void main(String [] args){
Dog dog = new Hound();
dog.bark();
}
}

Output: bowl
9. Write a JAVA program demonstrating the difference between method overloading
and constructor overloading.

Constructor Overloading:
class Student{
private String
name;
public Student(String n){
name = n;
}
public Student(){
name = "unknown";
}
public void printName(){
System.out.println(name);
}
}
class Cu1{
public static void main(String[] args)
{ Student a = new Student("xyz");
Student b = new Student();
a.printName();
b.printName();
}
}

Output:
xyz
unknown
10. Write a JAVA program that describes exception handling mechanism
class Division {
public static void main(String[] args) {

int a, b, result;
Scanner input = new Scanner(System.in);
System.out.println("Input two
integers"); a = input.nextInt();
b = input.nextInt();

// try block
try {
result = a / b;
System.out.println("Result = " +
result);
}

// catch block
catch (ArithmeticException e) {
System.out.println("Exception caught: Division by zero.");
}
}
}

Output:
Input two integers
6
0
Exception caught: Division by zero.
11. Write a JAVA program for example of try and catch block. In this check whether the given
array size is negative or not.

import java.util.*;
class Neg_Arr_Size_Exep
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Size of Array");
int n=sc.nextInt();
try
{
int[] arr=new int[n];
for(int i=0;i<arr.length;i++)
{
System.out.println("enter "+i+" th element");
arr[i]=sc.nextInt();
}
System.out.println("Elements of Array");
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
catch(NegativeArraySizeException e)
{
System.out.println("Exception Caught: You have Given Negative Array Size");
}
}
}

Output:
Enter Size of Array
5
enter 0 th element
2
enter 1 th element
3
enter 2 th element
4
enter 3 th element
5
enter 4 th element
4
Elements of Array
2
3
4
5
4

Enter Size of Array


-1
Exception Caught: You have Given Negative Array Size
12. Write a JAVA program to illustrate sub class exception precedence over base class.
import java.io.*;
class Parent
{
void msg()throws ArithmeticException
{
System.out.println("parent");
int a=10,b=0;
int c=a/b;
}
}
class TestExceptionChild extends Parent
{
void msg()
{
int arr[]=new int[4];
System.out.println("child");
arr[4]=4;
}
public static void main(String args[]){
Parent p=new TestExceptionChild();
try
{
p.msg();
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception
Caught");
}
}
}

Output:
child
ArrayIndexOutOfBounds Exception Caught
13. Write a JAVA program for creation of user defined exception.

import java.io.*;
class myexception extends Exception
{
myexception(String s)
{
super(s);
}
}
class user
{
public static void main(String argv[])throws myexception
{
int marks=180;
if( marks > 100 )
{
throw new myexception ("marks are more than 100 ");
}
else
System.out.println("marks "+marks);
}
}

Output:
Exception in thread "main" myexception: marks are more than 100
at user.main(user.java:16)
14. Write a JAVA program to illustrate creation of threads using runnable class.(start method start
each of the newly created thread. Inside the run method there is sleep () for suspend the
thread for 500 milliseconds).

class MyThread implements Runnable {


String name;
Thread t;
MyThread (String thread){
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start();
}
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}

class MultiThread {
public static void main(String args[]) {
new MyThread("One");
new MyThread("Two");
new NewThread("Three");
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
Output:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Three: 3
Two: 3
One: 2
Three: 2
Two: 2
One: 1
Three: 1
Two: 1
One exiting.
Two exiting.
Three exiting.
Main thread exiting.
15. Write a JAVA program to create a class MyThread in this class a constructor, call the base
class constructor, using super and starts the thread. The run method of the class starts after
this. It can be observed that both main thread and created child thread are
executedconcurrently.

class MyThread extends Thread


{
MyThread()
{
super (“Using Thread class”);
System.out.println (“Child thread:” + this);
start();
}
public void run()
{
try
{
for ( int i =5; i > 0; i--)
{
System.out.println (“Child thread” + i);
Thread.sleep (500);
}
} catch (InterruptedException e) { }
System.out.println (“exiting child thread …”);
}
}
class TestMyThread
{
public static void main(String args[])
{
new MyThread();
try {
for ( int k = 5; k < 0; k--)
{
System.out.println (“Running main thread :” + k);
Thread.sleep(1000);
}
}catch (InterruptedException e) { }
System.out.println (“Exiting main thread . . .”);
}
}

Output:
Child thread:Thread[Using Thread class,5,main]
Exiting main thread . . .
Child thread5
Child thread4
Child thread3
Child thread2
Child thread1
exiting child thread …
16. Write a JAVA program illustrating multiple inheritance using interfaces.

interface Writeable
{
void writes();
}
interface Readable
{
void reads();

}
class Student implements Readable,Writable
{
public void reads()
{
System.out.print(“Student reads.. ”);
}
public void writes()
{
System.out.print(“ Student writes..”);
}

public static void main(String args[])


{
Student s = new Student();
s.reads();
s.writes();
}
}

Output:
Student reads..
Student writes..

Or

interface MotorBike
{
int speed=50;
public void totalDistance();
}
interface Cycle
{
int distance=150;
public void speed();
}
public class TwoWheeler implements MotorBike,Cycle
{
int totalDistance;
int avgSpeed;
public void totalDistance()
{
totalDistance=speed*distance;
System.out.println("Total Distance Travelled : "+totalDistance);
}
public void speed()
{
int avgSpeed=totalDistance/speed;
System.out.println("Average Speed maintained : "+avgSpeed);
}
public static void main(String args[])
{
TwoWheeler t1=new TwoWheeler();
t1.totalDistance(); t1.speed();
}
}

Output:
Total Distance Travelled : 7500
Average Speed maintained : 150
17. Write a JAVA program to create a package named pl, and implement this package in ex1class.

package p1;
public class ex
{
public ex()
{
System.out.println("Created");
}
public void display()
{
System.out.println("Hello");
}
}

import p1.*;
class ex1
{
public static void main(String[] a)
{
ex e=new ex();
e.display();
}
}

Output:

Hello
18. Write a JAVA program that describes the life cycle of an applet.

*/< applet code = cycle width=200 height=200 >


< / applet >*/

public class cycle extends java.applet. Applet


{
public void init()
{
// Display the this statement at the bottom of the Window
showStatus(“ The applet is initializing …” );
// Pause for a period of time
for(int i = 1;i < 1000000; i++);
}
public void start()
{
showStatus(“ The applet is starting …”);
for(int i =1;i < 1000000;i++);
}
public void destroy()
{
showStatus(“ The applet is being destroyed ...” );
for(int i = 1 ;i < 1000000;i++);
}
}
// After compiling this run the program using appletviewer.
// appletviewer filename (html file name).

Output:

Or

/* <applet code="AppletLifeCycle.class" width="300" height="300"></applet>*/

import java.applet.Applet;
import java.awt.Graphics;
public class AppletLifeCycle extends Applet
{
public void init()
{
System.out.println("1.I am init()");
}
public void start()
{
System.out.println("2.I am start()");
}
public void paint(Graphics g)
{
System.out.println("3.I am paint()");
}
public void stop()
{
System.out.println("4.I am stop()");
}
public void destroy()
{
System.out.println("5.I am destroy()");
}
}
Output:

After minimizing the applet-Output:

After maximizing the applet-Output:

After closing the applet-Output:


19. Write a JAVA program to create a dialog box and menu.

import java.awt.*;
public class DialogExample extends Frame
{
Dialog dialog;
public static void main (String args [ ])
{
DialogExample win = new DialongExample();
}
public DialogExample ( )
{
super (“DialogExample”);
pack ( );
resize (400,400);
addMenus();
createDialog();
show();
}
void addMenus()
{
MenuBar menubar = new MenuBar();
Menu file = new Menu (“File”);
Menu dialog = new Menu
(“Dialog”); file.add (“Quit”);
dialog.add(“Show”);
dialog.add(“Hide”);
menubar.add (file);
menubar.add(file);
menubar.add(dialog);
setMenuBar (menubar);
}
void createDialog ( )
{
dialog = new Dialog (this, “Dialog Box”, false);
dialog.resize (200,200);
}
public boolean handleEvent(Event event)
{
if (event.id = =Event.WINDOW_DESTROY)
{
System.exit (0);
return true;
}
else if (event.id == Event.ACTION_EVENT &&
event.target instanceof MenuItem)
{
if (“Quit.” equals (event.arg) )
{
System.exit (0);
return true;
} else if (“Show”.equals (event.arg ) ) {
dialog.show ( );
return true;
} else
{
dialog.hide ();
return true;
}
}
else
return false;
}

Output:
20. Write a JAVA program to create a grid layout control.
import java.awt.*;
public class grid1 extends Frame
{
public grid1()
{
super (“ Grid Layout 1”);
setLayout (new GridLayout (3, 3, 30, 5) );
add (new Button (“Button 1” ) );
add (new Button (“Button 2”) );
add (new Button ( “Button 3”) );
add (new Button ( “Button 4” ) );
add (new Button (“Button 5” ) );
setBounds(100,100,200,100);
setVisible (true);
}
public static void main(String arg [ ])
{
new grid1();
}
}

Output:
21. Write a JAVA program to create a border layout control.

import java.awt.*;
public class border1 extends Frame
{
public border1()
{
super (“Border Layout 1”);
setFont (new Font (“Helvetica”, Font. PLAIN, 16 ) );
setLayout (new BorderLayout (5, 5));
add ( new Button ("Button 1"),BorderLayout.WEST);
add ( new Button ("Button 2"),BorderLayout.NORTH);
add ( new Button ("Button 3"),BorderLayout.EAST);
add ( new Button ("Button 4"),BorderLayout.SOUTH);
add ( new Button ("Button 5" ),BorderLayout.CENTER);
setBounds(100, 100, 300, 200);
setVisible(true);
}
public static void main (String arg [ ])
{
new border1( );
}

Output:
22. Write a JAVA program to create a padding layout control.

import java.awt.*;
public class border2 extends Frame
{
public border2 ( )
{
super (“Border Layout 1”);
setFont (new Font (“Helvetica”, Font.PLAIN, 16) );
setLayout (new BorderLayout (5, 5) );
Panel p1 = new Panel();
p1.add (new Button (“Button 1”) );
add (“West”, p1);
Panel p2 = new Panel();
p2.add ( new Button (“Button 2” ) );
add( “North”, p2);
Pane1 p3 = new Panel();
p3.add ( new Button (“Button 3”) );
add (“East”, p3);
Pane1 p4 = new Panel();
p4.add ( new Button (“Button 4”) );
add (“South”, p4);
Pane1 p5 = new Panel();
p5.add ( new Button (“Button 5”) );
add (“Center”, p5);
setBounds (100, 100, 300, 200);
setVisible (true);
}
static public void main (String [ ]argv )
{
new border2 ( );
}
}

Output:
23. Write a JAVA program to create a simple calculator.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Appletdemo extends Applet
{
Button b[];
TextField t1;
String txt="";
int no1=0,no2=0,no3=0;
String oprt="";
public void init()
{
b = new Button[16];
for(int i =0; i <= 9; i++)
{
b[i] = new Button(i + "");
}
b[10] = new Button("+");
b[11] = new Button("-");
b[12] = new Button("*");
b[13] = new Button("/");
b[14] = new Button("=");
b[15] = new Button("C");
t1 = new TextField(25);
add(t1);

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


{
add(b[i]);
b[i].addActionListener(new Bh());
}
}
class Bh implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
if (s.equals("+") || s.equals("-") ||
s.equals("*") || s.equals("/") )
{
no1 =
Integer.parseInt(t1.getText()); oprt
= s;
t1.setText(no1+ "");
txt = "";
}
else if (s.equals("C"))
{
no1 = no2 = 0;
txt = "";
t1.setText("");
}
else if (s.equals("="))
{
no2 = Integer.parseInt(t1.getText());
if (oprt.equals("+"))
t1.setText((no1 + no2) + "");
if (oprt.equals("-"))
t1.setText((no1 - no2) + "");
if (oprt.equals("*"))
t1.setText((no1 * no2) + "");
if (oprt.equals("/"))
t1.setText((no1 / no2) + "");
txt = "";
}
else
{
txt = txt + s;
t1.setText(txt);
}
}
}
}

Output:
24. Write a JAVA program that displays the x and y position of the cursor movementusing Mouse.

import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);

l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{ l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e)
{ l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}

Output:
25. Write a JAVA program that displays number of characters, lines and words in text file.

import java.util.*;
import java.io.*;
class Cfile
{
public static void main(String args[])throws IOException
{
int nl=1,nw=0;
char ch;
Scanner scr=new Scanner(System.in);
System.out.print("\nEnter File name: ");
String str=scr.nextLine();
FileInputStream f=new FileInputStream(str);
int n=f.available();
for(int i=0;i<n;i++)
{
ch=(char)f.read();
if(ch=='\n') nl+
+;
else if(ch==' ')
nw++;

}
System.out.println("\nNumber of lines : "+nl);
System.out.println("\nNumber of words : "+(nl+nw));
System.out.println("\nNumber of characters : "+n);

}
}

Output:

You might also like