File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

infinite loop

 
Rajani Sudhakar
Ranch Hand
Posts: 60
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 24
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 60
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi..

Thankyou Guys for your answers..

regards,
rajani.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic