Infinite or infinite not

This is a snippet of code construct in java which gives a simple output :-----

1
2
3
4
5
byte k=1;
for(  ; k>0 ; k++){

 }
System.out.println(k);

The answer to the question is the value printed i.e. the final value of 'k'. Note : Its a good question so please do not spoil its fun by using a computer to solve it.Have fun...


The answer is -128.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Kartikay Shandil
Jun 27, 2014

When the loop value increases then it continues till the value of k reaches maximum a byte can contain i.e. k=127. That all bits are one but the sign bit is zero.
Sign bit zero represents "+" i.e. +ve integer. Sign bit one represents "-" i.e. -ve integer. Now when we call the "k++" and as all the bits are "1" except the sign bit the k++ changes it also to one and thus a -ve number i.e. -128 is generated . This acts as the exit condition for the loop and after that "-128" is printed.

good explaination..!! (Y)

Harshvardhan Mehta - 6 years, 11 months ago

could not understand anything. can you explain that from the point of view of a non programmer, please?

Andrea Toffanin - 6 years, 11 months ago

Log in to reply

In a computer the data is stored in form of binary digits i.e. 0 & 1 The different datatypes in java represent different storing capacities of a number here byte ...... Its Capacity is -128 to 127. When max value is reached then all bits are one then when the k++ statement is called then the - , + bit is also increased from 0 to one (0 representing + and 1 -) so we get the -ve number -128 to understand more read binary representation of a number

Kartikay Shandil - 6 years, 11 months ago

Good explanation. However, a signed byte can only store positive values till 127 (-(2^7) to 2^7-1) not 128. Therefore,k=127 is the largest value after which it wraps to -128(which is less than 0)

PradyGame Dev - 6 years, 8 months ago

Log in to reply

Thanks I have done the needful

Kartikay Shandil - 6 years, 8 months ago

thought that it would be 127

Aishwary Omkar - 6 years, 7 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...