JAVA #11 – Conditional Statements and Switch Cases

Share on WhatsApp
Share via email Share

Conditional Statements in Java

A conditional statement is an expression that produces a true or false result. You can use that result as you see fit. To create the expression, you use the Boolean operators we studied in the previous lesson. In the previous lesson, we saw only how to perform the operations and how to get the results, not how to use them. To use the result of a Boolean operation, the Java programming language provides some specific conditional operators.

There are three types of conditional statements in Java.

  1. Switch Case.
  2. If,Eles-if and Else.
  3. Ternay Operator.

Syntax of switch case

The syntax of a switch case statement is the following:

 

  • switch: theswitch keyword is followed by a parenthesized expression, which is tested for equality with the following cases. There is no bound to the number of cases in a switch
  • case: thecase keyword is followed by the value to be compared to and a colon. Its value is of the same data type as the variable in the switch. The case which is equal to the value of the expression is executed.
  • default: If no case value matches theswitch expression value, execution continues at the default  This is the equivalent of the “else” for the switch statement. It is conventionally written after the last case, and typically isn’t followed by break because execution just continues out of the switch. However, it would be better to use a breakkeyword to default case, too. If no case matched and there is no default clause, execution continues after the end of the switch statement.
  • break: Thebreak statement causes execution to exit the switch  If there is no break, execution flows through into the next case, but generally, this way is not preferred.
Share on WhatsApp
Share via email Share

Leave a Reply

Your email address will not be published.