Integer.MAX_VALUE, Double.POSITIVE_INFINITY and Double.NaN in Java

I have three questions for you in form of loop, you have to write a simple declaration by which the loop will never terminate and will run infinitely.

I have given the hint in the title itself.

 

for(int i=start;i<=start+1;i++)
{

}

This loop as though it should run only for two iterations. But, by taking the advantage of hint i.e. Integer.MAX_VALUE you can make it run indefinitely as below.


int start =Integer.MAX_VALUE=-1;
for(int i=start;i<=start+1;i++)
{

}

The first line will set start to 1 less than MAX_VALUE. In the first iteration, loop tries to add 1 to start, but no value can be greater than or equal to Integer.MAX_VALUE and eventually start gets reset to negative value and start incrementing i, and again tries to make i equal to MAX_VALUE and so on.


Another puzzle :

while(i==i+1)
{

}

Looking at the loop it really seems it ought to terminate immediately. A number can never be itself plus 1, right ?. But infinity can we equal to infinity plus 1, only in terms of computer programming. Mathematically this is not true.
You guessed it right we can achieve this using Double.POSITIVE_INFINITY.

double i=Double.POSITIVE_INFINITY;
while(i==i+1)
{

}

There is one more simple way by which we can achieve this.

double i=1.0/0.0;
while(i==i+1)
{

}

Another puzzle :

while(i!=i)
{

}

You may think a number will always be equal to itself, right ?
But, what if the value is not a number, you guessed it right we will use Doubel.NaN.

double i=Double.NaN;
while(i!=i)
{

}

Floating point arithmetic reserves a special value to represent a quantity that is not a number. This value known as NaN. You can also initialize i with any floating point arithmetic expression that evaluates to NaN, for example.

double i=0.0/0.0;


Comments

Popular posts from this blog