Decision-making structures with one or more conditions evaluated or tested by the program, with a statement or statement that is executed, if the situation is set to be correct, and optionally, execute other statements In the situation of doing is determined to be wrong.
Decision Making Statements in Java
- if statement
- if-else statement
- else-if statement
- Conditional Operator
- switch statement
if statement -
If statements in Java were used for some condition, it used to execute some statement code block if the expression is evaluated to true, otherwise, it will get skipped. The control flow.
Syntax -
if(test_expression)
{
statement 1;
statement 2;
...
}
Example -
public class Sample{
public static void main(String args[]){
int a=20, b=30;
if(b>a)
System.out.println("b is greater");
}
}
if-else statement
If other statements in Java are used to control the program flow on a conditional basis, then the only difference is this: It is used to execute some statement code block if expression is evaluated correctly Otherwise, the other statements implement the code block.
Syntax -
if(test_expression)
{
//execute your code
}
else
{
//execute your code
}
Example -
public class Sample {
public static void main(String args[]) {
int a = 80, b = 30;
if (b & gt; a) {
System.out.println("b is greater");
} else {
System.out.println("a is greater");
}
}
}
else-if Statements
Syntax -
if(test_expression)
{
//execute your code
}
else if(test_expression n)
{
//execute your code
}
else
{
//execute your code
}
Example -
public class Sample {
public static void main(String args[]) {
int a = 30, b = 30;
if (b > a) {
System.out.println("b is greater");
}
else if(a > b){
System.out.println("a is greater");
}
else {
System.out.println("Both are equal");
}
}
}
switch Statements
Syntax -
switch(variable)
{
case 1:
//execute your code
break;
case n:
//execute your code
break;
default:
//execute your code
break;
}
Example -
public class Sample {
public static void main(String args[]) {
int a = 5;
switch (a) {
case 1:
System.out.println("You chose One");
break;
case 2:
System.out.println("You chose Two");
break;
case 3:
System.out.println("You chose Three");
break;
case 4:
System.out.println("You chose Four");
break;
case 5:
System.out.println("You chose Five");
break;
default:
System.out.println("Invalid Choice. Enter a no between 1 and 5");
break;
}
}
}
0 comments:
Post a Comment