Java compiler executes the code from top to bottom. The statements in the code are executed according to the order in which they appear. However, Java provides statements that can be used to control the flow of Java code. Such statements are called control flow statements. It is one of the fundamental features of Java, which provides a smooth flow of program.
Java provides three types of control flow statements.
Decision Making statements
if statements
switch statement
Loop statements
do while loop
while loop
for loop
for-each loop
Jump statements
break statement
continue statement
Indeed, decision-making statements, as their name implies, are responsible for determining which statement to execute and when to execute it. These statements assess a Boolean expression and govern the program's flow based on the outcome of the provided condition. In Java, there are primarily two types of decision-making statements: the "if" statement and the "switch" statement.
In programming languages, control statements are employed to manage the flow of program execution, depending on specific conditions. They enable the program to progress and branch in response to alterations in the program's state.
The "if" statement evaluates a boolean expression or condition.
If the condition is true, the code block associated with the "if" statement is executed.
If the condition is false, the code block is skipped, and program execution continues with the next statement.
The "if" statement can be followed by an optional "else" block, which is executed when the condition is false.
there are four types of if-statements given below.
Simple if statement
if-else statement
if-else-if ladder
Nested if-statement
1.Simple if statement:The basic "if" statement that evaluates a condition and executes a block of code if the condition is true. Optionally, it may include an "else" block for code to run when the condition is false.
Syntax:-
if(condition) {
statement 1; //executes when condition is true
}
Example:-
public class Demo{
public static void main(String[ ] args) {
int x = 20;
int y = 32;
if(x+y > 50) {
System.out.println("x + y is greater than 50");
}
}
}
Output:
x + y is greater than 50
2) if-else statement
This construct allows you to evaluate multiple conditions sequentially. If one condition is true, the corresponding block of code is executed, and the rest are skipped.
Syntax:-
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
Example:-
public class Demo{
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
3."if-else if-else" Statement: This construct allows you to evaluate multiple conditions sequentially. If one condition is true, the corresponding block of code is executed, and the rest are skipped.
Syntax:-
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
public class Demo {
public static void main(String[] args) {
String city = "Noida";
if(city == "Fatehpur") {
System.out.println("city is fatehpur");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Prayagraj") {
System.out.println("city is prayagraj");
}else {
System.out.println(city);
}
}
}
Output
city is noida
4.Nested "if" Statement: This involves placing one "if" statement inside another. It's used when you need to check multiple conditions in a hierarchical manner.
Syntax:-
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Example:
public class Student {
public static void main(String[] args) {
String address = "Kanpur, India";
if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Kanpur)) {
System.out.println("Your city is Kanpur");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}
Output:-
Your city is Kanpur
switch statements
In Java, switch statements are a construct similar to if-else-if statements. They consist of multiple code blocks called cases, and a particular case is executed based on the value of the variable being switched. Switch statements are often preferred over multiple if-else-if statements as they can enhance the readability of the program and offer a more structured way to handle multiple conditions.
In Java, the variables used in case statements can be of types like int, short, byte, char, or enumeration. Starting from Java version 7, the String type is also supported for case variables.
Cases within a switch statement must be unique; duplicates are not allowed.
The default statement is optional and is executed when none of the case values matches the expression.
The break statement is optional within a switch block. When used, it terminates the switch block upon satisfying the condition. If not used, the execution will continue to the next case.
It's important to note that when employing switch statements, the case expressions must match the type of the variable, and they must also be constant values.
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Example
public class Demo implements Cloneable {
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
Output
2
In the realm of programming, there are occasions when we must repeatedly execute a block of code as long as a certain condition remains true. Loop statements come into play in such scenarios, facilitating the execution of a specified set of instructions in a repetitive manner, contingent on a specific condition.
Within the context of Java, we encounter three distinct types of loops that share a common purpose. Nonetheless, variations exist in their syntax and the timing of condition evaluation.
for loop
while loop
do-while loop
1.for Loop: The for loop is used when you know the number of iterations in advance.
for(initialization, condition, increment/decrement) {
//block of statements
}
Example
public class Demo_for_loop {
public static void main(String[] args) {
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}
Output
The sum of first 10 natural numbers is 55
This type of loop is often referred to as an "entry-controlled loop" because it evaluates the condition at the beginning of each iteration. If the condition is true, the loop body is executed; otherwise, the statements following the loop are executed.
Syntax
while(condition){
//looping statements
}
Example
class Demo{
public static void main(String[] args) {
// declare variables
int i = 1, n = 4;
// while loop from 1 to 4
while(i <= n) {
System.out.println(i);
i++;
}
}
}
Output
1
2
3
4
It's also referred to as an "exit-controlled loop" because it doesn't check the condition beforehand. Here's the syntax for the do-while loop:
Syntex:-
do
{
//statements
} while (condition);
class Main {
public static void main(String[] args) {
int i = 2, n = 8;
// do...while loop from 1 to 8
do {
System.out.println(i);
i++;
} while(i <= n);
}
}
Output
2
3
4
5
6
7
8
Jump statements are control structures that facilitate the transfer of execution control within a program. In the Java programming language, two jump statements are available:
Break statement.
Continue statement.
Break statement:-In Java, the "break" statement serves the purpose of prematurely terminating the execution of the closest enclosing loop or switch statement. This "break" statement is commonly utilized with various loop types, including the for loop, while loop, and do-while loop, as well as with switch statements.
Syntax:-
break;
while (condition) {
// Code inside the loop
if (condition) {
break;
// break keyword
}
// Code continues inside the loop
}
// Code after the loop
for loop:
for (int i = 0; i < limit; i++) {
// Code inside the loop
if (condition) {
break;
// break keyword
}
// Code continues inside the loop
}
// Code after the loop
public class Main
{
public static void main(String args[])
{
for (int i = 10; i > 0 ;i--)
{
if (i%2 == 0)
continue;
System.out.println(i+ " ");
}
}
}
Output
9
7
5
3
1
Operators form the fundamental components of any programming language, and Java offers a diverse range of operators for performing a wide array of calculations and operations, including logical, arithmetic, and relational tasks. These operators are categorized based on their specific functions, and here are some of the main types.
Arithmetic Operators
Unary Operators
Assignment Operator
Syntax:
variable = Exp1 ? Exp2: Exp3
If operates similarly to that of the if-else statement as in Exr2 is executed if Exp1 is true else Exp3 is executed.
if(Exp1)
{
variable = Exp2;
}
else
{
variable = Exp3;
}
Example:-
class Ternary_Demo {
public static void main(String[] args)
{
// variable declaration
int n1 = 5, n2 = 10, max;
System.out.println("First num: " + n1);
System.out.println("Second num: " + n2);
// Largest among n1 and n2
max = (n1 > n2) ? n1 : n2;
// Print the largest number
System.out.println("Maximum is = " + max);
}
}
Output
First num: 5
Second num: 10
Maximum is = 10
Example-2
public class TernaryOperatorDemo {
public static void main(String[] args)
{
boolean condition = true;
String result = (condition) ? "True" : "False";
System.out.println(result);
}
}
Output
True
Advantages of ternary operator.