*
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


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "infinite loop" Watch "infinite loop" New topic
Author

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..
rajani.
Ab Sharma
Greenhorn

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
Greenhorn

Joined: May 12, 2004
Posts: 24
Ab,

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..

Greetz
Rajani Sudhakar
Ranch Hand

Joined: Apr 28, 2004
Posts: 60
Hi..

Thankyou Guys for your answers..

regards,
rajani.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: infinite loop
 
Similar Threads
oddness while question.
byte
about primitive
Doubt with ++ operator
Infinite Loop