Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it inefficient to pass large objects as parameters in Java?

Let's say for example I have a class A that creates an instance of a fairly big object B. Is passing B as a parameter to a method in a class C inefficient?

That is, does it just pass a reference or does it shift the object's memory around as well?

Thanks.

like image 244
rtheunissen Avatar asked Jul 29 '11 08:07

rtheunissen


People also ask

Can I pass an object as a parameter Java?

In Java, we can pass a reference to an object (also called a "handle")as a parameter. We can then change something inside the object; we just can't change what object the handle refers to.

Why do we pass objects as parameters in Java?

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.

What is the maximum number of arguments that can be passed to a method in Java?

The number of method parameters is limited to 255 by the definition of a method descriptor (§4.3. 3), where the limit includes one unit for this in the case of instance or interface method invocations. Section §4.3.

Can we pass the objects as parameter?

Passing and Returning Objects in C++ In C++ we can pass class's objects as arguments and also return them from a function the same way we pass and return other variables. No special keyword or header file is required to do so.


1 Answers

It just passes a reference. It's important to understand that the value of any expression in Java is never an object. It's only ever a reference or a primitive value.

This isn't just relevant for parameter passing - it's important to understand for return types, arrays, simple assignment etc.

like image 168
Jon Skeet Avatar answered Sep 22 '22 21:09

Jon Skeet