search
HomeJavajavaTutorial[Java Introduction Notes] Java Language Basics (4): Process Control

Process control refers to the way to control the direction of the program while it is running. It is mainly divided into the following categories:

Sequential structure

Sequential structure, as the name suggests, means that the program is executed sequentially from top to bottom. There is no judgment or jump in the middle.

Branch structure

Java provides two branch structures: if and switch. The if statement uses Boolean expressions or Boolean values ​​to judge the branch control, while the switch statement uses integers, String types, and enumeration types. .

if statement

if statement uses Boolean expressions or Boolean values ​​to judge and control branches. There are mainly three structures:

if statement

if (condition) {

//Statement

}

Execution trend

[Java Introduction Notes] Java Language Basics (4): Process Control

Example:

int score = 65;if(score >= 60){
System.out.PRintln("You passed");
}

if…else statement

if (condition) {
                                                                                                                                                       Example:

int score = 65 ;if(score >= 60){
System.out.println("You passed, congratulations");

} else {

System.out.println("Failed, cleaning toilets for three months");

}

[Java Introduction Notes] Java Language Basics (4): Process Control

if…else if statement

if (condition) {

//statement } else if (condition) {
//statement } else {
//statement
}

Program flow chart



Example:

Evaluation of students’ final exam scores

Score>=90: Excellent

Score>=80: Good

[Java Introduction Notes] Java Language Basics (4): Process Control Score>=60: Moderate

Score

int score = 70; //Examination score if ( score >= 90 ) {

System.out.println("Excellent");

} else if (score >= 80 ) {

System.out. println("Good");

} else if (score >= 60 ) {

 System.out.println("Medium");

} else {

 System.out.println("Poor");

}


contains another if statement in the if statement

If (condition 1) { if (condition 2) { if (condition 3) {

}else{
}
}………
}

Normally, the statement blocks of these types of judgment statements are wrapped in {} brackets, but if the statement has only one sentence, you don’t need to use curly braces, for example

boolean b = true;if( b)
System.out.println("You can not use curly braces"); else
System.out.println("It is recommended to put curly braces");

If there is only one statement in the judgment statement, it can be omitted. Curly braces are used, but it is recommended that you still use curly braces.

switch statement

switch (expression) //Calculate the value of the expression{  case constant 1: //If equal to constant 1 Statement; break;  case constant 2: //If equal to constant 2 Statement; break; Default: //If no matching value is found Statement

Break; }


Different from the if statement, the expression of the switch statement can pass values ​​of byte, short, int, long, and String types.

String s = "Passed";switch(s){

 case "Passed":

 System.out.println("Performing well");

 break;
case "Failed":

 System.out. println("Clean the toilet");

  break;

 default:

  System.out.println("Didn't come for the exam? Call your parents");

  break;

}



int i = 1;switch(i){
 case 1:
  System.out.println("Won the first place");
  break;
 case 2:
  System.out.println("Won the second place" );
  break; case 3:
 System.out.println("Get third place");
 break;
 default:
 System.out.println("You are not the top three");
  break;
}

Pay attention to the break statement when using it. If you miss it, hey!

Comparison of switch and multiple if

Same points:

 Both can implement multi-branch structures

Differences:

 Switch: can only handle conditional judgments of equal values, and the conditions are equal to integer variables or character variables Value judgment

Multiple if: The processing also includes other if structures in the else part, which is especially suitable for situations when a certain variable is in a certain range

Loop structure

Loop statements are also called iteration statements. Loop statements can satisfy Under the condition of conditions, repeatedly execute a certain code. The cycle statement includes:

while cycle

while (cycle condition) {// meet the conditions and continue to execute the cycle; Operation}

Features: Judge first, then execute

[Java Introduction Notes] Java Language Basics (4): Process Control

Example sentence: Print out 30 Hello

int i = 1;while(i System.out.println ("Hello");
i++;
}

do-while loop

do {

Loop operation //Perform the loop operation first} while (loop condition); //If the conditions are met, the loop continues to execute; otherwise, Loop exit

Features: Execute first, then judge

[Java Introduction Notes] Java Language Basics (4): Process Control

//Whether he has passed or not, clean the toilet first, and then see whether he has passed or not. int i = 65;do{

System.out.println("Unlucky, need to clean the toilet");
} while(i

Infinite loop problem: all loop control statements, if none of them exit condition, it will enter an infinite loop state. In the above example, if i is less than 60, it will always be "cleaning the toilet" and cannot continue to execute.

for loop

for (parameter initialization; conditional judgment; update loop variable) {

loop operation;
}

Features: initialize parameters first, judge the condition, if it is true, execute the loop body, and then update the loop variable, and then return to the conditional judgment. If it is not established, exit the loop directly.

[Java Introduction Notes] Java Language Basics (4): Process Control

for (int i = 0 ; i  System.out.println("I'm the best");
}

Control loop structure

break statement

in a certain Sometimes, we need to forcefully terminate the loop when a certain condition occurs, and we can use break to complete this function. For example:

[Java Introduction Notes] Java Language Basics (4): Process Control

for(int i = 1; i }
System.out.println("Complete a circle") ;
}

In the above example, 10 laps should have been completed, but when reaching the 8th lap, I couldn’t hold on anymore and broke, and the rest will not be executed.

[Java Introduction Notes] Java Language Basics (4): Process Control


continue statement

The functions of continue and break are somewhat similar. The difference is that continue only skips this loop, and subsequent loops will still be executed. For example:

[Java Introduction Notes] Java Language Basics (4): Process Control


for(int i = 1; i }
System.out.println("Complete one Lap");
}

He was supposed to run 10 laps, but he actually only ran 9 laps.

[Java Introduction Notes] Java Language Basics (4): Process Control


The above is the content of [Java Getting Started Notes] Java Language Basics (4): Process Control. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!



Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.