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?
Related
In Java, when we only declare a variable of a class type, only a reference is created (memory is not allocated for the object). Is to hold the reference t somewhere space will be created on heap ? or if i'm wrong then what happens exactly in memory when we just declare variable ?
Test t;
In Java, when we only declare a variable of a class type, only a reference is created (memory is not allocated for the object).
This is correct.
Is to hold the reference t somewhere space will be created on heap?
The answer depends on the context in which the declaration appears. If the said declaration is part of an object (i.e. t is a field) then the space for the reference would be allocated from the heap, along with the space for the rest of the object containing the field. Otherwise, the space for the reference would be allocated in JVM's stack frame.
When you declare a variable:
Test t;
space is made for the reference (a fixed amount, doesn't depend on the number of members in the class). When you instantiate a variable, using the new keyword:
t = new Test();
then space for the variable is made on the heap, and t references that space. This has to be large enough to hold all the members of a Test.
I know that when declaring object instances in c++ like so:
Object object
the Object constructor is called and memory is provided for that object, however i find that when you do this in java the object instance doesn't have a value until:
object = new Object()
is written. I want to know specifically when memory is provided for the object. I thought that both construction and the new keyword allocated memory so Object object = new Object() seems redundant. I read on oracle's site that declaration "reserves" memory and new "allocates" memory, I would like to know what is the difference between the two.
You need to differentiate between the space required for the variable and the space required for the object. Bear in mind that the value of the variable is just a reference - very much like a pointer in C++. So if you have:
Object x = null;
then the variable x itself takes up enough space for a reference (usually 4 or 8 bytes). Now if you have:
x = new Object();
that creates an object - the value of x is now a reference to the newly created object. x itself takes up the same amount of space as before, but there's also the space required for the object itself (basically the fields, a reference for the type of the object, and data for synchronization and house-keeping).
When you do something like
Object object = new Object()
in Java, object is a reference to the actual instance on the managed heap. Compared to C++, that's roughly doing
Object* object=new Object()
So when you do
Object object;
in Java, a place is created for the 'reference' to a instance.
Similar to
Object* object;
in C++.
Object foo=null;
in meaning of C++ creates reference foo to the object of class Object. So, it consumes memory for reference only.
Object realFoo=new Object();
creates such reference and also real object with whatever is with this object. So, it is memory for the reference and object itself.
In Java there is no memory reservation - only memory allocation.
declaration reserves memory: parameters and variables inside a method will have memory reserved for them in the stackframe.
allocates memory: at runtime, when executing "new", memory will be allocated for the new Object on the heap
It's important to understand that in Java, Object object is simply a reference to an Object called object. If you're familiar with C++, you can think of this reference as a pointer (though it's not quite the same).
On a 64-bit machine, the object reference is 8 bytes. When you actually instantiate an Object using the new keyword and assign it to the reference, this is where memory is allocated for your Object.
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.
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.
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 ... }