your programing

Return과 Break 문의 차이점

lovepro 2020. 12. 26. 16:14
반응형

Return과 Break 문의 차이점


return진술은 진술과 어떻게 다릅니 break까?.
내가 조건 경우 종료해야하는 경우 하나의 내가 선호해야하는 returnbreak?


break루프를 종료하고 싶을 때 return사용되며 , 호출 된 단계로 돌아가거나 추가 실행을 중지하는 데 사용됩니다.


break현재 실행중인 for-loop, while-loop,- switch을 종료 (이스케이프)하는 데 사용됩니다 .

return 현재 실행중인 전체 메서드를 종료합니다 (선택 사항으로 호출자에게 값을 반환 할 수도 있음).

(다른 사람의 의견과 답변에서 언급 한 것처럼) 그래서 당신이 중 하나를 사용할 수 없습니다 귀하의 질문에 대답 breakreturn탈출 할 if-else-statement 자체를. 다른 범위를 이스케이프하는 데 사용됩니다.


다음 예를 고려하십시오. x내부 while루프 의 값은 루프 아래의 코드가 실행되는지 여부를 결정합니다.

void f()
{
   int x = -1;
   while(true)
   {
     if(x == 0)
        break;         // escape while() and jump to execute code after the the loop 
     else if(x == 1)
        return;        // will end the function f() immediately,
                       // no further code inside this method will be executed.

     do stuff and eventually set variable x to either 0 or 1
     ...
   }

   code that will be executed on break (but not with return).
   ....
}

또는을 if사용 하는 조건 에서만 종료 할 수 없습니다 .returnbreak

return실행이 완료된 후 메서드에서 반환해야 할 때 / 나머지 메서드 코드를 실행하고 싶지 않을 때 사용됩니다. 따라서를 사용 return하면 if조건에서뿐만 아니라 전체 방법에서도 반환됩니다 .

다음 방법을 고려하십시오-

public void myMethod()
{
    int i = 10;

    if(i==10)
        return;

    System.out.println("This will never be printed");
}

여기에서 사용 return하면 3 행 후 전체 메소드 실행이 중지되고 실행이 호출자에게 돌아갑니다.

breakloop또는 switch에서 분리하는 데 사용됩니다 . 이 예를 고려하십시오-

int i;

for(int j=0; j<10; j++)
{
    for(i=0; i<10; i++)
    {
        if(i==0)
            break;        // This break will cause the loop (innermost) to stop just after one iteration;
    }

    if(j==0)
        break;    // and then this break will cause the outermost loop to stop.
}

switch(i)
{
    case 0: break;    // This break will cause execution to skip executing the second case statement

    case 1: System.out.println("This will also never be printed");
}

이러한 유형의 break문이라고 unlabeled break합니다. 라는 또 다른 형태의 휴식이 labeled break있습니다. 이 예를 고려하십시오-

int[][] arrayOfInts = { { 32, 87, 3, 589 },
                            { 12, 1076, 2000, 8 },
                            { 622, 127, 77, 955 }
                          };
int searchfor = 12;

int i;
int j = 0;
boolean foundIt = false;

search:
    for (i = 0; i < arrayOfInts.length; i++)
    {
        for (j = 0; j < arrayOfInts[i].length; j++)
        {
            if (arrayOfInts[i][j] == searchfor)
            {
                foundIt = true;
                break search;
            }
        }
    }

이 예제에서는 중첩 된 for 루프를 사용하여 2 차원 배열의 값을 검색합니다. 값이 발견되면 레이블이 지정된 브레이크가 외부 for 루프를 종료합니다 ( "검색"레이블이 지정됨).

에서 더 많은 abour breakreturn진술을 배울 수 있습니다 JavaDoc.


위반은 없지만 (지금까지) 다른 답변 중 어느 것도 옳지 않습니다.

breakfor루프, while루프 또는 switch을 즉시 종료하는 데 사용됩니다 . 블록 break에서는 할 수 없습니다 if.

return 메서드를 종료하는 데 사용됩니다 (그리고 값을 반환 할 수도 있음).

return물론 루프 또는 블록 내의 A 는 해당 루프 / 블록을 즉시 종료합니다.


break :-이 transfer 문은 나머지 반복을 건너 뛰어 현재 루프 외부로 올바른 실행 흐름을 우회합니다.

class test
{
    public static void main(String []args)
    {
        for(int i=0;i<10;i++)
        {
            if(i==5)
            break;
        }
        System.out.println(i);
    }
} 

output will be 
0
1
2
3
4

계속 :-이 transfer 문은 나머지 명령을 모두 건너 뛰어 다음 반복을 계속하기 위해 루프 시작점으로의 실행 흐름을 우회합니다.

class test
{
    public static void main(String []args)
    {
        for(int i=0;i<10;i++)
        {
            if(i==5)
            continue;
        }
        System.out.println(i);
    }
} 

output will be:
0
1
2
3
4
6
7
8
9 

return :-메소드에서 언제든지 return 문을 사용하여 실행이 메소드 호출자에게 다시 분기되도록 할 수 있습니다. 따라서 return 문은 실행 된 메서드를 즉시 종료합니다. 다음 예는이 점을 보여줍니다. 여기서 return은 main ()을 호출하는 런타임 시스템이므로 Java 런타임 시스템으로 실행을 반환합니다.

class test
{
    public static void main(String []args)
    {
        for(int i=0;i<10;i++)
        {
            if(i==5)
            return;
        }
        System.out.println(i)
    }
} 


output will be :
0
1
2
3
4

break현재 루프 return를 끊고 계속하는 동안 현재 메서드를 중단하고 해당 메서드를 호출 한 위치에서 계속됩니다.


Return will exit from the method, as others have already pointed out. If you need to skip just over some part of the method, you can use break, even without a loop:

label: if (some condition) {
    // some stuff...
    if (some other condition) break label;
    // more stuff...

}

Note, that this is usually not good style, though useful sometimes.


Break statement will break the whole loop and execute the code after loop and Return will not execute the code after that return statement and execute the loop with next increment.

Break

for(int i=0;i<5;i++){
    print(i)
    if(i==2)
    {
      break;
    }
}

output: 0 1

return

for(int i=0;i<5;i++)
{
   print(i)
   if(i==2)
   {
    return;
   }
}

output: 0 1 3 4


You use break break out of a loop or a switch statement.

You use return in the function to return a value. Return statement ends the function and returns control to where the function was called.


In this code i is iterated till 3 then the loop ends;

int function (void)
{
    for (int i=0; i<5; i++)
    {
      if (i == 3)
      {
         break;
      }
    }
}

In this code i is iterated till 3 but with an output;

int function (void)
{
    for (int i=0; i<5; i++)
    {
      if (i == 3)
      {
         return i;
      }
    }
}

break just breaks the loop & return gets control back to the caller method.


How does a return statement differ from break statement?. Return statement exits current method execution and returns value to calling method. Break is used to exit from any loop.

If I have to exit an if condition, which one should I prefer, return or break?

To exit from method execution use return. to exit from any loop you can use either break or return based on your requirement.


If you want to exit from a simple if else statement but still stays within a particular context (not by returning to the calling context), you can just set the block condition to false:

if(condition){
//do stuff
   if(something happens)
        condition = false;
}

This will guarantee that there is no further execution, the way I think you want it..You can only use break in a loop or switch case

ReferenceURL : https://stackoverflow.com/questions/6620949/difference-between-return-and-break-statements

반응형