Java TUTORIAL - if else



ReferenceDesigner.com tutorials are different. We do not follow a bookish way of learning in a certain pattern. We instead present the matters that HELPS you learn the language AND the conepts and in a non linear fashion. That is why we present the matters in a slightly different order than those presented by books or other online tutorials.

The if else statement is the fundamental building block of any programming language. It is the basic decision making statement that gives a programming language ability to code and run an algorithm.

Let us now write a java code which will compare a given variable against a constant number and print the result accordingly.

  1. /*
  2.   ReferenceDesigner.com Tutorial for beginners
  3.   If statement
  4.   Example Program showing use of if else statement
  5. */
  6. class ifelse {
  7.  
  8. public static void main (String args[]) {
  9.  
  10. int x = 48 ;
  11. if ( x > 50)
  12. {
  13. System.out.println("x is greater than 50");
  14. System.out.println("Bye !");
  15. }
  16. else
  17. {
  18. System.out.println("x is less than or equal to 50");
  19. System.out.println("Learning Java is easy and fun with referencedesigner.com tutorial!");
  20. }
  21. }
  22.  
  23. }


If you compile and run this program, you will get the output as follows


C:\Program Files\Java\jdk1.7.0_17\bin>java ifelse
x is less than or equal to 50
Learning Java is easy and fun with referencedesigner.com tutorial!

C:\Program Files\Java\jdk1.7.0_17\bin>




Exercises



We believe that the best way to learn coding is by exercises. So here are some exercises for you

Exercise 1

Change the value of x in the above program such that print the first set of statements in place of the second set of statements/

Exercise 2

Define two integer variables x and y and assign them some constant value. Write a console output depending upon whether their sum is greater than 100 or not.

Let us now write another meaningful example that will printout the maximum of three given numbers

  1. /*
  2.   ReferenceDesigner.com Tutorial for beginners
  3.   Eaxmple showing boolean operator
  4.   And also != relational operator
  5. */
  6. class max {
  7.  
  8. public static void main (String args[]) {
  9.  
  10. int x = 5 ;
  11. int y = 41 ;
  12. int z = 13 ;
  13. int max;
  14.  
  15. if (x > y)
  16. {
  17. max = x;
  18. }
  19. else
  20. {
  21. max = y;
  22. }
  23.  
  24. if (z > max)
  25. max = z;
  26.  
  27.  
  28. System.out.print("The max of x, y and z is ");
  29. System.out.println(max);
  30. }
  31.  
  32. }


As you may have expected, it gives the following output


C:\Program Files\Java\jdk1.7.0_17\bin>java max
The max of x, y and z is 41