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
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function