Initializing an array after the declaration - java

Why we cannot use array intializer after declaring an variable.
For example:
int arr[];
arr = {1,2,3,4};
But,
int arr[] = {1,2,3,4};
is correct.
Is there any way to use array initialize after declaring an variable.

This is how you can.
int arr[];
arr = new int[]{1, 2, 3, 4};

There are three steps to creating an array, declaring it, allocating it and initializing it.
Declaring Arrays
Like other variables in Java, an array must have a specific type like byte, int, String or double. Only variables of the appropriate type can be stored in an array. You cannot have an array that will store both ints and Strings, for instance.
Like all other variables in Java an array must be declared. When you declare an array variable you suffix the type with [] to indicate that this variable is an array. Here are some examples:
int[] k;
float[] yt;
String[] names;
In other words you declare an array like you'd declare any other variable except you append brackets to the end of the variable type.
Allocating Arrays
Declaring an array merely says what it is. It does not create the array. To actually create the array (or any other object) use the new operator. When we create an array we need to tell the compiler how many elements will be stored in it. Here's how we'd create the variables declared above:
k = new int[3];
yt = new float[7];
names = new String[50];
The numbers in the brackets specify the dimension of the array; i.e. how many slots it has to hold values. With the dimensions above k can hold three ints, yt can hold seven floats and names can hold fifty Strings. Therefore this step is sometimes called dimensioning the array. More commonly this is called allocating the array since this step actually sets aside the memory in RAM that the array requires.
This is also our first look at the new operator. new is a reserved word in java that is used to allocate not just an array, but also all kinds of objects. Java arrays are full-fledged objects with all that implies. For now the main thing it implies is that we have to allocate them with new.
Initializing Arrays
Individual elements of the array are referenced by the array name and by an integer which represents their position in the array. The numbers we use to identify them are called subscripts or indexes into the array. Subscripts are consecutive integers beginning with 0. Thus the array k above has elements k[0], k[1], and k[2]. Since we started counting at zero there is no k[3], and trying to access it will generate an ArrayIndexOutOfBoundsException.
You can use array elements wherever you'd use a similarly typed variable that wasn't part of an array.
Here's how we'd store values in the arrays we've been working with:
k[0] = 2;
k[1] = 5;
k[2] = -2;
yt[6] = 7.5f;
names[4] = "Fred";
We can even declare, allocate, and initialize an array at the same time providing a list of the initial values inside brackets like so:
int[] k = {1, 2, 3};
float[] yt = {0.0f, 1.2f, 3.4f, -9.87f, 65.4f, 0.0f, 567.9f};
see http://www.cafeaulait.org/javatutorial.html#xtocid499429

Because an array doesn't work like that in java.
int arr[4];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;

Check this
example :-
int data[] = new int[] {10,20,30,40,50,60,71,80,90,91 };
or
int data[];
data=new int[] {10,20,30,40,50,60,71,80,90,91 };

Related

Get size of second dimension while first dimension is empty [duplicate]

Well, that might be a strange question, and maybe just because I'm not familiar enough with Java.
So, I declared a 2D int array:
int[][] arr = new int[0][10]
Now, as you can see, the second dimension's length is 10, while the first dimension's length is 0. I'm not sure how Java treats these kind of arrays, but the compiler doesn't produce any errors, which means it's a legit declaration.
Well, I passed the array to some function, and I want to retrieve from within the function, the length of the second dimension.
Of course something like:
arr[0].length
won't work. is there another way to do this?
The objects created by new int[0][10] and new int[0][20] are equivalent. There is no logical "second dimension" here. Effectively you're running something like this:
int[][] createArray(int d1, int d2) {
int[][] ret = new int[d1][];
for (int i = 0; i < d1; i++) {
ret[i] = new int[d2];
}
return ret;
}
Now if you translate that into your scenario, you'll end up with code which never reads d2.
If you want to represent a general-purpose rectangular array (instead of an array of arrays) you might want to consider creating your own type for it.
Arrays in Java, and most every other programming language, are zero-based. Consider this 2D array:
int[][] arr = new int[1][10];
This means that there is one row and ten columns in it.
Now, consider this array:
int[][] arr = new int[0][10];
This means that there are zero rows and (an irrelevant amount of columns) in it.
If you try to index into the second array, you'll find that you can't - an array of length zero has no starting point.
The compiler sees it as valid because you declared dimensions with it, but you won't be able to actually use it in any meaningful way in Java.
There is no such thing as the length of the second dimension. Consider:
int[][] arr = new int[10][10];
arr[5] = new int[42];
What is the length of the second dimension? 10 or 42?
No. It doesnt work this way. arr is an array with ten elements, each of which must be a reference of an int array (or null). That's all there is to say.

Java arrays objects and initializer confusion

I'm learning java and was told arrays are implemented as objects. But they show two different codes without diving into details.
First they ask us to use arrays like this, but the downside is to manually add the values:
int nums[] = new int[10];
nums[0] = 99;
nums[1] = -622;
.
.
.
Then they use this in some programs saying new is not needed because Java automatically does stuff:
int nums[] = {99, - 10, 100123, 18, - 972 ......}
If the second code is shorter and allows me to use arrays straightaway whats the point of the first code if they do the same thing but the first one require more code to input value by hand.
Let's say you were initializing an array of 1 million values, would you use the second method? No, because you would have a huge java file.
The first method is essentially allocating space:
int[] array = new int[1000000];
Creates 1 million spaces in memory with default value 0. Now if you want to initialize them, you may use a loop:
for (int i = 0; i < array.length; i++) {
array[i] = i;
}
If you wanted an array of 10 million values, you only change one number:
// Just add a 0 to 1000000
int[] array = new int[10000000]
Now, if the size of your array changes, you don't have to change the loop. But if you used the second method and wanted an array of 10 million values, you would have to add 9 million values, and 9 million commas to your java file - not scalable.
int[] array = {1, 2, 3, 4, ... 1000000};
The second method is not "scalable." It only works for small arrays where you can confidently assume that the default values of that array won't change. Otherwise, it makes A LOT more sense to use the first (more common) method.
//This is one way of declaring and initializing an array with a pre-defined size first
int nums[] = new int[10];
//This is initializing the array with a value at index 0
nums[0] = 99;
//This is initializing the array with a value at index 1 and likewise allocating rest of array index values
nums[1] = -622;
//This is another way of declaring and initializing an array directly with pre-defined values. Here if you see instead of declaring array size first, directly the values are initialized for it
int nums[] = {99, - 10, 100123, 18, - 972 ......}
It depends on the way you prefer to use the arrays, but you must remember that whenever you use "new" keyword, there is a new space or resource created every time in memory.
When you don't know the items of array at the time of array declaration, then prefer method-1,
and,
when you know the all the values of array at the time of array declaration, then go for method-2
Imagine you want to generate a series of random integers at runtime and want to store in the array:
int[] array = new int[1000000];
Random r = new Random();
for (int i = 0; i < array.length; i++)
array[i] = r.nextInt();

Multidimensional array declaration

Which one is valid statement?
int[] x =new int[0]{};
new int[2];
int[] x=new int[][]{{1}}[0];
int[][] x = new int[]{0}[0][0];
int x= new int[2]{}[];
The correct answer is 3, and I can understand why it's not 1, 2 or 5, but I don't understand 3 or 4 mean.
1) int[] x =new int[0]{};
You cannot specify both a length 0 and an array initializer at the same time.
2) new int[2];
It's not a statement. It would become a statement if it were assigned to something else, among other possibilities.
3) int[] x=new int[][]{{1}}[0];
This declares and initializes a 1x1 2D array, with 1 being its only element. Then, array access is used to immediately access the "row" at position 0, the only such "row", which is itself a 1-length 1D array, and that is assigned to a 1D array.
4) int[][] x = new int[]{0}[0][0];
There is a lot wrong here. A 1-length, 1D array is created, but there are two array accesses on it. You can only supply one, because it's a 1D array.
5) int x= new int[2]{}[];
The extra [] doesn't do anything and is invalid syntax. Even if they're removed, you can't assign an int array to a scalar int. Also you can't specify a length and an array initializer {} at the same time.
When you declare and initialize an array using {} you are not allowed to indicate the number of items in the array ergo int[0] should be int[]. So it should have been int[] x = new int[]{}.
This is an initialization without a declaration so it should have been something like int[] x = new int[2].
This is correct because it assigns a declaration to an item of two-dimensional array which is an array itself. So the array returned from new int[][]{{1}}[0] is new int[]{1} and thus int[] x = new int[]{1}.
This is totally wrong and messed up. new int[]{0}[0][0] is trying to get a value of a two-dimensional array from a one-dimensional array and assign that to a the array x.
Here as discussed already in point 1, plus trying to access an array with an empty index [] which not possible.

What is the difference Between Primitive array and Array of Reference .

I read in net and Found reference array store references. References in sense the array is going to store memory address of variables i Guess if i am not mistaken. If that's the Case why i don't see the memory address when i loop through string array as Below.
String[] arrNames = new String[3];
arrNames[0] = "John";
arrNames[1] = "Mac";
arrNames[2] = "Alex";
Now as per the definition the arrNames array is going to store References at arrNames[0],arrNames[1], arrNames[2]. Which means memory address which is going to point to Names i.eJohn, Max and Alex.
If it is Primitive array its directly going to store the values like below.
int[] Num = new int[3];
Num[0] = 1;
Num[1] = 2;
Num[2] = 3;
The Num[0] is directly going to hold Numbers 1 instead of address which points to number.
Please correct me if i misunderstood it.
In java there is no primitive array. Even though we had the primitive values in an array, then the array itself considered as array object.
Primitive arrays and Reference arrays are exactly similar object.
Moreover, default values also applied with a primitive array:
int[] myPrimitiveArray = new int[1];
assertTrue(myPrimitiveArray[0], 0) //passed since 0 by default in each cell
Same as:
Integer[] myReferenceArray = new Integer[1];
assertTrue(myPrimitiveArray[0], 0) //passed since 0 by default in each cell

java multidimensional array notation

To create an length 5 int array, we use the syntax:
int[] x = new int[5]
To create a 2 dimensional array, an array of int arrays, we say:
int[][] x = new int[5][];
This creates an array of length 5, which can hold int[] objects.
For this second case, why isn't the syntax this: ?
int[][] x = new int[][5]
After all, 5 defines how many int arrays we can have. Not the size of the int arrays that we're going to put into x.
It would be really weird to have the indices for lookups be different from the indices for construction. So if you had int[][] x= new int[][5], then you'd look up the elements with x[0..4][foo], which is just more confusing than the alternative.
The array bring declared is the first dimension, so declaring the referenced array size does nothing to allocate the actual array. It would be similar to coding this:
int[] a = new int[];

Categories