
Just a simple trick question to see if guys are on their toes [?] public class Test { public static void main(String[] args) { int n = 0; for (int m = 0; m < 5; m++) { n = n++; System.out.println(n); } } } Output: 0 0 0 0 0 Why? Who will be first to answer correctly? -- Regards Brian Ngure

Easy. It's because you assign n to itself before you increment it. The expected way would be simply n++; instead of n = n++; To give you the output of 1 2 3 4 5

Right. Quite simple. But I saw this question on a forum and the guy just could not get it. Makes you wonder.... On Thu, May 26, 2011 at 9:08 PM, Haggai Nyang <haggai.nyang@gmail.com>wrote:
Easy. It's because you assign n to itself before you increment it. The expected way would be simply
n++;
instead of
n = n++;
To give you the output of
1 2 3 4 5
_______________________________________________ Skunkworks mailing list Skunkworks@lists.my.co.ke http://lists.my.co.ke/cgi-bin/mailman/listinfo/skunkworks ------------ Skunkworks Rules http://my.co.ke/phpbb/viewtopic.php?f=24&t=94 ------------ Other services @ http://my.co.ke
-- Regards Brian Ngure

However, that's noob coding, I'd refactor that to something like: int n = 0; while(n <= 5) { System.out.println(++n); }

Yes. No reason to use two variables. Also, not know that n++ is a post increment is a bit green. On Thu, May 26, 2011 at 9:18 PM, Haggai Nyang <haggai.nyang@gmail.com>wrote:
However, that's noob coding, I'd refactor that to something like:
int n = 0; while(n <= 5) { System.out.println(++n); }
_______________________________________________ Skunkworks mailing list Skunkworks@lists.my.co.ke http://lists.my.co.ke/cgi-bin/mailman/listinfo/skunkworks ------------ Skunkworks Rules http://my.co.ke/phpbb/viewtopic.php?f=24&t=94 ------------ Other services @ http://my.co.ke
-- Regards Brian Ngure
participants (2)
-
Brian Ngure
-
Haggai Nyang