Java Arrays and Method Parameters Help | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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.

5th Jun 2018, 11:57 PM
Andre Daniel
Andre Daniel - avatar
3 Answers
+ 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.
6th Jun 2018, 12:27 AM
Andre Daniel
Andre Daniel - avatar
+ 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.
6th Jun 2018, 2:52 AM
Minnie Mouse
Minnie Mouse - avatar
+ 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!
6th Jun 2018, 4:35 AM
Andre Daniel
Andre Daniel - avatar