Need clarification for java array declaration - java

If we do int[] b = {2, 4}; then we have an array called b, with length 2. From what I understand, the java compiler is implicity doing int[] b = new int[] {2, 4}; for me, fine.
Similarly, if we do int[] c = new int[2]; , then we get an array called c initialzed to {0, 0} My confusion comes from why the following doesn't work:
Why can't I do int[] d = new int[2] {5, 6};

It's just a compiler thing. Besides, why would you want to manually input the size anyway?
This will just be a source of error.
The int[] b = new int[] {2, 4} notation is for convenience, if you already know the contents of the array that you want to declare.

Related

What's the advantages in these 2 types of declaration?

I have a question on the styles of declaration of arrays
//I get that you may just want to initliaze array with 0s for some reason
int[] myIntArray = new int[3];
//I get that you already know what values you want in this array
int[] myIntArray = {1, 2, 3};
What's the advantage in declaring in these 2 notations:
//Woulnd't I just use the 1st notation for this
int[] myIntArray;
myIntArray=new int[3];
//Wouldn't I just use the 2nd notation for this
int[] myIntArray = new int[]{1,2,3};
The 4th notation is almost as same as the 2nd notation except the fact that there are 2 references,myIntArray and an anonymous array, to the object {1,2,3} where the 2nd reference,anonymous is lost instantly
The difference between int[] myIntArray = {1, 2, 3}; and int[] myIntArray = new int[]{1,2,3}; is that the first syntax only works when initializing a variable.
So if you have code like this:
int[] myIntArray = {1, 2, 3};
// some code
if (someCondition) {
myIntArray= new int[] {4, 5, 6};
}
You can not replace the second one with just {4, 5, 6}, because that syntax is reserved for initializing only.
But new int[] {4, 5, 6} is a general expression that works basically anywhere.
It's mostly used where you want to construct an array and not assign it to a variable, such as directly passing it to a method call:
someFunctionTakingAnIntArray(new int[] {3, 4, 5});

Java multidimensional array layout

I am studying for an exam and this is about memory allocation of a multidimensional java array.
Given is the following code:
double [][] a = new double[4][];
for (int i = 0; i < 4; i++)
a[i] = new double[4-i];
I am supposed to draw the memory layout of this array, but I am afraid I don't fully comprehend how it even works.
It would also be very kind of you if you could show me how to print this array as list to the console so I can look at it. :)
Thank you for your time.
you don't have to create new array in the for loop. Try this:
double[][] a = new double[4][3];
Or you can initialize it in one statement like:
double[][] a = {
{1, 3, 2},
{4, 5, 6},
{7, 8, 9}
};
And then print:
System.out.println(Arrays.deepToString(a))
Since your array a is an array of array (2D) , you can use enhanced for loop to print elements.
So, your outer loop has double[] as type, and hence that declaration. If you iterate through your a in one more inner loop, you will get the type double.
double[][] a = {
{1, 3},
{4, 5},
{7, 8}
};
List<Double> dou = new ArrayList<Double>();
for (double[] k: a) {
for (double element: k) {
dou.add(element) ;
}
}
System.out.println(dou);
Output
[1.0, 3.0, 4.0, 5.0, 7.0, 8.0]
I am not sure if this answers your question.
Above picture depicts how array elements will be stored in memory.

What is the most efficient way to initialize an array with values? [duplicate]

I know how to do it normally, but I could swear that you could fill out out like a[0] = {0,0,0,0}; How do you do it that way? I did try Google, but I didn't get anything helpful.
Check out the Arrays.fill methods.
int[] array = new int[4];
Arrays.fill(array, 1); // [1, 1, 1, 1]
You can also do it as part of the declaration:
int[] a = new int[] {0, 0, 0, 0};
Arrays.fill(). The method is overloaded for different data types, and there is even a variation that fills only a specified range of indices.
In Java-8 you can use IntStream to produce a stream of numbers that you want to repeat, and then convert it to array. This approach produces an expression suitable for use in an initializer:
int[] data = IntStream.generate(() -> value).limit(size).toArray();
Above, size and value are expressions that produce the number of items that you want tot repeat and the value being repeated.
Demo.
Arrays.fill(arrayName,value);
in java
int arrnum[] ={5,6,9,2,10};
for(int i=0;i<arrnum.length;i++){
System.out.println(arrnum[i]+" ");
}
Arrays.fill(arrnum,0);
for(int i=0;i<arrnum.length;i++){
System.out.println(arrnum[i]+" ");
}
Output
5 6 9 2 10
0 0 0 0 0
An array can be initialized by using the new Object {} syntax.
For example, an array of String can be declared by either:
String[] s = new String[] {"One", "Two", "Three"};
String[] s2 = {"One", "Two", "Three"};
Primitives can also be similarly initialized either by:
int[] i = new int[] {1, 2, 3};
int[] i2 = {1, 2, 3};
Or an array of some Object:
Point[] p = new Point[] {new Point(1, 1), new Point(2, 2)};
All the details about arrays in Java is written out in Chapter 10: Arrays in The Java Language Specifications, Third Edition.
Array elements in Java are initialized to default values when created. For numbers this means they are initialized to 0, for references they are null and for booleans they are false.
To fill the array with something else you can use Arrays.fill() or as part of the declaration
int[] a = new int[] {0, 0, 0, 0};
There are no shortcuts in Java to fill arrays with arithmetic series as in some scripting languages.
int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

Is there any way of creating an array filled with a particular value in java? [duplicate]

I know how to do it normally, but I could swear that you could fill out out like a[0] = {0,0,0,0}; How do you do it that way? I did try Google, but I didn't get anything helpful.
Check out the Arrays.fill methods.
int[] array = new int[4];
Arrays.fill(array, 1); // [1, 1, 1, 1]
You can also do it as part of the declaration:
int[] a = new int[] {0, 0, 0, 0};
Arrays.fill(). The method is overloaded for different data types, and there is even a variation that fills only a specified range of indices.
In Java-8 you can use IntStream to produce a stream of numbers that you want to repeat, and then convert it to array. This approach produces an expression suitable for use in an initializer:
int[] data = IntStream.generate(() -> value).limit(size).toArray();
Above, size and value are expressions that produce the number of items that you want tot repeat and the value being repeated.
Demo.
Arrays.fill(arrayName,value);
in java
int arrnum[] ={5,6,9,2,10};
for(int i=0;i<arrnum.length;i++){
System.out.println(arrnum[i]+" ");
}
Arrays.fill(arrnum,0);
for(int i=0;i<arrnum.length;i++){
System.out.println(arrnum[i]+" ");
}
Output
5 6 9 2 10
0 0 0 0 0
An array can be initialized by using the new Object {} syntax.
For example, an array of String can be declared by either:
String[] s = new String[] {"One", "Two", "Three"};
String[] s2 = {"One", "Two", "Three"};
Primitives can also be similarly initialized either by:
int[] i = new int[] {1, 2, 3};
int[] i2 = {1, 2, 3};
Or an array of some Object:
Point[] p = new Point[] {new Point(1, 1), new Point(2, 2)};
All the details about arrays in Java is written out in Chapter 10: Arrays in The Java Language Specifications, Third Edition.
Array elements in Java are initialized to default values when created. For numbers this means they are initialized to 0, for references they are null and for booleans they are false.
To fill the array with something else you can use Arrays.fill() or as part of the declaration
int[] a = new int[] {0, 0, 0, 0};
There are no shortcuts in Java to fill arrays with arithmetic series as in some scripting languages.
int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

Inline Array Definition in Java

Sometimes I wish I could do this in Java:
for (int i : {1, 2, 3, 4, 5})
System.out.println(i);
Unfortunately, I have to do something like this instead:
int [] i = {1, 2, 3, 4, 5};
// ...
My recollection is that C++ has this sort of feature. Is there an OOP replacement for inline array definitions (maybe even to the point of instantiating anonymous classes)?
I think the closest you are gonna get is:
for(int i : new int[] {1,2,3,4})
You could create the int[] array in the for loop.
for (int i : new int[] {1, 2, 3, 4, 5}) {
...
}
Here you are making an anonymous int array, which is the closest thing to what you want. You could also loop through a Collection.
Note that this question has nothing to do with OOP. It's merely a matter of syntax. Java supports anonymous arrays/objects just like C++.
You don't have to create a separate variable for this. The syntax {1, 2, ...} is valid only for declarations, but you can always say new int[] {1, 2, ...}:
for (int i : new int[] {1, 2, 3, 4, 5})

Categories