Failed to pass array as parameter in java - java

I have a method doSomething() which accept Array as parameter. When I pass array like bellow:
package org.my;
public class ArrayMistry {
public static void main(String ... args) {
doSomething({1,2});// Compilation Error
}
public static void doSomething(int[] params) {
}
}
I am getting compilation error:
Exception in thread "main" java.lang.Error: Unresolved compilation
problems: Syntax error on token "doSomething", # expected before
this token Syntax error, insert "enum Identifier" to complete
EnumHeader Syntax error, insert "EnumBody" to complete
BlockStatements
at org.my.ArrayMistry.main(ArrayMistry.java:6)
Note:
if I pass as bellow then its OK:
public static void main(String ... args) {
int[] p = {1,2};
doSomething(p);// no Error
doSomething(new int[]{1,2});// no Error
}

Arrays are passed by reference. You need to create an array object with [1,2] and pass the reference of that created object to dosomething. The new keyword allocates space for the creation of this int array.
int[] arr = new int[]{1,2};
doSomething(arr);

It's because you aren't declaring {1, 2} as a new array. It must be declared as new int[]{1,2} to function properly, otherwise you are not creating an array.

You have to make an array to pass into a method because you initialized the method that way. The reason this doSomething({1,2}); doesn't work is because the array has not been initialized and {1, 2} is not an array, it is just some numbers in a parenthesis. if you wanted to send an array you have to do something like this
int[] p = {1,2};
doSomething(p);

Your method doSomething() specifically accepts an array of integers as its parameters.
Note in both cases where it worked, you either passed an existing array, or created a new one when passing it in.
In your original example, you are passing an arbitrary set of numbers with no memory reserved, or type specified.

Another way to solve the problem is by passing a reference as a parameter to the function like this:
doSomething(new int[]{1,2});

Related

How to enter one dimensional array filled with unknown values of variable

I'm a Java beginner and I don't understand how to make it. When I write in my code something like in the example, my IDE underlines it and says it's wrong when I only started writing my code. Can anybody help me guys?
Example:
public class ArrayUtils {
public static int[] lookFor(int[] array) {
int[] array = {};
}
}
The variable named array is already passed in as a parameter. Which means that you cannot create a new int[] named array inside the java method. Try naming it something else.
Syntax with {} means initialization of your array like int[] array = {1,2,3}.
But you can't initialize the variable with the same name as parameter's name.
You can assign a new array to the variable:
public static int[] lookFor(int[] array) {
array = new int[6]; // assign to variable new array with length 6
array = new int[]{1,3,5}; // assign to variable new array with initialized values
}
Note: in first case all 6 values will be zero
Update: as it was mentioned by #ernest_k reassigning method parameters is a bad practice. To avoid it method parameter usually marked as final int[] lookFor(final int[] array)

Accessing static constant arrays from Jtwig template

So, I simply cannot gather access to values in constant static arrays.
Let this be an array in my code:
public static int[] MY_ARRAY;
And this is how i trying to access that array:
{{ constant("com.package.configs.MainConfig.MY_ARRAY")[0] }}
This attempt leads to an error:
java.lang.ClassCastException: [I cannot be cast to [Ljava.lang.Object;
at org.jtwig.value.convert.collection.ArrayToCollectionConverter.convert(ArrayToCollectionConverter.java:11)
at org.jtwig.value.convert.CompositeConverter.convert(CompositeConverter.java:15)
at org.jtwig.render.expression.calculator.MapSelectionExpressionCalculator.calculate(MapSelectionExpressionCalculator.java:19)
at org.jtwig.render.expression.calculator.MapSelectionExpressionCalculator.calculate(MapSelectionExpressionCalculator.java:12)
at org.jtwig.render.expression.CalculateExpressionService.calculate(CalculateExpressionService.java:14)
...
I also tried to assign a constant to variable first, then accessing it, but nothing changed.
Previously, in an older versions of JTwig i was able to access any public static field of a object that i passed to the model. But now such fields are being ignored.
The version i am using is 5.86.0.
Any idea on how to beat this, or at this moment it's technically impossible?
The exception
java.lang.ClassCastException: [I cannot be cast to [Ljava.lang.Object;
means the array MY_ARRAY is an int-type array, and int is a primitive, thus it's not a sub type of Object, so you can not cast it to an Object-type array.
In this case, you can change MY_ARRAY's Signature to public static Integer[] MY_ARRAY.
Integer wraps the int value in an Object.
This is illustrated by the following example:
public static void main(String args[]) {
int[] arr = new int[5];
Integer[] arrI = new Integer[5];
test(arr); // error:The method test(Object[]) in the type Demo is not applicable for the arguments (int[])
test(arrI); // ok
}

Accepting any array as a parameter

I am trying to get getIntArrayString to accept parameters given to it, unlike abc.getAverage which uses the field testArray.
edit: Forgot to ask the question.
how would I be able to send parameters such as test1 to getIntArrayString()?
private int testArray;
public static void main(String[] args)
{
int[] testArray = new int[]{2,4,6,8,9};
ArrayHW abc = new ArrayHW(testArray);
System.out.printf(abc.getAverage());
int[] test1= new int[]{3,4,5,6,7};
System.out.printf("Array Values: %s\n",ahw.getIntArrayString());
int[] test1= new int[]{3,4,5,6,7}
System.out.printf("Array Values: %s\n",ahw.getIntArrayString());
}
I'm assuming you have a method named getIntArrayString inside another class. If you want to send the values of test1, the method getIntArrayString must have a parameter of test1's datatype. For example,
public int getIntArrayString(int [] x)
{
}
You should review your knowledge of methods.
Having two variables called testArray may seem a little confusing, but it's not syntactiacally wrong. However, it's less confusing to read your code if you don't, and even better if you remove any unused variables.
You are not posting any error messages, but I suppose you can't compile because you haven't declared any variable "ahw", and ahw.getIntArrayString() produces a compiler error.
In general, in order to be able to send a parameter of type int[] to a method it would be declared like this:
public String getIntArrayString(int[] intArray) { ... }
And you would call it like this
System.out.println(x.getIntArrayList(test1));
where test1 is an int array as declared in your own code.

please explain this output that using explicit cast to Object

class VarArgs {
public static void printArray(Object... args) {
for (Object obj : args)
System.out.print(obj + " ");
System.out.println();
}
public static void main(String[] args) {
printArray( new Integer[] { 1, 2, 3 });
}
}
The console's output is:
[Ljava.lang.Integer;#1888759
just want to know what is this output. The supposed castiing was via Object[] and that gives 1,2,3 as output, but when I use Object for casting I get this output
You can use
Arrays.toString(new Integer[]{1,2,3});
to view the actual contents of the array.
Or cast new Integer[]{1,2,3} to Object[] instead of Object, i.e:
printArray((Object[])new Integer[]{1,2,3});
Explanation of what is happening in your code:
When you are calling the printArray method you are casting your array to an Object so in fact you are passing just one object (not an array).
The foreach loop in the printArray method iterates only once as only one argument has been passed to the printArray method - the Integer[] {1,2,3} array.
Therefore When your code is calling toString, the toString from the Array class is called, not the toString from the Integer class as you might expect.
Finally the result you got: [Ljava.lang.Integer;#1888759 is caused by the lack of the implementation of the toString method in the array classes in Java.
To fix the issue in your code:
Replace:
printArray((Object)new Integer[]{1,2,3});
with:
printArray((Object[])new Integer[]{1,2,3});
To print the content of an array call:
Arrays.toString(new Integer[]{1,2,3});
As Marco said, this uses the default toString method of an Object, which is its (virtual) memory address.
I would recommend using the Arrays.toString method here
With regards to your use of variable arguments - try disassembling the class file by running
javap -verbose VarArgs
to see what this compiles down into - you should see that your integer array is being passed as the single element of an array.
That is not the same as passing an array! That is the same as passing a variable length of parameters, so the method treats the array as one object, not an array of objects, hence the printout.
public static void printArray(Object[] args) {
for (Object o : args) {
System.out.println(o);
}
}
Object[] objects = new Integer[] { 1, 2, 3, 4 };
printArray(objects);
Notice that you need to use the wrapper for int, primitive types are not subclasses of object.

Java array pass without reference

I am trying to pass an array without using a reference, but directly with the values :
public static void main(String[] args){
int[] result = insertionSort({10,3,4,12,2});
}
public static int[] insertionSort(int[] arr){
return arr;
}
but it returns the following exception :
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Syntax error on token(s), misplaced construct(s)
Syntax error on token ")", delete this token
When I try the following code , it works , can anybody please explain the reason ?
public static void main(String[] args){
int[] arr = {10,3,4,12,2};
int[] result = insertionSort(arr);
}
public static int[] insertionSort(int[] arr){
return arr;
}
It has to be
int[] result = insertionSort(new int[]{10,3,4,12,2});
{10,3,4,12,2} is a syntactic sugar for array initialization, which must go with the declaration statement like the one in the following -
int[] arr = {10,3,4,12,2};
Something as follows is not allowed too -
int[] arr; // already declared here but not initialized yet
arr = {10,3,4,12,2}; // not a declaration statement so not allowed
insertionSort({10,3,4,12,2})
is not valid java because you don't specify a type in your method call.
The JVM does not know what type of array this is. Is it an array with double values or with int values?
What you can do is insertionSort(new int[]{10, 3 ,4 12, 2});
int[] array = { a, b, ...., n } is a shorthand initialization - you have to write:
int[] result = insertionSort(new int[]{10,3,4,12,2});
to initialize it anonymously.
Nothing much to add to what others said.
However I believe the reason why you should use new int[]{10,3,4,12,2} (like others stated) and Java doesn't let you use just {10,3,4,12,2} is that Java is strong typed.
If you just use {10,3,4,12,2} there is no clue of what the type of the array elements can be. They seem to be integers, but they can be int, long, float, double, etc...
Well, actually it might infer the type from the method signature, and fire a compile error if it doesn't fit, but it seems complicated.

Categories