
Decision making in java with examples
Previous Chapter >>>> Operators in Java
Decision making is a very commonly used concept in any programming language. It directs the compiler to choose either of the paths based on a condition for program execution.
We can make decisions in Java using either of two statements:
1. The If statement
If statement can be further used as:
(a) if-then statement
Example:
int iNumber1=10;
int iNumber2 = 20;
if (iNumber1+iNumber2<40)
{
System.out.println("Sum is less than forty");
}
(b) if-then-else & if-else_if-else
Example:
int iNumber1=10;
int iNumber2 = 20;
if (iNumber1+iNumber2<40)
{
System.out.println("Sum is less than forty");
}
else
{
System.out.println("Sum is greater than forty");
}
(c) if-else_if-else
Example:
int iNumber1=10;
int iNumber2 = 20;
if (iNumber1+iNumber2<40)
{
System.out.println("Sum is less than forty");
}
else if ((iNumber1+iNumber2>40))
{
System.out.println("Sum is greater than forty");
}
2. The Switch statement
The switch case comes handy In case you have multiple cases. The switch statement is multi-directional . It easily routes program execution to different parts of code based on expression's value.
Example:
public class SwitchExample {
public static void main(String[] args) {
int vowel = 4;
String vowelString;
switch (vowel) {
case 1: vowelString = "a";
break;
case 2: vowelString = "e";
break;
case 3: vowelString = "i";
break;
case 4: vowelString = "o";
break;
case 5: vowelString = "u";
break;
default: vowelString = "Invalid vowel";
break;
}
System.out.println(vowelString);
//This will print vowel "o" as standard output!
}
}
Next Chapter >>>> Arrays in Java
No comments:
Post a Comment
Thanks a lot for your valuable Comment!