Implicit vs Explicit passing of objects - java

One of the difference between C function and a java method is that the objects are passed explicitly in C and implicitly in Java,
Can any one provide an example of what implicit and explicit passing pls?

I'm not sure what you mean by this, but perhaps you're looking for how object-oriented style is achieved in C.
Java is a true object-oriented language. This means that it has classes and objects. When you write a method that needs to access the object it was called on, one can use the this keyword, which refers to the object in question:
int getSomething()
{
return this._something;
}
So the actual value of the this keyword is dependent of the object - it's then considered as an implicit argument of the parameter.
However, in C, there are no real classes nor objects. If you want to realize OO-style code, you have to pass the argument corresponding to Java's this (i. e., the "object" on which you're calling the "method") explicitly to the function. For example in the cURL networking library:
CURL *hndl = curl_easy_init();
curl_easy_setopt(hndl, CURLOPT_URL, "http://example.com");
curl_easy_perform(hndl);
is roughly equivalent to some OO code like this:
CURL hndl = new CURL;
hndl->setopt(CURLOPT_URL, "http://example.com");
hndl->perform();
Note that in C, the "object" is often called a "context" or a "handle" when writing code in this style.

At least in Java if it's passed by reference, the reference that gets passed, the pointer I recall it's called in C , is a COPY of the original pointer and not the original pointer itself.
So there's a memory area with the information about the object. Then there's a pointer TO that memory area. When Java passes by reference, it first COPIES that pointer to the memory area, then passes that COPY of the pointer as a parameter.
This is all completely separate from the other pass by reference and pass by value distinction.

Related

Java, passing variables/objects into a function [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 9 years ago.
I'm interested to know exactly what's happening under the bonnet when passing a variable or object into a function.
When passing an object or variable into a function, is a new copy of the object/variable created in the new scope? (A set of parentheses constitutes a scope in java right?). Or is the reference to the existing variable/object in memory passed in? Although that would only make sense for a global object/variable?
java is always pass by value so a new variable or reference variable(which refer to some object) will be created in the function to receive the value that has passed to it...
The scope of these variable will be withing that function in which it has created.
One thing you should know that even object are passed by value in java...when people say we pass the object to method ,that time we actually pass the value referred by reference variable not the object...so both the old and new reference variable refer to same object in heap memory..
check this for reference...
http://javadude.com/articles/passbyvalue.htm
http://www.programmerinterview.com/index.php/java-questions/does-java-pass-by-reference-or-by-value/
The easiest way to think of this is to get away from thinking of variables as ever being objects. A reference variable or expression is either null or a pointer to an object of appropriate class for its type.
Under this model, all Java argument passing is by value.
When you pass a reference to a method, you pass the null-or-pointer value to it. Assignment to the argument only affects the argument. It does not affect any variables in the caller's environment. On the other hand, if it is not null it points to the same object as the caller's variable or expression pointed to. Calling a value-changing method in that object changes its value for all code using a pointer to that object, including the caller.
Both - you get a copy of the object reference (for objects), and a copy of the value for primitives.
So unlike C, you can't pass in a variable reference (for a string for example) and end up with it being repointed to something else. And you can't pass in an int, for example, and change it's value within the method - any changes it to it will only be within the method scope.
e.g:
MyObjectHolder holder = new MyObjectHolder();
holder.setObject(new Object());
//holder reference id = 1
// holder.object reference id = 2
doIt(holder);
public void doIt(MyObjectHolder methodScopeHolder) {
// methodScpeHolder reference id = 3
// methodScopeHolder.object reference id = 2
}
In Java your program's "local" variables are maintained in a "stack frame", which is a section of a large array whose elements can contain any data type.
When you call, you copy the parameters (which may be either "scalars" -- chars, ints, floats, etc -- or "references") into a new area of the array (the "top"). Then, during the call, the index values that control which elements of the array you can access are adjusted, and the copied parameters become the "bottom" of a new stack frame, with the called method's local variables being above parameters. So to the new method its copies of the parameters are just like local variables.
Effectively, each method has a "window" into the overall stack, and the "windows" overlap to cover the parameter list.
Of course, when you "pass" an object you're really just passing a reference to the object, and the object itself is not copied.
When you pass a variable, you are passing the reference.
When you pass an object, you are passing a copy of it.

Copy constructor over assignment

After searching a lot, at least this question helped me to understand the difference of using copy constructor and assignment operatorMy question is about this line instance has to be destroyed and re-initialized if it has internal dynamic memory If I initialize an instance like
Object copyObj = null; and then then assign copyObj = realObj then still this overhead (destruction and re-initialization) remains?If not, then Now in this scenario, why should I use Copy Constructor instead of direct assigning the object
The concept of using a copy constructor by overriding the = simply does not exist in Java. You can't override operators. The concept of a copy constructor in Java works like this:
public class MyType {
private String myField;
public MyType(MyType source) {
this.myField = source.myField;
}
}
A copy constructor is a constructor that takes a parameter of the same type and copies all it's values. It is used to get a new object with the same state.
MyType original = new MyType();
MyType copy = new MyType(original);
// After here orginal == copy will be false and original.equals(copy) should be true
MyType referenceCopy = original
// After here orginal == referenceCopy will be true and original.equals(referenceCopy) will also be true
The = operator does the same: Assigning an object to a variable. It produces no overhead. The thing that can differ in runtime is the constructor call.
A Copy constructor allows you to keep two references; one to the "old" object, one to the "new". These objects are independent ( or should be depending upon how deep you allow the copy to be )
If you do a reassignment, you only have a reference to the "new" object. The "old" object will no longer be accessible ( assuming there are no other references to it ) and will be eligible for garbage collection.
It comes down to what it is your trying to achieve. If you want an exact copy of the object, and you want this object to have an independent life of its own, use a copy constructor. If you just want a new object and don't care about the old one, reassign the variable.
PS - I have to admit, I didn't read the question you linked to ..
First some basics about copy construction and copy assignment in C++ and Java
C++ and Java are two very different beasts due to object semantics in C++ and Reference semantics in Java. What I mean by this is:
SomeClass obj = expr;
In C++ this line denotes a new object that gets initialized with expr. In Java, this line creates not a new object but a new reference to an object, and that reference refers to what ever the expression gives. Java references can be null, meaning "no object". C++ objects are, so there is no "no object"-object ;-) Java references are very much like C++ pointers. The only thing that can make the distinction difficult is that while C++ has pointers and objects and dereferences pointers with ->, in Java everything is a reference (except int and a few other basic types), and accessing objects through references uses ., wich easily can be confused with access to "direct" objects in C++. "Everything is a reference" means, that any object (except int & Co.) is conceptually created on the heap.
Having said that, let's have a look at assignments and copies in both languages.
Copy construction means the same in both languages, you essentially create a new object that is a copy of another. Copy constructor definition is similar:
SomeClass(SomeClass obj) { /* ... */ } //Java
SomeClass(SomeClass const& obj) { /* ... */ } //C++
The difference is only that C++ explicitly has to declare the parameter as a reference, while in Java everything is a reference anyways. Writing the first line in C++ would define a constructor that takes it's argument by copy, i.e. the compiler would have to create a copy already, using the copy constructor, for which it has to create a copy,... - not a good idea.
Using copy construction in the two languages will look like this:
SomeClass newObj = new SomeClass(oldObj); //Java
SomeClass newObj = oldObj; //C++ object
SomeClass* ptrNewObj = new SomeClass(oldObj); //C++ pointer
When you look at the first and third line, they look essentially the same. This is because they are essentially the same, since Java references are essentially like pointers in C++. Both expressions create a new object that can outlive the function scope it is created in. The second line creates a plain C++ object on the stack, wich does not exist in Java. In C++, copies are also created implicitly by the compiler eg. when an object is passed to a function that accepts its parameter by value instead of by reference.
Defining copy assignment: In C++, you can define operator= wich (normally) assigns the values of an object to an already existing object, discarding the old values of the object you assign to. If you don't define it yourself, the compiler will do it's best to generate one for you, doing a plain elementwise copy of the objects' elements. In Java, you cannot overload operators, so you will have to define a method, called e.g. assign:
void assign(SomeObject other) {/* ... */} //Java
SomeObject& operator=(SomeObject const& other) {/* ... */} //C++
Note thet here again we explicitly declare the parameter as reference in C++ but not in Java.
Using copy assignment:
objA = objB; //C++ copy assignment
objA = objB; //Java ref assignment
ptrObjA = ptrObjB; //C++ pointer assignment
objA.assign(objB); //Java
objB.change();
Here the first two lines look exactly the same but could not be more different. Remember that in C++, objA and objB deonte the objects themselves, while in Java they are only references. So in C++ this is copy assignment on objects, meaning you finish with two objects that have the same content. After changing objB you will have objA with the value that objB had before the assignment, while objB has changed.
In Java (line 2) that assignment is an assignment of references, meaning after that the two references objA and objB refer to the very same object, while the object previously referred ba objA is not referred to any more and so it will be garbage collected. Calling objB.change() will change the single object both references point to and accessing it through the reference objA will reveal these changes.
Again it's (nearly) the same with C++ pointers. You see you cannot distinguish the syntax of object and pointer assignment, it's all determined by the types that get assigned. The difference with C++ is that it has no garbace collector and you end up with a memory leak because the object ptrObjA pointed to can not be deleted any more.
About your question:
Consider a C++ class:
class X {
int* pi;
unsigned count;
public:
X(X const&);
X& operator= (X const&);
~X();
};
Suppose each X object allocates it's own dynamic array of ints, the pointer to it gets stored in pi. Since C++ has no garbage collection, the X objects have to care themselves for their allocated memory, i.e. they have to destroy it manually:
X::~X() { delete[] pi; }
A copy constructor will copy the dynamic array of the original, so the two do not conflict while using the same array. This is called deep copy and is used equally in Java and C++:
X::X(X const& other) : pi(NULL), count(0) {
pi = new int[other.count]; //allocates own memory
count = other.count;
std::copy(other.pi, other.pi+count, pi); //copies the contents of the array
}
Now to the qoute in your question:
Consider two objects x1 and x2 and the assignment x1 = x2. If you leave everythign to the compiler, it will generate an assignment operator like this:
X& X::operator=(X const& other) {
pi = other.pi;
count = other.count;
}
In the first line x1.pi gets the pointer value of x2.pi. Like I explained in the section about copy assignment, this will lead to both pointers pointing to the same array, and the array previously owned by x1 will be lost in space, meaning you have a leak and odd behavior when both objects work on their shared array.
The correct implementation would be:
X& X::operator=(X const& other) {
delete[] pi; //1
pi = new int[other.count]; //allocates own memory
count = other.count;
std::copy(other.pi, other.pi+count, pi); //copies the contents of the array
}
Here you see what the quote says: First, the object is "cleaed up", i.e. the memory is freed, essentially doing what the destructor does ("instance has to be destroyed").
Then, the deep copy is performed, doing what the copy constructor does ("...and re-initialized").
This is called the "Rule of Three": If you have to write your own copy constructor (because the generated one does not what you want it to do), you will mostly have to write your own destructor and assignment operator as well. Since C++11 it has become the "Rule of Five", because you have move assignment and move construction that have to be considered as well.

Are arrays passed by value or passed by reference in Java? [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 2 years ago.
Arrays are not a primitive type in Java, but they are not objects either, so are they passed by value or by reference? Does it depend on what the array contains, for example references or a primitive type?
Everything in Java is passed by value. In case of an array (which is nothing but an Object), the array reference is passed by value (just like an object reference is passed by value).
When you pass an array to other method, actually the reference to that array is copied.
Any changes in the content of array through that reference will affect the original array.
But changing the reference to point to a new array will not change the existing reference in original method.
See this post: Is Java "pass-by-reference" or "pass-by-value"?
See this working example:
public static void changeContent(int[] arr) {
// If we change the content of arr.
arr[0] = 10; // Will change the content of array in main()
}
public static void changeRef(int[] arr) {
// If we change the reference
arr = new int[2]; // Will not change the array in main()
arr[0] = 15;
}
public static void main(String[] args) {
int [] arr = new int[2];
arr[0] = 4;
arr[1] = 5;
changeContent(arr);
System.out.println(arr[0]); // Will print 10..
changeRef(arr);
System.out.println(arr[0]); // Will still print 10..
// Change the reference doesn't reflect change here..
}
Your question is based on a false premise.
Arrays are not a primitive type in Java, but they are not objects either ... "
In fact, all arrays in Java are objects1. Every Java array type has java.lang.Object as its supertype, and inherits the implementation of all methods in the Object API.
... so are they passed by value or by reference? Does it depend on what the array contains, for example references or a primitive type?
Short answers: 1) pass by value, and 2) it makes no difference.
Longer answer:
Like all Java objects, arrays are passed by value ... but the value is the reference to the array. So, when you assign something to a cell of the array in the called method, you will be assigning to the same array object that the caller sees.
This is NOT pass-by-reference. Real pass-by-reference involves passing the address of a variable. With real pass-by-reference, the called method can assign to its local variable, and this causes the variable in the caller to be updated.
But not in Java. In Java, the called method can update the contents of the array, and it can update its copy of the array reference, but it can't update the variable in the caller that holds the caller's array reference. Hence ... what Java is providing is NOT pass-by-reference.
Here are some links that explain the difference between pass-by-reference and pass-by-value. If you don't understand my explanations above, or if you feel inclined to disagree with the terminology, you should read them.
http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/topic/com.ibm.xlcpp8a.doc/language/ref/cplr233.htm
http://www.cs.fsu.edu/~myers/c++/notes/references.html
Related SO question:
Is Java "pass-by-reference" or "pass-by-value"?
Historical background:
The phrase "pass-by-reference" was originally "call-by-reference", and it was used to distinguish the argument passing semantics of FORTRAN (call-by-reference) from those of ALGOL-60 (call-by-value and call-by-name).
In call-by-value, the argument expression is evaluated to a value, and that value is copied to the called method.
In call-by-reference, the argument expression is partially evaluated to an "lvalue" (i.e. the address of a variable or array element) that is passed to the calling method. The calling method can then directly read and update the variable / element.
In call-by-name, the actual argument expression is passed to the calling method (!!) which can evaluate it multiple times (!!!). This was complicated to implement, and could be used (abused) to write code that was very difficult to understand. Call-by-name was only ever used in Algol-60 (thankfully!).
UPDATE
Actually, Algol-60's call-by-name is similar to passing lambda expressions as parameters. The wrinkle is that these not-exactly-lambda-expressions (they were referred to as "thunks" at the implementation level) can indirectly modify the state of variables that are in scope in the calling procedure / function. That is part of what made them so hard to understand. (See the Wikipedia page on Jensen's Device for example.)
1. Nothing in the linked Q&A (Arrays in Java and how they are stored in memory) either states or implies that arrays are not objects.
Arrays are in fact objects, so a reference is passed (the reference itself is passed by value, confused yet?). Quick example:
// assuming you allocated the list
public void addItem(Integer[] list, int item) {
list[1] = item;
}
You will see the changes to the list from the calling code. However you can't change the reference itself, since it's passed by value:
// assuming you allocated the list
public void changeArray(Integer[] list) {
list = null;
}
If you pass a non-null list, it won't be null by the time the method returns.
No that is wrong. Arrays are special objects in Java. So it is like passing other objects where you pass the value of the reference, but not the reference itself. Meaning, changing the reference of an array in the called routine will not be reflected in the calling routine.
Everything in Java is passed by value .
In the case of the array the reference is copied into a new reference, but remember that everything in Java is passed by value .
Take a look at this interesting article for further information ...
The definitive discussion of arrays is at http://docs.oracle.com/javase/specs/jls/se5.0/html/arrays.html#27803 . This makes clear that Java arrays are objects. The class of these objects is defined in 10.8.
Section 8.4.1 of the language spec, http://docs.oracle.com/javase/specs/jls/se5.0/html/classes.html#40420 , describe how arguments are passed to methods. Since Java syntax is derived from C and C++, the behavior is similar. Primitive types are passed by value, as with C. When an object is passed, an object reference (pointer) is passed by value, mirroring the C syntax of passing a pointer by value. See 4.3.1, http://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#4.3 ,
In practical terms, this means that modifying the contents of an array within a method is reflected in the array object in the calling scope, but reassigning a new value to the reference within the method has no effect on the reference in the calling scope, which is exactly the behavior you would expect of a pointer to a struct in C or an object in C++.
At least part of the confusion in terminology stems from the history of high level languages prior to the common use of C. In prior, popular, high level languages, directly referencing memory by address was something to be avoided to the extent possible, and it was considered the job of the language to provide a layer of abstraction. This made it necessary for the language to explicitly support a mechanism for returning values from subroutines (not necessarily functions). This mechanism is what is formally meant when referring to 'pass by reference'.
When C was introduced, it came with a stripped down notion of procedure calling, where all arguments are input-only, and the only value returned to the caller is a function result. However, the purpose of passing references could be achieved through the explicit and broad use of pointers. Since it serves the same purpose, the practice of passing a pointer as a reference to a value is often colloquially referred to a passing by reference. If the semantics of a routine call for a parameter to be passed by reference, the syntax of C requires the programmer to explicitly pass a pointer. Passing a pointer by value is the design pattern for implementing pass by reference semantics in C.
Since it can often seem like the sole purpose of raw pointers in C is to create crashing bugs, subsequent developments, especially Java, have sought to return to safer means to pass parameters. However, the dominance of C made it incumbent on the developers to mimic the familiar style of C coding. The result is references that are passed similarly to pointers, but are implemented with more protections to make them safer. An alternative would have been the rich syntax of a language like Ada, but this would have presented the appearance of an unwelcome learning curve, and lessened the likely adoption of Java.
In short, the design of parameter passing for objects, including arrays, in Java,is esentially to serve the semantic intent of pass by reference, but is imlemented with the syntax of passing a reference by value.
Kind of a trick realty... Even references are passed by value in Java, hence a change to the reference itself being scoped at the called function level. The compiler and/or JVM will often turn a value type into a reference.

Pass by value or reference . Simple View [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is Java pass by reference?
After reading the discussion on this topic, can one conclude that when Java passes a variable, say A (excluding primitive type), it means it passes the object, which the variable (A) is referencing. So any changes made on that object reflects in variable (A). So at last does it work as pass by reference in general term?
No, that's not correct.
Everything is passed by value in JAVA - no exceptions!
However it's crucial to understand that what you pass is not the object, but a reference to it.
This reference is passed by value (so you can't change it in the method).
You indeed can alter the objects data through this reference, but as I said - you can't change the reference to refer to a different object (or null for that matter).
Java passes parameters to methods using pass by value semantics. That is, a copy of the value of each of the specified arguments to the method call is passed to the method as its parameters.
Note very clearly that a lot of people confuse the "reference" terminology with respect to Java's references to objects and pass by reference calling semantics. The fact is, in dealing with Java's references to objects, a copy of the reference's value is what is passed to the method -- it's passed by value. This is, for example, why you cannot mutate the (original, caller's) reference to the object from inside the called method.
"pass by reference" means if you pass a variable into a method, its value can be modified. This is possible in many languages, like Pascal, Ada, and C++, but not in many other languages like C and Java.
here is a good discussion about it . http://www.jguru.com/faq/view.jsp?EID=430996
See Is Java "pass-by-reference" or "pass-by-value"?
Java is always calls-by-value. In the case of when objects are passed it passes the "value of the reference" which gives Java the semantics of call-by-object-sharing (it does this through call-by-value-of-the-reference though!).
I like to say: When an object is passed it is not copied. Then, since it is the same object on the inside of the method -- the variable is just a different "name" for it -- if you change the object (not the variable!) inside the method, you change that object outside -- everywhere, really -- as well. (It is the same object, ater all :-)
Please note that variables are never passed. They are evaluated as expression and the values that they evaluate to are passed.
Some languages like C++ support call-by-reference. This is different than either call-by-value or call-by-object-sharing because these functions are called with (a generally restricted set of) "lvalues" as arguments and reassignment to the parameters in the function will affect the "lvalues" on the outside. "lvalues" are normally variables and support for this kind of calling convention differs by language (many do not support it!).
Happy coding.
Java does not pass by reference. It also does not pass objects. It passes object references by value. Inside a method, you can make changes to the object that was passed, but you cannot change the reference itself in the calling code.
void foo(Object obj) {
foo = new Object();
}
Object obj = new Object();
Object obj2 = obj;
foo(obj2);
System.out.println("obj2 passed by " + (obj == obj2 ? "value" : "reference"));
This code will print "pass by value".
I would conclude more along the lines of:
Java passes all parameters, primitive and non-primitive, by value. In the case of non-primitive types, what Java actually passes is a pointer (or "reference") to the object instance, by value. This means that the caller's copy of the reference itself (i.e. the memory location that the pointer actually points to) cannot be changed. But at the same time, any state internal to the referenced object instance that the callee modifies will be modified in the caller's "copy" of the object as well, because there is in fact only a single instance of the object that both the caller and callee share.

in Java the arguments are passed by value? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is Java pass by reference?
Hi guys,
I have a question about the arguments passing in Java, I read it from a book "In Java the arguments are always passed by value", what does this mean?
I have no experience of C++ and C, so it is a little bit hard for me to understand it.
Can anyone explain me?
Yes, java method parameters are always passed by value. That means the method gets a copy of the parameter (a copy of the reference in case of reference types), so if the method changes the parameter values, the changes are not visible outside the method.
There are two alternative parameter passing modes:
Pass by reference - the method can basically use the variable just like its caller, and if it assigns a new value of the variable, the caller will see this new value after the method finishes.
Pass by name - the parameter is actually only evaluated when it's accessed inside the method, which has a number of far-reaching consequences.
It means that when you pass a variable to a method, the thing that is passed is the value that is currently held by the variable. Thus, subsequents assignments to the method's argument will not affect the value of that variable (caller side), nor the opposite.
A pass-by-reference means that the callee receives a handle to the caller-side variable. Thus, assignments within the method will affect the caller-side variable.
In Java everything is an object. Object is a pointer like C. But in Java, it points the memory place of a class. Passed by value means, what object's value is, this value is passed by value. For example; Integer a=new Integer(); Integer b=new Integer(); setAInteger(b);
public void setAInteger(Integer c){
a= c;
}
After this operation a points the memory place of b. Lets say, at the beginning a=2500 b=3500, after method is called, new a value is 3500. By the way, 2500 and 3500 are memory addresses.

Categories