Wednesday 10 June 2015

Conditional Operators

public class ConditionalDemo {
        /* && conditional AND
         * || conditional OR
         */
        public static void main(String[] args) {
                int val1 = 100;
                int val2 = 500;

                // Test if val1 is equal 100 AND val2 is equal to 500.
                if((val1 == 100) && (val2 == 500))
                        System.out.println("val1 equals 100 and val2 equals 500");

                /* Change val2 to 300. But keep the test the same. The
                 * print statement should not execute as the values no longer
                 * meet the test criteria.
                 */
                val2 = 300;

                if((val1 == 100) && (val2 == 500))
                        System.out.println("val1 equals 100 and val2 equals 500");

                /* Test if val1 is 100 OR val2 is 500. Only one of the values
                 * will need to meet the test criteria.
                 */

                if((val1 == 100) || (val2 == 500))
                        System.out.println("val1 is " + val1 + " val2 is " + val2);

                // Change the test so val2 is 500 and val1 is 900.
                val1 = 900;
                val2 = 500;

                if((val1 == 100) || (val2 == 500))
                        System.out.println("val1 is " + val1 + " val2 is " + val2);

                // Now none of the values match.
                val2 = 0;
                if((val1 == 100) || (val2 == 500))
                        System.out.println("val1 is " + val1 + " val2 is " + val2);
        }
}

No comments:

Post a Comment

Translate