Below are 4 example of the if - else structure. Copy each to BlueJ and run.
/** >>>>>>>>>>> Basic if - else statement <<<<<<<<<<<< * Below is a the basic if-else statement which * you should already be familiar with. * Copy it into BlueJ and run it. Make sure you * understand how it works. */ class TestIf { public static void main(String[] args) { int x = 12; int y = 10; if( x == y ) { System.out.println(x + " equals " + y); } else if( x > y ) { System.out.println(x + " is greater than " + y); } else { System.out.println(x + " is less than " + y); } } }
/** >>>>>>>>>>> if - else with Strings <<<<<<<<<<<< * Below is an if - else statement which prints two * strings in Alphabetical order, using the compareTo method. * * Copy to BlueJ and run, make sure you understand it. */ class StringIf { public static void main(String[] args) { String pet1 = "cat"; String pet2 = "dog"; if( pet1.compareTo(pet2) < 0) { System.out.println(pet1 + " is before " + pet2); } else if( pet1.compareTo(pet2) > 0) { System.out.println(pet2 + " is before " + pet1); } else { System.out.println(pet1 + " equals " + pet2); } } }
/** >>>>>>>>>>> if - else with null Strings <<<<<<<<<<<< * Below is an example of using null with if statements. * When you set something to null it refers to NO object. * * Copy to BlueJ and run, make sure you understand it. */ class nullExample { public static void main(String[] args) { String name = "Haas"; String car = "Toyota Rav4"; String boat = null; if(name != null) { System.out.println("Hello " + name); } if(car != null) { System.out.println("Car = " + car); } else { System.out.println("You do not own a car."); } if(boat != null) { System.out.println("Boat = " + boat); } else { System.out.println("You do not own a boat."); } } }
/** >>>>>>>>>>> BOOLEAN if - else <<<<<<<<<<<< * Below are 10 example using boolean valiables * with if statements. * * Read it over carefully. Try to decide what the output * will be before you run it. * * Copy to BlueJ and run, make sure you understand it. */ public class BooleanIf { public static void main (String args[]) { boolean a = true; boolean b = false; if (a) { System.out.println ("Example 1"); } if (b) { System.out.println ("Example 2"); } if (a && b) { System.out.println ("Example 3"); } if (a || b) { System.out.println ("Example 4"); } if (a == b) { System.out.println ("Example 5"); } if (a != b) { System.out.println ("Example 6"); } // the following are examples of DeMorgans law if (!(a && b)) { System.out.println ("Example 7"); } if (!(a || b)) { System.out.println ("Example 8"); } if (!a && !b) { System.out.println ("Example 9"); } if (!a || !b) { System.out.println ("Example 10"); } } }