why I need 'new' for array parameter? [duplicate] - java

This question already has answers here:
Passing directly an array initializer to a method parameter doesn't work
(3 answers)
Closed 2 years ago.
int add(int[] scores){ ... }
-------------------------------
int result = add({1,2,3}); //wrong
int result = add(new int[] {1,2,3}); //correct
I know I have to code like this but
why we must put 'new int[]' for parameter??

The array initializer syntax ({1, 2, 3}) can only be used in certain circumstances:
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.
In other circumstances, you would need to use an array creation expression (e.g. new int[] {1, 2, 3}).
This is just how the language is specified. It could be different, but it's not.

As it has been pointed out, the array initialize can only be used in variable declarations.
You might want to use varargs in you example like that:
int add(int... scores){ ... }
You can call it in two ways:
int result = add(1,2,3);
int result = add(new int[] {1,2,3});

Related

Why I can't declare an array and then assign value in this fashion? [duplicate]

This question already has answers here:
Array initialization syntax when not in a declaration
(4 answers)
How do I declare and initialize an array in Java?
(31 answers)
Closed 4 years ago.
Why when I try to initialize the array like that it gives me an error
package practicejava;
class Test {
public static void main(String[] args) {
int[] array;
array ={};
}
}
Why the following code shows me an error?
Change as follow:
int[] array;
array = new int[]{};
Your current way of assigning the array is invalid.
you have to declare array size in array like as below
array = new int[5];
The array needs to be declared on the same line of code as:-
int[] array = new int[]{...};
The first line of your code that is:-
int [] array = {...}
This line is allowed by Java and is just a shorthand notation for the above declaration. Note that, this is only allowed if the declaration and initialization of the array is done simultaneously (the allocation of array is handled internally and is done accordingly to the number of elements).
The line
int [] array;
just creates a reference in the stack which is null that is it doesn't point to anything.
But, when you do array = {...}, it is no longer valid as the memory needs to be allocated prior to initialization. Java does not handle such initialization internally.
So, it is recommended to initialize
array = new int[]{...}
instead.

what's the differences between static initialization and dynamic initialization in Java? [duplicate]

This question already has answers here:
How do I declare and initialize an array in Java?
(31 answers)
Closed 5 years ago.
Recently when I do some practice on LeetCode,I find some trick solution.It use an Object o to reference an arrayObject o = new Object[]{null,null};,I guess maybe it's because in java everything is object.But when I tried this way,it went wrong.Object o3 = {1,2};So I tried every way to initialization a array and I want to see the difference,like these
int arr[] = {1,2};
Object o = arr;
Object o1 = new int[2];
Object o2 = new int[]{1,2};
Object o3 = {1,2};
Only the o3 will compile an error.I don't know if it's because the way of initialization.I know when I use static initialization it will allocate memory first,when use dynamic initialization it will not.Any other differences between them cause this error?When I use new to create a array.what did it do in jvm?Thanks in advance.
The initializer {1,2} is shorthand for new int[] {1,2}. This shorthand can only be used as an initializer for a variable of type int[].1 For instance, while the following works:
int arr[] = {1,2};
this doesn't:
int arr[];
arr = {1,2}; // ERROR
Instead, you would need to use:
int arr[];
arr = new int[] {1,2};
Similarly, you can use:
Object o3 = new int[] {1,2};
P.S. The above applies to static as well as instance fields, and also to local variables. Java doesn't have such a distinction as "static vs. dynamic initialization". That's more C++ terminology.
1Well, it could also be for a variable of type byte[], long[],
float[], Integer[], etc., for which the literals 1 and 2 are assignment compatible. See the Section 10.6 of the Java Language Specification.

How to set array elements after I have initialized it? [duplicate]

This question already has answers here:
Initializing an array after the declaration
(4 answers)
Closed 6 years ago.
I am looking for a simple way to set the elements of an array after it is initialized. I have tried this :
package com.ehsan.app;
public class Main {
public static void main(String[] args) {
int[] test = new int[6];
test = {1,2,3,4,5};
}
}
However compiling this gives error :
Error:(7, 16) java: illegal start of expression
Error:(7, 17) java: not a statement
Error:(7, 18) java: ';' expected
Error:(9, 1) java: class, interface, or enum expected
I can use this way to put values in the array:
test[0] = 1;
test[1] = 2;
test[2] = 3;
test[3] = 4;
// and so on.
I am just looking for a simple way to do that.
Edit
I know I can use this :
int[] test = {1,2,3,4};
But what I want is a simple way to put values in array after its initialization.
And one another thing : I am not looking for loops!
Edit
The answer #Python gave was what I was looking for!
You can simply do this by using Arrays's static method in one line:
Integer[] test = new Integer[10];
Arrays.<Integer>asList(1,2,3,4,5,6,7).toArray(test);
Note: using 'int' is also fine but then you to add explicit casting (int[])
If you want to initialize an array, try using Array Initializer:
int[] test = new int[6];
int[] test = {1,2,3,4,5,6};
OR
int[] test = new int[]{1,2,3,4,5,6};
Initialize using a for loop:
for(int i=0;i<test.length-1;i++){
test[i]=i;
}
this will make the test array have, 0,1,2,3,4,5 as its contents;
I believe there is no other way than having a loop to populate your already-instantiated array.
However, you don't need to write the loop by yourself:
System.arrayCopy() does the work. And one day JVM may decide to do something like memcpy to do the work, by using such kind of built-in functions, you may benefit from such JVM change without change in your source code.
After initializing you can't assign values all at once,
you can do it this way :
test[0]=1;
test[1]=2;
and likewise..
hope this will help

Array as parametar [duplicate]

This question already has answers here:
Java array initialization within argument list
(4 answers)
Closed 7 years ago.
I don't understand, and can't find on google how do I call my method, whose parameter is an array?
private static void printArray(double a[],int p){
int count[]=new int[p];
for(int i=0;i<a.length;i++){
for(int j=0;j<p;j++){
if((a[i]>=100/p*j) && (a[i]<100/p*(j+1))){
count[j]++;
for example, how do I call this method in my main method:
I tried printArray({1,2,3,4,5},5); and it's not working or printArray([10],5); but still doesn't work?
You would first need to create an array. Like you did here:
int count[]=new int[p];
In your example something like
double myArray[] = {1,2,3,4,5};
Then you would pass the variable name to your method like:
printArray(myArray, someInt);
Hope this helps.
The issue with your calls is:
printArray({1,2,3,4,5},5); - {1,2,3,4,5} as a parameter is not recognized. You need to create an array which is of type double.
printArray([10],5); - [10] is also not recognized by the compiler and is not the correct way to pass double[].
This is how to initialize an array inline in java:
new double[]{1,2,3,4,5}
So, this is how you call it:
printArray(new double[]{1,2,3,4,5},5);
you can call your method like this, if the method is in the same class with method main.
double[] arr = {1,2,3,4,5};
printArray(arr,5);
[10] is not a variable. When you pass an array you do not need brackets. Just the variable name. For example:
double array1[] = {10,12,13};
printArray(array1);

Array declaration in main method [duplicate]

This question already has answers here:
Difference between int[] array and int array[]
(26 answers)
Closed 8 years ago.
I was reading and faced with interesting look of main method which I didn't see before. Is there any difference between
public static void main(String[] args)
and
public static void main(String a[])
As I see applying either of them gives me the same output
public static void main(String a[]){
List <Integer> li = new ArrayList <Integer>();
ListIterator <Integer> liItr = null;
li.add(1);
li.add(2);
li.add(3);
li.add(4);
li.add(5);
li.add(6);
li.add(7);
liItr = li.listIterator();
System.out.println("Elemnets in forward direction");
while(liItr.hasNext()){
System.out.println(liItr.next());
}
System.out.println("Elements in backward direction");
while(liItr.hasPrevious()){
System.out.println(liItr.previous());
}
}
}
P.S. I consider myself as a beginner of Java. If someone could highlight giving me some explanation on that it would be nice
From http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.2
The [] may appear as part of the type at the beginning of the
declaration, or as part of the declarator for a particular variable,
or both.
For example:
byte[] rowvector...
This declaration is equivalent to:
byte rowvector[]...
BTW, not many realize that unfortunately this rule affects also Type methodSignature pair, not only Type variable. So something like
int giveMeArray()[]{
// ^^^^^^^^^^^^^ - method signature
return new int[10];
}
is also valid Java code.
Anyway this way of declaring array can be useful if you would like to create... lets say 2 and 3 dimensional arrays. So instead of
int[][] arr2d;
int[][][] arr3d;
you can just write
int[][] arr2d, arr3d[];
// ^^-additional dimension
No, there's no difference. The only difference is the array declaration:
String[] args
vs
String a[]
Both are valid.
From Java Language Specification. Chapter 10. Arrays. 10.2. Array Variables. (emphasis mine):
Example 10.2-1. Declarations of Array Variables
int[] ai; // array of int
short[][] as; // array of array of short
short s, // scalar short
aas[][]; // array of array of short
Object[] ao, // array of Object
otherAo; // array of Object
Collection<?>[] ca; // array of Collection of unknown type
The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both.
For example:
byte[] rowvector, colvector, matrix[];
This declaration is equivalent to:
byte rowvector[], colvector[], matrix[][];
No there isn't a difference. See also http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html which states this: "You can also place the brackets after the array's name:", but suggests it is bad form.
String[] args is as valid as String args[] and as String a[].
Java has no restriction regarding arguments naming and authorizes both styles of array declaration syntaxes (brackets after or before the variable name) => Matter of taste.

Categories

Resources