+ 1
Java Arrays and Method Parameters Help
I know for integers, I can do: int i= 200; System.out.println(method(i)); and change it to one line: System.out.println(method(200)); Similarly how do I do it for arrays? I know: int[] i = {200, 300}; System.out.println(method(i)); How to make it: System.out.println(method({200, 300}); Because this line brings errors and I'm sure there's a proper syntax to that. And unfortunately google did not help.
3 Antworten
+ 2
With help I figured it out.
Using:
System.out.println(method(new int[]{200,300})); you can pass an array as a parameter to a method without defining it.
+ 1
👍Andre!
new keyword creates a new instance, in this case an integer array, which is initialized with values {200,300}. But you are not assigning your new object instance to a variable like, int[] myArray = new int[] {200,300}, to have access to it later.
+ 1
Minnie Mouse I don't need it for later. It's just 2 hard coded values for an example, I just wanted an easy way to do it. So if I need to change the numbers, they are both there, and people reading the code do not have to search for the variable and alter it etc. But thank you for replying!