Java, similar to any remaining programming language, is furnished with specific statements that permit us to check a condition and execute specific pieces of code contingent upon whether the condition is valid or false. Such statement
are called conditional, and are a type of composite statement.
In Java, there are 4 types of conditional statements:
If statement
the if-else statement
the if-else-if statement
the switch statement
The Java If the statement is the most basic decision statement. It is utilized to choose whether a specific statement or square of Statement will be executed or not i.e if a specific condition is valid then a block of statement is executed in any case not.
Syntax:
if (condition ) {
// Statements to execute if
// condition is true
}
If else Statement
Decision Making in Java assists with composing choice-driven Statements and executing a specific set of code dependent on specific conditions.
The if statement alone lets us know that assuming a condition is valid it will execute a block of statement and in case the condition is false it won't. In any case, imagine a scenario in which we need to accomplish something different in case the condition is false. Here comes the else statement. We can utilize the else explanation with if statement to execute a block of code when the condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Java if-else-if stepping stool is utilized to settle on various choices. The if statements f are executed starting from the top. When one of the conditions controlling the if is true, the proclamation related to that in the case is executed, and the remainder of the stepping stool is skirted. Assuming that none of the conditions is valid, then, at that point, the last else statement will be executed.
Syntax:
if (condition)
statement 1;
else if (condition)
statement 2;
.
.
else
statement;
Switch Statement
The switch statement is a multi-way branch statement. It gives a simple method for dispatching execution to various pieces of code dependent on the worth of the expression. Essentially, the expression can be a byte, short, char, and int primitive data types. Starting with JDK7, it additionally works with identified kinds ( Enums in java), the String class, and Wrapper classes.
Syntax:
// switch statement
switch(expression)
{
// case statements
// values must be of same type of expression
case value1 :
// Statements
break; // break is optional
case value2 :
// Statements
break; // break is optional
//We can have quite a few case statement
//blew is a default statement, utilized when none of the cases is valid.
//No break is required in the default case.
default :
// Statements
}
No comments:
Post a Comment