Java while return value

Java 8 операторы управления порядком выполнения

Инструкции (операторы) в программе выполняются сверху вниз по исходному файлы. Операторы управления порядком выполнения позволяют прервать обычный ход выполнения, позволив выполнить один кусок кода несколько раз, выполнить кусок кода только при выполнении определённого условия.

Оператор if-then и if-then-else

Оператор if — then / if — then — else позволяет выполнить один оператор или блок операторов только при выполнении определённого условия. Он имеет две формы. Форма if — then позволяет выполнить кусок кода при выполнении определённого условия, а форма if — then — else в дополнение к этому позволяет ещё указать кусок кода, который будет выполняться при НЕвыполнении этого условия.

Синтаксис if — then для куска кода из одного оператора:

Синтаксис if — then для блока операторов:

Оператор if — then выполняется так:

  1. Вычисляется результат выражения , которое должно обязательно вернуть тип boolean .
  2. Если выражение вернуло true , то выполняется для случая с одним оператором и , , … для случая блока операторов.

Согласно официальному соглашения о кодировании рекомендуется всегда использовать блок операторов, даже если оператор только один. Пример:

  1. Если вернуло true , то выполняется оператор или блок операторов внутри фигурных скобок, как и для if — then .
  2. Если вернуло false , то выполняется оператор или блок операторов в else .

Согласно соглашению о кодировании нужно всегда использовать вариант с блоком операторов (инструкций), даже если оператор только один, не смотря на то что компилятор позволяет в любом из кусков кода then и else использовать вариант с одним оператором и с блоком.

Можно в блоке else проверить другое условие, тогда получится конструкция вида:

Обратите внимание, что может быть абсолютно любым выражением, возвращающим boolean , можно использовать даже операцию присвоения переменной логического типа, так как операция присвоения тоже возвращает значение:

Однако согласно соглашению о кодировании в Java использовать подобную возможность не стоит.

Оператор switch

Рассмотрим следующий кусок кода:

В куске кода, приведённом выше, проверяется значение переменной mode . Для значений 0, 1 и 2 предусмотрены отдельные блоки кода, и ещё один блок кода предусмотрен для всех остальных значений. Оператор switch делает то же самое, но делает код более наглядным:

Этот кусок кода с оператором switch делает абсолютно то же самое, что и кусок кода с if , рассмотренный до этого, но рекомендуется использовать вариант со switch , так как он более нагляден.

Оператор switch работает в следующем порядке:

  1. Вычисляется выражение в скобках (в данном примере оно состоит просто из переменной mode )
  2. Полученное значение проверяется подряд со значениями в case , и выполняется тот блок операторов, который относится к case со значением, совпадающим со значением выражения.
  3. Если ни одно из значений не совпало, то выполняется блок default .
  4. По ключевому слову break выполнение блока внутри case или default завершается и управление передаётся на следующую инструкцию за блоком switch .
Читайте также:  Php mail sender id

С помощью if — then и if — then — else можно проверять любые условия, но с помощью switch можно проверять только значения выражений типа byte , short , char , int , перечисления (будет описано позднее), String (начиная с Java SE 7), а также классы java . lang . Byte , java . lang . Short , java . langCharacter , java . lang . Integer . Проверяемые значения в case обязательно должны быть константными литералами. Если значение выражения в switch равно null , то возникает java . lang . NullPointerException . Нагляднее всего switch выглядит именно с перечислениями.

Ключевое слово break не обязательно. В случае его отсутствия по завершении выполнения блока операторов внутри одного case выполняются операторы следующего за ним case . Это позволяет использовать один блок операторов для нескольких значений case :

Источник

Exit a While Loop in Java

Exit a While Loop in Java

  1. Exit a while Loop After Completing the Program Execution in Java
  2. Exit a while Loop by Using break in Java
  3. Exit a while Loop by Using return in Java

This tutorial introduces how you can exit a while-loop in Java and handle it with some example codes to help you understand the topic further.

The while-loop is one of the Java loops used to iterate or repeat the statements until they meet the specified condition. To exit the while-loop, you can do the following methods:

  • Exit after completing the loop normally
  • Exit by using the break statement
  • Exit by using the return statement

Exit a while Loop After Completing the Program Execution in Java

This method is a simple example where a while-loop exits itself after the specified condition marks as false .

The while-loop repeatedly executes until the specified condition is true and exits if the condition is false . See the example below where we are iterate list elements using the while-loop and have the loop exit when all the elements get traversed.

import java.util.Arrays; import java.util.List; public class SimpleTesting  public static void main(String[] args)   ListInteger> list = Arrays.asList(new Integer[]12,34,21,33,22,55>);  int i = 0;  while(ilist.size())   System.out.println(list.get(i));  i++;  >  > > 

Exit a while Loop by Using break in Java

This way is another solution where we used a break-statement to exit the loop. The break-statement is used to cut the current execution thread, and control goes outside the loop that leads the loop to exit in between. You can use break to exit the while-loop explicitly. See the example below:

import java.util.Arrays; import java.util.List; public class SimpleTesting  public static void main(String[] args)   ListInteger> list = Arrays.asList(new Integer[]12,34,21,33,22,55>);  int i = 0;  while(ilist.size())   if(i == 3)  break;  System.out.println(list.get(i));  i++;  >  > > 

Exit a while Loop by Using return in Java

Java uses a return-statement to return a response to the caller method, and control immediately transfers to the caller by exiting a loop(if it exists). So we can use return to exit the while-loop too. Check the code below to see how we used return .

import java.util.Arrays; import java.util.List;  public class SimpleTesting  public static void main(String[] args)   boolean result = show();  if(result)   System.out.println("Loop Exit explicitly");  >else System.out.println("Loop not exit explicitly");  >  static boolean show()   ListInteger> list = Arrays.asList(new Integer[]12,34,21,33,22,55>);  int i = 0;  while(ilist.size())   if(i == 3)  return true;  System.out.println(list.get(i));  i++;  >  return false;  > > 
12 34 21 Loop Exit explicitly 

Related Article — Java Loop

Источник

Java continue and return keyword

Sometime you may require that for a particular repetition of a loop, you don’t want to execute few or all instructions of loop body. To solve such requirements java provides continue keyword which allows programmers to skip the current iteration of a loop and move to the next iteration, which means if you want to skip the execution of code inside a loop for a particular iteration, you can use continue statement. Only the code written after the continue statement will be skipped, code before the continue statement will execute as usual for that iteration.

continue statement can be used only inside for , while and do while loops of java. In case of break statement the control flow exits from the loop, but in case of continue statement, the control flow will not be exited, only the current iteration of loop will be skipped. It is mostly used along with conditional statements( if , else ). The syntax of continue statement is:

Control flow diagram of continue statement

java continue statement

Once continue statement is executed inside for loop, the control flow moves back to for loop to evaluate increment/decrement expression and then condition expression. If continue statement is executed inside while and do while loop, the control flow jumps to condition expression for evaluation.

Java Program of continue Statement

 class ContinueStatement < public static void main(String [] args) < for(int i=1; iif(i==4) < continue; > System.out.println("i string">"line after for loop"); > >

i = 1
i = 2
i = 3
i = 5
line after for loop

As you can see in above program, for i==4 the continue statement is executed which skips the current iteration and move to the next iteration, that is why value i = 4 is not printed.

If continue statement is used inside any inner loop, it skips current iteration of inner loop only, the outer loop will be executed as usual.

 class InnerLoppContinueStatement < public static void main(String [] args) < for(int i=1; i"Outer loop i keyword">for(int j=1; jif(i==2) < continue; > System.out.println(" j string">"line after outer for loop"); > >

Outer loop i = 1
j = 1
j = 2
Outer loop i = 2
Outer loop i = 3
j = 1
j = 2
line after outer for loop

Can I use break and continue statement together in a loop ?

Yes you can definitely use both statements in a loop.

Labeled continue Statement

A Labeled continue statement allows programmer to skip the current iteration of that label.

Java Program of labeled continue statement

 class LabeledContinueStatement < public static void main(String [] args) < firstLable: for(int i=1;i<=3;i++) < System.out.println("Outer loop i keyword">for(int j=1;j<=3;j++) < if(i==2) < continue firstLable; > System.out.println(" j string">"line after end of firstLable "); > >

Outer loop i = 1
j = 1
j = 2
j = 3
Outer loop i = 2
Outer loop i = 3
j = 1
j = 2
j = 3
line after end of firstLable

In above program as soon as the value of i becomes 2, the continue firstLable; statement is executed which moves the execution flow to outer loop for next iteration, that is why inner loop doesn’t print anything for i=2 .

Java return Statement

As the return keyword itself suggest that it is used to return something. Java return statement is used to return some value from a method. Once a return statement is executed, the control flow exited from current method and returns to the calling method. The syntax of return statement is:

Who get’s the value that is returned by method ?

The caller of the method. This value can be assigned in some variable.

The return statement given above has two forms:

  • First that returns a value. To return a value, just place the value or expression after return keyword. for eg. return 10 , return a+b , return «refresh java» etc. The data type of the returned value must match the return type of it’s method declaration.
  • Second that doesn’t returns a value. To use, just place return keyword. When the return type of method is declared as void , you can use this form of return as it doesn’t return a value, or you can also leave out to use return keyword for such methods.

Java Program of return statement

 class ReturnStatement < public static void main(String [] args) < int sum = sum(10,20); System.out.println("Sum keyword">public static int sum(int a, int b) < return a+b; > >

In above program, a and b are integers, so a+b will also be an integer which is equivalent to return type of method sum which is also an int .

  • continue statement cannot be used outside of a loop, if used it will result in compile time error.
  • Use continue statement more precisely inside while and do while block, if not used precisely, it may result as infinite loop
  • Ensure all letter of continue keyword is small, can not use Continue, contiNue, CONTINUE etc.
  • Ensure all letter of return keyword is small, can not use Return, RETURN etc.
  • return keyword can be used anywhere inside method, but not outside method.

Источник

Оцените статью