Introduction to Control Flow Statements
The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code. This section describes the decision-making statements (if, if-else) supported by the Java programming language.
The if-else statements are used to apply decisions in a program. If the expression produces a true value, the statement is executed otherwise it is skipped. For example, you apply a decision in your program that if a student’s marks are greater than 900 then print “Passed” else print “fail”.
Syntax
// Execute statement if condition is true otherwise action is skipped.
If (boolean-expression) statement
// Execute statement if condition is true otherwise execute else statement if the condition is flase. Else statement is optional.
If (boolean-expression) statement
else statement
// Apply multiple decisions. Conditions are evaluated from top to bottom. Statement is executed whose condition gets true first, remaining actions are skipped. Braces { } are used to make the block of statements.
if (boolean-expression) {
statement
statement
} else if (boolean-expression) {
Statement
} else {
Statement
}
// Use nested if statements
If (boolean-expression)
If (boolean-expression) statement
Example
1. /**
2. * @(#)ConditionalSatementDemo.java
3. *
4. *
5. * @author
6. * @version 1.00 2009/11/5
7. */
8.
9. public class ConditionalSatementDemo {
10.
11. /**
12. * Creates a new instance of ConditionalSatementDemo.
13. */
14. public ConditionalSatementDemo() {
15. }
16.
17. /**
18. * @param args the command line arguments
19. */
20. public static void main(String[] args) {
21. // TODO code application logic here
22.
23.
24. int testscore = 77;
25. String grade;
26.
27. if (testscore > 95) {
28. grade = "A+";
29. } else if (testscore >= 90 && testscore <= 95) {
30. grade = "A";
31. } else if (testscore >= 80 && testscore < 90) {
32. grade = "B";
33. } else if (testscore >= 70 && testscore < 80) {
34. grade = "C";
35. } else if (testscore >= 60 && testscore < 70) {
36. grade = "D";
37. } else {
38. grade = "F";
39. }
40.
41. System.out.println("Grade = " + grade);
42.
43. }
44. }
Output
Grade = C
