Confusion in pass by value vrs pass by reference/pointer - java

Following declaration
void insert_LL(Node *head, int data);
when called, a copy of head pointer reaches the function, so if a node is added at the head, the value of the head is changed. But, as we have the local copy of head so the actual head pointer isn't changed. So we declare it as follows
void insert_LL(Node **head, int data);
My question:
Is the above explanation correct?
If yes, so that means in C, it is always a pass by value (a copy of pointer is reached in the function) which is same as in Java. Am I correct?
If yes, so how does pass by reference/pointer come into the picture?

1- YES
2- YES
3- In C, Pass-by-reference is simulated by passing the address of a variable (a pointer) and dereferencing that address within the function to read or write the actual variable. This is referred as "C style pass-by-reference.".

Pass by reference is not the term to be used in C. The address value of the pointer variable is passed. The compiler stores references to the variables with the names given to the memory locations where the variable is held.
The major difference between a reference and a pointer is that "pointer" can take any address value unless made "const". Whereas when you pass by reference, you can't.
What are the differences between a pointer variable and a reference variable in C++?
This thread will do all the needful.

Related

Why do programmers say that "pass by reference" is really "passing references by value?" Why is that important?

I know the whole concept of passing by reference in C & C++, and the similar concept of only pass by value in Java.
But in a point of view Everything is pass by value isnt it?
In C we pass a pointer of the variable to the function. So we are just passing the value of the reference of to the function. And that is the reason we say Java doesnt support pass by reference because we just pass the value of reference variable to the functions. So we pass the reference by value. Though in C++ there is a way of passing by reference since we can pass arguments and the function will work with the same memory location using this format
void swap(int &x, int &y)
But passing by reference by pointers in C is just passing the pointers by value.
void swap(int* x, int* y)
I know the question might seem a bit stupid, but i feel there is a big gaping hole in the whole concept that i have. So what is the actual defination of call by reference, is this just a pseduo name of call by value in another context?
Passing by reference means the called functions' parameter will be the same as the callers' passed argument (not the value, but the identity - the variable itself). Pass by value means the called functions' parameter will be a copy of the callers' passed argument. The value will be the same, but the identity - the variable - is different. Thus changes to a parameter done by the called function in one case changes the argument passed and in the other case just changes the value of the parameter in the called function (which is only a copy).
Simple Example in C++
#include <iostream>
void by_val(int arg) { arg += 2; }
void by_ref(int&arg) { arg += 2; }
int main()
{
int x = 0;
by_val(x); std::cout << x << std::endl; // prints 0
by_ref(x); std::cout << x << std::endl; // prints 2
int y = 0;
by_ref(y); std::cout << y << std::endl; // prints 2
by_val(y); std::cout << y << std::endl; // prints 2
}
C++ is defined by a standard, modulo bugs. The C++ standard does not specify how references are implemented, nor how they are passed to functions. Nor does it define calling conventions in general, nor does it define pointer layout, the stack, the heap, or a myriad of other implementation details.
Instead it attempts to define what the C++ code means.
References end up being aliases to other values. The most common way to implement them is as a pointer under the hood: but in as there is no way to access that pointer value, nor side effects from accessing through it, this makes it easy for compilers to eliminate the existence of the reference completely, and just use the referred to value directly.
If the complier cannot do this, it will typically pass a pointer or equivalent.
Despite often being implemented as a pointer, it is still different as the semantics of interaction with it are different: they cannot be reseated, they cannot have their address taken, and they cannot be uninitialized (null or equivalent).
Naturally these rules can be broken via undefined behavior.
Two main points:
There is no call by reference in C.
Pass by value and pass by reference are different. They are not same.
Pass by value: the called function creates a new set of variables in stack and copies the values of the arguments into them.
Pass by reference: instead of passing values to the function being called, references/pointers to the original variables are passed.
Why do programmers say that “pass by reference” is really “passing references by value?”
In passing references/pointers to the original variables, in fact objects/addresses are passed by value. So, you can say pass by reference is passing reference by value but this doesn't imply that pass by reference is pseudo name of pass by value. The difference between the two is well explained in this answer. I am copying the excerpt:
If I tell you the URL, I'm passing by reference. You can use that URL to see the same web page I can see. If that page is changed, we both see the changes. If you delete the URL, all you're doing is destroying your reference to that page - you're not deleting the actual page itself.
If I print out the page and give you the printout, I'm passing by value. Your page is a disconnected copy of the original. You won't see any subsequent changes, and any changes that you make (e.g. scribbling on your printout) will not show up on the original page. If you destroy the printout, you have actually destroyed your copy of the object - but the original web page remains intact.
You cannot say "pass by reference" is really "passing references by value" without giving a definition of "reference".
In Java, the statement is true (at first approx.) because inside a function you can change the value of a formal parameter that is a reference without changing the value of the parameter passed in the call :
void f(Object param) {
param = null;
}
void g() {
Object o = new Object();
System.out.println(o);
f(o);
System.out.printn(o);
}
Everybody knows that the two print statements will give the exact same results. In fact in Java there is no pass by reference, there is only references that can be passed; and there is only one way to pass arguments : by value.
In C++, this is really different. When you change the value of the reference parameter inside the function, the parameter passed in the call is modified:
void f(int &param) {
param = 0;
}
void g() {
int i=12;
cout << i << endl;
f(i);
cout << i << endl;
}
Every C++ programmer knows that the second print will display 0 (while the first is 12).
So in C++, you cannot say that "pass by reference" is "passing references by value". In C++ references have no value, they are just names associated to memory chunks (Standard section 8.3.2 Reference: [ Note: A reference can be thought of as a name of an object. — end note ]). Inside f() there is only one variable which has two names. Of course, you may object that most of C++ references implementations are hidden pointers, so the statement can be true; but you should be aware that there is many cases where using hidden pointers to implement references can be avoided (Standard section 8.3.2/7 References. It is unspecified whether or not a reference requires storage)... So in C++ the statement is not valid. C++ has really two ways of passing parameters : by value and by reference.

changing address of object in Java (pass-by-value again??)

Before I post my question, I have read the following excellent articles on java-pass-by-value.
I am convinced I have understood it well.
Is Java "pass-by-reference" or "pass-by-value"?
http://www.javaworld.com/article/2077424/learn-java/does-java-pass-by-reference-or-pass-by-value.html
My question has to do with a side-by comparison of Java with other language that supports pass-by-reference(C++ may be).
In case of Java, you have a handle (reference) pointing to the object in location A. so object itself could be modified. But It is not possible to change the object location itself.
I.e An object stored in memory address 0X945 cannot be changed to 0X948.
In languages such as C++, you can choose to pass-by-value or pass-by-reference. (It is in the hands of the programmer correct?). Hence it is possible to change the location of object in memory space correct?
P.S: I have good background on Java but on C++. so my views above may be wrong.
It is claimed in the article 1, I cited above that there is no notion of pointers in Java. I dont know how far that is true? (why do NullPointerException exists then)
EDIT:
consider this example:
void swap(Object A,Object B) {
Object temp=B;
Object B=A;
Oject A=temp;
}
when I call the method in Java such as swap(A,B), nothing happens
but in C++ (I presume), swap happens. which probably means I am changing the location of objects in memory correct?
In java even - references to objects are passed by value. i.e, everything is pass-by-value. Next,
you can choose to pass-by-value or pass-by-reference. (It is in the hands of the programmer correct?).
Correct. But you can't do it in Java.
An object stored in memory address 0X945 cannot be changed to 0X948.
You can't do this in both java and C++.
NullPointerException is thrown when you try to access a property / method of something which doesn't exist (is null). i.e, the reference points to null when an instance of the object is required.
Object o = null;
o.toString() --> NPE. o points to null.
so in C++, do pass-by-reference means you pass the object itself, so that it could be reassigned in swap method
In C++, pass by reference, swap(Object &A, Object &B) appears to be close to java's pass by value.
In Java Object A is a reference to an Object and is null by default. As Object is already a reference and so when this reference is copied, it is passed by value.
In C++, Object A is an instance of an Object and is always a unique object. As Object is an instance, you are passing by reference using Object& because the Object is not passed, but a reference to it.
Java is always pass by value, it's just when you are passing objects, the value passed is the location in memory so it can act like pass by reference.
when I call the method in Java such as swap(A,B), nothing happens but
in C++ (I presume), swap happens.
No it doesn't. "Nothing" also happens in C++.
A correct translation of the code to C++ would be:
void swap(Object *A,Object *B) {
Object *temp=B;
B=A;
A=temp;
}
(Yes, the syntax for types is different between the languages. Namely, the pointer-to-Foo type is written as Foo * in C++ and Foo in Java; that's just a syntactical difference between the languages.)

Difference between reference and pointer [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 9 years ago.
I’ve read a lot of articles about how “pass-by-reference” doesn’t exist in Java since a copy of the value of the reference is passed, hence “pass-by-copy-of-reference-value”.
The articles also say a reference value is a pointer.
(So pointers do exist in Java.)
Some other articles say: Java has no pointers.
So what is the correct solution?
How does a pointer differ from a reference (or reference value), and do they exist in Java?
They aren't like C pointers. There's no pointer arithmetic allowed.
Java has only one mechanism for passing parameters: pass by value in all cases. For primitives, the value is passed. For objects, the reference to the object on the heap is passed.
A pointer is a reference type; it refers to something. What you're basically asking is: "Does Java have Dobermans? Because some articles say it has dogs."
As noted in Wikipedia entry for Pointer:
A pointer is a simple, more concrete implementation of the more abstract reference data type. Several languages support some type of pointer, although some have more restrictions on their use than others
It goes on to say this about Java specifically:
Unlike C, C++, or Pascal, there is no explicit representation of pointers in Java. Instead, more complex data structures like objects and arrays are implemented using references. The language does not provide any explicit pointer manipulation operators. It is still possible for code to attempt to dereference a null reference (null pointer), however, which results in a run-time exception being thrown. The space occupied by unreferenced memory objects is recovered automatically by garbage collection at run-time.
Looking up Reference you find:
In computer science, a reference is a value that enables a program to indirectly access a particular datum, such as a variable or a record, in the computer's memory or in some other storage device. The reference is said to refer to the datum, and accessing the datum is called dereferencing the reference.
A reference is distinct from the data itself. Typically, a reference is the physical address of where the data is stored in memory or in the storage device. For this reason, a reference is often called a pointer or address, and is said to point to the data. However a reference may also be the offset (difference) between the datum's address and some fixed "base" address, or an index into an array.
Java chose to use the broader term "reference" instead of "pointer" because of the differences between Java and C. (Thus creating a sisyphus-like situation where we have to keep explaining that Java is pass-by-value).
You don't have a C pointer, you have a Java Reference. This has nothing to do with a C++ reference, or pass-by-reference.
Because Java is pass-by-value it is similar to using a C pointer in that when you pass it to a method, the value (e.g. memory address) is copied.
It is right to say both:)
Java has no pointers since java has simplified pointers as references.
Object o=new Object();
We got an object o here; o is actually a pointer.
Basically, pointers and references are the same thing; they point to (refer to) something else in memory. However, you cannot do integer arithmetic on references. You may find some pages on this slide useful:
http://www.cis.upenn.edu/~matuszek/cit594-2005/Lectures/15-pointers-and-references.ppt
You have to get your head around the different, but related concepts of types, variables and objects. If we ignore for now the fundamental types like int and only consider class types, then in Java there are variables, which are "named things", and objects. Both variables and objects have a type. However, a variable of type T is not an object; rather, it is a mechanism for locating an object of type T, and for informing the runtime that this object is in use. A variable may at any point not locate any object, in which case it is null, or it may, and in that case the very existence of the variable keeps the object alive.
Let's repeat: Variables have names. Objects don't have names. Variables are not objects.
When you pass a variable as an argument into a function call, the corresponding function parameter becomes duplicate of the argument, so that there are now two variables which both locate the same object. When you assign one variable to another, you make the left-hand variable locate the same object (possibly null) as the right-hand variable, relinquishing the possibly previously held location. But no objects are being affected by this; the objects exist in some unrelated, unprobable plane of existence.
Also, variables have a deterministic lifetime, which is determined by their scope (essentially block-local or static-global). The lifetime of variables is non-deterministically related to the lifetime of objects, but the lifetime of objects cannot be controlled directly.
That's the type system and object model of Java (for class types) in a nutshell. It's up to you what you want to label this; it makes sense to say that "variables are references", since that's what they do, but you might as well just stop trying to compare yourself to other languages and just say "variables", which is clear enough within the context of Java. Variables are variables, objects are objects, neither one is ever the other, and you need the former to talk about the latter.
In Java, a reference is a pointer, usually one that isn't null. That's why it's called NullPointerException, not NullReferenceException. "The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object. "
Java pointers/references are akin to Pascal pointers, not to C or C++ pointers, in that they are very strongly typed and do not support address arithmetic.

Primitives vs Objects in Java

I'm trying to do some practice for an exam and need some help (did I do them correctly? If not, why?) on these problems about java primitives and java objects. These are all true or false.
The following variable declaration is a reference to an object which is dynamically allocated and stored in the heap: int x = 7;
False, because it is pass by value since int is primitive
The following variable declaration is a reference to an object which is dynamically allocated and stored in the heap: Integer x = 7;
True, because it is referencing an object stored on the heap
If you pass the variable ‘x’ as declared in (1) to a method, that variable is passed by reference, and its value may be modified by the called function.
False,because Java only does pass by value
If you pass the variable ‘x’ as declared in (2) to a method, a copy of that
variable is created in the heap, and passed to the function, so that the function’s object
reference is pointing to a distinct place in memory.
True, because variable is in the stack but it is pointing to a place in the heap
Thank you all for the help.
(4) is false for two reasons:
"a copy of that variable is created in the heap" is false. Only objects are on the heap. The local variable in a function is not on the heap. The value of that variable is simply passed, i.e. copied into the stack frame of the called function.
"the function’s object reference is pointing to a distinct place in memory." is false. The function's reference will point to the same place in memory. That's the point of passing -- the value of the variable inside the function is the same as the value that was passed. The value of a reference is where it points.
4) If you pass the variable ‘x’ as declared in (2) to a method, a copy
of that variable is created in the heap, and passed to the function,
so that the function’s object reference is pointing to a distinct
place in memory.
Okay, this can be a little sketchy. If dealing with objects, you are not creating a copy of the object and passing the copy to the method. You are creating a copy of the reference to the object, and passing that over by value.
Actually there is a reason 2 is wrong - but its probably not the reason the person who set it expects.
Integer x = 7;
Will get turned into:
Integer x = Integer.valueOf(7);
Which will re-use a cached value for all integers in the range -128 to +127 inclusive. (It may reuse them for other values too).
So you will get a reference to an object which is present in the JVM implementation dependant cached storage for common Integer values.
False because Integer is an object. So you will be passing just the reference to the object address in the function. It is standard in Java.

What's your deep comprehension of pointer,reference and Handle in C,C++ and Java?

What's your deep comprehension of pointer,reference and Handle in C,C++ and Java?
We usually think about the pointer,reference and Handle on the specify language level, it's easy to make confusion by the newbie like me.
Actually all those concept in java, just a encapsulation of pointer.
All pointer just a encapsulation of main memory addresses .
So all of those ,just a encapsulation wiles.
all above, it's my personal glimpse. And what's your comprehension ?
welcome to share with me.
Each language has differences to this respect. In C there are only pointers that are variables holding a memory address. In C you can use pointer arithmetic to move through memory, if you have an array, you can get a pointer to the first element and navigate the memory by incrementing the pointer.
Java references are similar to pointers in that they refer to a location in memory, but you cannot use pointer arithmetic on them. Only assignments are allowed. Note that the reference is not the object, but a way of accessing an object. This can be seen in argument passing semantics: objects are not passed by reference, references are passed by value:
public static void swap( Object o1, Object o2 )
{
Object tmp = o1;
o1 = o2;
o2 = tmp;
}
The previous piece of code is a complex no-op. References to two objects are passed by value, they are played with inside the method and nothing happens from the caller perspective: the real objects do not suffer any change, nor do the references the caller has into those objects. That is, if the call is swap( ref1, ref2 ), the system will make copies of the references into o1 and o2, the copies are changed within the method, but the caller variables ref1 and ref2 will remain unchanged after the method call.
In C++ you have two concepts: pointers are the same as C pointers and close to Java references, while C++ references are aliases into the objects they refer. C++ references can only be initialized with one object/data element in construction and from there on, using the original object and the reference is exactly the same. Besides the fact that references don't hold the resource and thus the destructor will not be called when the reference goes out of scope, nor will the reference notice if the referred object is destroyed, for all other uses the two names are the same element.
template <typename T>
void swap( T & a, T & b )
{
T tmp( a );
a = b;
b = tmp;
}
The code above in C++ differs from the Java version in that it does change the caller objects. If a caller uses swap( var1, var2 ), then the references are bound to those variables, and it is var1 and var2 the ones that suffer the change. After the call, the value of var1 and var2 is actually swapped.
Handles are in a different level, they are not language construct but tokens provided by a library so that you can later on refer to some resource that the library manages internally. The most general case are integer handles that are ids (or offsets) into a resource table, but I have seen strings used as handles. It is the library internally who decides what is exactly a handler (a pointer, an integer, a string or a more complex data structure). Handles are meant to be opaque in that the only sensible use is to store them and later give it back to the same library as part of other function signatures.
In C++ a pointer is a variable that points to a location in memory. You can access the object or data stored there by dereferencing the pointer. A reference is simply a pointer that has two distinctions from a pointer. First, you cannot change what a reference points to once the reference is initialized. Second the dereferencing semantics are removed so you can access a reference as if it were an object allocated on the stack instead of on the heap with new.
In Java, there are no pointers, only references. Every object you use is a reference to an object allocated on the heap. The downside is you can't do pointer math tricks. That's also the upside.
EDIT:
As pointed out in the comments, a Java reference differs from a C++ reference in that it can be reassigned once initialized. They are still called 'reference types' by the language specification, but behaviorally they act like pointers in terms of being able to be reassigned and passed to functions, but the semantics of dereferencing them look like non-pointer access looks in C++.

Categories

Resources