top of page
Search
  • Writer's pictureHarshit Sharma

Conditional Statements in JAVA

The conditional statement in java is:

if

if-else

else if

Nested if

Switch

if statement:if(condition)

{

statement sequence

}

else statement:if(condition)

{ statement sequence }

else { statement sequence }

If the conditional expression is true, the target of the if will be executed; otherwise, if it exists, the target of the else will be executed. At no time will both of them be executed. The conditional expression controlling the if must produce a boolean result.

else if statement: The else if the statement is used if we want to use more conditions:

Nested if:

The main thing to remember about nested ifs in Java is that an else statement always refers to the nearest if statement that is within the same block as the else and not already associated with an else. Here is an example: if(i == 10) { if(j < 20) a = b; if(k > 100) c = d; else a = c; // this else refers to if(k > 100) } else a = d; // this else refers to if(i == 10)

switch:The switch provides for a multi-way branch. Thus, it enables a program to select among several alternatives. Although a series of nested if statements can perform multi-way tests, for many situations the switch is a more efficient approach. switch(expression) { case constant1: statement sequence break; case constant2: statement sequence break; case constant3: statement sequence break; ... default: statement sequence }



3 views0 comments

Recent Posts

See All

Comments


Post: Blog2_Post
bottom of page