Passing Objects to Methods in Java Programming Language

In this tutorial, you will learn how to pass objects to methods in java programming.

You will learn what is the advantage of passing objects to methods, how to do that, how it works in detail with example.

Source code for this video tutorial

Code for Box.java

package oops;

public class Box {

  int width;
  int height;
  
  Box(int w, int h){
   width = w;
   height = h;
  }
  
  Box(Box b){
   this.width = b.width;
   this.height = b.height;
  }
  
  boolean isEqual(Box b){
   if(this.width == b.width && this.height == b.height)
    return true;
   else
    return false;
  }
  
  Box duplicate(){
   Box temp = new Box(this.width,this.height);
   return temp;
   
  }
  
  static boolean isTwoObectsEqual(Box b1, Box b2){   
   if(b1.width == b2.width && b1.height == b2.height)
    return true;
   else
    return false;   
  }
  
  void display(){
   System.out.println("Width is "+this.width+" and height is "+this.height);
  }
 
}

Code for Tutorials.java

package oops;

public class Tutorials {

 public static void main(String[] args) {
  
  Box b1 = new Box(10,20);
  Box b2 = new Box(30,40);
  
  Box b3 = new Box(b1);
  
  Box b4 = b2.duplicate();
  
  b1.display();
  b3.display();
  
  b2.display();
  b4.display();
  
  if(b1.isEqual(b2)){
   System.out.println("Both b1 and b2 are eaual");
  }else{
   System.out.println("Both b1 and b2 are not eaual");
  }
  
  
  if(Box.isTwoObectsEqual(b1, b3)){
   System.out.println("Both b1 and b3 are eaual");
  }else{
   System.out.println("Both b1 and b3 are not eaual");
  }
 }
}
Back To Top