+ 1
Can anyone tell me how to use break, return, continue statement in java.
2 Antworten
+ 5
Break and continue are used inside loops and return is used in methods.
When your loop gets to a break statment it stops itself. The loop just won't continue to run and the code after the loop will be excecuted.
for example, this loop will print the numbers from 0 to 3:
for(int i = 0; i<10; i++){
if(i == 4)
break;
System.out.println(i);
}
When a loop gets to a continue statment it will skip to the next loop time.
For example, this code will print every number between 0 and 10 except 3.
for(int i = 0; i<=10; i++){
if(i == 3)
continue;
System.out.println(i);
}
The return keyword is used on method that their "return type" is not void.
If method's return type is void, it means that it doesn't have any value, it just doing something, like printing. When the return type is not void the method should return a value from that type. The return keyword declars the value that the method returns.
For example:
public static int sum(int x, int y){
return x+y;
}
public static void main(....){
int z = sum(2, 3);
}
+ 1
Break is used to BREAK out of a loop for switch case. Return is like printing. It returns the variable/method data.