I have no idea what does this mean:
this.x = x < 0 ? 0 : x;
this.y = y < 0 ? 0 : y;
I could not find the meaning of these operators, any help will be greatly appreciated!
I have no idea what does this mean:
this.x = x < 0 ? 0 : x;
this.y = y < 0 ? 0 : y;
I could not find the meaning of these operators, any help will be greatly appreciated!
Yes. That Terinary (or Conditional) Operator in java. A short hand for if and else condition.
The code this.x = x < 0? 0 : x;
equivalent to
if (x<0) {
this.x = 0
} else{
this.x =x
}
Your class has a field named x
. this.x
is used to refer to that field unambiguously: you need to do this if there is a local x
in your scope.
x < 0 ? 0 : x;
is an idiom that exploits the ternary operator. It evaluates to no less than zero.
In this case:
this.x = x < 0? 0 : x;
This means that the value of x is dependent on the condition (the one before the question mark x < 0
), the value of x is the first (the value before the :
which is 0
) if the condition evaluates to true, else the second value (the value after the :
which is x
itself).
Also, The value of x is equal to 0 if it is a negative number, other than this case the value is x itself.
It means
if (x < 0) {
this.x = 0;
} else {
this.x = x;
}
Which basically means this.x = Math.max(0,x)
.
This is the ternary if operator and basically is equal to:
if(x < 0){
this.x = 0;
else
this.x = x;
same thing for the y
and its syntax is condition ? if_part : else_part;
it means that:
if (x < 0) {
this.x = 0;
} else {
this.x = x;
}
the same for y;
The conditional operator (?:) returns one of two values depending on the value of a Boolean expression.
Syntax: condition ? first_expression : second_expression;
this.x = x < 0? 0 : x;
this.y = y < 0? 0 : y;
Means if x<0 if true then it will return 0 else return x
So the value of x
is depend on the conditions.
Refere ?: Operator .
Hope this may help you!
It's called Ternary Operator.
(condition) ? [if true]
: [if false]
In your case:
this.x = x < 0? 0 : x;
this.y = y < 0? 0 : y;
It's the shorthand conditional operator.
The statement
int n = x > 0 ? x : 0
will set n
to x
if x > 0
returns true. Otherwise, n
is set to 0
.