Previous | Home | Next |
Java supports both conditional statements and loops to determine control flow just like C and C++. First we deal with the conditional statements and then move on to loops. In end we discuss the somewhat cumbersome switch statement that we can use when we have to test for many values of a single expression.
Block Scope
A block or compound statement is any number of simple Java statements that are surrounded by a pair of braces. Blocks define the scope of your variables and can be nested inside one another. Here is a block that is nested inside the block of the main method.
Example
public static void main(String[] args) { int p; . . . { int q; . . . } // q's scope is upto here }
It is not possible to declare same named variables in two nested blocks.
he conditional statement in Java has the form if (condition) statement, just like in C and C++. In Java you will often execute multiple statements when a single condition is true. For this you use a block statement that takes the form.
Example
{ statement1; statement2; . . . } For instance, if (num >= 10) { System.out.println("The value of num is :"+num); }
In above example the statements surrounded by the braces will be executed when num is greater than or equal to 10.
Java, like C and C++ also has if-else conditional statements which takes the form
Example
(condition is true) { //will execute statements if condition is true otherwise control passes to else block statment1; statement2; } else { // will execute if condition is false statement3; }
Java uses this statement for the execution of the multiple alternatives and is quite common,
Example
f (totalmarks >= 400) { Grade = "A"; result = "Excellent"; } else if(totalmarks>=300) { Grade = "B"; result = "Good"; } else if (totalmarks>=200) { Grade = "C"; result = "Average"; } else { System.out.println("Failed"); }
Previous | Home | Next |