Hi everybody,

I'm new to Java language & was previously working with C++. I'm totally confused as to what is the mechanism of passing variables having

1) built-in datatypes
2) array datatypes
3) user-defined objects as datatypes

to any function. Is it pass by value or reference ? If arguments can be passed in one of the ways, what is the manner in which they can be passed by the other mechanism ? Do pointers or references exist in Java ?

-Jishnu

Function arguments in Java are by value, however, since object and array variables are references themselves, they are effectively by reference (sort of). Objects and arrays passed as parameters can be modified by the method, but the reference itself cannot be changed. This means that a function doSomething(Object someObject) can modify the properties of someObject, but changing the reference someObject to point to some other object will have no effect on the reference in the calling class.

Hi everybody,

Do pointers or references exist in Java ?

-Jishnu

no

> no
There are pointers in Java, just no pointer arithmetic.

and everything is a reference, except primitives. Just not references in the C++ meaning of the word :)

Java is ALWAYS pass by value. When you're passing a reference you're passing a reference by value.

So the following does NOT have any effect in Java:

public void swap(int a, int b) {
  int c = a;
  a = b;
  b = c;
}

when the following C++ would work

public void swap(int& a, int& b)
{
  int& c = a;
  a = b;
  b = c;
}

Effectively everything you pass to a method is final as far as the calling method is concerned (though you CAN call methods on object references passed which affect the state of the objects referred to by those references), changes to the actual method argument value are never reflected outside the method (remember that in Java when you pass an object reference the value passed is that reference, not the object itself so that can change state but cannot be replaced by another object).

> So the following does NOT have any effect in Java
The same would have no effect in C++, you are after all passing primitives. Since no reference variable here, hence no side effects.

true, but the same goes for variables as well.
And a lot of people seem to think that because you pass references in Java you're always passing by reference...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.