In Java, when I have the following statement:
int[] ns = new int[5];
the following doubts arise:
In Java, when I have the following statement:
int[] ns = new int[5];
the following doubts arise:
Is an object created of what type?
ns
will have an object of type array of int
and can not be changed. Note that because it is a reference type the variable will have a pointer to the actual object.
For each value in an index, do I call it an instance?
For each value in a location that can be accessed by an index there will be an instance of type int
. Because it is a type by value, the instance already exists right there in the variable, that is, the variable ns[0]
will have an integer of 4 bytes, in ns[1]
also, and so on.
System.out.println(1);
System.out.println("x");
System.out.println(new Object());
System.out.println(new ArrayList());
The first has an instantiated object of type int
and it is used to print. The object is originally in the static part of the code. When the println()
method is called, a copy of it is passed as an argument, so the parameter will receive a new instance of int
identical to the original. We are sure that it is a new instance because the value of the argument could change without problems (in this case it does not change because it is a constant) and would not affect the value being used within println()
, after all are two completely different instances. There is an instance, it is an object, based on primitive type. I'm not going to go into detail that some implementation might force boxing and the value to be copied for the heap , which is inefficient.
The second is very similar. What most people do not understand is that the string literal is actually a new String("x")
. The string type looks like a primitive type because it has value semantics, but in fact it is a type by reference. It will probably be allocated in heap because of new
, but this is not guaranteed, there can be an optimization and be allocated in stack (that is only implementation details) . Note that in this case there will not even be an actual allocation because string will be in the static part of the code and the required reference will point to this address.
The third creates an object by reference, probably allocated in heap , and it is of type Object
. Since there is no structure in it, the allocation will be empty (but it consumes memory space anyway (if I'm not mistaken 20 bytes).
The fourth creates an object in the same way, and it will be derived from Object
. Do not confuse object with Object
. One is a word we use to designate presumably material things, the other is the name of a root class used in some so-called object-oriented languages, such as Java.
See Memory Allocation in C # - Value Types and Reference Types . In Java it's the same.