You can stop an infinite loop with CTRL + C . You can generate an infinite loop intentionally with while True . The break statement can be used to stop a while loop immediately.
In for() loop: To avoid ending up in an infinite loop while using a for statement, ensure that the statements in the for() block never change the value of the loop counter variable. If they do, then your loop may either terminate prematurely or it may end up in an infinite loop.
Basically, the infinite loop happens when the condition in the while loop always evaluates to true. This can happen when the variables within the loop aren't updated correctly, or aren't updated at all. Let's say you have a variable that's set to 10 and you want to loop while the value is less than 100.
The only way to stop a thread asynchronously is the stop() method.
double i = Double.NaN;
The API for Double.equals() spells out the answer: "Double.NaN==Double.NaN has the value false". This is elaborated in the Java Language Specification under "Floating-Point Types, Formats, and Values":
NaN
is unordered, so the numerical comparison operators<
,<=
,>
, and>=
returnfalse
if either or both operands areNaN
. The equality operator==
returnsfalse
if either operand isNaN
, and the inequality operator!=
returnstrue
if either operand isNaN
. In particular,x!=x
istrue
if and only ifx
isNaN
, and(x<y) == !(x>=y)
will befalse
ifx
ory
isNaN
.
The value of i
is then Invalid. "Not a Number".
After some googling, i found out that you CAN have NaN ( Not a Number ) in Java! So, a Float Pointing number is the Data Type and the Value is NaN. See here
double i = Double.NaN;
NaN is not equal to anything, including itself.
float i = Float.NaN;
while(i == i) ;
System.out.println("Not infinite!");
Since others said it's NaN I got curious about the official (JDK 6) implementation of Double.isNaN
, and behold:
/**
* Returns <code>true</code> if the specified number is a
* Not-a-Number (NaN) value, <code>false</code> otherwise.
*
* @param v the value to be tested.
* @return <code>true</code> if the value of the argument is NaN;
* <code>false</code> otherwise.
*/
static public boolean isNaN(double v) {
return (v != v);
}
I'm not sure, but I believe (i == i) is not atomic operation in multithreaded process, so if i value will be changed by other thread between pushes of it's value to stack on thread executing the loop, then that condition can be false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With