• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to write: IF statement with range of values (e.g. if 5 > x > 10, then ... )

 
Zak Tacc
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey, got a question for you guys...

How do I write an if statement for a variable in java with two constraints? Like if i wanted my program to check a variable to see if it's greater than some number and less than another?

For example:

If X>24 and <30, then ...


Thanks
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15495
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch.

The && operator means "and", so you write:

 
Zak Tacc
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you
 
Rajeev Trikha
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can also use single ampersand towards the same end. Like

if (x > 24 & x < 30)

However && is more efficient as it doesn't calculate the expression after && if the first expression has failed the condition. Whilst single & calculates both the expressions.
 
Zak Tacc
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
that's good to know thank you
 
Campbell Ritchie
Sheriff
Pie
Posts: 50284
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Probably best to avoid the single ampersand for "AND" unless you need to maintain precedence with the ^ operator.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic