elibraryportal Logo

Control Statements in Java

We need to execute a set of statements based on a condition, we need to use control flow statements.

Types of control statements.

  1. if statement
  2. if-else statement
  3. if-else-if statement
  4. Nested if statement

1) if statement in Java

if statement is used to test the condition this statements get execute only when the given condition is true. If the condition is false then the statements inside if statement body are completely ignored.

Syntax:

if statement in java

Example:

Show in Fig.

if statement in java

2) If-else statement in Java

if-else statement also tests the condition. when if condition is true then print your if body statement, else part statement do not tuch.

Otherwise if part statement is false then else block is executed.

Syntax:

Example1: Leap Year Program

if Else statement in java

Example2: Odd and Even Program

if Else statement in java

Ternary Operator

Using Ternary Operator (? :) to perform the task like if...else statement. If the condition is true, the result of ? is returned. But, if the condition is false, the result of : is returned.

Ternary Operator  in java

Example Ternary Operator :- Odd and Even Program

Ternary Operator  in java

3) if-else-if Statement

Multiple statements, executes one condition

Syntax

Example : Grading system for fail, D grade, C grade, B grade, A grade and A+

If Else Ladeer  in java

4) Nested if statement in Java

Nested if statement represents the if block within another if block. Here, the inner if block condition executes only when outer if block condition is true.

Syntax :

Example 1

Output

Nested If Else in java

Example 2 : Leap Year Program, Input by User

Output

Nested If Else in java