0

When I pass an Object to another Class in Java - is this memory consuming or not? Does the object function as some kind of pointer, such as c-language?

Or when passing it to another class's constructor - I am making a copy of the object?

for instance in Android

 Context context

 Class Foo = new Foo(this.context);
tbodt
  • 16,609
  • 6
  • 58
  • 83
user2991252
  • 760
  • 2
  • 11
  • 28

3 Answers3

2

Objects in Java aren't passed at all. Object references are passed by value. Passing references does not copy the contents, so only a few bytes (the size of the reference type) are used when passing them, see here for more clarification: Is Java "pass-by-reference" or "pass-by-value"?

Passing object references to constructors has no specific semantics. It totally depends on the constructor whether it creates copies of the content.

Community
  • 1
  • 1
fpw
  • 801
  • 4
  • 12
2

Object references are actually pointers, they store a memory address. They do not store an actual copy of the object's data. For example, this code in Java:

Object o = new Object();
System.out.println(o.toString());

is the same as this code in C++ (assuming there is an Object class):

Object *o = new Object();
cout << o.toString();

In C++, you can pass an actual copy of the object data if you want to. This is not possible in Java, because it is more efficient to just have a pointer and not consume a lot of memory.

However, if you pass an object to a constructor (or any method), it could do whatever it wants with it, including make a copy of it (using clone) or gather some data from it to use in constructing itself. So the constructor could make a copy, but you are not making a copy just by passing the object to a constructor.

See also: Is Java "pass-by-reference"?

Community
  • 1
  • 1
tbodt
  • 16,609
  • 6
  • 58
  • 83
1

When I pass an Object to another Class in Java To start with, you never pass an object is Java. Everything in Java is Passed by Value. Object are somewhat handled differently. Object references are passed by value. So, if you try to pass an object what is actually happening you are passing a reference of that object. And the called method creates it's own copy of the object reference(passed by value principle). is this memory consuming or not The answer is Yes. As a copy of reference is created 32 bits of memory(In 32 bit JVM) is used on stack to point to same object on heap.

Prateek
  • 1,916
  • 1
  • 12
  • 22