Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Array declaration with an expression

Tags:

java

arrays

This might be a trivial question, but I came across this syntax for an Array Declaration:

   void someFunction(int n){
      int[] myArray = new int[ n == 0 ? 1 : n ];
      ...
   }

I tried looking up online for some tutorials to understand what is happening with no luck.
Can anyone explain the expression in the right bracket, and when is something like that typically used?

like image 646
rgamber Avatar asked Mar 01 '26 13:03

rgamber


1 Answers

The right expression is a 'shortcut' to the 'if/(then)/else'

The first part of the expression is the 'if', the condition and can (but doesn't have to be) included in brackets, for clarification purposes.

Then comes the ?, stating 'Condition over, what's the result?' After that comes the 'true' statement, and after the colon the 'else' statement.

In short that means: If n == 0, allocate an array of size 1, otherwise allocate n elements.

It's a rather common c syntax and a nice way to shorten variable assignments, but doesn't really have anything to do with arrays per definition.

like image 198
ATaylor Avatar answered Mar 04 '26 03:03

ATaylor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!