File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes infinite loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "infinite loop" Watch "infinite loop" New topic

infinite loop

Rajani Sudhakar
Ranch Hand

Joined: Apr 28, 2004
Posts: 60
What will happen when you invoke the following method?

void infiniteLoop ( ) {
byte b = 1 ;
while ( ++b > 0 ) ;
System . out . println ( " Welcome to Java " ) ;

Options :

a . The loop never ends ( infinite loop ) .
b . Prints " Welcome to Java " to the console
c . Compilation error at line 5. ++ operator should not be used for byte type variables.
d . Prints nothing but terminates after some time

Answer : b

Can anyone explain me the reason...
I guess while(++b>0); is an infinite loop.

thanks in advance..
Ab Sharma

Joined: May 23, 2004
Posts: 5
No Rajani,

b is a byte... so has 7 bits ie can attain calues from +127 to -128. So the loop wraps around after 128 and gets the cvalue -127 and terminates.

Hope that clarifies..
Geoffrey Vlassaks

Joined: May 12, 2004
Posts: 24

In fact, a byte has 8 bits where the first bit is the sign. It's true that it can contain the range from -128 till 127. In the code, the byte b will increment until 127. The next increment will result in a value of -128, so that it leaves the while loop..

Rajani Sudhakar
Ranch Hand

Joined: Apr 28, 2004
Posts: 60

Thankyou Guys for your answers..

I agree. Here's the link:
subject: infinite loop
It's not a secret anymore!