Can pls. someone explain me this? What will happen when you invoke the following method? 1: void infiniteLoop() 2: { 3: byte b = 1; 4: 5: while ( ++b > 0 ) 6: ; 7: System.out.println("Welcome to Java"); 8: }
A) The loop never ends(infiniteLoop). B) Prints "Welcome to Java". C) Compilation error at line 5. ++ operator should not be used for byte type variables. D) Prints nothing.
Originally posted by VR: Can pls. someone explain me this? What will happen when you invoke the following method? 1: void infiniteLoop() 2: { 3: byte b = 1; 4: 5: while ( ++b > 0 ) 6: ; 7: System.out.println("Welcome to Java"); 8: }
A) The loop never ends(infiniteLoop). B) Prints "Welcome to Java". C) Compilation error at line 5. ++ operator should not be used for byte type variables. D) Prints nothing.
Correct Answer:B Thank you VR
Byte ranges from -128 to 127.When the while loop is executed upto b= 127 and in the next iteration it becomes negative(-128) and hence comes out of the while loop and prints the "Welcome to Java".Hope this clears your doubt.
i think b would be promoted 2 int for comparison ... then also it shold throw an exception when a num greater then -2^31 is supplied 2 it ... it cant print the option c
Well, if you put this statement System.out.println("b = " + b); after while ( ++b > 0 ), it prints from b = 2 to b = 127 and then it prints Welcome to Java. It corroborates Jaypii's explanation, though it wasn't expected by me. Thanks...