Conditional statements in Java allow you to execute different blocks of code based on whether a given condition is true or false. The primary conditional statements in Java are Conditional statements allow you to execute code blocks conditionally, based on whether a given condition is true or false. I Will provide Conditional Statements of each type
Here’s an examples of If Condition and expected outputs
Syntax :- if(Condition)
{
// Write Statements Hare.
}
Example :- int a = 10;
if(a>=5)
{
System.out.println(“a is greater than 5”);// Hare condition is true then output is 5.
}
Output :- a is greater than 5
Syntax :-
if (condition)
{
// code block executed if the condition is true
}
else
{
// code block executed if the condition is false
}
Example :-
int age = 18;
if (age >= 18)
{
System.out.println(“You are an adult.”);
}
else
{
System.out.println(“You are not an adult.”);
}
Output :- You are an adult.
Syntax :- if (condition1)
{
if (condition2)
{
// code block executed if both condition1 and condition2 are true
}
else
{
// code block executed if condition1 is true but condition2 is false
}
}
else
{
// code to be executed if condition1 is false
}
Example :-
int n1 = -4, n2 = 3, n3 = 5;
if(n1 >= n2)
{
if(n1 >= n3)
System.out.println(n1 + ” is the largest number.”);
else
System.out.println(n3 + ” is the largest number.”
}
else
{
if(n2 >= n3)
System.out.println(n2 + ” is the largest number.”);
else
System.out.println(n3 + ” is the largest number.”);
}
Output :- 5 is the largest number.
Syntax :-
if (condition1)
{
// code block 1
}
else if (condition2)
{
// code block 2
}
else {
// default code block
}
Example :-
int marks = 85;
if (marks >= 90)
{
System.out.println(“Grade A”);
}
else if (marks >= 80)
{
System.out.println(“Grade B”);
}
else if (marks >= 70)
{
System.out.println(“Grade C”);
}
else {
System.out.println(“Grade D”);
}
Output :- Grade B
Syntax :-
switch (expression)
{
case value1:
//Statements Write hare block 1;
break;
case value2:
//Statements Write hare block 2;
break;
…
…
…
default:
//Statements Write hare in Defualt block ;
}
Example :-
int day = 5;
switch (day)
{
case 1:
System.out.println(“Monday”);
break;
case 2:
System.out.println(“Tuesday”);
break;
case 3:
System.out.println(“Wednesday”);
break;
case 4:
System.out.println(“Thursday”);
break;
case 5:
System.out.println(“Friday”);
break;
case 6:
System.out.println(“Saturday”);
break;
case 7:
System.out.println(“Sunday”);
break;
default:
System.out.println(“Invalid day”);
}
Output :- Friday
If you remove the break statements from the code blocks in the switch case statement, the code will continue to execute until it reaches the end of the switch block. This is known as fall-through. It is important to use break statements explicitly to control the flow of execution in your switch case statements.