Signed in as:
filler@godaddy.com
Signed in as:
filler@godaddy.com
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.
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.
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.
ADVERTISEMENT
Let's understand the if-statements one by one.
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.
Consider the following example in which we have used the if statement in the java code.
Student.java
Student.java
Output:
x + y is greater than 20
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:
Consider the following example.
Student.java
Output:
x + y is greater than 20
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.
Consider the following example.
Student.java
Output:
Delhi
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.
Consider the following example.
Student.java
Output:
Delhi
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 syntax to use the switch statement is given below.
Consider the following example to understand the flow of the switch statement.
Student.java
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.
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.
Let's understand the loop statements one by one.
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.
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
Output:
The sum of first 10 natural numbers is 55
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.
Consider the following example to understand the functioning of the for-each loop in Java.
Calculation.java
Output:
Printing the content of the array names:
Java
C
C++
Python
JavaScript
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.
The flow chart for the while loop is given in the following image.
Consider the following example.
Calculation .java
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
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.
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
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
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.
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
Output:
0
1
2
3
4
5
6
break statement example with labeled for loop
Calculation.java
Output:
0
1
2
3
4
5
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.
Output:
0
1
2
3
5
1
2
3
5
2
3
5
==========================================================================
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.
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
Example:
Output:
Age is greater than 18
The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else block is executed.
Syntax:
Example:
Output:
odd number
Leap Year Example:
A year is leap, if it is divisible by 4 and 400. But, not by 100.
Output:
LEAP YEAR
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:
Output:
odd number
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
Example:
Output:
C grade
Program to check POSITIVE, NEGATIVE or ZERO:
Output:
NEGATIVE
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:
Example:
Output:
You are eligible to donate blood
Example 2:
Output:
You are not eligible to donate blood
=============================================================================
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.
Syntax:
Flowchart of Switch Statement
Example:
SwitchExample.java
Output:
20
Finding Month Example:
SwitchMonthExample.javaHTML
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
Output:
Vowel
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
Output:
20
30
Not in 10, 20 or 30
Java allows us to use strings in switch expression since Java SE 7. The case statement should be string literal.
Example:
SwitchStringExample.java
Output:
Your Level is: 3
We can use switch statement inside other switch statement in Java. It is known as nested switch statement.
Example:
NestedSwitchExample.java
Output:
Data Communication and Networks, MultiMedia
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
Output:
Sunday
Monday
Twesday
Wednesday
Thursday
Friday
Saturday
Java allows us to use four wrapper classes: Byte, Short, Integer and Long in switch statement.
Example:
WrapperInSwitchCaseExample.java
Output:
You are eligible for vote.
========================================================
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.
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:
Syntax:
Flowchart:
Example:
ForExample.java
Output:
1
2
3
4
5
6
7
8
9
10
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
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Pyramid Example 1:
PyramidExample.java
Output:
*
* *
* * *
* * * *
* * * * *
Pyramid Example 2:
PyramidExample2.java
Output:
* * * * * *
* * * * *
* * * *
* * *
* *
*
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:
Example:
ForEachExample.java
Output:
12
23
44
56
78
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.
Syntax:
Example:
LabeledForExample.java
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
Output:
1 1
1 2
1 3
2 1
3 1
3 2
3 3
ADVERTISEMENT
If you use two semicolons ;; in the for loop, it will be infinitive for loop.
Syntax:
Example:
ForExample.java
Output:
infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c
Now, you need to press ctrl+c to exit from the program.
=======================================================================
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:
The different parts of do-while loop:
ADVERTISEMENT
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
Output:
1
2
3
4
5
6
7
8
9
10
If you pass true in the while loop, it will be infinitive while loop.
ADVERTISEMENT
Syntax:
Example:
WhileExample2.java
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 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:
The different parts of do-while loop:
Backward Skip 10sPlay VideoForward Skip 10sADVERTISEMENT
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++;
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
Output:
1
2
3
4
5
6
7
8
9
10
If you pass true in the do-while loop, it will be infinitive do-while loop.
Syntax:
Example:
DoWhileExample2.java
Output:
ADVERTISEMENT
infinitive do while loop
infinitive do while loop
infinitive do while loop
ctrl+c
In the above code, we need to enter Ctrl + C command to terminate the infinite loop.
========================================================================
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:
Flowchart of Break Statement
Example:
BreakExample.java
Output:
1
2
3
4
It breaks inner loop only if you use break statement inside the inner loop.
Example:
BreakExample2.java
Output:
1 1
1 2
1 3
2 1
3 1
3 2
3 3
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
Output:
1 1
1 2
1 3
2 1
Example:
BreakWhileExample.java
Output:
1
2
3
4
Example:
BreakDoWhileExample.java
Output:
1
2
3
4
To understand the example of break with switch statement, please visit here: Java Switch Statement.
=============================================================================
The continue statement is used in loop control structure when you need to jump to the next iteration of the loop immediately. It can be used with for loop or while loop.
The Java continue statement is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition. In case of an inner loop, it continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.
Syntax:
Backward Skip 10sPlay VideoForward Skip 10sADVERTISEMENT
ContinueExample.java
Output:
1
2
3
4
6
7
8
9
10
As you can see in the above output, 5 is not printed on the console. It is because the loop is continued when it reaches to 5.
It continues inner loop only if you use the continue statement inside the inner loop.
ContinueExample2.java
Output:
ADVERTISEMENT
1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3
We can use continue statement with a label. This feature is introduced since JDK 1.5. So, we can continue any loop in Java now whether it is outer loop or inner.
Example:
ContinueExample3.java
Output:
1 1
1 2
1 3
2 1
3 1
3 2
3 3
ContinueWhileExample.java
Output:
1
2
3
4
6
7
8
9
10
ADVERTISEMENT
ContinueDoWhileExample.java
Output:
1
2
3
4
6
7
8
9
10
The Java comments are the statements in a program that are not executed by the compiler and interpreter.
There are three types of comments in Java.
The single-line comment is used to comment only one line of the code. It is the widely used and easiest way of commenting the statements.
Single line comments starts with two forward slashes (//). Any text in front of // is not executed by Java.
ADVERTISEMENTADVERTISEMENT
Syntax:
Let's use single line comment in a Java program.
CommentExample1.java
Output:
10
The multi-line comment is used to comment multiple lines of code. It can be used to explain a complex code snippet or to comment multiple lines of code at a time (as it will be difficult to use single-line comments there).
Multi-line comments are placed between /* and */. Any text between /* and */ is not executed by Java.
Syntax:
Let's use multi-line comment in a Java program.
CommentExample2.java
Output:
10
Documentation comments are usually used to write large programs for a project or software application as it helps to create documentation API. These APIs are needed for reference, i.e., which classes, methods, arguments, etc., are used in the code.
To create documentation API, we need to use the javadoc tool. The documentation comments are placed between /** and */.
Syntax:
Some of the commonly used tags in documentation comments:
TagSyntaxDescription{@docRoot}{@docRoot}to depict relative path to root directory of generated document from any page.@author@author name - textTo add the author of the class.@code{@code text}To show the text in code font without interpreting it as html markup or nested javadoc tag.@version@version version-textTo specify "Version" subheading and version-text when -version option is used.@since@since releaseTo add "Since" heading with since text to generated documentation.@param@param parameter-name descriptionTo add a parameter with given name and description to 'Parameters' section.@return@return descriptionRequired for every method that returns something (except void)
Let's use the Javadoc tag in a Java program.
Calculate.java
Compile it by javac tool:
Create Document
Create documentation API by javadoc tool:
Now, the HTML files are created for the Calculate class in the current directory, i.e., abcDemo. Open the HTML files, and we can see the explanation of Calculate class provided through the documentation comment.
Ans: As we know, Java comments are not executed by the compiler or interpreter, however, before the lexical transformation of code in compiler, contents of the code are encoded into ASCII in order to make the processing easy.
Test.java
Output:
The above code generate the output because the compiler parses the Unicode character \u000d as a new line before the lexical transformation, and thus the code is transformed as shown below:
Test.java
Thus, the Unicode character shifts the print statement to next line and it is executed as a normal Java code.
======================================================================
Java programs are frequently asked in the interview. These programs can be asked from control statements, array, string, oops etc. Java basic programs like fibonacci series, prime numbers, factorial numbers and palindrome numbers are frequently asked in the interviews and exams. All these programs are given with the maximum examples and output. If you are new to Java programming, we will recommend you to read our Java tutorial first. Let's see the list of Java programs.
We use cookies to analyze website traffic and optimize your website experience. By accepting our use of cookies, your data will be aggregated with all other user data.