Why `Integer[100] arr;` is invalid, while `Ineger[] arr;` is valid? - java

I was trying to allocate an Integer array for 100 items, why this declaration isn't valid in Java?
Integer[100] intArr1; ----- (1)
Whereas this is valid:
Integer[] intArr; ----- (2)
As (2) is valid, how much memory does it occupy? Can anyone help to explain a bit.
There are some questions in SO which resemble my question, however they are not the same, and I did look in SO before asking this question.

The first one isn't valid because that's not proper Java syntax.
The second one occupies 0 memory, as you haven't created an array. Only a reference to an array, with the reference being null.
You need a new Integer[100] there to actually create the array object.

You are mixing two different things.
One thing is the type of variable. In your case, you want to say "the type of variable intArr is array of Integers", which is this code Integer[] intArr;
In variable, which type is array of Integers you can put any array of Integers you like, no matter the size, therefore you cannot pre-defined it.
The second thing is assign to a variable.
Integer[] intArr = new Integer[10];

To initialise an array with 100 items you write:
Integer intArr1[] = new Integer[100];
Your second line of code just declares a variable, there is no size declared.

When you declare an array, you don't give it a length. You only give it a length when you initialise it.
This is just a declaration:
int[] myArray;
If you want to initialize it with an array of length 100, you do this:
myArray = new int[100];
An uninitialised array is null by default, or inaccessible if it is in a local scope.

Related

What type of syntax is the Java "new Type[]{...}" array literal initialization?

What grabbed my attention, which I cannot explain to myself, is a thought about this well known code:
String[] str = new String[]{"a","b","c"};
Is new String[] a cast? If it is, why do we use new and no brackets? We would cast as in:
float i = (float) 3;
It also seem not to be a constructor, because then we would use it like a function call (e.g new String[](...)).
So what kind of syntax is it, and do we have more of that kind in Java?
This syntax is an example of an 10.6. Array Initializer as part of an 15.10.1. Array Creation Expression.
An array initializer may be specified in a field declaration (§8.3, §9.3) or local variable declaration (§14.4), or as part of an array creation expression (§15.10.1), to create an array and provide some initial values.
new String[]
is an array creation expression and
{"a","b","c"}
is an array initializer.
Since there are no dimension expression in your array creation expression (i.e. nothing inside the square brackets), there must be an array initializer:
If there are no dimension expressions, then there must be an array initializer.
A newly allocated array will be initialized with the values provided by the array initializer as described in §10.6.
It's called an Array Initializer, and its sole purpose, as the name suggests, is to initialize arrays.
The syntax is related to the array initializer:
An array initializer may be specified in a field declaration (§8.3, §9.3) or local variable declaration (§14.4), or as part of an array creation expression (§15.10.1), to create an array and provide some initial values.
Basically you not only create the array, but also initialize all its fields in the same instruction.
It is not a cast.
Note that the code:
String[] str = new String[]{"a","b","c"};
is a single command to create and initialize the array but it is also possible to use a less verbose version:
String[] str = {"a","b","c"};
Arrays can be created in multiple ways like below, and you are using the second one which is called the Array Initializer where you create the array while also initializing it.
int[] abc = new int[3]; // This means an array of integers with size 3 is created.
int[] def = new int[]{1,2,3}; // This means an array of integers with size 3 is created and also initialized with the values 1, 2 and 3.
In the second statement, I am creating an array of integers with the elements as 1, 2 and 3 where the size is implicitly 3.
So, in your case String[] str = new String[]{"a","b","c"}; , this statement is creating an array of String values with elements "a", "b" and "c" with the implicit size of the array being 3 due to the 3 elements which it is initialized with.

Create array of arrays (2D) without initializing inner arrays in Java

I want to build a 2D array from N (one-dimensional) arrays. The only problem is, as far as I can tell, the only way to declare a multi-dimensional array in Java requires you to specify all inner dimension sizes, and those sub-arrays get created. In this case, this seems wasteful, since they will be overwritten
In C++, I could do this:
Object** arr = new Object*[n];
for(int i=0;i<n; ++i)
{
arr[i] = getObjArr();
}
In Java, you have to say this:
Object[][] arr = new Object[n][0]; //inner dimension is required
Each of those n zero-length arrays will be created, only to get overwritten as the array is populated. Is there a way to declare a multi-dimensional array (similar to the pointer to pointer(s) syntax of C) without allocating the inner arrays?
Sure. I don't know why you think you have to do that!
double[][] foo = new double[2][];
is perfectly fine. The "inner" arrays will be null.
Inner dimensions do not have to be specified. This is legal in Java:
Object[][] arr = new Object[n][];
This creates an array of n elements, where each element has type Object[]. Since you did not specify an inner dimension, those n elements are all initialized to null. You can then assign any Object[] you want to any of those n array elements.
For higher-dimensional arrays, the rule (if you don't have an initializer) is that you can say new T followed by one or more specified dimensions ([some-value]), followed by zero or more [] for unspecified dimensions. You can't have [] followed by [value].

Why do we need to define array length when creating one-dimensional arrays object?

for example: why this statement long[] n= new long[]; is wrong but this statement
long[][] n= new long[1][]; is right? How does the memory know how much memory needs to be assigned to the object in the second statement?
How does the memory know how much memory needs to be assigned to the object in the second statement?
Two things to remember here to figure out what's going on:
2D Java arrays aren't square, they're arrays of arrays.
You specify the size of an array when it's created.
So in this example, you're creating an array of longs (of size 1) to hold another array of longs - but you're not yet creating the second array (so you don't need to specify how large it will be.) In effect, the first array provides an empty "slot" (or slots if the outer array is longer than 1) for the inner array(s) to sit in - but the inner array(s) haven't yet been created, so their size doesn't need to be specified.
It doesn't just create an array of arbitrary length at all, it simply doesn't create any inner arrays.
You can perhaps see this more clearly if you try to access or store a long in the 2D array:
long[][] x = new long[2][];
x[0][0] = 7;
...will produce a NullPointerException (on the second line), because there is no inner array there to access.
In the first example that doesn't compile, you're trying to actually create an array of longs, but not giving it a dimension, hence the error.
when you write this - long[][] n= new long[1][];
you are creating array of arrays of long but you are not actually initializing those arrays right now
So if you do n[0] == null it will return true
that way you are free to initialize new array in any point of time later-
n[0] = new long[10];
So the point is - you need to provide size while initializing your array , that is why long[] n= new long[]; is wrong

Calling methods with array output twice in same scope

Suppose you have a method that outputs arrays of different sizes.
Before you use it, you need to create an array reference variable. Before you can do that, you need to find the array length, e.g.
int[] intArray = new int[methodReturnsArray().length]
And then you can set intArray to your array produced by methodReturnsArray().
I feel a bit uneasy about this, because we're calling methodReturnsArray() twice: once to find out how big the array is, and again to set it equal to the reference variable.
Is that wasting resources to call the method twice, or is the array only created once (when you find its size)?
Edit: I know you can just initialize intArray to the method returned by the array. But for some complicated reasons (to do with "methodReturnsArray" being called in a loop with a different-sized array for each iteration) I need to know whether calling twice will waste computational resources.
It depends on how you will then fill new array variable.
But the common approach will be introducing new local variable for saving reference to original array from method methodReturnsArray. i.e.:
int[] methodArray = methodReturnsArray();
int[] intArray = new int[methodArray.length];
...
Then the best way for copying an array is System.arrayCopy(...) method.
This approach will work in any case, and it will prevent you from doing things in method methodReturnsArray twice.

How is length implemented in Java Arrays?

I was wondering about the implementation of length of a Java Array. I know that using arrayName.length gives us the number of elements in the array, but was wondering if this is a method / function or it is just a data member of Array?
I guess it must be a data member as we do not use parenthesis() when invoking it. But if it is a data member how/when is the value of this length assigned/computed?
According to the Java Language Specification (specifically §10.7 Array Members) it is a field:
The public final field length, which contains the number of components of the array (length may be positive or zero).
Internally the value is probably stored somewhere in the object header, but that is an implementation detail and depends on the concrete JVM implementation.
The HotSpot VM (the one in the popular Oracle (formerly Sun) JRE/JDK) stores the size in the object-header:
[...] arrays have a third header field, for the array size.
You're correct, length is a data member, not a method.
From the Arrays tutorial:
The length of an array is established when the array is created. After creation, its length is fixed.
If you have an array of a known type or is a subclass of Object[] you can cast the array first.
Object array = new ????[n];
Object[] array2 = (Object[]) array;
System.out.println(array2.length);
or
Object array = new char[n];
char[] array2 = (char[]) array;
System.out.println(array2.length);
However if you have no idea what type of array it is you can use Array.getLength(Object);
System.out.println(Array.getLength(new boolean[4]);
System.out.println(Array.getLength(new int[5]);
System.out.println(Array.getLength(new String[6]);
Yes, it should be a field. And I think this value is assigned when you create your array (you have to choose the length of array while creating, for example: int[] a = new int[5];).
I believe its just a property as you access it as a property.
String[] s = new String[]{"abc","def","ghi"}
System.out.println(s.length)
returns 3
if it was a method then you would call s.length() right?
From the JLS:
The array's length is available as a
final instance variable length
And:
Once an array object is created, its
length never changes. To make an array
variable refer to an array of
different length, a reference to a
different array must be assigned to
the variable.
And arrays are implemented in the JVM. You may want to look at the VM Spec for more info.
It is a public final field for the array type. You can refer to the document below:
http://java.sun.com/docs/books/jls/third_edition/html/arrays.html#10.7
Every array in java is considered as an object. The public final length is the data member which contains the number of components of the array (length may be positive or zero)
Java arrays, like C++ arrays, have the fixed length that after initializing it, you cannot change it. But, like class template vector - vector <T> - in C++ you can use Java class ArrayList that has many more utilities than Java arrays have.

Categories

Resources