Friday, April 15, 2011

Java : IF Statements

The if statement is a fundamental programming construct. “If” allows a program to execute different blocks of code depending on the result of a test. In this article I will describe the variations of the “if” statement in Java Programming Language.

The general form of a Java if statement is:

if (satement) {

code_block_execute;

} else {

Code_block_non_execute;

}

Where statement is anything that evaluates as a boolean value. If the statement is true then the Java code in the “code_block_execute” block is executed. Otherwise, the code in “code_block_non_execute” is executed. The else statement is optional, so the simplest example of the if statement is:

if (x == 1) {

System.out.println(“As you see, x is one”);

}

A block of code is either a single line of code or several lines of code contained in curly braces. Note that in this example, enclosing the code in curly braces is not required, although some programmers prefer to use them anyway since it makes it clearer what code is exectued.

Multiple else if conditions can be chained together:

In this code given below we will decide if the score Exellent, Good etc. Take score from the user and return a logical value for entered scrore.

import java.util.Scanner;

public class IfElseIfExample

{

public static void main(String args[])

{

System.out.println("Enter your score : ");

Scanner sc = new Scanner(System.in);

int score = sc.nextInt();

if ( score >= 90 )

{

System.out.println("Excellent");

}

else if ( score >= 80 )

{

System.out.println("Good");

}

else if ( score >= 70 )

{

System.out.println("Satisfied");

}

else if ( score >= 60 )

{

System.out.println("Not too bad");

}

else

{

System.out.println("Need to improve");

}

}

}

No comments:

Post a Comment