Passing Objects to Methods in Java Programming Language

In this tutorial, you will learn about Passing Objects to Methods in java programming language.

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 Source Code for Box.java

 1 package oops;
 2 
 3 public class Box {
 4 
 5     int width;
 6     int height;
 7     
 8     Box(int w, int h){
 9         width = w;
10         height = h;
11     }
12     
13     Box(Box b){
14         this.width = b.width;
15         this.height = b.height;
16     }
17     
18     boolean isEqual(Box b){
19         if(this.width == b.width && this.height == b.height)
20             return true;
21         else
22             return false;
23     }
24     
25     Box duplicate(){
26         Box temp = new Box(this.width,this.height);
27         return temp;
28         
29     }
30     
31     static boolean isTwoObectsEqual(Box b1, Box b2){   
32         if(b1.width == b2.width && b1.height == b2.height)
33             return true;
34         else
35             return false;   
36     }
37     
38     void display(){
39         System.out.println("Width is "+this.width+" and height is "+this.height);
40     }
41     
42 }


Source Code for Source Code for Tutorials.java

 1 package oops;
 2 
 3 public class Tutorials {
 4 
 5     public static void main(String[] args) {
 6         
 7         Box b1 = new Box(10,20);
 8         Box b2 = new Box(30,40);
 9         
10         Box b3 = new Box(b1);
11         
12         Box b4 = b2.duplicate();
13         
14         b1.display();
15         b3.display();
16         
17         b2.display();
18         b4.display();
19         
20         if(b1.isEqual(b2)){
21             System.out.println("Both b1 and b2 are eaual");
22         }else{
23             System.out.println("Both b1 and b2 are not eaual");
24         }
25         
26         
27         if(Box.isTwoObectsEqual(b1, b3)){
28             System.out.println("Both b1 and b3 are eaual");
29         }else{
30             System.out.println("Both b1 and b3 are not eaual");
31         }
32     }
33 }

Watch this video to learn how this works