Thursday, March 31, 2016

Conditional Statements

Hey guys, today we're gonna learn about Condition Statements and how it works in java.

Conditional statementsconditional expressions and conditional constructs are features of a programming language, which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false. Apart from the case of branch predication, this is always achieved by selectively altering the control flow based on some condition.
In imperative programming languages, the term "conditional statement" is usually used, whereas in functional programming, the terms "conditional expression" or "conditional construct" are preferred, because these terms all have distinct meanings.
Although dynamic dispatch is not usually classified as a conditional construct, it is another way to select between alternatives at runtime

Ex ; - Student gets the results of an exam and we wanna check 'if' he is pass or fail. 
         Let's take margin as 50 marks.

class main{
public static void main(String []args){
int results = 68;
if (results < 50){
System.out.println("Student is FAIL");
}else{
System.out.println("Student is PASS");

}
}
}
  • Up in there we declared a variable called 'results' as integer & initialized to 68
  • Next a Conditional Statements to check whether the student is pass or fail.
  • In this case 'else' means " if results more than 50 (results > 50).

                               Nested IF Statements

Now we're gonna do something advanced. Now we need find out the 'grade' of the result.
Here we go....

class main{
public static void main(String []args){

int results = 68;

if (results > 75){
System.out.println("Student has A grade");
}else if (results > 60){
System.out.println("Student has B grade");

}else if (results > 50){
System.out.println("Student has C grade");
}else{
System.out.println("Student has FAILED");
}
}

}

  • in first if condition we check whether result is more than 75 or not.
  • If the condition true it executes the code "System.out.println("Student has A grade");"
  • Unless it skips it goes to the next one. If it's true then executes "System.out.println("Student has A grade");"
  • Unless skips & moves onto the next.
  • Finally last code.
That's how the nested if condition works in JAVA


No comments:

Post a Comment