| Author |
Assertions
|
Saumya Tangeda
Greenhorn
Joined: Jul 09, 2006
Posts: 24
|
|
In the code below, what happens when assertions are disabled?The answer given is that it prints ABCE. My question is if it prints E then why doesn't it go through next iterations of the for loop and print more letters?please explain. class C { String m1(int i) { switch (i) { case 0: return "A"; case 1: return "B"; case 2: return "C"; default: assert false; } return "E"; } public static void main(String[] args) { C c = new C(); for (int i = 0; i < 4; i++) { System.out.print(c.m1(i)); }}}
|
 |
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2341
|
|
The only reason it will only return E when none of the cases match. This happens when i is 3 in this case. [ July 18, 2006: Message edited by: Keith Lynn ]
|
 |
Buhi Mume
Greenhorn
Joined: Jul 16, 2006
Posts: 17
|
|
|
The for loop runs from 0-3. Thus, you will only get 4 characters.
|
 |
d jones
Ranch Hand
Joined: Mar 13, 2006
Posts: 76
|
|
When 3 is passed into the switch statement should it not go into the default case and throw an assertion error and cause the program to fail? I can see that it is actually going into the default case but why isn't throwing an assertion error and causing the program to fail? Thanks
|
 |
Aum Tao
Ranch Hand
Joined: Feb 14, 2006
Posts: 210
|
|
In the code below, what happens when assertions are disabled?The answer given is that it prints ABCE.
We are discussing the case when assertions are disabled. If assertions are enabled, then the default case will be entered and an assertion error will be thrown.
|
SCJP 1.4 85%
|
 |
Roger van't Hul
Greenhorn
Joined: Jul 19, 2006
Posts: 4
|
|
Hi Saumya, You asked why the code doesn't go through the next iterations of the for loop. It actually goes through all the iterations. Each time the for loop calls c.m1, only the String which belongs to the case-statement with the corresponding value of i is returned. Return means that the code immediately goes back to the calling method. So, when i =0 (in the for loop), only the value of case 0 is returned and printed. The same goes for 1 and 2. Because i = 3 is matched to the default case, and assert is off (which means that that part of the code is ignored), the method m1 is allowed to finish and therefore returns "E". The following code "proves" that all four iterations run: class C { String m1(int i) { switch (i) { case 0: return "A"; case 1: return "B"; case 2: return "C"; default: assert false; } return "E"; } public static void main(String[] args) { C c = new C(); for (int i = 0; i < 4; i++) { System.out.println(c.m1(i)); System.out.println("Iteration number: " + (i + 1) ); } } } I hope this clarifies your question. Regards, Roger
|
 |
 |
|
|
subject: Assertions
|
|
|