You are on page 1of 49

Faculty of Engineering and Technology

Subject name : OOPJ


Subject Code : 203105334
B-tech : CSE
Year :3
Semester :5
Name : Ayan Siddiqui
Enrollment No : 190305105250

EXPERIMENT NO 1
AIM: - Write a program to count the number of words that start with a capital letter.

Code:-

//program starts from here

import java.util.*;

class Cap
{
public static void main(String m[])
{
Scanner in=new Scanner(System.in);
String s=new String();
System.out.println("Enter a line:");
s=in.nextLine();
char c;
int ct=0;
for(int i=0;i<s.length();i++)
{
c=s.charAt(i);
if(c>=65 && c<=90)
{
ct++;

}
}
System.out.println("total number of words start with capital letters are :"+ct);
}
}
Faculty of Engineering and Technology
Subject name : OOPJ
Subject Code : 203105334
B-tech : CSE
Year :3
Semester :5
Name : Ayan Siddiqui
Enrollment No : 190305105250

EXPERIMENT NO 1.1
AIM: - Write a java program to take an array of string as an input, and arrange strings in
ascending order.

Code:-

public class SortAsc {    
    public static void main(String[] args) {        
            
        //Initialize array     
        int [] arr = new int [] {5, 2, 8, 7, 1};     
        int temp = 0;    
            
        //Displaying elements of original array    
        System.out.println("Elements of original array: ");    
        for (int i = 0; i < arr.length; i++) {     
            System.out.print(arr[i] + " ");    
        }    
            
        //Sort the array in ascending order    
        for (int i = 0; i < arr.length; i++) {     
            for (int j = i+1; j < arr.length; j++) {     
               if(arr[i] > arr[j]) {    
                   temp = arr[i];    
                   arr[i] = arr[j];    
                   arr[j] = temp;    
               }     
            }     
        }    
          
        System.out.println();    
            
       //Displaying elements of array after sorting    
        System.out.println("Elements of array sorted in ascending order: ");    
        for (int i = 0; i < arr.length; i++) {     
            System.out.print(arr[i] + " ");    
        }    
    }    
}    

Output:

Elements of original array:


5 2 8 7 1
Elements of array sorted in ascending order:
1 2 5 7 8
Faculty of Engineering and Technology
Subject name : OOPJ
Subject Code : 203105334
B-tech : CSE
Year :3
Semester :5
Name : Ayan Siddiqui
Enrollment No : 190305105250

EXPERIMENT NO 2
AIM: - Write a program to find the largest number in an array of numbers using
command line arguments.

Code:-

public class LargestInArrayExample{  
public static int getLargest(int[] a, int total){  
int temp;  
for (int i = 0; i < total; i++)   
        {  
            for (int j = i + 1; j < total; j++)   
            {  
                if (a[i] > a[j])   
                {  
                    temp = a[i];  
                    a[i] = a[j];  
                    a[j] = temp;  
                }  
            }  
        }  
       return a[total-1];  
}  
public static void main(String args[]){  
int a[]={1,2,5,6,3,2};  
int b[]={44,66,99,77,33,22,55};  
System.out.println("Largest: "+getLargest(a,6));  
System.out.println("Largest: "+getLargest(b,7));  
}}  

Output:

Largest: 6
Largest: 99

Faculty of Engineering and Technology


Subject name : OOPJ
Subject Code : 203105334
B-tech : CSE
Year :3
Semester :5
Name : Ayan Siddiqui
Enrollment No : 190305105250

EXPERIMENT NO 2.1
AIM: - Write a program to find factorial of number, Here, take number as command line
argument.

Code:-

// Java program to find the factorial of a number


// using command line arguments

class GFG {

// Method to find factorial of given number


static int factorial(int n)
{
int res = 1, i;
for (i = 2; i <= n; i++)
res *= i;
return res;
}

// Driver code
public static void main(String[] args)
{

// Check if length of args array is


// greater than 0
if (args.length > 0) {

// Get the command line argument and


// Convert it from string type to integer type
int num = Integer.parseInt(args[0]);

// Get the command line argument


// and find the factorial
System.out.println(factorial(num));
}
else
System.out.println("No command line "
+ "arguments found.");
}
}

Output:- No command line arguments found

Faculty of Engineering and Technology


Subject name : OOPJ
Subject Code : 203105334
B-tech : CSE
Year :3
Semester :5
Name : Ayan Siddiqui
Enrollment No : 190305105250
EXPERIMENT NO 3
AIM: - Write a program to demonstrate class and object using concept of an array object.

Code:-

// Java program to demonstrate initializing


// an array of objects using constructor

class GFG {

public static void main(String args[])


{

// Declaring an array of student


Student[] arr;

// Allocating memory for 2 objects


// of type student
arr = new Student[2];

// Initializing the first element


// of the array
arr[0] = new Student(190305105250, "Ayan");

// Initializing the second element


// of the array
arr[1] = new Student(19030510556, "Stark");

// Displaying the student data


System.out.println(
"Student data in student arr 0: ");
arr[0].display();

System.out.println(
"Student data in student arr 1: ");
arr[1].display();
}
}

// Creating a student class with


// id and name as a attributes
class Student {

public int id;


public String name;

// Student class constructor


Student(int id, String name)
{
this.id = id;
this.name = name;
}

// display() method to display


// the student data
public void display()
{
System.out.println("Student id is: " + id + " "
+ "and Student name is: "
+ name);
System.out.println();
}
}

Output
Student data in student arr 0:
Student id is: 190305105250 and Student name is: Ayan

Student data in student arr 1:


Student id is: 19030510556 and Student name is: Stark
Faculty of Engineering and Technology
Subject name : OOPJ
Subject Code : 203105334
B-tech : CSE
Year :3
Semester :5
Name : Ayan Siddiqui
Enrollment No : 190305105250

EXPERIMENT NO 3.1
AIM: - Declare a class box. Overload Box constructions with zero argument, one
argument and three argument to initialize the members of the class. Declare a method to
find the volume of the box.

Code:-

// Java program to illustrate


// Constructor Overloading
class Box
{
double width, height, depth;

// constructor used when all dimensions


// specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}

// constructor used when no dimensions


// specified
Box()
{
width = height = depth = 0;
}

// constructor used when cube is created


Box(double len)
{
width = height = depth = len;
}

// compute and return volume


double volume()
{
return width * height * depth;
}
}

// Driver code
public class Test
{
public static void main(String args[])
{
// create boxes using the various
// constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);

double vol;

// get volume of first box


vol = mybox1.volume();
System.out.println(" Volume of mybox1 is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);

// get volume of cube


vol = mycube.volume();
System.out.println(" Volume of mycube is " + vol);
}
}
Faculty of Engineering and Technology
Subject name : OOPJ
Subject Code : 203105334
B-tech : CSE
Year :3
Semester :5
Name : Ayan Siddiqui
Enrollment No : 190305105250

EXPERIMENT NO 4
AIM: - Write a program to show demonstrate garbage collection using System.gc() or
Runtime.gc()

Code:-

// Java program to demonstrate requesting


// JVM to run Garbage Collector
public class Test
{
public static void main(String[] args) throws InterruptedException
{
Test t1 = new Test();
Test t2 = new Test();

// Nullifying the reference variable


t1 = null;

// requesting JVM for running Garbage Collector


System.gc();

// Nullifying the reference variable


t2 = null;

// requesting JVM for running Garbage Collector


Runtime.getRuntime().gc();

@Override
// finalize method is called on object once
// before garbage collecting it
protected void finalize() throws Throwable
{
System.out.println("Garbage collector called");
System.out.println("Object garbage collected : " + this);
}
}

Garbage collector called


Object garbage collected : Test@46d08f12
Garbage collector called
Object garbage collected : Test@481779b8

Faculty of Engineering and Technology


Subject name : OOPJ
Subject Code : 203105334
B-tech : CSE
Year :3
Semester :5
Name : Ayan Siddiqui
Enrollment No : 190305105250

EXPERIMENT NO 4.1
AIM: - Write a program to show the use of finalize method for garbage collection.

Code:-

class A
{
    int i;
 
    public A(int i)
    {
        this.i = i;
    }
 
    @Override
    protected void finalize() throws Throwable
    {
        System.out.println("From Finalize Method, i = "+i);
 
        //Calling super class finalize() method explicitly
 
        super.finalize();
    }
}
 
public class Test
{
   public static void main(String[] args)
   {
       //Creating two instances of class A
 
       A a1 = new A(10);
 
       A a2 = new A(20);     
 
       //Calling finalize() method of a1 before it is abandoned
       try
       {
           a1.finalize();
       }
       catch (Throwable e)
       {
           e.printStackTrace();
       }
 
       //Assigning a2 to a1
 
       a1 = a2;
 
       //Now both a1 and a2 will be pointing same object
 
       //An object earlier referred by a1 will become abandoned
 
       System.out.println("done");
   }
}

Faculty of Engineering and Technology


Subject name : OOPJ
Subject Code : 203105334
B-tech : CSE
Year :3
Semester :5
Name : Ayan Siddiqui
Enrollment No : 190305105250

EXPERIMENT NO 5
AIM: - Write a program to demonstrate static constants and final constants.

Code:-

Static Constants Example

//Java Program to demonstrate the use of static variable  
class Student{  
   int rollno;//instance variable  
   String name;  
   static String college ="ITS";//static variable  
   //constructor  
   Student(int r, String n){  
   rollno = r;  
   name = n;  
   }  
   //method to display the values  
   void display (){System.out.println(rollno+" "+name+" "+college);}  
}  
//Test class to show the values of objects  
public class TestStaticVariable1{  
 public static void main(String args[]){  
 Student s1 = new Student(111,"Karan");  
 Student s2 = new Student(222,"Aryan");  
 //we can change the college of all objects by the single line of code  
 //Student.college="BBDIT";  
 s1.display();  
 s2.display();  
 }  
}  

Output:

111 Karan ITS


222 Aryan ITS

Final Constants Example

class Bike{  
  final void run(){System.out.println("running");}  
}  
     
class Honda extends Bike{  
   void run(){System.out.println("running safely with 100kmph");}  
     
   public static void main(String args[]){  
   Honda honda= new Honda();  
   honda.run();  
   }  
}  

Output: Compile Time Error

Faculty of Engineering and Technology


Subject name : OOPJ
Subject Code : 203105334
B-tech : CSE
Year :3
Semester :5
Name : Ayan Siddiqui
Enrollment No : 190305105250

EXPERIMENT NO 5.1
AIM: - Write a program to create a class named as bike which consist one final method
called as run(). Declare a subclass Bike & demonstrate the use of final method.

Code:-

class Bike9{  
 final int speedlimit=90;//final variable  
 void run(){  
  speedlimit=400;  
 }  
 public static void main(String args[]){  
 Bike9 obj=new  Bike9();  
 obj.run();  
 }  
}//end of class

Java final method

If you make any method as final, you cannot override it.

Can we initialize blank final variable?

Yes, but only in constructor. For example:

class Bike10{  
  final int speedlimit;//blank final variable  
    
  Bike10(){  
  speedlimit=70;  
  System.out.println(speedlimit);  
  }  
  
  public static void main(String args[]){  
    new Bike10();  
 }  
}  

EXPERIMENT NO 6
AIM: - Write a program to explain static polymorphism in java.

Code:-

One of the ways by which Java supports static polymorphism is method


overloading. An example showing the case of method overloading in static
polymorphism is shown below:
Example:
class SimpleCalculator
{
    int add(int a, int b)
    {
         return a+b;
    }
    int  add(int a, int b, int c)  
    {
         return a+b+c;
    }
}
public class Demo
{
   public static void main(String args[])
   {
  SimpleCalculator obj = new SimpleCalculator();
       System.out.println(obj.add(25, 25));
       System.out.println(obj.add(25, 25, 30));
   }
}

Output of the program


50
80

EXPERIMENT NO 6.1
AIM: - Write a program to find volume of box using concept of method
overloading .

Code:-

This is a Java program to accomplish following task.

1. Create a user-defined package box which has a class definition. For box having
data member and disp( )method . (Assume suitable data )
2. Source file imports above package and calculates the volume of box .

import java.lang.*;

import java.io.*;

Pacakage BoxPackage

public class Box

int length, breadth, height;

Box(int I,int b,int h)


{

Length = l;

breadth= b;

height = h;

public void display()

int volume=length*breadth*height;

System.out.println("Volume of Box is"+volume);

import.BoxPackage.*;

class Boxdemo

public static void main(string args[])

Box b=new Box(10,20,30);

b.display();

}
EXPERIMENT NO 7
AIM: - Write a program to find the factorial of a number using interface.

Code:-

Let's see the factorial program in java using recursion.

class FactorialExample2{  
 static int factorial(int n){    
  if (n == 0)    
    return 1;    
  else    
    return(n * factorial(n-1));    
 }    
 public static void main(String args[]){  
  int i,fact=1;  
  int number=4;//It is the number to calculate factorial    
  fact = factorial(number);   
  System.out.println("Factorial of "+number+" is: "+fact);    
 }  
}  

Output:

Factorial of 4 is: 24
EXPERIMENT NO 7.1
AIM: - Write a program to implement multiple inheritance in java using interface.

Code:-

interface AnimalEat {

void eat();

interface AnimalTravel {

void travel();

class Animal implements AnimalEat, AnimalTravel {

public void eat() {

System.out.println("Animal is eating");

public void travel() {

System.out.println("Animal is travelling");

public class Demo {

public static void main(String args[]) {

Animal a = new Animal();


a.eat();

a.travel();

Output :-

Animal is eating

Animal is travelling

EXPERIMENT NO 7.2
AIM: - Create a package called Mathsoperation1, which contain classes to perform
addition, subtraction, Create another package called Mathoperation2, which must
contain classes to perform multiplication and division operation. Create a main
class and import the Mathsoperation1, Mathsoperation1 package in to perform all
the operations on the input numbers provided by the user. Finally, display the
result of each operation on the console.

Code:-
EXPERIMENT NO 8
AIM: - Write a program to design student registration form using AWT
components.

Code:-

PROCEDURE:
1)Start the program.

2) Create a class frame that extends frame and implements ActionListener interface.

3)Create objects for MenuBar, Menu and MenuItem.

4)Include MenuBar in the frame.

5)Include the menu Registration in the menubar.

6)Include the menuitem Register in the menu.

7)Add all the methods in the interface.

8)Create a class exno9 that extends the frame.

9)Create a class frame1, textfields, labels and buttons in the frame.

10)When the Register menuitem is clicked, the Registration form is displayed.

11)When the Exit menuitem is clicked, the program exits.

12)Stop the program.

SOURCE CODE:

import java.awt.*;
import java.awt.event.*;
class frame extends Frame implements ActionListener
{
Frame f;
frame(String title,Frame f)
{
super(title);
MenuBar mb=new MenuBar();
setMenuBar(mb);
Menu mr=new Menu("Registration");
MenuItem mi=new MenuItem("Register");
MenuItem m1=new MenuItem("-");
MenuItem m=new MenuItem("Exit");
mb.add(mr);
mr.add(mi);
mr.add(m1);
mr.add(m);
mi.addActionListener(this);
m.addActionListener(this);
this.f=f;
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("Register"))
f.setVisible(true);

if(str.equals("Exit"))
System.exit(0);
}
}

class frame1 extends Frame


{
frame1()
{
super("Form_frames");
setLayout(null);

Label b=new Label("Name");


b.setBounds(22,35,60,36);
add(b);

TextField tf=new TextField(30);


tf.setBounds(120,40,200,30);
add(tf);

Label l1=new Label("Register No");


l1.setBounds(22,70,70,40);
add(l1);

TextField tf1=new TextField(30);


tf1.setBounds(120,75,200,30);
add(tf1);

Label l2=new Label("Address");


l2.setBounds(22,110,70,36);
add(l2);

TextField tf2=new TextField(30);


tf2.setBounds(120,115,200,30);
add(tf2);

Label l3=new Label("Phone No");


l3.setBounds(22,150,70,30);
add(l3);

TextField tf3=new TextField(30);


tf3.setBounds(120,150,200,30);
add(tf3);

Button bt=new Button("Save");


bt.setBounds(60,200,70,30);
add(bt);

Button bt1=new Button("View");


bt1.setBounds(150,200,70,30);
add(bt1);
}
}
public class exno9
{
public static void main(String args[])
{
frame1 f=new frame1();
frame f1=new frame("Registration",f);
f1.setVisible(true);
f1.setSize(500,500);
f.setVisible(false);
f.setSize(400,400);
}
}
EXPERIMENT NO 8.1
AIM: - Write a program for Calculator Operations Using AWT controls &
appropriate layout manager.

Code:-

import java.awt.*;

import java.awt.event.*;

public class calculator implements ActionListener

int c,n;

String s1,s2,s3,s4,s5;

Frame f;

Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17;

Panel p;

TextField tf;

GridLayout g;

calculator()

f = new Frame("My calculator");

p = new Panel();

f.setLayout(new FlowLayout());

b1 = new Button("0");
b1.addActionListener(this);

b2 = new Button("1");

b2.addActionListener(this);

b3 = new Button("2");

b3.addActionListener(this);

b4 = new Button("3");

b4.addActionListener(this);

b5 = new Button("4");

b5.addActionListener(this);

b6 = new Button("5");

b6.addActionListener(this);

b7 = new Button("6");

b7.addActionListener(this);

b8 = new Button("7");

b8.addActionListener(this);

b9 = new Button("8");

b9.addActionListener(this);

b10 = new Button("9");

b10.addActionListener(this);

b11 = new Button("+");

b11.addActionListener(this);

b12 = new Button("-");


b12.addActionListener(this);

b13 = new Button("*");

b13.addActionListener(this);

b14 = new Button("/");

b14.addActionListener(this);

b15 = new Button("%");

b15.addActionListener(this);

b16 = new Button("=");

b16.addActionListener(this);

b17 = new Button("C");

b17.addActionListener(this);

tf = new TextField(20);

f.add(tf);

g = new GridLayout(4,4,10,20);

p.setLayout(g);

p.add(b1);p.add(b2);p.add(b3);p.add(b4);p.add(b5);p.add(b6);p.add(b7);p.add(b8
);p.add(b9);

p.add(b10);p.add(b11);p.add(b12);p.add(b13);p.add(b14);p.add(b15);p.add(b16);
p.add(b17);

f.add(p);
f.setSize(300,300);

f.setVisible(true);

public void actionPerformed(ActionEvent e)

if(e.getSource()==b1)

s3 = tf.getText();

s4 = "0";

s5 = s3+s4;

tf.setText(s5);

if(e.getSource()==b2)

s3 = tf.getText();

s4 = "1";

s5 = s3+s4;

tf.setText(s5);

if(e.getSource()==b3)

s3 = tf.getText();
s4 = "2";

s5 = s3+s4;

tf.setText(s5);

}if(e.getSource()==b4)

s3 = tf.getText();

s4 = "3";

s5 = s3+s4;

tf.setText(s5);

if(e.getSource()==b5)

s3 = tf.getText();

s4 = "4";

s5 = s3+s4;

tf.setText(s5);

if(e.getSource()==b6)

s3 = tf.getText();

s4 = "5";

s5 = s3+s4;
tf.setText(s5);

if(e.getSource()==b7)

s3 = tf.getText();

s4 = "6";

s5 = s3+s4;

tf.setText(s5);

if(e.getSource()==b8)

s3 = tf.getText();

s4 = "7";

s5 = s3+s4;

tf.setText(s5);

if(e.getSource()==b9)

s3 = tf.getText();

s4 = "8";

s5 = s3+s4;

tf.setText(s5);
}

if(e.getSource()==b10)

s3 = tf.getText();

s4 = "9";

s5 = s3+s4;

tf.setText(s5);

if(e.getSource()==b11)

s1 = tf.getText();

tf.setText("");

c=1;

if(e.getSource()==b12)

s1 = tf.getText();

tf.setText("");

c=2;

}
if(e.getSource()==b13)

s1 = tf.getText();

tf.setText("");

c=3;

if(e.getSource()==b14)

s1 = tf.getText();

tf.setText("");

c=4;

if(e.getSource()==b15)

s1 = tf.getText();

tf.setText("");

c=5;

if(e.getSource()==b16)
{

s2 = tf.getText();

if(c==1)

n = Integer.parseInt(s1)+Integer.parseInt(s2);

tf.setText(String.valueOf(n));

else

if(c==2)

n = Integer.parseInt(s1)-Integer.parseInt(s2);

tf.setText(String.valueOf(n));

else

if(c==3)

n = Integer.parseInt(s1)*Integer.parseInt(s2);

tf.setText(String.valueOf(n));

if(c==4)

try
{

int p=Integer.parseInt(s2);

if(p!=0)

n=
Integer.parseInt(s1)/Integer.parseInt(s2);

tf.setText(String.valueOf(n));

else

tf.setText("infinite");

catch(Exception i){}

if(c==5)

n = Integer.parseInt(s1)%Integer.parseInt(s2);

tf.setText(String.valueOf(n));

if(e.getSource()==b17)

{
tf.setText("");

public static void main(String[] abc)

calculator v = new calculator();

OUTPUT:

1. Compile: javac calculator.java

2. Run: java calculator

EXPERIMENT NO 9
AIM: - Write a program to demonstrate array index out of bounds exception.

Code:-

Example
import java.util.Arrays;
import java.util.Scanner;

public class AIOBSample {


public static void main(String args[]) {
int[] myArray = {897, 56, 78, 90, 12, 123, 75};
System.out.println("Elements in the array are:: ");
System.out.println(Arrays.toString(myArray));
Scanner sc = new Scanner(System.in);
System.out.println("Enter the index of the required element ::");
int element = sc.nextInt();
System.out.println("Element in the given index is :: "+myArray[element]);
}
}
But if you observe the below output we have requested the element with the index 9 since
it is an invalid index an ArrayIndexOutOfBoundsException raised and the execution
terminated.

Output
Elements in the array are::
[897, 56, 78, 90, 12, 123, 75]
Enter the index of the required element ::
7
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at AIOBSample.main(AIOBSample.java:12)
Handling the exception
You can handle this exception using try catch as shown below.

Example
import java.util.Arrays;
import java.util.Scanner;

public class AIOBSampleHandled {


public static void main(String args[]) {
int[] myArray = {897, 56, 78, 90, 12, 123, 75};
System.out.println("Elements in the array are:: ");
System.out.println(Arrays.toString(myArray));
Scanner sc = new Scanner(System.in);
System.out.println("Enter the index of the required element ::");
try {
int element = sc.nextInt();
System.out.println("Element in the given index is :: "+myArray[element]);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("The index you have entered is invalid");
System.out.println("Please enter an index number between 0 and 6");
}
}
}
Output
Elements in the array are::
[897, 56, 78, 90, 12, 123, 75]
Enter the index of the required element ::
7
The index you have entered is invalid
Please enter an index number between 0 and 6

EXPERIMENT NO 9.1
AIM: - Create an interface Account with two methods deposit and withdraw. Create class
Savings Account which implements the interface. Write a custom Exception handler for
Savings Account to handle the scenarios when withdraw amount is larger than the
balance in the account.

Code:-

class TestAccountInterface

public static void main(String s[])

IAccount account = new HDFCAccount();

System.out.println("Transacting using HDFC Account");

transactOnAccount(account);

System.out.println();

account = new StateBankAccount();

System.out.println("Transacting using State Bank Account");

transactOnAccount(account);

public static void transactOnAccount(IAccount account)


{

System.out.println("------------------------------");

account.deposit(10000.0);

printBalance("depositing 10,000.0", account);

account.withdraw(2500.0);

printBalance("withdrawing 2,500.0", account);

account.withdraw(4100.0);

printBalance("withdrawing 4,100.0", account);

account.deposit(5000.0);

printBalance("depositing 5,000.0", account);

System.out.println("------------------------------");

public static void printBalance(String message, IAccount account)

System.out.println("The balance after " + message + " is " + account.getBalance() +".");

interface IAccount

double getBalance();

void deposit(double amount);

void withdraw(double amount);

}
class HDFCAccount implements IAccount

double deposits;

double withdrawals;

public double getBalance()

return deposits - withdrawals;

public void deposit(double amount)

deposits += amount;

public void withdraw(double amount)

withdrawals += amount;

class StateBankAccount implements IAccount

double balance;

public double getBalance()

{
return balance;

public void deposit(double amount)

balance += amount;

public void withdraw(double amount)

balance -= amount;

OUTPUT

Transacting using HDFC Account

------------------------------

The balance after depositing 10,000.0 is 10000.0.

The balance after withdrawing 2,500.0 is 7500.0.

The balance after withdrawing 4,100.0 is 3400.0.

The balance after depositing 5,000.0 is 8400.0.

------------------------------

Transacting using State Bank Account

------------------------------
The balance after depositing 10,000.0 is 10000.0.

The balance after withdrawing 2,500.0 is 7500.0.

The balance after withdrawing 4,100.0 is 3400.0.

The balance after depositing 5,000.0 is 8400.0.

------------------------------

EXPERIMENT NO 10
AIM: - Write a program to demonstrate class object locking using method level
synchronization.

Code:-

// Java program to illustrate class level lock

class Geek implements Runnable {

public void run() { Lock(); }

public void Lock()

System.out.println(

Thread.currentThread().getName());

synchronized (Geek.class)

System.out.println(

"in block "


+ Thread.currentThread().getName());

System.out.println(

"in block "

+ Thread.currentThread().getName()

+ " end");

public static void main(String[] args)

Geek g1 = new Geek();

Thread t1 = new Thread(g1);

Thread t2 = new Thread(g1);

Geek g2 = new Geek();

Thread t3 = new Thread(g2);

t1.setName("t1");

t2.setName("t2");

t3.setName("t3");

t1.start();

t2.start();

t3.start();

}
}

Output:-
t1

t2

t3

in block t1

in block t1 end

in block t3

in block t3 end

in block t2

in block t2 end

EXPERIMENT NO 10.1
AIM: - Write a program that excludes two threads. One thread will print the even
numbers and another thread will print odd number 1 to 50.

Code:-

// Java program for the above approach

public class GFG {

// Starting counter

int counter = 1;
static int N;

// Function to print odd numbers

public void printOddNumber()

synchronized (this)

// Print number till the N

while (counter < N) {

// If count is even then print

while (counter % 2 == 0) {

// Exception handle

try {

wait();

catch (

InterruptedException e) {

e.printStackTrace();

// Print the number


System.out.print(counter + " ");

// Increment counter

counter++;

// Notify to second thread

notify();

// Function to print even numbers

public void printEvenNumber()

synchronized (this)

// Print number till the N

while (counter < N) {

// If count is odd then print

while (counter % 2 == 1) {

// Exception handle

try {

wait();

catch (
InterruptedException e) {

e.printStackTrace();

// Print the number

System.out.print(

counter + " ");

// Increment counter

counter++;

// Notify to 2nd thread

notify();

// Driver Code

public static void main(String[] args)

// Given Number N

N = 10;

// Create an object of class

GFG mt = new GFG();

// Create thread t1

Thread t1 = new Thread(new Runnable() {

public void run()


{

mt.printEvenNumber();

});

// Create thread t2

Thread t2 = new Thread(new Runnable() {

public void run()

mt.printOddNumber();

});

// Start both threads

t1.start();

t2.start();

---------------------------------------*--------------------------------------------------*-----------------------------*----

Faculty of Engineering and Technology


Subject name : OOPJ
Subject Code : 203105334
B-tech : CSE
Year :3
Semester :5
Name : Ayan Siddiqui
Enrollment No : 190305105250

You might also like