When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
The Java break statement is used to break loop or switch statement. It breaks the current flow of the program at specified condition. In case of inner loop, it breaks only inner loop.
We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.
Syntax:
jump-statement;
break;
Flowchart of Break Statement
Java Break Statement with Loop
Example:
BreakExample.java
//Java Program to demonstrate the use of break statement
//inside the for loop.
public class BreakExample {
public static void main(String[] args) {
//using for loop
for(int i=1;i<=10;i++){
if(i==5){
//breaking the loop
break;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
Java Break Statement with Inner Loop
It breaks inner loop only if you use break statement inside the inner loop.
Example:
BreakExample2.java
//Java Program to illustrate the use of break statement
//inside an inner loop
public class BreakExample2 {
public static void main(String[] args) {
//outer loop
for(int i=1;i<=3;i++){
//inner loop
for(int j=1;j<=3;j++){
if(i==2&&j==2){
//using break statement inside the inner loop
break;
}
System.out.println(i+" "+j);
}
}
}
}
Output:
1 1
1 2
1 3
2 1
3 1
3 2
3 3
Java Break Statement with Labeled For Loop
We can use break statement with a label. The feature is introduced since JDK 1.5. So, we can break any loop in Java now whether it is outer or inner loop.
Example:
BreakExample3.java
//Java Program to illustrate the use of continue statement
//with label inside an inner loop to break outer loop
public class BreakExample3 {
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
//using break statement with label
break aa;
}
System.out.println(i+" "+j);
}
}
}
}
Output:
1 1
1 2
1 3
2 1
Java Break Statement in while loop
Example:
BreakWhileExample.java
//Java Program to demonstrate the use of break statement
//inside the while loop.
public class BreakWhileExample {
public static void main(String[] args) {
//while loop
int i=1;
while(i<=10){
if(i==5){
//using break statement
i++;
break;//it will break the loop
}
System.out.println(i);
i++;
}
}
}
Output:
1
2
3
4
Java Break Statement in do-while loop
Example:
BreakDoWhileExample.java
//Java Program to demonstrate the use of break statement
//inside the Java do-while loop.
public class BreakDoWhileExample {
public static void main(String[] args) {
//declaring variable
int i=1;
//do-while loop
do{
if(i==5){
//using break statement
i++;
break;//it will break the loop
}
System.out.println(i);
i++;
}while(i<=10);
}
}
The Java do-while loop is used to iterate a part of the program repeatedly, until the specified condition is true. If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use a do-while loop.
Java do-while loop is called an exit control loop. Therefore, unlike while loop and for loop, the do-while check the condition at the end of loop body. The Java do-while loop is executed at least once because condition is checked after loop body.
Syntax:
do{
//code to be executed / loop body
//update statement
}while (condition);
The different parts of do-while loop:
1. Condition: It is an expression which is tested. If the condition is true, the loop body is executed and control goes to update expression. As soon as the condition becomes false, loop breaks automatically.
Example:
i <=100
2. Update expression: Every time the loop body is executed, the this expression increments or decrements loop variable.
Example:
i++;
Note: The do block is executed at least once, even if the condition is false.
Flowchart of do-while loop:
Example:
In the below example, we print integer values from 1 to 10. Unlike the for loop, we separately need to initialize and increment the variable used in the condition (here, i). Otherwise, the loop will execute infinitely.
DoWhileExample.java
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
Output:
1
2
3
4
5
6
7
8
9
10
Java Infinitive do-while Loop
If you pass true in the do-while loop, it will be infinitive do-while loop.
Syntax:
do{
//code to be executed
}while(true);
Example:
DoWhileExample2.java
public class DoWhileExample2 {
public static void main(String[] args) {
do{
System.out.println("infinitive do while loop");
}while(true);
}
}
Output:
infinitive do while loop
infinitive do while loop
infinitive do while loop
ctrl+c
The Java while loop is used to iterate a part of the program repeatedly until the specified Boolean condition is true. As soon as the Boolean condition becomes false, the loop automatically stops.
The while loop is considered as a repeating if statement. If the number of iteration is not fixed, it is recommended to use the while loop.
Syntax:
while (condition){
//code to be executed
I ncrement / decrement statement
}
The different parts of do-while loop:
1. Condition: It is an expression which is tested. If the condition is true, the loop body is executed and control goes to update expression. When the condition becomes false, we exit the while loop.
Example:
i <=100
2. Update expression: Every time the loop body is executed, this expression increments or decrements loop variable.
Example:
i++;
Flowchart of Java While Loop
Here, the important thing about while loop is that, sometimes it may not even execute. If the condition to be tested results into false, the loop body is skipped and first statement after the while loop will be executed.
Example:
In the below example, we print integer values from 1 to 10. Unlike the for loop, we separately need to initialize and increment the variable used in the condition (here, i). Otherwise, the loop will execute infinitely.
WhileExample.java
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10
Java Infinitive While Loop
If you pass true in the while loop, it will be infinitive while loop.
Syntax:
while(true){
//code to be executed
}
Example:
WhileExample2.java
public class WhileExample2 {
public static void main(String[] args) {
// setting the infinite while loop by passing true to the condition
while(true){
System.out.println("infinitive while loop");
}
}
}
Output:
infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop
ctrl+c
In the above code, we need to enter Ctrl + C command to terminate the infinite loop.
The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop.
There are three types of for loops in Java.
Simple for Loop
For-each or Enhanced for Loop
Labeled for Loop
Java Simple for Loop
A simple for loop is the same as C/C++. We can initialize the variable, check condition and increment/decrement value. It consists of four parts:
Initialization: It is the initial condition which is executed once when the loop starts. Here, we can initialize the variable, or we can use an already initialized variable. It is an optional condition.
Condition: It is the second condition which is executed each time to test the condition of the loop. It continues execution until the condition is false. It must return boolean value either true or false. It is an optional condition.
Increment/Decrement: It increments or decrements the variable value. It is an optional condition.
Statement: The statement of the loop is executed each time until the second condition is false.
Syntax:
for(initialization; condition; increment/decrement){
//statement or code to be executed
}
Flowchart:
Example:
ForExample.java
//Java Program to demonstrate the example of for loop
//which prints table of 1
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10
Java Nested for Loop
If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely whenever outer loop executes.
Example:
NestedForExample.java
public class NestedForExample {
public static void main(String[] args) {
//loop of i
for(int i=1;i<=3;i++){
//loop of j
for(int j=1;j<=3;j++){
System.out.println(i+" "+j);
}//end of i
}//end of j
}
}
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Pyramid Example 1:
PyramidExample.java
public class PyramidExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
Output:
*
* *
* * *
* * * *
* * * * *
Pyramid Example 2:
PyramidExample2.java
public class PyramidExample2 {
public static void main(String[] args) {
int term=6;
for(int i=1;i<=term;i++){
for(int j=term;j>=i;j--){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
Output:
* * * * * *
* * * * *
* * * *
* * *
* *
*
Java for-each Loop
The for-each loop is used to traverse array or collection in Java. It is easier to use than simple for loop because we don’t need to increment value and use subscript notation.
It works on the basis of elements and not the index. It returns element one by one in the defined variable.
Syntax:
for(data_type variable : array_name){
//code to be executed
}
Example:
ForEachExample.java
//Java For-each loop example which prints the
//elements of the array
public class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
Output:
12
23
44
56
78
Java Labeled For Loop
We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful while using the nested for loop as we can break/continue specific for loop.
Note: The break and continue keywords breaks or continues the innermost for loop respectively.
Syntax:
labelname:
for(initialization; condition; increment/decrement){
//code to be executed
}
Example:
LabeledForExample.java
//A Java program to demonstrate the use of labeled for loop
public class LabeledForExample {
public static void main(String[] args) {
//Using Label for outer and for loop
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
System.out.println(i+" "+j);
}
}
}
}
Output:
1 1
1 2
1 3
2 1
If you use break bb;, it will break inner loop only which is the default behaviour of any loop.
LabeledForExample2.java
public class LabeledForExample2 {
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break bb;
}
System.out.println(i+" "+j);
}
}
}
}
Output:
1 1
1 2
1 3
2 1
3 1
3 2
3 3
Java Infinitive for Loop
If you use two semicolons ;; in the for loop, it will be infinitive for loop.
Syntax:
for(;;){
//code to be executed
}
Example:
ForExample.java
//Java program to demonstrate the use of infinite for loop
//which prints an statement
public class ForExample {
public static void main(String[] args) {
//Using no condition in for loop
for(;;){
System.out.println("infinitive loop");
}
}
}
Now, you need to press ctrl+c to exit from the program.
Java for Loop vs while Loop vs do-while Loop
Comparison
for loop
while loop
do-while loop
Introduction
The Java for loop is a control flow statement that iterates a part of the programs multiple times.
The Java while loop is a control flow statement that executes a part of the programs repeatedly on the basis of given boolean condition.
The Java do while loop is a control flow statement that executes a part of the programs at least once and the further execution depends upon the given boolean condition.
When to use
If the number of iteration is fixed, it is recommended to use for loop.
If the number of iteration is not fixed, it is recommended to use while loop.
If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use the do-while loop.
Syntax
for(init;condition;incr/decr){ // code to be executed }
The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. The switch statement works with byte, short, int, long, enum types, String and some wrapper types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement.
In other words, the switch statement tests the equality of a variable against multiple values.
Points to Remember
There can be one or N number of case values for a switch expression.
The case value must be of switch expression type only. The case value must be literal or constant. It doesn’t allow variables.
The case values must be unique. In case of duplicate value, it renders compile-time error.
The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums and string.
Each case statement can have a break statement which is optional. When control reaches to the break statement, it jumps the control after the switch expression. If a break statement is not found, it executes the next case.
The case value can have a default label which is optional.
Syntax:
itch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Flowchart of Switch Statement
Example:
SwitchExample.java
public class SwitchExample {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Output:
20
Finding Month Example:
SwitchMonthExample.javaHTML
//Java Program to demonstrate the example of Switch statement
//where we are printing month name for the given number
public class SwitchMonthExample {
public static void main(String[] args) {
//Specifying month number
int month=7;
String monthString="";
//Switch statement
switch(month){
//case statements within the switch block
case 1: monthString="1 - January";
break;
case 2: monthString="2 - February";
break;
case 3: monthString="3 - March";
break;
case 4: monthString="4 - April";
break;
case 5: monthString="5 - May";
break;
case 6: monthString="6 - June";
break;
case 7: monthString="7 - July";
break;
case 8: monthString="8 - August";
break;
case 9: monthString="9 - September";
break;
case 10: monthString="10 - October";
break;
case 11: monthString="11 - November";
break;
case 12: monthString="12 - December";
break;
default:System.out.println("Invalid Month!");
}
//Printing month of the given number
System.out.println(monthString);
}
}
Output:
7 - July
Program to check Vowel or Consonant:
If the character is A, E, I, O, or U, it is vowel otherwise consonant. It is not case-sensitive.
SwitchVowelExample.java
public class SwitchVowelExample {
public static void main(String[] args) {
char ch='O';
switch(ch)
{
case 'a':
System.out.println("Vowel");
break;
case 'e':
System.out.println("Vowel");
break;
case 'i':
System.out.println("Vowel");
break;
case 'o':
System.out.println("Vowel");
break;
case 'u':
System.out.println("Vowel");
break;
case 'A':
System.out.println("Vowel");
break;
case 'E':
System.out.println("Vowel");
break;
case 'I':
System.out.println("Vowel");
break;
case 'O':
System.out.println("Vowel");
break;
case 'U':
System.out.println("Vowel");
break;
default:
System.out.println("Consonant");
}
}
}
Output:
Vowel
Java Switch Statement is fall-through
The Java switch statement is fall-through. It means it executes all statements after the first match if a break statement is not present.
Example:
SwitchExample2.java
//Java Switch Example where we are omitting the
//break statement
public class SwitchExample2 {
public static void main(String[] args) {
int number=20;
//switch expression with int value
switch(number){
//switch cases without break statements
case 10: System.out.println("10");
case 20: System.out.println("20");
case 30: System.out.println("30");
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Output:
20
30
Not in 10, 20 or 30
Java Switch Statement with String
Java allows us to use strings in switch expression since Java SE 7. The case statement should be string literal.
Example:
SwitchStringExample.java
//Java Program to demonstrate the use of Java Switch
//statement with String
public class SwitchStringExample {
public static void main(String[] args) {
//Declaring String variable
String levelString="Expert";
int level=0;
//Using String in Switch expression
switch(levelString){
//Using String Literal in Switch case
case "Beginner": level=1;
break;
case "Intermediate": level=2;
break;
case "Expert": level=3;
break;
default: level=0;
break;
}
System.out.println("Your Level is: "+level);
}
}
Output:
Your Level is: 3
Java Nested Switch Statement
We can use switch statement inside other switch statement in Java. It is known as nested switch statement.
Example:
NestedSwitchExample.java
//Java Program to demonstrate the use of Java Nested Switch
public class NestedSwitchExample {
public static void main(String args[])
{
//C - CSE, E - ECE, M - Mechanical
char branch = 'C';
int collegeYear = 4;
switch( collegeYear )
{
case 1:
System.out.println("English, Maths, Science");
break;
case 2:
switch( branch )
{
case 'C':
System.out.println("Operating System, Java, Data Structure");
break;
case 'E':
System.out.println("Micro processors, Logic switching theory");
break;
case 'M':
System.out.println("Drawing, Manufacturing Machines");
break;
}
break;
case 3:
switch( branch )
{
case 'C':
System.out.println("Computer Organization, MultiMedia");
break;
case 'E':
System.out.println("Fundamentals of Logic Design, Microelectronics");
break;
case 'M':
System.out.println("Internal Combustion Engines, Mechanical Vibration");
break;
}
break;
case 4:
switch( branch )
{
case 'C':
System.out.println("Data Communication and Networks, MultiMedia");
break;
case 'E':
System.out.println("Embedded System, Image Processing");
break;
case 'M':
System.out.println("Production Technology, Thermal Engineering");
break;
}
break;
}
}
}
Output:
Data Communication and Networks, MultiMedia
Java Enum in Switch Statement
Java allows us to use enum in switch statement. Java enum is a class that represent the group of constants. (immutable such as final variables). We use the keyword enum and put the constants in curly braces separated by comma.
Example:
JavaSwitchEnumExample.java
//Java Program to demonstrate the use of Enum
//in switch statement
public class JavaSwitchEnumExample {
public enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat }
public static void main(String args[])
{
Day[] DayNow = Day.values();
for (Day Now : DayNow)
{
switch (Now)
{
case Sun:
System.out.println("Sunday");
break;
case Mon:
System.out.println("Monday");
break;
case Tue:
System.out.println("Tuesday");
break;
case Wed:
System.out.println("Wednesday");
break;
case Thu:
System.out.println("Thursday");
break;
case Fri:
System.out.println("Friday");
break;
case Sat:
System.out.println("Saturday");
break;
}
}
}
}
Java allows us to use four wrapper classes: Byte, Short, Integer and Long in switch statement.
Example:
WrapperInSwitchCaseExample.java
//Java Program to demonstrate the use of Wrapper class
//in switch statement
public class WrapperInSwitchCaseExample {
public static void main(String args[])
{
Integer age = 18;
switch (age)
{
case (16):
System.out.println("You are under 18.");
break;
case (18):
System.out.println("You are eligible for vote.");
break;
case (65):
System.out.println("You are senior citizen.");
break;
default:
System.out.println("Please give the valid age.");
break;
}
}
}
The Java if statement is used to test the condition. It checks boolean condition: true or false. There are various types of if statement in Java.
if statement
if-else statement
if-else-if ladder
nested if statement
Java if Statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition){
//code to be executed
}
Example:
//Java Program to demonstate the use of if statement.
public class IfExample {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
}
}
}
Output:
Age is greater than 18
Java if-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Example:
//A Java Program to demonstrate the use of if-else statement.
//It is a program of odd and even number.
public class IfElseExample {
public static void main(String[] args) {
//defining a variable
int number=13;
//Check if the number is divisible by 2 or not
if(number%2==0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
}
}
Output:
odd number
Leap Year Example:
A year is leap, if it is divisible by 4 and 400. But, not by 100.
public class LeapYearExample {
public static void main(String[] args) {
int year=2020;
if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0)){
System.out.println("LEAP YEAR");
}
else{
System.out.println("COMMON YEAR");
}
}
}
Output:
LEAP YEAR
Using Ternary Operator
We can also use ternary operator (? 🙂 to perform the task of if…else statement. It is a shorthand way to check the condition. If the condition is true, the result of ? is returned. But, if the condition is false, the result of : is returned.
Example:
public class IfElseTernaryExample {
public static void main(String[] args) {
int number=13;
//Using ternary operator
String output=(number%2==0)?"even number":"odd number";
System.out.println(output);
}
}
Output:
odd number
Java if-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Example:
//Java Program to demonstrate the use of If else-if ladder.
//It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
Output:
C grade
Program to check POSITIVE, NEGATIVE or ZERO:
public class PositiveNegativeExample {
public static void main(String[] args) {
int number=-13;
if(number>0){
System.out.println("POSITIVE");
}else if(number<0){
System.out.println("NEGATIVE");
}else{
System.out.println("ZERO");
}
}
}
Output:
NEGATIVE
Java Nested if statement
The 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:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
Example:
//Java Program to demonstrate the use of Nested If Statement.
public class JavaNestedIfExample {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
}
}}
Output:
You are eligible to donate blood
Example 2:
//Java Program to demonstrate the use of Nested If Statement.
public class JavaNestedIfExample2 {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=25;
int weight=48;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
} else{
System.out.println("You are not eligible to donate blood");
}
} else{
System.out.println("Age must be greater than 18");
}
} }
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
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and when. Decision-making statements evaluate the Boolean expression and control the program flow depending upon the result of the condition provided. There are two types of decision-making statements in Java, i.e., If statement and switch statement.
1) If Statement:
In Java, the “if” statement is used to evaluate a condition. The control of the program is diverted depending upon the specific condition. The condition of the If statement gives a Boolean value, either true or false. In Java, there are four types of if-statements given below.
Simple if statement
if-else statement
if-else-if ladder
Nested if-statement
Let’s understand the if-statements one by one.
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression and enables the program to enter a block of code if the expression evaluates to true.
Syntax of if statement is given below.
if(condition) {
statement 1; //executes when condition is true
}
Consider the following example in which we have used the if statement in the java code.
Student.java
Student.java
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block. The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
Consider the following example.
Student.java
public class Student {
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 ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we can say that it is the chain of if-else statements that create a decision tree where the program may enter in the block of code where the condition is true. We can also define an else statement at the end of the chain.
Syntax of if-else-if statement is given below.
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
}
Consider the following example.
Student.java
public class Student {
public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
}
}
}
Output:
Delhi
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if statement.
Syntax of Nested if-statement is given below.
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
}
}
Consider the following example.
Student.java
public class Student {
public static void main(String[] args) {
String address = "Delhi, India";
if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}
Output:
Delhi
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks of code called cases and a single case is executed based on the variable which is being switched. The switch statement is easier to use instead of if-else-if statements. It also enhances the readability of the program.
Points to be noted about switch statement:
The case variables can be int, short, byte, char, or enumeration. String type is also supported since version 7 of Java
Cases cannot be duplicate
Default statement is executed when any of the case doesn’t match the value of expression. It is optional.
Break statement terminates the switch block when the condition is satisfied. It is optional, if not used, next case is executed.
While using switch statements, we must notice that the case expression will be of the same type as the variable. However, it will also be a constant value.
The syntax to use the switch statement is given below.
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Consider the following example to understand the flow of the switch statement.
Student.java
public class Student 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
While using switch statements, we must notice that the case expression will be of the same type as the variable. However, it will also be a constant value. The switch permits only int, string, and Enum type variables to be used.
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some condition evaluates to true. However, loop statements are used to execute the set of instructions in a repeated order. The execution of the set of instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in their syntax and condition checking time.
for loop
while loop
do-while loop
Let’s understand the loop statements one by one.
Java for loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the condition, and increment/decrement in a single line of code. We use the for loop only when we exactly know the number of times, we want to execute the block of code.
for(initialization, condition, increment/decrement) {
//block of statements
}
The flow chart for the for-loop is given below.
Consider the following example to understand the proper functioning of the for loop in java.
Calculation.java
public class Calculattion {
public static void main(String[] args) {
// TODO Auto-generated method stub
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
Java for-each loop
Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-each loop, we don’t need to update the loop variable. The syntax to use the for-each loop in java is given below.
for(data_type var : array_name/collection_name){
//statements
}
Consider the following example to understand the functioning of the for-each loop in Java.
Calculation.java
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {
System.out.println(name);
}
}
}
Output:
Printing the content of the array names:
Java
C
C++
Python
JavaScript
Java while loop
The while loop is also used to iterate over the number of statements multiple times. However, if we don’t know the number of iterations in advance, it is recommended to use a while loop. Unlike for loop, the initialization and increment/decrement doesn’t take place inside the loop statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the condition is true, then the loop body will be executed; otherwise, the statements after the loop will be executed.
The syntax of the while loop is given below.
while(condition){
//looping statements
}
The flow chart for the while loop is given in the following image.
Consider the following example.
Calculation .java
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
}
}
}
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
Java do-while loop
The do-while loop checks the condition at the end of the loop after executing the loop statements. When the number of iteration is not known and we have to execute the loop at least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax of the do-while loop is given below.
do
{
//statements
} while (condition);
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop in Java.
Calculation.java
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In other words, jump statements transfer the execution control to the other part of the program. There are two types of jump statements in Java, i.e., break and continue.
Java break statement
As the name suggests, the break statement is used to break the current flow of the program and transfer the control to the next statement outside a loop or switch statement. However, it breaks only the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be written inside the loop or switch statement.
The break statement example with for loop
Consider the following example in which we have used the break statement with the for loop.
BreakExample.java
public class BreakExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}
}
}
}
Output:
0
1
2
3
4
5
6
break statement example with labeled for loop
Calculation.java
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
a:
for(int i = 0; i<= 10; i++) {
b:
for(int j = 0; j<=15;j++) {
c:
for (int k = 0; k<=20; k++) {
System.out.println(k);
if(k==5) {
break a;
}
}
}
}
}
}
Output:
0
1
2
3
4
5
Java continue statement
Unlike break statement, the continue statement doesn’t break the loop, whereas, it skips the specific part of the loop and jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in Java.
public class ContinueExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4) {
continue;
}
System.out.println(j);
}
}
}
}
Java keywords are also known as reserved words. Keywords are particular words that act as a key to a code. These are predefined words by Java so they cannot be used as a variable or object name or class name.
List of Java Keywords
A list of Java keywords or reserved words are given below:
abstract: Java abstract keyword is used to declare an abstract class. An abstract class can provide the implementation of the interface. It can have abstract and non-abstract methods.
boolean: Java boolean keyword is used to declare a variable as a boolean type. It can hold True and False values only.
break: Java break keyword is used to break the loop or switch statement. It breaks the current flow of the program at specified conditions.
byte: Java byte keyword is used to declare a variable that can hold 8-bit data values.
case: Java case keyword is used with the switch statements to mark blocks of text.
catch: Java catch keyword is used to catch the exceptions generated by try statements. It must be used after the try block only.
char: Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode characters
class: Java class keyword is used to declare a class.
continue: Java continue keyword is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition.
default: Java default keyword is used to specify the default block of code in a switch statement.
do: Java do keyword is used in the control statement to declare a loop. It can iterate a part of the program several times.
double: Java double keyword is used to declare a variable that can hold 64-bit floating-point number.
else: Java else keyword is used to indicate the alternative branches in an if statement.
enum: Java enum keyword is used to define a fixed set of constants. Enum constructors are always private or default.
extends: Java extends keyword is used to indicate that a class is derived from another class or interface.
final: Java final keyword is used to indicate that a variable holds a constant value. It is used with a variable. It is used to restrict the user from updating the value of the variable.
finally: Java finally keyword indicates a block of code in a try-catch structure. This block is always executed whether an exception is handled or not.
float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point number.
for: Java for keyword is used to start a for loop. It is used to execute a set of instructions/functions repeatedly when some condition becomes true. If the number of iteration is fixed, it is recommended to use for loop.
if: Java if keyword tests the condition. It executes the if block if the condition is true.
implements: Java implements keyword is used to implement an interface.
import: Java import keyword makes classes and interfaces available and accessible to the current source code.
instanceof: Java instanceof keyword is used to test whether the object is an instance of the specified class or implements an interface.
int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
interface: Java interface keyword is used to declare an interface. It can have only abstract methods.
long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
native: Java native keyword is used to specify that a method is implemented in native code using JNI (Java Native Interface).
new: Java new keyword is used to create new objects.
null: Java null keyword is used to indicate that a reference does not refer to anything. It removes the garbage value.
package: Java package keyword is used to declare a Java package that includes the classes.
private: Java private keyword is an access modifier. It is used to indicate that a method or variable may be accessed only in the class in which it is declared.
protected: Java protected keyword is an access modifier. It can be accessible within the package and outside the package but through inheritance only. It can’t be applied with the class.
public: Java public keyword is an access modifier. It is used to indicate that an item is accessible anywhere. It has the widest scope among all other modifiers.
return: Java return keyword is used to return from a method when its execution is complete.
short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
static: Java static keyword is used to indicate that a variable or method is a class method. The static keyword in Java is mainly used for memory management.
strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.
super: Java super keyword is a reference variable that is used to refer to parent class objects. It can be used to invoke the immediate parent class method.
switch: The Java switch keyword contains a switch statement that executes code based on test value. The switch statement tests the equality of a variable against multiple values.
synchronized: Java synchronized keyword is used to specify the critical sections or methods in multithreaded code.
this: Java this keyword can be used to refer the current object in a method or constructor.
throw: The Java throw keyword is used to explicitly throw an exception. The throw keyword is mainly used to throw custom exceptions. It is followed by an instance.
throws: The Java throws keyword is used to declare an exception. Checked exceptions can be propagated with throws.
transient: Java transient keyword is used in serialization. If you define any data member as transient, it will not be serialized.
try: Java try keyword is used to start a block of code that will be tested for exceptions. The try block must be followed by either catch or finally block.
void: Java void keyword is used to specify that a method does not have a return value.
volatile: Java volatile keyword is used to indicate that a variable may change asynchronously.
while: Java while keyword is used to start a while loop. This loop iterates a part of the program several times. If the number of iteration is not fixed, it is recommended to use the while loop.
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
Unary Operator,
Arithmetic Operator,
Shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Ternary Operator and
Assignment Operator.
Java Operator Precedence
Operator Type
Category
Precedence
Unary
postfix
expr++ expr--
prefix
++expr --expr +expr -expr ~ !
Arithmetic
multiplicative
* / %
additive
+ -
Shift
shift
<< >> >>>
Relational
comparison
< > <= >= instanceof
equality
== !=
Bitwise
bitwise AND
&
bitwise exclusive OR
^
bitwise inclusive OR
|
Logical
logical AND
&&
logical OR
||
Ternary
ternary
? :
Assignment
assignment
= += -= *= /= %= &= ^= |= <<= >>= >>>=
Java Unary Operator
The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.:
incrementing/decrementing a value by one
negating an expression
inverting the value of a boolean
Java Unary Operator Example: ++ and —
public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}
Output:
10
12
12
10
Java Unary Operator Example 2: ++ and —
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a);//10+12=22
System.out.println(b++ + b++);//10+11=21
}}
Output:
22
21
Java Unary Operator Example: ~ and !
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}}
Output:
-11
9
false
true
Java Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as basic mathematical operations.
Java Arithmetic Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
Output:
15
5
50
2
0
Java Arithmetic Operator Example: Expression
public class OperatorExample{
public static void main(String args[]){
System.out.println(10*10/5+3-1*4/2);
}}
Output:
21
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified number of times.
Java Left Shift Operator Example
public class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}
Output:
40
80
80
240
Java Right Shift Operator
The Java right shift operator >> is used to move the value of the left operand to right by the number of bits specified by the right operand.
Java Right Shift Operator Example
public OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}
Output:
2
5
2
Java Shift Operator Example: >> vs >>>
public class OperatorExample{
public static void main(String args[]){
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}}
Output:
5
5
-5
1073741819
Java AND Operator Example: Logical && and Bitwise &
The logical && operator doesn’t check the second condition if the first condition is false. It checks the second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}}
Output:
false
false
Java AND Operator Example: Logical && vs Bitwise &
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c);//false && true = false
System.out.println(a);//10 because second condition is not checked
System.out.println(a<b&a++<c);//false && true = false
System.out.println(a);//11 because second condition is checked
}}
Output:
false
10
false
11
Java OR Operator Example: Logical || and Bitwise |
The logical || operator doesn’t check the second condition if the first condition is true. It checks the second condition only if the first one is false.
The bitwise | operator always checks both conditions whether first condition is true or false.
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}}
Output:
true
true
true
10
true
11
Java Ternary Operator
Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in Java programming. It is the only conditional operator which takes three operands.
Java Ternary Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
2
Another Example:
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
5
Java Assignment Operator
Java assignment operator is one of the most common operators. It is used to assign the value on its right to the operand on its left.
Java Assignment Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}
Output:
14
16
Java Assignment Operator Example
public class OperatorExample{
public static void main(String[] args){
int a=10;
a+=3;//10+3
System.out.println(a);
a-=4;//13-4
System.out.println(a);
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);
}}
Output:
13
9
18
9
Java Assignment Operator Example: Adding short
public class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine
a=a+b;//Compile time error because 10+10=20 now int
System.out.println(a);
}}
Output:
Compile time error
After type cast:
public class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
a=(short)(a+b);//20 which is int now converted to short
System.out.println(a);
}}
Unicode is a universal international standard character encoding that is capable of representing most of the world’s written languages.
Why java uses Unicode System?
Before Unicode, there were many language standards:
ASCII (American Standard Code for Information Interchange) for the United States.ISO 8859-1 for Western European Language.KOI-8 for Russian.GB18030 and BIG-5 for chinese, and so on.
Problem
This caused two problems:A particular code value corresponds to different letters in the various language standards.The encodings for languages with large character sets have variable length.Some common characters are encoded as single bytes, other require two or more byte.
Solution
To solve these problems, a new language standard was developed i.e. Unicode System.
In unicode, character holds 2 byte, so java also uses 2 byte for characters.