java programming if and else statement tutorial

In today's lesson, you'll learn how to use them (if Statement) in which allows you to perform a certain section of codes, only if a particular condition is true to check out the program below. The body of the if-statement is only executed when the condition of the statement is true Guess what the program prints.

 public class Main{
  public static void main(String [] args){
  int a=7;
  if(a<20){
  System.out.println(a is less than 20);
  }
 
  if(a>0){
  System.out.println("a is greater than 0");

  }
  if(a%2==0) // To check the value of even or odd
  {
  System.out.println("a is even");
  }
  }
 }

 Notice what it prints "a" is less than 20 The printline statement is executed because the condition is true. Now we've added a second statement that print "a" is greater than "0" if "a" is greater than "0" you should see the codes above, Now try changing the initial value of "a" to 30 notice the result. As you can see the first println statement is no longer executed because the condition is "false" Now let's try to Mix it up. try to add on "if statement" to print "a" is even if variable "a" is even. You can use the remainder operator (a%2) in the condition. As of now, we are done for the "if-statement" You can check the other conditional statement below.


if-else Statement

in the previous article, we study the characteristic of "if-statement" and how it be executed, Now in this lesson, you'll learn the other type of conditional statement which you are about to approach the "if-else statement" which can only be run if the certain condition is not true, then the "else" part will be executed. Look at the program below and guess what it prints


public class Main{
public static void main(String[] args){
int i = 1245;
int j = 908;
int min;
if(i<j){
//To Assign min
min=i;
}
else{

// To assign min
min=j;
}
System.out.println("The minimum of i and j is:"+min);

if(i<j){
System.out.println("i is less than j");
}
else{
System.out.println("i is not less than j");
}
}
}

in this case! the else part is executed because "i" is not less than "j" and the program prints "i" is not less than "j". Now you may also use the (if-else-statement) to find the minimum of "i" and "j" and assign it to variable min. see the codes above I've added, Now guess what it prints when you run the program. The result should be "The minimum of I and j is:908"









Post a Comment

0 Comments