Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java Lambda Expressions
Next article icon

Passing and Returning Objects in Java

Last Updated : 27 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Although Java is strictly passed by value, the precise effect differs between whether a primitive type or a reference type is passed. When we pass a primitive type to a method, it is passed by value. But when we pass an object to a method, the situation changes dramatically, because objects are passed by what is effectively call-by-reference. Java does this interesting thing that's sort of a hybrid between pass-by-value and pass-by-reference. 
Basically, a parameter cannot be changed by the function, but the function can ask the parameter to change itself via calling some method within it.

  • While creating a variable of a class type, we only create a reference to an object. Thus, when we pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument.
  • This effectively means that objects act as if they are passed to methods by use of call-by-reference.
  • Changes to the object inside the method do reflect the object used as an argument.

Illustration: Let us suppose three objects 'ob1' , 'ob2' and 'ob3' are created: 

ObjectPassDemo ob1 = new ObjectPassDemo(100, 22); ObjectPassDemo ob2 = new ObjectPassDemo(100, 22); ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);
Passing Objects as Parameters and Returning Objects

From the method side, a reference of type Foo with a name a is declared and it's initially assigned to null. 

boolean equalTo(ObjectPassDemo o);
Passing Objects as Parameters and Returning Objects

As we call the method equalTo, the reference 'o' will be assigned to the object which is passed as an argument, i.e. 'o' will refer to 'ob2' as the following statement execute. 

System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));
Passing Objects as Parameters and Returning Objects

Now as we can see, equalTo method is called on 'ob1' , and 'o' is referring to 'ob2'. Since values of 'a' and 'b' are same for both the references, so if(condition) is true, so boolean true will be return. 

if(o.a == a && o.b == b)

Again 'o' will reassign to 'ob3' as the following statement execute. 

System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));
Passing Objects as Parameters and Returning Objects
  • Now as we can see, the equalTo method is called on 'ob1' , and 'o' is referring to 'ob3'. Since values of 'a' and 'b' are not the same for both the references, so if(condition) is false, so else block will execute, and false will be returned.

In Java we can pass objects to methods as one can perceive from the below program as follows:

Example:

Java
// Java Program to Demonstrate Objects Passing to Methods.  // Class // Helper class class ObjectPassDemo {     int a, b;      // Constructor     ObjectPassDemo(int i, int j)     {         a = i;         b = j;     }      // Method     boolean equalTo(ObjectPassDemo o)     {         // Returns true if o is equal to the invoking         // object notice an object is passed as an         // argument to method         return (o.a == a && o.b == b);     } }  // Main class public class GFG {     // MAin driver method     public static void main(String args[])     {         // Creating object of above class inside main()         ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);         ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);         ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);          // Checking whether object are equal as custom         // values         // above passed and printing corresponding boolean         // value         System.out.println("ob1 == ob2: "                            + ob1.equalTo(ob2));         System.out.println("ob1 == ob3: "                            + ob1.equalTo(ob3));     } } 

Output
ob1 == ob2: true ob1 == ob3: false

Defining a constructor that takes an object of its class as a parameter

One of the most common uses of object parameters involves constructors. Frequently, in practice, there is a need to construct a new object so that it is initially the same as some existing object. To do this, either we can use Object.clone() method or define a constructor that takes an object of its class as a parameter.

Example

Java
// Java program to Demonstrate One Object to // Initialize Another  // Class 1 class Box {     double width, height, depth;      // Notice this constructor. It takes an     // object of type Box. This constructor use     // one object to initialize another     Box(Box ob)     {         width = ob.width;         height = ob.height;         depth = ob.depth;     }      // constructor used when all dimensions     // specified     Box(double w, double h, double d)     {         width = w;         height = h;         depth = d;     }      // compute and return volume     double volume() { return width * height * depth; } }  // MAin class public class GFG {     // Main driver method     public static void main(String args[])     {         // Creating a box with all dimensions specified         Box mybox = new Box(10, 20, 15);          //  Creating a copy of mybox         Box myclone = new Box(mybox);          double vol;          // Get volume of mybox         vol = mybox.volume();         System.out.println("Volume of mybox is " + vol);          // Get volume of myclone         vol = myclone.volume();         System.out.println("Volume of myclone is " + vol);     } } 

Output
Volume of mybox is 3000.0 Volume of myclone is 3000.0

Returning Objects

In java, a method can return any type of data, including objects. For example, in the following program, the incrByTen( ) method returns an object in which the value of an (an integer variable) is ten greater than it is in the invoking object.

Example

Java
// Java Program to Demonstrate Returning of Objects  // Class 1 class ObjectReturnDemo {     int a;      // Constructor     ObjectReturnDemo(int i) { a = i; }      // Method returns an object     ObjectReturnDemo incrByTen()     {         ObjectReturnDemo temp             = new ObjectReturnDemo(a + 10);         return temp;     } }  // Class 2 // Main class public class GFG {      // Main driver method     public static void main(String args[])     {          // Creating object of class1 inside main() method         ObjectReturnDemo ob1 = new ObjectReturnDemo(2);         ObjectReturnDemo ob2;          ob2 = ob1.incrByTen();          System.out.println("ob1.a: " + ob1.a);         System.out.println("ob2.a: " + ob2.a);     } } 

Output
ob1.a: 2 ob2.a: 12

Note: When an object reference is passed to a method, the reference itself is passed by use of call-by-value. However, since the value being passed refers to an object, the copy of that value will still refer to the same object that its corresponding argument does. That's why we said that java is strictly pass-by-value.


Next Article
Java Lambda Expressions

G

Gaurav Miglani
Improve
Article Tags :
  • Java
  • School Programming
Practice Tags :
  • Java

Similar Reads

  • Classes and Objects in Java
    In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects, wh
    12 min read
  • Understanding Classes and Objects in Java
    The term Object-Oriented explains the concept of organizing the software as a combination of different types of objects that incorporate both data and behavior. Hence, Object-oriented programming(OOPs) is a programming model, that simplifies software development and maintenance by providing some rul
    10 min read
  • Inner Class in Java
    In Java, inner class refers to the class that is declared inside class or interface which were mainly introduced, to sum up, same logically relatable classes as Java is object-oriented so bringing it closer to the real world. Now geeks you must be wondering why they were introduced? There are certai
    11 min read
  • Anonymous Inner Class in Java
    Nested Classes in Java is prerequisite required before adhering forward to grasp about anonymous Inner class. It is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain "extras" such as o
    7 min read
  • Nested Classes in Java
    In Java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation and creates more readable and maintainable code. The scope of a nested cl
    5 min read
  • Java.util.Objects class in Java
    Java 7 has come up with a new class Objects that have 9 static utility methods for operating on objects. These utilities include null-safe methods for computing the hash code of an object, returning a string for an object, and comparing two objects. Using Objects class methods, one can smartly handl
    7 min read
  • Different Ways to Create Objects in Java
    Java is an object-oriented programming language where objects are instances of classes. Creating objects is one of the most fundamental concepts in Java. In Java, a class provides a blueprint for creating objects. Most of the time, we use the new keyword to create objects but Java also offers severa
    5 min read
  • How are Java Objects Stored in Memory?
    In Java, all objects are dynamically stored in the Heap memory while references to those objects are stored in the stack. Objects are created with the help of "new" keyword and are allocated in the heap memory. However, declaring a variable of a class type does not create an object it only creates r
    5 min read
  • Passing and Returning Objects in Java
    Although Java is strictly passed by value, the precise effect differs between whether a primitive type or a reference type is passed. When we pass a primitive type to a method, it is passed by value. But when we pass an object to a method, the situation changes dramatically, because objects are pass
    6 min read
  • Java Lambda Expressions
    Lambda expressions in Java, introduced in Java SE 8. It represents the instances of functional interfaces (interfaces with a single abstract method). They provide a concise way to express instances of single-method interfaces using a block of code. Key Functionalities of Lambda ExpressionLambda Expr
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences