search
HomeJavajavaTutorialWhat are the three basic control statements in Java?

The three basic control statements of Java are: sequence structure, selection structure, and loop structure. The following article will take you through it, I hope it will be helpful to you.

What are the three basic control statements in Java?

Sequential structure

Sequential structure is the simplest and most basic process control of the program. As long as it is solved according to Write the corresponding statements in the order of the questions, and then execute them in the order of the codes; most of the codes in the program are executed in this way.

The execution order is top to bottom and executed in sequence.

package Test3;

public class OrderDemo {
    public static void main(String[] args) {
        System.out.println(1);
        System.out.println(2);
        System.out.println(3);
    }
}

Sequential output: 1 2 3

Selection structure

The selection structure is used to judge the given conditions, according to The result of the judgment determines certain conditions, and the flow of the program is controlled based on the result of the judgment. When using a selection structure statement, use conditional expressions to describe the conditions.

Java has two kinds of conditional statements:

● if statement

● switch statement

if statement

An if statement contains a Boolean expression and one or more statements. If the value of the Boolean expression is true, the code block in the if statement is executed, otherwise the code following the if statement block is executed.

Grammar

if (布尔表达式) {        
  // 如果布尔表达式为true将执行的语句
}

The if statement can be followed by an else statement. When the Boolean expression value of the if statement is false, the else statement block will be executed. Syntax:

if(布尔表达式){
   //如果布尔表达式的值为true
}else{
   //如果布尔表达式的值为false
}

Example:

public class Test {
 
   public static void main(String args[]){      int x = 30; 
      if( x < 20 ){
         System.out.print("这是 if 语句");
      }else{
         System.out.print("这是 else 语句");
      }
   }
}

Output:

这是 else 语句

switch statement

switch statement judgment Whether a variable is equal to a value in a series of values, each value is called a branch.

Grammar

switch(expression){
    case value :
       //语句
       break; //可选
    case value :
       //语句
       break; //可选
    //你可以有任意数量的case语句
    default : //可选
       //语句
}

The switch statement has the following rules:

●The variable type in the switch statement can be: byte, short, int or char. Starting from Java SE 7, switch supports string type, and case labels must be string constants or literals.

● The switch statement can have multiple case statements. Each case is followed by a value to be compared and a colon.

● The data type of the value in the case statement must be the same as the data type of the variable, and it can only be a constant or literal constant.

●When the value of the variable is equal to the value of the case statement, then the statements after the case statement begin to execute, and the switch statement will not be jumped out until the break statement appears.

●When encountering a break statement, the switch statement terminates. The program jumps to the statement following the switch statement for execution. The case statement does not need to contain a break statement. If no break statement occurs, the program continues execution of the next case statement until a break statement occurs.

● The switch statement can contain a default branch, which must be the last branch of the switch statement. default is executed when no case statement is equal to the variable value. The default branch does not require a break statement.

Example:

public class Test {
   public static void main(String args[]){      //char grade = args[0].charAt(0);
      char grade = &#39;C&#39;; 
      switch(grade)
      {         case &#39;A&#39; :
            System.out.println("优秀"); 
            break;         case &#39;B&#39; :         case &#39;C&#39; :
            System.out.println("良好");            break;         case &#39;D&#39; :
            System.out.println("及格");         case &#39;F&#39; :
            System.out.println("你需要再努力努力");            break;         default :
            System.out.println("未知等级");
      }
      System.out.println("你的等级是 " + grade);
   }
}

Output:

良好
你的等级是 C

Loop structure

Program statements of sequential structure only Can be executed once. If you want to perform the same operation multiple times, you need to use a loop structure.

The loop structure can reduce the workload of repeated writing of the source program and is used to describe the problem of repeatedly executing a certain algorithm. This is the program structure that best utilizes the computer's expertise in programming. The loop structure can be seen as a combination of a conditional statement and a turnaround statement.

Programming languages ​​generally have three main loop structures:

●while loop

●do...while loop

● for loop

while loop

while is the most basic loop, its structure is:

while( 布尔表达式 ) {
    // 循环内容
}

As long as the Boolean expression is true, The loop will continue to execute.

Example:

int x = 10;while( x < 15 ) {
     System.out.println("value of x : " + x );
      x++;
}

Output:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14

do...while loop

For while statement , if the conditions are not met, the loop cannot be performed. But sometimes we need to execute it at least once even if the conditions are not met. The do...while loop is similar to the while loop, except that the do...while loop is executed at least once.

do {
        //代码语句
}while(布尔表达式);

Note: The Boolean expression is after the loop body, so the statement block has been executed before monitoring the Boolean expression. If the Boolean expression evaluates to true, the statement block is executed until the Boolean expression evaluates to false.

Example:

int x = 10; 
do{
   System.out.println("value of x : " + x );
   x++;
}while( x < 15 );

Output:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14

for loop

for The number of times the loop is executed is before execution That's for sure. The syntax format is as follows:

for(初始化; 布尔表达式 ; 更新) {
        // 代码语句
}

Regarding the for loop, there are the following instructions:

● Perform the initialization step first. A type can be declared, but one or more loop control variables can be initialized, or it can be an empty statement.

● Then, check the value of the Boolean expression. If it is true, the loop body is executed; if it is false, the loop terminates and the statements following the loop body begin to be executed.

●After executing a loop, update the loop control variables.

● Monitor the Boolean expression again. Perform the above process in a loop.

Example:

for(int x = 10; x < 15; x = x+1) {
   System.out.println("value of x : " + x );
}

Output:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14

The above is the detailed content of What are the three basic control statements in Java?. For more information, please follow other related articles on the PHP Chinese website!

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
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

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 Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software