Brainware Interview Question
Software Engineer / DevelopersEverything is by value. But note that when you declare an object, the variable is really a reference. Java passes object references by value.
Object obj = new Object();
Here obj is an object reference, and this reference is passed by value (copy of the reference is created) when passed to a method.
it is call by value always.
for primitives, copies of the values are sent.
for objects, copies of the reference is sent.
public void method( object ref)
{
ref= new Object();// when the method finishes, you main method will still have the ref
to the original object..
}
String is an object in java and immutable. Then how the string passed "pass by value" or "pass by reference"?
Like any other Object in Java, a String object is also passed by value (value of the reference to String object is passed). This by no means defeat immutable nature of String objects - that is, if inside the method, you try to change the string object, it will still create a new String object for the modified string either in heap (if creates using new String() constructor) or String constant pool (otherwise).
No.. Java supports both call by value and call by reference.. When primitive types are passed to a function they are passed by value.Objects are always passed call by reference and when u pass reference explicitly then call by value takes place.
- tadivijaykumar July 15, 2011