Professional Documents
Culture Documents
Lab Record
of
Name: _
Roll No: _
Year: Sem:
Branch: Section _
OBJECT ORIENTED PROGRAMMING through JAVA
CERTIFICATE
INDEX
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;
Output:
// value a, b, and c
double a = 2.3, b = 4, c = 5.6;
double root1, root2;
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:
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();
}
}
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;}
Overriding
class Dog{
public void bark(){
System.out.println("woof ");
}
}
class Hound extends Dog{
public void sniff(){
System.out.println("sniff ");
}
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
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 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.
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..”);
}
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.
Output:
Or
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:
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);
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: