<< Back Computer Science Club

October 30 2019 - Java 3 (if else statements 2, conditionals)

At this meeting, we went over another part of if and else statements along with conditional operators.




If and Else Statements

Check out the first part of if and else statements in the previous meeting log.


Else If

You can smack an else if in between your if and else to check for other conditions in the same statement. Here's an example:

if (number >= 20) {

 //runs whatever's in here only if the number variable is greater than or equal to 20

} else if (number >= 10) {

 //runs whatever's in here if the number variable is NOT greater than or equal to 20 but IS greater than or equal to 10.

} else {

 //runs whatever's in here only if the number variable is less than both 20 and 10.

}

//runs code over here no matter what




Conditional Operators

Conditional operators compare two sets of comparisons and will only return true if it passes all the statements correctly (you'll see what I mean). You can put the following operators in between two comparisons (see relational operators).


and
Using && in between two comparisons will only let the if statement return true if both comparisons are true.

if (number == 20 && someOtherNumber >= 4000) {

 //code here only runs if both of those are true

}



or
Using || in between two comparisons will let the if statement return true if at least one of the comparisons is true.

if (number == 20 || someOtherNumber >= 4000) {

 //code here will run as long as at least one of those is true

}



not
This is a bit different. Using ! in front of comparisons will return the opposite of what it would normally return.

if (!(someOtherNumber >= 4000) {

 //code here will only run if someOtherNumber is NOT greater than or equal to 4000

}

if (!(number == 20 && someOtherNumber >= 4000) {

 //code here will only run if at least one of those is not true (because when one is not true, then the && makes the whole thing false, but the ! makes it the opposite so false becomes true yay)

}

if (!(number == 20 || someOtherNumber >= 4000) {

 //code here will only run if both of those are false

}




If you have any questions, ask them at Computer Science Club!