Reputation: 5849
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?
Upvotes: 2
Views: 212
Reputation: 30453
Here is a simple declaration of array with length 5:
int[] myArray = new int[5];
n == 0 ? 1 : n
provides a number (1
if n == 0
and n
if not), it is an example of ternary operator.
So
int[] myArray = new int[ n == 0 ? 1 : n ];
is shorthand to
int[] myArray;
if (n == 0) {
myArray = new int[1];
} else {
myArray = new int[n];
}
Upvotes: 1
Reputation: 16516
As @ATaylor and @SperanskyDanil told,
Syntax will create array with size 1, when n=0
and it'll create Array with size n
, when n != 0
.
as Shown in below diagram.
Upvotes: 1
Reputation: 2598
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.
Upvotes: 5
Reputation: 18459
It is java ternary operator (?) is used to check if n is 0. if n is zero, create array of size 1.
if n is >1 , use that for creating array. Zero length arrays are legal in java, so not sure what author meant here.
If it to safeguard from bad values for in is should have been checking for n > 0 ? n :1
, so even negative values get a array of size 1
Upvotes: 1
Reputation: 14998
It's a ternary operator. The boolean statement before the ?
is evaluated and, if it's true, the expression is evaluated to the value before the :
, else it evaluates to the second value.
Upvotes: 1