Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is going on in this piece of logic ? Java, parenthesis

Tags:

java

logic

private int hour;
private int minute;
private int second;

public void setTime(int h, int m, int s){
hour = ((h>=0 && h < 24) ? h : 0);
}

from this mrbostons java tutorial:

https://www.thenewboston.com/videos.php?cat=31&video=18001

Though you could (?) write the same code with a if statement, I'd like to know what is going on in this code and how I use it in other places

like image 408
zython Avatar asked Dec 13 '25 14:12

zython


2 Answers

Here is the equivalent of

hour = ((h>=0 && h < 24) ? h : 0);

with if/elses :

if(h>=0 && h < 24) 
    hour = h;
else
    hour = 0;

The first notation is using a ternary operator.

like image 132
Mohammed Aouf Zouag Avatar answered Dec 15 '25 08:12

Mohammed Aouf Zouag


hour = ((h>=0 && h < 24) ? h : 0);

if h is greater than or equal to zero, and less than 24, then set hour to the value of h, else set hour to zero.

like image 37
EkcenierK Avatar answered Dec 15 '25 09:12

EkcenierK