Robotics C++ Physics II AP Physics B Electronics Java Astronomy Other Courses Summer Session  

Sample Code

 

 

Example 1:

Using if Statement With && (And) Operator

Example 2

Using if Statement With || Or Operator

 

Example 3

Using if-else Statement with && and || (Or) Operators

Example 4
switch Statements

 

 

Be careful with "short-circuit" evaluations

Example 1: Using if Statement With && And Operator

 

Code

 

public class Lesson8

{

      public static void main (String[]args)

      {

            int x = 5;

            int y = 7;

            if ((x > 4) && (y > 3))                  

            {

                  System.out.println("x = " + x + " and " + "y = " + y);

                  System.out.println ("x > 4 and y > 3");

            }    

      }

}

 

Output

 

x = 5 and y = 7

x > 4 and y > 3

 

Example 2: Using if-Statement With || Or Operator

Code

 

public class Lesson8

{

      public static void main (String[]args)

      {

            int x = 5;

            int y = 7;

            System.out.println("x = " + x + " and " + "y = " + y);

            if ((x > 4) || (y > 30))

            {

                  System.out.println ("The Boolean ((x > 4) || (y > 30))is true");

            }    

      }

}

 

Output

 

x = 5 and y = 7

The Boolean (x > 4) || (y > 30) is true

 

Example 3: Using if-else Statement With && and || Operators

Code

 

public class Lesson8

{

      public static void main (String[]args)

      {

            int x = 5;

            int y = 7;

            System.out.println("x = " + x + " and " + "y = " + y);

            if (((x == 2)|| (y == 7))&& (x < 4))

            {

                  System.out.println ("The Boolean (((x == 2)|| (y == 7))&& (x < 4))is true");

            }    

            else

            {

                  System.out.println ("The Boolean (((x == 2)|| (y == 7))&& (x < 4))is not true");

            }

      }

}

 

Output

 

x = 5 and y = 7

The Boolean (((x == 2)|| (y == 7))&& (x < 4))is not true