• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why is it printing...

 
Shubh Bhat
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Welcome to Java" once. How come a byte if incremented becomes -128.
I am really not good at bits can you please show me the conversion? And could you please provide me some links to mock exams which deal with more on bits, ingeneral.

[
public class ByteI
{
public static void main (String [] args ) {
byte b = 1 ;
) ;
while ( ++b > 0 ) ;
System . out . println ( " Welcome to Java") ;
}
}
]
 
Soum Sark
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
that is because b gets incremented till it goes above 127 and since b++ is equivalent to b = (byte)b + 1 ; only the last 8 digits(bits) are taken so it becomes 1111 1111 which is a -ve no and so it prints 'welcome...' once.also not that there is a ";" after while so it does not have any body..it merely keeps incrementing and breaks off the loop when the condition isn't true and goes to the next line..in effect the print statement is not within the while loop
 
Shubh Bhat
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh my goodness, I didn't see that ; at all. Thanks for the reply.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic