Control Flow Statements
The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements,
however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute
particular blocks of code. This section describes
the decision-making statements (if-then
, if-then-else
, switch
),
the looping statements (for
, while
, do-while
), and the branching statements (break
, continue
, return
) supported by the Java programming language.
The if-then and if-then-else Statements
The
Theif-then
Statementif-then
statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates totrue
. For example, theBicycle
class could allow the brakes to decrease the bicycle's speed only if the bicycle is already in motion. One possible implementation of theapplyBrakes
method could be as follows:If this test evaluates tovoid applyBrakes(){ if (isMoving){ // the "if" clause: bicycle must be moving currentSpeed--; // the "then" clause: decrease current speed } }false
(meaning that the bicycle is not in motion), control jumps to the end of theif-then
statement. In addition, the opening and closing braces are optional, provided that the "then" clause contains only one statement:
Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more brittle. If a second statement is later added to the "then" clause, a common mistake would be forgetting to add the newly required braces. The compiler cannot catch this sort of error; you'll just get the wrong results.void applyBrakes(){ if (isMoving) currentSpeed--; // same as above, but without braces }
The
Theif-then-else
Statementif-then-else
statement provides a secondary path of execution when an "if" clause evaluates tofalse
. You could use anif-then-else
statement in theapplyBrakes
method to take some action if the brakes are applied when the bicycle is not in motion. In this case, the action is to simply print an error message stating that the bicycle has already stopped.The following program,void applyBrakes(){ if (isMoving) { currentSpeed--; } else { System.err.println("The bicycle has already stopped!"); } }IfElseDemo
, assigns a grade based on the value of a test score: an A for a score of 90% or above, a B for a score of 80% or above, and so on.
The output from the program is:class IfElseDemo { public static void main(String[] args) { int testscore = 76; char grade; if (testscore >= 90) { grade = 'A'; } else if (testscore >= 80) { grade = 'B'; } else if (testscore >= 70) { grade = 'C'; } else if (testscore >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("Grade = " + grade); } }You may have noticed that the value ofGrade = Ctestscore
can satisfy more than one expression in the compound statement:76 >= 70
and76 >= 60
. However, once a condition is satisfied, the appropriate statements are executed(grade = 'C';)
and the remaining conditions are not evaluated.
The switch Statement
Unlikeif-then
andif-then-else
, theswitch
statement allows for any number of possible execution paths. Aswitch
works with thebyte
,short
,char
, andint
primitive data types. It also works with enumerated types (discussed in Classes and Inheritance) and a few special classes that "wrap" certain primitive types:Character
,Byte
,Short
, andInteger
(discussed in Simple Data Objects ). The following program,SwitchDemo
, declares anint
namedmonth
whose value represents a month out of the year. The program displays the name of the month, based on the value of month, using theswitch
statement.
In this case, "August" is printed to standard output.class SwitchDemo { public static void main(String[] args) { int month = 8; switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; default: System.out.println("Invalid month.");break; } } }
The body of aswitch
statement is known as a switch block. Any statement immediately contained by theswitch
block may be labeled with one or morecase
ordefault
labels. Theswitch
statement evaluates its expression and executes the appropriatecase
.
Of course, you could also implement the same thing withif-then-else
statements:
Deciding whether to useint month = 8; if (month == 1) { System.out.println("January"); } else if (month == 2) { System.out.println("February"); } . . . // and so onif-then-else
statements or aswitch
statement is sometimes a judgment call. You can decide which one to use based on readability and other factors. Anif-then-else
statement can be used to make decisions based on ranges of values or conditions, whereas aswitch
statement can make decisions based only on a single integer or enumerated value. Another point of interest is thebreak
statement after eachcase
. Eachbreak
statement terminates the enclosingswitch
statement. Control flow continues with the first statement following theswitch
block. Thebreak
statements are necessary because without them,case
statements fall through; that is, without an explicitbreak
, control will flow sequentially through subsequentcase
statements. The following program,SwitchDemo2
, illustrates why it might be useful to havecase
statements fall through:
class SwitchDemo2 { public static void main(String[] args) { int month = 2; int year = 2000; int numDays = 0; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numDays = 31; break; case 4: case 6: case 9: case 11: numDays = 30; break; case 2: if ( ((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0) ) numDays = 29; else numDays = 28; break; default: System.out.println("Invalid month."); break; } System.out.println("Number of Days = " + numDays); }
This is the output from the program.}
Number of Days = 29Technically, the finalbreak
is not required because flow would fall out of theswitch
statement anyway. However, we recommend using abreak
so that modifying the code is easier and less error-prone. Thedefault
section handles all values that aren't explicitly handled by one of thecase
sections.
The while and do-while Statements
Thewhile
statement continually executes a block of statements while a particular condition istrue
. Its syntax can be expressed as:Thewhile (expression) { statement(s) }while
statement evaluates expression, which must return aboolean
value. If the expression evaluates totrue
, thewhile
statement executes the statement(s) in thewhile
block. Thewhile
statement continues testing the expression and executing its block until the expression evaluates tofalse
. Using thewhile
statement to print the values from 1 through 10 can be accomplished as in the followingWhileDemo
program:You can implement an infinite loop using theclass WhileDemo { public static void main(String[] args){ int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } } }while
statement as follows:
The Java programming language also provides awhile (true){ // your code goes here }do-while
statement, which can be expressed as follows:
The difference betweendo { statement(s) } while (expression);do-while
andwhile
is thatdo-while
evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within thedo
block are always executed at least once, as shown in the followingDoWhileDemo
program:class DoWhileDemo { public static void main(String[] args){ int count = 1; do { System.out.println("Count is: " + count); count++; } while (count <= 11); } }
The for Statement
Thefor
statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of thefor
statement can be expressed as follows:When using this version of thefor (initialization; termination; increment) { statement(s) }for
statement, keep in mind that:The following program,
- The initialization expression initializes the loop; it's executed once, as the loop begins.
- When the termination expression evaluates to
false
, the loop terminates.- The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
ForDemo
, uses the general form of thefor
statement to print the numbers 1 through 10 to standard output:
The output of this program is:class ForDemo { public static void main(String[] args){ for(int i=1; i<11; i++){ System.out.println("Count is: " + i); } } }Notice how the code declares a variable within the initialization expression. The scope of this variable extends from its declaration to the end of the block governed by theCount is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Count is: 6 Count is: 7 Count is: 8 Count is: 9 Count is: 10for
statement, so it can be used in the termination and increment expressions as well. If the variable that controls afor
statement is not needed outside of the loop, it's best to declare the variable in the initialization expression. The namesi
,j
, andk
are often used to controlfor
loops; declaring them within the initialization expression limits their life span and reduces errors. The three expressions of thefor
loop are optional; an infinite loop can be created as follows:
Thefor ( ; ; ) { // infinite loop // your code goes here }for
statement also has another form designed for iteration through Collections and arrays This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read. To demonstrate, consider the following array, which holds the numbers 1 through 10:
The following program,int[] numbers = {1,2,3,4,5,6,7,8,9,10};EnhancedForDemo
, uses the enhancedfor
to loop through the array:
In this example, the variableclass EnhancedForDemo { public static void main(String[] args){ int[] numbers = {1,2,3,4,5,6,7,8,9,10}; for (int item : numbers) { System.out.println("Count is: " + item); } } }item
holds the current value from the numbers array. The output from this program is the same as before:We recommend using this form of theCount is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Count is: 6 Count is: 7 Count is: 8 Count is: 9The for StatementThefor
statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of thefor
statement can be expressed as follows:When using this version of thefor (initialization; termination; increment) { statement(s) }for
statement, keep in mind that:The following program,
- The initialization expression initializes the loop; it's executed once, as the loop begins.
- When the termination expression evaluates to
false
, the loop terminates.- The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
ForDemo
, uses the general form of thefor
statement to print the numbers 1 through 10 to standard output:
The output of this program is:class ForDemo { public static void main(String[] args){ for(int i=1; i<11; i++){ System.out.println("Count is: " + i); } } }Notice how the code declares a variable within the initialization expression. The scope of this variable extends from its declaration to the end of the block governed by theCount is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Count is: 6 Count is: 7 Count is: 8 Count is: 9 Count is: 10for
statement, so it can be used in the termination and increment expressions as well. If the variable that controls afor
statement is not needed outside of the loop, it's best to declare the variable in the initialization expression. The namesi
,j
, andk
are often used to controlfor
loops; declaring them within the initialization expression limits their life span and reduces errors. The three expressions of thefor
loop are optional; an infinite loop can be created as follows:
Thefor ( ; ; ) { // infinite loop // your code goes here }for
statement also has another form designed for iteration through Collections and arrays This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read. To demonstrate, consider the following array, which holds the numbers 1 through 10:
The following program,int[] numbers = {1,2,3,4,5,6,7,8,9,10};EnhancedForDemo
, uses the enhancedfor
to loop through the array:
In this example, the variableclass EnhancedForDemo { public static void main(String[] args){ int[] numbers = {1,2,3,4,5,6,7,8,9,10}; for (int item : numbers) { System.out.println("Count is: " + item); } } }item
holds the current value from the numbers array. The output from this program is the same as before:We recommend using this form of theCount is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5 Count is: 6 Count is: 7 Count is: 8 Count is: 9 Count is: 10for
statement instead of the general form whenever possible.Count is: 10for
statement instead of the general form whenever possible.
kiranvarma - npeducations
ReplyDeletekiranvarma3@gmail.com
http://www.npeducations.com
comments:Thank for the code! its really helpful. very clean and neat explanation
good post! thank you
I got a job by saying this answer in my last interview. thanks for awesome help.
ReplyDeleteI got more idea about Java from Besant Technologies. If anyone wants to get Java Training in Chennai visit Besant Technologies.
thanks for code very usefull to my ongoing project session
ReplyDeleteNice to see the best portal for Java Tutorials . I will re visit again to follow all updates .
ReplyDeleteJava Tutorial
Great stuff!! Keep doing and I would like to share with my friends.
ReplyDeleteSelenium Training in Chennai
Best selenium training in chennai
iOS Training in Chennai
Digital Marketing Training in Chennai
.Net coaching centre in chennai
Salesforce Developer 501 Training in Chennai
Salesforce Developer 502 Training in Chennai
Big Data Training in Chennai
Wow it is really wonderful and awesome thus it is veWow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your site.ry much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your site.
ReplyDelete.Hadoop Training in Bangalore
Excellent information with unique content and it is very useful to know about the salesforce.salesforce developer training in bangalore
ReplyDeleteGreat blog thanks for sharing Masters of building brands, Adhuntt Media is making waves in the Chennai digital market! Known for their out of their box ideas, if a creative overhaul for your brand is what you need, you’ve come to the right place. Right from Search Engine Optimization-SEO to Social Media Marketing, Adhuntt Media is your pitstop for original brand identity creation from scratch. Let’s boost your sales right now at Adhuntt Media.
ReplyDeletesocial media marketing company in chennai
Excellent blog thanks for sharing Karuna Nursery Gardens provides you with the best nursery solutions for setting you up with a glamorous landscape. That’s right, you have finally found the perfect nursery to set you up with the best house garden in Chennai.
ReplyDeleteplant nursery in chennai
"I have read so many articles or reviews however this blog post is genuinely a pleasant article, keep it up. .
ReplyDeleteDigital Marketing Training Course in Chennai | Digital Marketing Training Course in Anna Nagar | Digital Marketing Training Course in OMR | Digital Marketing Training Course in Porur | Digital Marketing Training Course in Tambaram | Digital Marketing Training Course in Velachery
"