[Interview Questions] What is the difference between continuebreak and return?

Sometimes the blog content will change. The first blog is the latest, and other blog addresses may not be synchronized. Check it carefully.https://blog.zysicyj.top

First blog address [1]

Interview question manual [2]

Series article address [3]


continue, break and return are control flow statements commonly used in programming, and they have different functions and usage scenarios.

  1. continue : When the program executes the continue statement, it will skip the remaining code in the current loop and start the next loop. Usually used to skip the current iteration and go directly to the next iteration when certain conditions are encountered in the loop.

    • For example, in a for loop, if you need to skip certain values, you can use the continue statement:
      for (int i = 0; i < 10; i++) {
                
                
          if (i == 5) {
              continue;
          }
          System.out.println(i);
      }
      The output result is: 0 1 2 3 4 6 7 8 9
  2. break : When the program executes the break statement, it will immediately terminate the current loop or switch statement and jump out of the code block outside the structure. It is usually used to end the loop early or jump out of the switch statement when a certain condition is met.

    • For example, in a while loop, you can use the break statement to terminate the loop when a certain condition is met:
      int i = 0;
      while (true) {
          if (i == 5) {
              break;
          }
          System.out.println(i);
          i++;
      }
      The output result is: 0 1 2 3 4
  3. return : Used to end the execution of the current method and return a value (if a return type is defined). When the program executes the return statement, it will exit the current method immediately and return the specified value to the caller. It is usually used to end the execution of a method early and return the result when a certain condition is met.

    • For example, in a method, return different results according to different situations:
      public int calculate(int a, int b) {
                
                
          if (b == 0) {
              return -1// 返回错误码表示除数为0
          }
          return a / b;
      }
      在上述代码中,如果除数为 0,则使用 return 语句返回-1 作为错误码;否则,计算 a 除以 b 的结果并返回。

总结:

  • continue用于跳过当前迭代,进入下一次迭代;
  • break用于终止循环或者 switch 语句,并跳出该结构体外部的代码块;
  • return用于结束当前方法的执行,并返回一个值给调用者。

需要注意的是,这三个关键字的使用要根据具体的场景和需求来选择合适的控制流语句。

参考资料

[1]

首发博客地址: https://blog.zysicyj.top/

[2]

面试题手册: https://store.amazingmemo.com/chapterDetail/1685324709017001

[3]

系列文章地址: https://blog.zysicyj.top/categories/技术文章/后端技术/系列文章/面试题精讲/

本文由 mdnice 多平台发布

Guess you like

Origin blog.csdn.net/njpkhuan/article/details/133365110