0

I was wondering if there is a way in java to initialize an array by listing its components. I could do it in c# like this:

int[] array = new int[10]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

I tried this in java but it doesn't work, is there a way to do something similar?

Amos
  • 13
  • 2
  • Additionally have a look at the tutorials at Oracle: [Java Tutorial - Arrays](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html) – LuCio Oct 09 '21 at 06:57
  • 2
    "I tried this in java" the only thing wrong here is `[10]`. The size comes from the number of elements you specify in the initializer, so use `[]` instead, if you're going to explicitly specify the type on the RHS. – Andy Turner Oct 09 '21 at 06:58
  • @AndyTurner Thank you – Amos Oct 14 '21 at 14:44

2 Answers2

0
int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
ProDec
  • 5,390
  • 1
  • 3
  • 12
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Oct 09 '21 at 07:17
0
int[] arr = {1,2,3,4,5,6,7,8,9,10};
deHaar
  • 17,687
  • 10
  • 38
  • 51
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Oct 09 '21 at 07:14