0

I was trying to make a program where there is a need to take an extra size of array than the actual number of elements. I was able to do it using traditional way of assigning the element one by one

int[] arr = new int[7];
    arr[0] = 2;
    arr[1] = 5;
    arr[2] = 1;
    arr[3] = 3;
    arr[4] = 8;
    arr[5] = 9;

I was able to do it successfully via this method, but is there any way in array where I can perform this task in a single line i.e. to declare the size and initialise in a single line

Something like following

int[] arr = new int[7]{2, 5, 1, 3, 8, 9};

or similar to this

int[] arr = new int[7];
arr = {2, 5, 1, 3, 8, 9};
Akshaya Amar
  • 169
  • 8
  • Doesnt this work? int[] arr = new int[7]{2, 5, 1, 3, 8, 9}; – vikingsteve May 11 '21 at 08:31
  • 2
    When using the array initializer (the curly brackets), you can't also define the array size (i.e. `new int[5] {...}`). The array size is implicitly taken from the amount of elements in your array initializer. -> e.g. `int[] arr = new int[] { 2, 5, 1, 3, 8, 9 };`. – maloomeister May 11 '21 at 08:34
  • 3
    Does this answer your question? [How to initialize an array in Java?](https://stackoverflow.com/questions/1938101/how-to-initialize-an-array-in-java) – maloomeister May 11 '21 at 08:36
  • 1
    The default value for int array is 0. So you could just append one or more 0 to your values to get the same behavior as with your multiple line solution, i.e for an array with length 7 `arr = new int[] { 2, 5, 1, 3, 8, 9, 0 };` for length 10 `arr = new int[] { 2, 5, 1, 3, 8, 9, 0, 0, 0, 0 };` – Eritrean May 11 '21 at 08:38
  • 1
    @vikingsteve: It doesn't work this way – Akshaya Amar May 11 '21 at 08:45
  • @Eritrean Very nice solution...but is there any direct way of declaring size and initialising array? – Akshaya Amar May 11 '21 at 08:48
  • @maloomeister: No..it doesn't because it's not fulfilling my requirement as I want to know the way to declare the size(which should be more than the number of elements in an array) and initialise an array simultaneously in a single line.. – Akshaya Amar May 11 '21 at 09:02
  • 1
    @AkshayaAmar As stated, you implicitly declare the size with the array initializer. So you you want to have more elements than defined, you have to pad with zeros like Eritrean showed. Other than that, there is no further way. – maloomeister May 11 '21 at 09:05
  • Whats wrong with `arr = {2, 5, 1, 3, 8, 9, 0};` ... if you want 7 entries, then simply provide 7 values within the braces! – GhostCat May 11 '21 at 09:10
  • @GhostCat: there is nothing wrong with the mentioned solution but just want to know if there is any other way of doing it without inserting additional 0's like in my question I have shown that though array size is 7 but I am inserting only 6 elements without inserting additional 0's... – Akshaya Amar May 11 '21 at 09:15

0 Answers0