Java Fundamentals-Control flow statements

Source: Internet
Author: User
Tags tag name terminates

In general, code executes in order from top to bottom, but by adding some judgments, loops, and jump statements, you can conditionally execute specific statements.

The next three sections describe the control flow statements for Java, which are judgment statements (,, if-then if-then-else ), loop statements (,,) switch , for while do-while and jump statements (,, break continue return ).

Judgment statement

If-then statements

The If-then statement is the most basic statement in a control flow statement that tells the program to execute a specific code if the condition is set to true.

If-then-else statements

The If-then-else statement provides two or more executable paths.

     intTestscore = 76; Chargrade; if(Testscore >= 90) {//if the after condition returns True, execute the flower registration code, then execute the last line of code, otherwise judge the next conditional sentence, and so on.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);

Switch statement

A switch statement is like a statement that matches execution. The data type in parentheses after switch can be byte,short,char in the underlying type, and int. You can also use an enumeration type and a string (string) to encapsulate the character,byte,short,integer of the underlying type. Its usage is shown in the following code:

 Public classSwitchdemo { Public Static voidMain (string[] args) {intMonth = 8;        String monthstring; Switch(month) { Case1:monthstring = "January";  Break;  Case2:monthstring = "February";  Break;  Case3:monthstring = "March";  Break;  Case4:monthstring = "April";  Break;  Case5:monthstring = "May";  Break;  Case6:monthstring = "June";  Break;  Case7:monthstring = "July";  Break;  Case8:monthstring = "August";  Break;  Case9:monthstring = "September";  Break;  Case10:monthstring = "October";  Break;  Case11:monthstring = "November";  Break;  Case12:monthstring = "December";  Break; default: monthstring = "Invalid Month";  Break;    } System.out.println (monthstring); }}

The main body of the switch statement is also called the switch code block, which can be labeled with multiple case tags within the switch code block, which means that if there is no matching result, the code for the default tag is executed, and notice the effect of break. If there is no break, all code within the switch code block will be executed, starting with the matching case.

Looping statements

While statement

If a specific condition is true, the while statement continues execution of a piece of code, and the condition is then judged to be cyclic when the condition is false, and the loop terminates.

 while (expression) {// when the condition is true, execute the code inside the curly braces and judge      statement (s)} again

Do-while statements

The Do-while statement acts like a while statement, but it executes the code first, then evaluates the condition and loops until the condition is false.

 Do {// Whether expression is true or not, first execute the inside code of the flower registration and then judge the condition       of the Loop while (expression); 

For statement

The For statement has two uses, one of which is:

    • for (initialization; termination;increment) {// note parentheses separated by semicolons statement (s)}
    • The initialization expression is the initialization of the entire loop and executes only once at the beginning of the loop.
    • The termination expression is used to determine whether the loop terminates and, if false, terminates.
    • increment expressions are executed once per loop and are typically used to add a value to a variable.

Another use is usually to iterate over an array or collection:

         int [] numbers =              {1,2,3,4,5,6,7,8,9,10};           for (int item:numbers) {// Note enclosed in parentheses with an expression quote             System.out.println ("Count is:" + Item);

Where the left expression is declaring a variable that is consistent with the array element type, or compatible (inherited or implemented), is the array variable on the right.

Jump statement

Break statement

Break statements are divided into both marked and unmarked cases where the break statement can be used in addition to the switch statement to interrupt the loop statement, and when there is no mark, break breaks the inner loop and breaks the loop at the marker when it is marked:

classBreakwithlabeldemo { Public Static voidMain (string[] args) {int[] arrayofints = {             { 32, 87, 3, 589 },            { 12, 1076, 2000, 8 },            { 622, 127, 77, 955 }        }; intSearchfor = 12; inti; intj = 0; BooleanFoundit =false; Search://tag is used before the statement of the Loop         for(i = 0; i < arrayofints.length; i++) {             for(j = 0; J <arrayofints[i].length; J++) {                if(Arrayofints[i][j] = =searchfor) {Foundit=true;  BreakSearch//if the interrupt tag is looped, indicate the tag name, which is the search                }            }        }        if(Foundit) {System.out.println ("Found" + searchfor + "at" + i + "," +j); } Else{System.out.println (searchfor+ "Not in the array"); }    }}

Above code output bit: Found at 1, 0

Continue statements

The Continue is used to skip the rest of the code in the loop, continue with the next loop, and the continue statement is also divided into tagged code and unmarked usage:

classContinuedemo { Public Static voidMain (string[] args) {String searchMe= "Peter Piper picked a" + "Peck of pickled Peppers"; intMax =searchme.length (); intNumps = 0;  for(inti = 0; i < Max; i++) {            //interested only in P ' s            if(Searchme.charat (i)! = ' P ')                Continue;//the rest of the code in the loop is skipped here//process P ' snumps++; } System.out.println ("Found" + numps + "P ' s in the string."); }}

The above code output is: Found 9 P ' s in the string.

Return statement

The return statement is used for the return in the method, and the return statement has two uses, followed by a return value and without a return value. After the return statement is executed, the program exits execution of the method.

Java Fundamentals-Control flow statements

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.