-5

Did what i write below the same thing?

if(number >= 0 && number <= 99){}

and

if(number >= 0){}
else if(number <= 9){}

I hope this question is readable Thanks**

Abdelillah
  • 79
  • 1
  • 14
  • 2
    No, it's not the same thing. Why don't you just try it out with a few statements and see how it behaves? – RaminS Mar 14 '19 at 20:55
  • If you had statements in your empty `{}` blocks, you would be able to check under what conditions they are called. You would find your alternatives are not equivalent. – khelwood Mar 14 '19 at 20:57
  • The second `if` is redundant, because any negative number is less than 9. – shmosel Mar 14 '19 at 21:11

2 Answers2

4

Notice, that in the latter case you have two blocks of code, so you can execute separate pieces of code on first and second condition. In the former, the block of code is executed only if both conditions resolve to true.

The first option is equivalent to:

if(number >= 0) {
    if(number <= 99){}
}
Andronicus
  • 25,419
  • 17
  • 47
  • 88
0

Whatever is inside an else if will execute instead if the first if statement does not return true. If that else if does not return true, you can add another else if and so on.

if(number >= 0 && number <= 99)
{

}

The above code block will only execute if both conditions are true.

if(number >=0 || number <= 99)
{

}

The above code block will execute if both conditions are true, or if only one of the conditions are true.

You could also use what are called ternary operators

num = (number >= 0) ? true : (number <= 99) ? true : false;

The ? and : are just another way of saying if, else if etc.

Ternary operators come in handy when you want to do condition checking within statements.

James
  • 300
  • 1
  • 4
  • 11
  • 1
    The "ternary operator" is formally called the [conditional operator](https://stackoverflow.com/questions/798545/what-is-the-java-operator-called-and-what-does-it-do). – RaminS Mar 14 '19 at 22:20