Declaration of array of objects - null value [duplicate] - java

This question already has answers here:
What is the default initialization of an array in Java?
(8 answers)
Closed 9 years ago.
I have two-dimensional array
protected MyClass[][] myArray;
in constructor I have this
this.myArray= new MyClass[20][20];
Now, without inicialization (aka this.myArray[2][2] = new MyClass(par0, par1);)
the value of this.myArray[2][2] is "null".
Is this guaranteed? And where can I read more about this subject? (for primitive types like int or boolean too)
Thanks

Yes, it's guaranteed. Array values are initialized with null (for objects), 0 (for numeric primitives) and false (for boolean primitives), just like fields.
See http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.6-100:
Space is allocated for a new array of that length. If there is insufficient space to allocate the array, evaluation of the array initializer completes abruptly by throwing an OutOfMemoryError. Otherwise, a one-dimensional array is created of the specified length, and each component of the array is initialized to its default value (§4.12.5).
(emphasis mine)

Yes, it is guaranteed. Every type has a default initialization value:
numeric primitives = 0
boolean = false
all Objects = null

Yes. This behavior is guaranteed. The default value of an Object is null. Therefore the default values for an array of Objects is also null so every element in the array needs to be instantiated. See Default Values in Data Types.

Related

Changing array in method changes array outside [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Are arrays passed by value or passed by reference in Java? [duplicate]
(7 answers)
Closed 9 years ago.
I have trouble with scope of variable.
public static void main(String[] args){
int[] test={1,2,3};
test(test);
System.out.println(test[0]+" "+test[1]+" "+test[2]);
}
static void test(int[] test){
test[0]=5;
}
I expected the output to 1 2 3, but the result was 5 2 3.
Why I changed the value in the array in the method, but the original array changed?
An array in Java is an object. When you create an array via new, it's created on the heap and a reference value (analogous to a pointer in C) is returned and assigned to your variable.
In C, this would be expressed as:
int *array = malloc(10 * sizeof(int));
When you pass that variable to a method, you're passing the reference value which is assigned (copied) to the local (stack) variable in the method. The contents of the array aren't being copied, only the reference value. Again, just like passing a pointer to a function in C.
So, when you modify the array in your method via that reference, you're modifying the single array object that exists on the heap.
You commented that you made a "copy" of the array via int[] temp=test ... again, this only makes a copy of the reference value (pointer) that points to the single array in memory. You now have three variables all holding the same reference to the same array (one in your main(), two in your method).
If you want to make a copy of the array's contents, Java provides a static method in the Arrays class:
int[] newArray = Arrays.copyOf(test, test.length);
This allocates a new array object on the heap (of the size specified by the second argument), copies the contents of your existing array to it, then returns the reference to that new array to you.
Definitions:
Reference = A variable that points to the location in memory where your array lives.
Value of a Reference = The actual memory address location itself
You passed the value of the reference of your array into your test() method. Since java is Pass By Value, it passes the value of the reference, not the value of your array (ie. a copy).
It may be easier to think of a reference as a pointer if you have a C background. So a value of a reference is essentially it's memory address (I'm fudging java rules here but it may be simplest to think of it this way)
So, in your example, you pass the value of the reference which points to your array, into your test() method, which then uses that reference value to lookup where your array is in memory, so it can access data in your array.
Since in your test() method you do not change your array's reference (where it points to, ie. test = new int[10];), then your test() method acts on the original data in the array (because it still points to your original array's location), leading to element 0 being set to a value of 5.

long Value assigned with Default Constructor in Java

I need to put a check for object elements to see if they are null or blank or are having their default values. I printed default value of a long element and it turned to be 0. In a review i have been asked to put a check for the long element to be greater than 0 too.
Will default object constructor construct a object with negative value for any of the member element.
Will default object constructor construct a object with negative value
for any of the member element.
No.
The Java class-members have default values as follows:
int, long, short, char, byte default to 0.
boolean defaults to false.
Non-primitive members default to null.
Have in mind that the Wrapper implementations will default also with null, because their instances are objects, not primitives.
In Java all values are initialized with null or 0 or false (whatever is applicable), so a check for this is as simple as value != null or value != 0.
The more important question is: why do you actually need to check this during construction? Because at this time, the value is equal to what you set it in your code, and no external function could have modified it at this time.
No there is no variable initialize with garbage value in JAVA, you will definately get the default value if you have not initialize the variables in object
like for boolean there is default value "false"
for int default value is 0
and Note all the instance (objects like non-primitive data types) are intialized with default value of null
Garbage collector in JAVA done that work for you of default initialization
In Java long is one of the primitive types.
When used as a class field without explicit initial value, it'll be assigned 0.

Are Java function parameters always passed-by-value for arrays? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is Java “pass-by-reference”?
if we have big byte[] array (like 40Mb) and we want to send it in method
method(array);
will the array be copied? So memory will increase by another 40Mb in Java env => 80Mb, right?
If yes, how can we destroy the 'first' array after calling the method?
No, the array will not be copied.
In Java, everything is always passed by value.
Variables of non-primitive types are references to objects. An array is an object, and a variable of an array type is a reference to that array object.
When you call a method that takes a non-primitive type parameter, the reference is passed by value - that means, the reference itself is copied, but not the object it refers to.
No new Object will be created, Just a reference will be copied to function parameter.
The variable array is actually just a reference to the array object. When you pass array to a function you are just copying the reference not the actual array the the reference refers.
Java is always pass by value. The value being passed is the value of the variable in the case of a primitive type and the value of the reference held by a variable in the case of an Object.
In this case, an array is an Object and what is passed by value is the reference to that Object. So no, the array will not be copied.
No, the array will not be copied. In fact, because:
In Java, everything is always passed by value.
Array itself is a object.
So, the result is array' will be copy for method, but the thing it contains: bytes elements DOES NOT copy. so, everything you change for array in the method will affect the original array.
So, memory will not double as you see :)

int array initialization

I have here a simple question related to Java.
Let's say you have an int array as instance variable:
int[] in = new int[5];
So, now by default it contains 5 zeros.
But what if you have the same array as local variable. Does it get initialized to zeros? That is not a homework, I am learning Java language.
Best regards
First thing to understand is that, local varibles are stored on stack which are not initialized explicitly with their default values. While instance variables are stored on Heap, and they are by default initialized with their default value.
Also, objects are also created on Heap, regardless of whether an instance reference variable is holding its reference, or a local reference variable.
Now, what happens is, when you declare your array reference like this as local variable, and initialize it with an array: -
int[] in = new int[5];
The array reference (in) is stored on stack, and a memory is allocated for array capable of holding 5 integer elements on heap (Remember, objects are created on Heap). Then, 5 contiguous memory location (size = 5), for storing integer value are allocated on Heap. And each index on array object holds a reference to those memory location in sequence. Then the array reference points to that array. So, since memory for 5 integer values are allocated on Heap, they are initialized to their default value.
And also, when you declare your array reference, and don't initialize it with any array object: -
int[] in;
The array reference is created on Stack (as it is a local variable), but it does not gets initialized to an array by default, and neither to null, as is the case with instance variables.
So, this is how allocation looks like when you use the first way of array declaration and initialization: -
"Your array reference"
"on stack"
| | "Array object on Heap"
+----+
| in |----------> ([0, 0, 0, 0, 0])
+----+
"Stack" "Heap"
It is the same thing if you do :
int[] in = new int[5] as instance variable or local variable. The array object in will contain zeros in both cases.
Difference would be if you would do something like :
Instance variable : int[] in; (it is initialized with null), and the in object will live in heap space.
Local variable : int[] in; (it has to be initialized by the user) will live in stack
For primitive type arrays it is initialized to their default values.
In the documentation it says :
a single-dimensional array is created of the specified length, and
each component of the array is initialized to its default value
For the integer type default value is 0.
Yes, when you initialise an array the contents will be set to the default value for that type, for int it would be 0 and for a reference type it would be null.
If you initialise an array and inspect the contents you can see this for yourself:
...
final int[] in = new int[5];
for (int i = 0; i < in.length; i++) {
System.out.println(in[i]);
}
...
This will print:
0
0
0
0
0
yes
public void method() {
int[] in = new int[5];
System.out.pritnln(in[0]); //output in 0
}
In this case, your Array is a local variable, all you need is to initialize your array. once you initialize you array, voila your array element**s get their **default values.
It does not really matter whether the declared array in an instance variable or a local variable it will get initialized to the default value.
Each class variable, instance variable, or array component is initialized with a default value when it is created.
As per JLS
An array initializer creates an array and provides initial values for all its components.
THe Array Doesn't Contain 5 zeroes when you instantiate it as a local variable.

Make default value of a "Short[]" element 0 instead of null?

I have a program that creates lists and needs any assigned values to be 0. Its been running fine when I do with int[] humpty_dumpty = new int[20]; but to optimize the size of the lists I set them to Short[] and now my program is breaking because it takes the zero's as inputs(and Short[] humpty_dumpty = new Short[20]; is making the default value null).
Is there a way to set it to default zero without having to iterate through the entire list(I can do this via a for loop but was wondering if there was a way to make its behavior similar to int)?
There is a difference between a Short[] and a short[]. Elements of the latter will be initialized to 0 because short is a "primitive" type and cannot be null. The capitalized Short class will be initialized to null because it is really just an Object wrapping a short value.
You may create an array of primitive type instead of wrapper,
short []ar=new short[20];
Short[] doesn't 'optimize the size of the lists' at all, and it has a default value of null. short[] does, and it has a default value of zero.
Answers, in order:
1) Requirement first, optimization last. Don't use sparse arrays, or try to be 'smart', unless you specifically need to do this & deal with the extra code/ overhead.
2) Use common methods (possibly in an Instance or Static Helper class) to avoid repeating common code.
eg. short sparseGet (Short[] array, int i) {return (array[i] != null ? array[i] : 0);}
3) Perhaps use short[] rather than Short[]? Uppercase types are not primitives, but Value Wrapper classes -- and stored as object references (pointers) to instances, thus slower & more memory-intensive.
4) Uppercase 'Value Wrapper' types are appropriate where you may have null values, from a database. eg. Person.Age would ideally be Integer, if there's any possibility you/ the database might not have data for that field.
Cheers.

Categories