+ 1

Can anyone tell me why getting unreachable error ?

class A { public static void main(String[] args) { for(int i=0; i<10; i++) { if(i%2 == 0) { continue; System.out.println(i); } } } } C:\Users\acer pc>javac A.java A.java:11: error: unreachable statement System.out.println(i); ^ 1 error

8th Nov 2020, 4:20 PM
Kamal
9 Respostas
+ 1
Kamal your print statement is unreachable in your 1st code because of continue inside if statement. In your 2nd code the print statement is outside the if block because when you do not provide curly braces { }, the if statement can execute only 1 statement. So print is outside.
8th Nov 2020, 4:41 PM
Avinesh
Avinesh - avatar
+ 1
The print statement makes no sence after continue, because that will be never executet. Now your code works as follows. class A { public static void main(String[] args) { for(int i=0; i<10; i++) { if(i%2 == 0) { continue; } System.out.println(i); } } }
8th Nov 2020, 4:49 PM
JaScript
JaScript - avatar
+ 1
Avinesh you explanation is great i get it Vadivelan thank you for understanding the problem JaScript thank you for the worderful code explanation which made it crystal clear thank you all... you all made my doubt completely clear. Thank you â˜ș
8th Nov 2020, 5:03 PM
Kamal
+ 1
Your welcome.
8th Nov 2020, 5:04 PM
JaScript
JaScript - avatar
0
Because continue keyword terminate the current iteration and go to next iteration, even statements exists after continue keyword. So the System.out.println(i) is unreachable.
8th Nov 2020, 4:25 PM
Vadivelan
0
Vadivelan class A { public static void main(String[] args) { for(int i=0; i<10; i++) { if(i%2 == 0) continue; System.out.println(i); } } } Still it will not work ???
8th Nov 2020, 4:30 PM
Kamal
0
Kamal your second code successfully running for me. It give to me this output👇: 1 3 5 7 9
8th Nov 2020, 4:34 PM
Vadivelan
0
Vadivelan that's my question why it's happening ??? My 1st code give error and second working fine but why ?
8th Nov 2020, 4:36 PM
Kamal
0
In first code if(i%2==0){ continue System.out.println(i) } Here if the condition is True, go to inside, then the continue keyword terminate the current iteration as I already said, In second code If we not put the curly brackets, it take the first line only is statement of condition.
8th Nov 2020, 4:42 PM
Vadivelan