-3

Hello friends i have a question to define id in java. why this define is wrong:

if(0<=hours<24)

but

if(0<=hours&&hours<24)

is true.

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180

4 Answers4

5

The first one parses as

if((0<=hours)<24)

or (for example, if hours was >= 0)

if(true<24)

which is invalid as a boolean cannot be less than an int.

In fact, no languages than I recall, except Python, allow this kind of syntax.

tckmn
  • 57,719
  • 27
  • 114
  • 156
1

Because the first inequality evaluates to a boolean. So this becomes,

if (true <= 24)

In Java, comparison between boolean and integers are not defined.

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
1

This is because the type of 0<=hours is a boolean and the < operator does not work on boolean and int.

sigpwned
  • 6,957
  • 5
  • 28
  • 48
1

The first one is syntactically incorrect. If you want to compare a variable against two other expressions you should have a valid operator like and (&&). That's why the second one is correct.

if (0 <= hours && hours < 24)

Here you are saying if hours is greater than or equal to 0 and at the same time stricktly less than 24.

Anton Belev
  • 11,963
  • 22
  • 70
  • 111