How to declare i and j to make it an infinite loop?

while( i <= j && i >= j && i != j) {} 

how to declare i and j to make it an infinite loop?

// This is an interview question that I met.

he asks which announcements i and j, let it always be true.

And I cannot do this by declaring I and j as number types. What other types can meet him?

+23
java infinite-loop
Nov 04 2018-11-11T00:
source share
3 answers
 Integer i=new Integer(1000); Integer j=new Integer(1000); System.out.println((i<=j)+" "+(i>=j)+" "+(i!=j)); 

i and j will be automatically unpacked into int for <= and >= , but not for != . i and j are different instances but have the same int value. That is why all three comparisons will return to the truth.

+38
Nov 04 2018-11-11T00:
source share

This also works ("on my machine"):

 Integer a = 128, b = 128; 

whereas this will not work:

 Integer a = 127, b = 127; 

Auto-boxing a int is the syntactic sugar for calling Integer.valueOf(int) . This function uses a cache for values ​​from -128 to 127 inclusive. It can cache other values, but in my case it is not.

Thus, destination 128 does not have a cache; it creates a new Integer instance with each automatic box operation, and the reference comparison a != b true. Target 127 has a cache, and the resulting Integer objects are the same cache instance. So, the reference comparison a != b is incorrect.

What I really want to note is to beware of comparing links to auto-boxing. A more likely real problem is that you expect a == b true, because they were assigned the same (automatic field) value, you run some unit tests that confirm your expectation, and then your code exits out of action in the wild when some counter exceeds the upper limit of the cache. Funny times!

+3
Sep 27 '13 at 16:16
source share

Any equal value of 'i' and 'j' will show true with this statement, say:

 Integer i = new Integer(1); Integer j = new Integer(1); while( i <= j && i >= j && i != j) {} 

Magic using the operator! In the case of the! = Operator, the compiler accepts operands as objects (including their values), whereas in the case> = or <=, the compiler accepts only the value of the operands. So the above statement returns true.

-2
Nov 20 '11 at 9:17
source share



All Articles