• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

infinite loop

 
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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..
 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi..

Thankyou Guys for your answers..

regards,
rajani.
 
Paper beats rock. Scissors beats tiny ad.
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic