String Array Assignment in Java [duplicate] - java

This question already has answers here:
Arrays constants can only be used in initializers error
(5 answers)
Closed 4 years ago.
Code:
String Foo[];
Foo={"foo","Foo"};
Error at Line 2: Illegal Start of expression
The code works if I say:
String Foo[]={"foo","Foo"};
Why does this happen, and how should I do the required without generating an error? This also happens with other data types.
Would appreciate if you could explain in layman terms.

{"foo","Foo"} is an array initializer and it isn't a complete array creation expression:
An array initializer may be specified in a declaration (§8.3, §9.3, §14.4), or as part of an array creation expression (§15.10), to create an array and provide some initial values.
Java Specification
Use new String[] {"foo","Foo"} instead.

You have to initialize the string array:
String foo[] = new String[]{"foo, "Foo"}; Or
String foo[] = {"foo, "Foo"};
Modern IDEs give error for not initializing the array objects. You can refer more details here:
http://grails.asia/java-string-array-declaration

Related

How to get Sum of byte arraylist objects in java [duplicate]

This question already has answers here:
What is a raw type and why shouldn't we use it?
(16 answers)
Closed 3 years ago.
I am trying to get the sum of all the byte arraylist from position 1 to end when i try to add i get error as "The operator + is undefined for the argument type(s) int, Object"
I have a finalbyte arraylist
ArrayList finalbyte = new ArrayList();
finalbyte.add(A);
finalbyte.add(B);
finalbyte.add(C);
finalbyte.add(D);
Am adding each value from different sources and the output of Syso looks like {67,8,1,-25,4,2,2,2,2}, the values are different for each run.Now am trying to add these values from {8,1,-25,4,2,2,2,2} 1st till the end position.
for(int i=0;i<finalbyte.size();i++) {
System.out.println(""+finalbyte.get(i));
value=value+finalbyte.get(i);
}
I want sum, value= {from 1st + end of byte list} and finalbyte.add(value); how can i add byte array values and add it back again to the bytearray list?
It doesn't understand what type finalbyte is. Much of the time this would have been more obvious but what you were doing requires that it knows that it needs two integers to add, not an integer an "Object"
There are two ways you could tell the compiler that it's an Integer--You can cast it when you get it out:
... +(Integer)finalbyte.get(i);
Or you can use generics when you declare it (BY FAR the better solution):
ArrayList<Integer> finalbyte = new ArrayList<>();
Once the compiler knows it's an Integer, it can properly auto-unbox the integer to an int, then + will work.
Note that your other operation worked because adding strings together actually uses the .toString() method--a method defined on "Object" itself so that it's always available.

Java function definition with brackets syntax [duplicate]

This question already has answers here:
Java Syntax: byte f()[] vs. byte[] f()
(4 answers)
Closed 3 years ago.
Was looking in the source for ByteArrayOutputStream, and I saw this function:
public synchronized byte toByteArray()[] {
return Arrays.copyOf(buf, count);
}
Where is this syntax documented? I mean the [] in front of the function. Is this the same as in declaring a regular array where the bracket can go after the name of the array or before, but in this case, the bracket can go after the function name?
String[] args;
Vs
String args[];
Edit: 2018-05-22
I found even more uses of this crazy syntax here: 10 things you didn't know about Java
#3 is where they make mention of all the ways the above syntax can be exploited
In JLS Sec 8.4:
MethodDeclarator:
Identifier ( [FormalParameterList] ) [Dims]
...
The declaration of a method that returns an array is allowed to place some or all of the bracket pairs that denote the array type after the formal parameter list. This syntax is supported for compatibility with early versions of the Java programming language. It is very strongly recommended that this syntax is not used in new code.

Inconsistency in returning primitive arrays in Java [duplicate]

This question already has answers here:
Java: Why can't return array using {..} without new operator?
(5 answers)
Closed 7 years ago.
The following show different ways of instantiating and returning a primitive array. However, for some reason, the last one doesn't work. Is there a valid explanation for this inconsistency? Why doesn't the last block work?
Block 1
int[] a = new int[] {50};
return a; // works fine
Block 2
int[] a = {50};
return a; // works fine
Block 3
return new int[] {50}; // works fine
Block 4
return {50}; // doesn't work
Why doesn't the last block work?
Because an array initializer (JLS 10.6) is only valid in either a variable declaration, as per your first and second blocks, or as part of an array creation expression (JLS 15.10.1), as per your third block.
Your fourth block isn't either a variable declaration or an array creation expression, so it's not valid.
Note that this isn't specific to primitive arrays at all - it's the same for all arrays.

Array inside a switch [duplicate]

This question already has answers here:
Array initialization syntax when not in a declaration
(4 answers)
Closed 8 years ago.
I'd like to ask if anyone knows how can I use the same array in a switch with different values for the different cases without getting error.
I have this code:
String [] measures;
switch(option){
case "Distance":
measures= {"Quilometers(km)", "Meters(m)"};
break;
case "Temperature":
measures= {"Celsius(ºC)", "Fahrenheit(ºF), "Kelvin(K)"};
break;
(...)
I'm getting the error "Array initializer is not allowed here" where I have measure={...}
But if I change the code and write inside each case,
String [] measures= {...}
I get the error "Variable measures is already defined in the scope".
Can you please help?
You can't initialize array with just braces { and } when you are not declaring the variable. But you can't re-declare measures because it has already been declared in the same block.
You need to explicitly use new String[] before the braces. Try
measures = new String[] {"Quilometers(km)", "Meters(m)"};
and likewise for your other cases.
Just say measures = new String[] {" instead of measures= {"....
Firstly, the String[] measures is not initialised. You should add in values in the array with String measures={...} or measures=new String[size];and then some values.
Secondly, and more importantly, Strings can not be used properly in a switch-case construct. It only tests equality and should be used only for intand char. Cheers!

Array error in java [duplicate]

This question already has answers here:
How is this illegal
(5 answers)
Closed 5 years ago.
int[][][] inputs;
inputs = new int[10][][];
inputs[0] = new int[1][];
inputs[0][0] = new int[14]{1,1,-1,-1,-1,1,-1,-1,1,-1,-1,-1,1,1};
This is an excerpt from my program, I have no idea why this is causing an error. Isn't this correct?
Thanks in advance :-)
In Eclipse I get a pretty clear error message:
Cannot define dimension expressions when an array initializer is provided.
That means that you can either specify the dimension or the array initializer (i.e. the values). You can't specify both at the same time.
Simply change your last line to
inputs[0][0] = new int[]{1,1,-1,-1,-1,1,-1,-1,1,-1,-1,-1,1,1};
You cannot construct an array with a declared length AND a static initialiser. It must be either one or the other.
change inputs[0][0] = new int[14]{1,1,-1,-1,-1,1,-1,-1,1,-1,-1,-1,1,1}; to inputs[0][0] = new int[]{1,1,-1,-1,-1,1,-1,-1,1,-1,-1,-1,1,1}; - the length of the new array is implicit because you are explicitly initialising the array with 14 elements.
The last line should simply be:
inputs[0][0] = {1,1, etc.};

Categories