The use of break in Java, like in C, is used to end the loop, however, what surprised me is the use of return-the end of the current Method!!! Seeing is believing, let's take a look at the code:
int i; for (i = 0;i < 8 ;i ++ ) { if(i == 7) break; else System.out.println(i); } System.out.println("ending******");
The results are as follows:
for (i = 0;i < 8 ;i ++ ) { if(i == 7) return; else System.out.println(i); } System.out.println("ending******");
The results are as follows:
Compare to discover:
There is no output ending***** when using return, why is this?
Break is the end of the current loop, so the current loop finishes and outputs ending***** before terminating the loop. The function of return is to terminate the current method (this is the main method), so the method terminates immediately after the return execution, so the program that outputs ending****** in the current method will no longer execute.
Java Learning Journey-8