Java Tutorial #9 — Boolean logic / operators

Topics Discussed: Boolean Logic / Operators

Source Code Available Here

HomeWork Available Here

Boolean operators
Boolean operators are variables which have two states, “true” or “false” (default is false if you use a simple declaration). These can be used in a variety of ways, but are most typically seen when you need to confirm that something happened in an if statement or a loop (in later lessons). Here’s an example:

int empPay1=0;
boolean isChanged;//ischanged defaults to false
System.out.println("Enter the income for employee 1 that is greater than 0.");
empPay1= input.nextInt(); // Enter pay

if (empPay1 > 0){// if the value is > 0, meaning it's been changed

if(isChanged){//if the value has been changed (by the if above)
     System.out.println("empPay has been changed");
//You could just use an else here, but instead you could use the following:

     System.out.println("empPay has not been changed");

In the above example I show that booleans can be used in place of the standard if conditionals and used as a simple true / false that is set as part of another conditional. At present these must seem convoluted, but in the future when our variables change around a bit more it will make more sense to use these than other pieces of code.