Java reference storage question - java

In java, when you pass an object to a method as a parameter, it is actually passing a reference, or a pointer, to that object because objects in Java are references.
Inside the function, it has a pointer to that object which is a location in memory. I am wondering where this pointer lives in memory? Is a new memory location created once inside the function to hold this reference?

Within a function, a parameter reference is stored on the stack. The thing-referenced can live anywhere.
When some code calls a method, what normally happens is that space is made on the executing thread's stack, and this space is used to hold the parameters that are passed to the function. If one of the parameters "is an object", what's really in play is a reference to an object; that reference is copied onto the stack so that the called code can find it. It's important to recognize that the object itself is not copied, just the reference.
The prologue section of the called code will then typically allocate more space on the stack, for the method's own local variables, but underneath, the JVM has a pointer to the stack frame with all the parameters, so the called code can locate the object named by the parameter. Items created with 'new' will be allocated from the heap, and can persist even after the method exits, but all items allocated on the stack are dumped simply by moving the stack pointer back to where it was before the call.

Objects are not references, but you use references everywhere. e.g.
String a = "abc";
the a is a reference to a String. So references get passed around everywhere. Are they pointers ? No. A reference is more like a handle to an object. The JVM is at liberty to move around objects within memory. A pointer would have to change to reflect this. A reference doesn't. A reference could be modelled as a pointer to a pointer.

Every parameter of the function is passed by value - however, the parameter is not an object, but instead is a reference.
So the same object exists with two references to it.
String s = "my string"; // reference to this object created
doSomething(s); // in the doSomething function, a new reference to the same point of memory is passed by value
This means when I have my function void doSomething(String str) I work the same way as I do outside the function, except I have a different reference. Same object being referenced, but different reference. So if inside my function I do str = "different string"; that won't change s - s still points to the same point of memory it did the whole time - but now str instead of pointing to what s points to, now points to where the "different string" is stored.

for example in JFrame you can start like this:
public myFrame mF;
public void Panel1(myFrame mF) { your code ... }

Related

Object without reference

I've been practicing component based design pattern and I was wondering if when you initialize an variable without reference meaning initialized as null, Java go ahead and attribute a space in memory that has the size of the variable even though it is set to null so that eventually when you need to reinitialize it with a new instance of a class it just copies the fields of the new instance?
A variable whose type is a reference type occupies the same amount of space whether it contains null or a reference to an object.
However, the variable only holds the reference ... not the object itself.
... when you need to reinitialize it with a new instance of a class it just copies the fields of the new instance?
Erm ... no. When you later "initialize" the variable, you are assigning a reference to the variable. You are not copying the fields of the object.
For example:
SomeType s = null; // the declaration sets aside space for one
// reference, and the initialization assigns
// `null` to it.
s = new SomeType(...) // the 'new' expression creates the object and
// which allocates the space, etcetera
// the assignment merely assigns the reference
// for that object to 's'.
What if "s" is an array of "Sometype" instead still initialized to null, will it be legit to assume that only space for one reference will be saved until you create a new valid reference for an array of the relevant type?
An array type is also a reference type. So, yes, the answer is the same. A declaration SomeType[] s would reserve space for one reference.
I was wondering if when you initialize an variable without reference meaning initialized as null, Java go ahead and attribute a space in memory that has the size of the variable even though it is set to null
Yes memory is allocated for the variable, but this is only a tiny address space bit of memory and nothing else. No memory is allocated for the eventual object.
so that eventually when you need to reinitialize it with a new instance of a class it just copies the fields of the new instance?
When you create an instance of anything, then memory is allocated on the heap for the object, and this happens whether or not the object is assigned to a variable, to no variables, or to 50 variables, and any variable that refers to the object has its address space pointing at the object's location on the heap (perhaps -- I don't think that the actual mechanics, the hows, are fully specified)
Have a look at oracle documentation page regarding objectcreation
Point originOne;
If you declare originOne like this, its value will be undetermined until an object is actually created and assigned to it. Simply declaring a reference variable does not create an object.
For that, you need to use the new operator, as described in the next section. You must assign an object to originOne before you use it in your code.
Instantiating a Class
The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.
Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.
The new operator returns a reference to the object it created. This reference is usually assigned to a variable of the appropriate type, like:
Point originOne = new Point(23, 94);
I hope above picture clarifies your queries.
The size of reference will be 4 bytes or 8 bytes. Have a look at this SE question:
How big is an object reference in Java and precisely what information does it contain?

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.

Method local variables and stack and heap

While reading on Thread Safety I came across this issue.
If I'm correct method local Primitives and object references lives inside a stack and actual objects pointed by the references inside the stack lives in the heap.
But when it comes to method local non primitive object initialization, wouldn't that cause a concurrency issue ? I mean if the method locals non primitives lives in the heap and only the pointers lives in the stacks, isn't it the same as of instance variables ?
Can someone please help me to understand this....
PS
Think of two threads with each having two stacks of their own and one heap. What I understood is that the two threads keep their method local primitive variables inside their stacks. I have no issue with that.
But what if we have a method with non primitive method local variables ? Then if the object for that variable is stored inside the heap, both the threads will have the access to the same object, won't they ? So if that's the case there would be Sync problems.
That is what I'm asking.
Thanks
But what if we have a method with non primitive method local variables
? Then if the object for that variable is stored inside the heap, both
the threads will have the access to the same object, won't they ? So
if that's the case there would be Sync problems.
I wonder why you will think the two references will refer to the same object.
The creation of the object referred is explicitly done by new (or other similar method, but idea is the same)
Therefore, unlike in C++, if you are declaring this in Java
Foo foo;
there is no Foo object instantiated. foo is just a pointer pointing to nothing.
This will create you a Foo object instance in heap.
Foo foo = new Foo();
If two thread is running this piece of code, thread 1 will have a Foo reference in stack, and ask to allocate a new Foo object in heap, and then assign the address of that Foo obj to the reference foo. Thread 2 is doing the same. Note that Thread 2 is also asking to allocate a new Foo object, it will be a different object from what Thread 1 is allocated.
That's the basic (and much simplified) idea.
Both threads could have access to the same object if they both have a reference to the object. If you have a method like the following:
public String concat(String a, String b) {
StringBuilder builder = new StringBuilder();
builder.append(a);
builder.append(b);
return builder.toString();
}
The StringBuilder object is indeed in the heap, but only one thread has a reference to this object. No other thread can have a reference to this StringBuilder. So it's inherently thread-safe.
If, on the contrary, you have the following:
public String concat(String a, String b) {
final StringBuilder builder = new StringBuilder();
new Thread(new Runnable() {
#Override
public void run() {
builder.append("haha!");
}
}).start();
builder.append(a);
builder.append(b);
return builder.toString();
}
Then you have a thread-safety issue, because you shere the locally created object reference with another thread, and StringBuilder is not thread-safe.
But what if we have a method with non primitive method local variables ? Then if the object for that variable is stored inside the heap, both the threads will have the access to the same object, won't they ? So if that's the case there would be Sync problems
You partially answered your own question.That reference value is stored in the stack but the actual object content is stored in heap and when you call new Object() each thread creates different new object that will be stored in the heap and each thread access the object it has created using the reference value stored in its own stack
Local variables are either primitives, references to objects created somewhere else (if you do an assignation), or references to newly created objects (using "new" operator)
For the first case, as you said, there is no issue.
For the last case, as you are locally craeting a new object, a new object will be created at every call, so no concurrency issue because there will be one object in the heap for each call
But for the second case, as the object has been created somewhere else, you have to think about concurrency
Just to toss in my thoughts regarding what may be your point of confusion: the heap is not managed like the stack. It is shared, yes - in that objects created by all threads are in the heap. However as each object is created, it's given a unique location/space in the heap. Two methods on two threads running concurrently and creating an object instance will create distinctly different objects in the shared heap.
They're created in this shared heap so that if method foo returns the object reference, or stores it, or calls another method that indirectly stores it... it won't be destroyed when foo returns and the stack is popped.
The magic of having a garbage collector is that you don't have to keep track of this "stuff" and destroy it yourself at some appropriate point in the future. Keeps your code simple, lets you focus on algorithms (or learning to program). But I digress...

Object vs Reference in Java

In Java, if I declare,
MyClass obj;
Is obj called a "reference" or an "object". I am not instantiating class here.
obj is a Reference to an instance of MyClass.
Currently, that Reference is NULL because you haven't assigned it to refer to any instance.
Technically MyClass must be a subclass of Object, so it is possible to say that obj is a Reference to an instance of Object as well.
Reference: A variable that points to some object in memory.
It is stored in stack they can be contained in other objects (then they are not really variables, but fields), which puts them on the heap also.
Object: An instance of class that is created dynamically.
It is stored in heap
Example:
MyClassI aObj,aObj1;
aObj=new MyClass2();
At first line aObj and aObj1 are references
At second line aObj referencing to object of MyClass2(New operator creates an object of Myclass2 and its address is assigned to aObj).
To understand even better consider a class Car which has driverName as a member.
Car c1,c2;
c1.driverName="Andrew"
c2.driverName="Gabriel"
System.out.println(c1.driverName);//gives Andrew
System.out.println(c2.driverName);//gives Gabriel
c1=c2;
c2=null;
// gives gabriel because the address of c2 is copied to reference c1.
// the object is not nullified because c2 is just a reference when
// assigning null the address that is stored on c2 in nullified not
// the object it points..
system.out.println(c1.driverName);
In computer science, a reference is a
value that enables a program to
indirectly access a particular data
item, 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 data item, and
accessing that data is called
dereferencing the reference.
In computer science, an object is any
entity that can be manipulated by the
commands of a programming language,
such as a value, variable, function,
or data structure. (With the later
introduction of object-oriented
programming the same word, "object",
refers to a particular instance of a
class)
so obj is a reference and new MyClass() can be seen as an object
obj is a Reference of type MyClass. The current reference does not point to anything (ie: null).
Sometimes you'll hear people say "Design an method that takes an object as a parameter and..."
If you're new to programming, and especially with Java, such statements can lead to some confusion. These people are using the word "object" to refer to an instance of a class in very general OOP terms, not necessarily Java specific.
When we're talking specifics about Java and the code you have there, it is a reference to an instance of MyClass, which is NULL.
'obj' is a variable. It holds either a reference or null. If it holds a reference, that refers to an object.
In Java, all objects are accessed by reference, and you never have direct access to the object itself.
reference :- is a variable that has a name and can be used to access the contents of an object, A reference can be assigned to another reference passed to a method, or returned from a method. All references are the same size, no matter what their type is Like "Object object ;".
object:- is an entity that's exists in memory allocated by the Java run time environment, An object sits on the heap and does not have a name Like "Object object=new Object();".
so MyClass obj Here is A reference referred to Null.
We can summarize this principle with the following two rules:
The type of the object determines which properties exist within the object in memory.
The type of the reference to the object determines which methods and variables are accessible to the Java program.
The reference is a variable that has a name and can be used to access the contents of an object. A reference can be assigned to another reference, passed to a method, or returned from a method.
All references are the same size, no matter what their type is.
An object sits on the heap and does not have a name. Therefore, you have no way to access an object except through a reference. Objects come in all different shapes and sizes and consume varying amounts of memory. An object cannot be assigned to another object, nor can an object be passed to a method or returned from a method. It is the object that gets garbage collected, not its reference.

Java reference type

How does Java deal with passing reference data type arguments?? Can somebody give a clear picture?
Java passes a copy of the reference to the method. The reference still points to the same instance.
Imagine if I had a slip of paper with a restaurant's address on it. You also want to go to the same restaurant so I get a new slip of paper and copy the address of the restaurant on to that paper and give it to you. Both slips of paper point to the same restaurant but they are separate references to the instance.
The restaurant itself is not duplicated, only the reference to it is duplicated.
Jon Skeet provides a similar analogy:
The balloon analogy
I imagine every
object as a helium balloon, every
reference as a piece of string, and
every variable as something which can
hold onto a piece of string. If the
reference is a null reference, that's
like having a piece of string without
anything attached to the end. If it's
a reference to a genuine object, it's
a piece of string tied onto the
balloon representing that object. When
a reference is copied (either for
variable assignment or as part of a
method call) it's as if another piece
of string is created attached to
whatever the first piece of string is
attached to. The actual piece of
string the variable (if any) is
holding onto doesn't go anywhere -
it's only copied.
Here is an example:
// Here I have one instance and one reference pointing to it
Object o = new Object();
// At this moment a copy of "o" is made and passed to "foo"
foo(o);
void foo(Object obj) {
// In here I have obj which is a copy of whatever
// reference was passed to me
}
All Java objects (everything except primitives such as int, float, boolean, etc...) are references to the pointed-to-object.
So for example:
Foo f = new Foo();
Above, f is a reference to an object of type Foo. If you then have a function:
void doSomething(Foo myFoo) { ... }
doSomething(f);
The doSomething() function receives the same object that f refers to. So if doSomething() mutates f, it is mutating that object.
Unlike C++, there is no choice between passing by value, reference or using pointers: All class-type variables are references (or pointer depending on your exact terminology).
One problem here is that people often try to apply their C++ knowledge and terminology to Java, which won't work.

Categories