This question already has answers here:
How to make loop infinite with "x <= y && x >= y && x != y"?
(4 answers)
How can i define variables to make an infinity while loop with these conditions? [closed]
(4 answers)
Closed 9 years ago.
Here is the code i have to figure it out how is it possible. I have a clue but i do not know how to do it. I think it is about negative and positive numbers and maybe the variable modifiers as well. I am a beginner i looked the solution everywhere but i could not find anything usable.
the question is that: You need to declare and initialize the two variables. The if condition must be true.
the code:
if( a <= b && b <= a && a!=b){
System.out.println("anything...");
}
I appreciate you taking the time.
This is not possible with primitive types. You can achieve it with boxed Integers:
Integer a = new Integer(1);
Integer b = new Integer(1);
The <= and >= comparisons will use the unboxed value 1, while the != will compare the references and will succeed since they are different objects.
This works too:
Integer a = 128, b = 128;
This doesn't:
Integer a = 127, b = 127;
Auto-boxing an int is syntactic sugar for a call to Integer.valueOf(int). This function uses a cache for values less than 128. Thus, the assignment of 128 doesn't have a cache hit; it creates a new Integer instance with each auto-boxing operation, and a != b (reference comparison) is true.
The assignment of 127 has a cache hit, and the resulting Integer objects are really the same instance from the cache. So, the reference comparison a != b is false.
Another rare case for class-variables may be that another thread could change the values of a and b while the comparison is executing.
Related
This question already has answers here:
How to make loop infinite with "x <= y && x >= y && x != y"?
(4 answers)
Closed 7 years ago.
I had this question in my Java test where I had to assign values to a and b so this expression evaluates to true:
(a<=b && b<=a && a!=b)
Sadly, I had no idea what the answer was.
There's a simple trick here.
You cannot think this through with boolean logic only. Using that, this combination...
a is less than or equal to b, and
b is less than or equal to a, and
a is not equal to b
...would never return true.
However, the != operator compares references if its operands are objects.
So, the following will return true:
Integer a = 1;
Integer b = new Integer(1);
System.out.println(a<=b && b<=a && a!=b);
What happens here is: a as an object reference is not equal to b as an object reference, although of course they hold equal integer values.
This question already has answers here:
Java: Integer equals vs. ==
(7 answers)
Closed 8 years ago.
Please can you explain the below behaviour.
public class EqAndRef {
public static void main(String[] args) {
Integer i = 10;
Integer j = 10;
Double a = 10D;
Double b = 10D;
System.out.println(i.equals(j));
System.out.println(i == j);
System.out.println(a.equals(b));
System.out.println(a == b);
}
}
Output on jdk 6
true
true
true
false
why a==b is false and i==j not false?
The Integers i and j are constructed (via auto boxing) from integer literals from the range –128 to 127 and thus are guaranteed to be pooled by the JVM so the same object (see flyweight pattern) is used for them. Hence, they compare identical by object references.
For the Doubles a and b on the other hand, no such pooling guarantee exists and, in your case, you got two different objects that did not compare identical.
Using == to compare objects if you don't mean to check identity is to be considered suspect and should be avoided. The equals methods of both types are overridden to compare the boxed values (as opposed to object identity) which is why they return true in both cases (and should be used).
Initialize the Integers the following way then you will get the difference as #5gon12eder said
The Integer s i and j are constructed (via auto boxing) from integer literals from the range –128 to 127 which are guaranteed to be pooled by the JVM so the same object (see flyweight pattern ) is used for them. Hence, they compare equal by object references.
try this code to initialize your integers
Integer i = new Integer(10);
Integer j = new Integer(10);
This question already has answers here:
Integer wrapper objects share the same instances only within the value 127? [duplicate]
(5 answers)
Closed 8 years ago.
I was writing some test code and found one strange thing, and still confused how this is happening?
Integer i1 = 220;
Integer i2 = 220;
System.out.println(i1 == i2);
prints false as expected. But
Integer i1 = 20;
Integer i2 = 20;
System.out.println(i1 == i2);
prints true, but both are different references referring to different objects (I assume that).
How come second snippet prints true?
The == operator only works for Integer values between -128 and 127. That is why it doesn't work for 220 but does for 20. In general it is best to always use .equals() when comparing Integers and you should never rely on the == operator.
More information can be found here: https://www.owasp.org/index.php/Java_gotchas#Immutable_Objects_.2F_Wrapper_Class_Caching
This question already has answers here:
Why is 128==128 false but 127==127 is true when comparing Integer wrappers in Java?
(8 answers)
Closed 6 years ago.
The following code seemed really confusing to me since it provided two different outputs.The code was tested on jdk 1.7.
public class NotEq {
public static void main(String[] args) {
ver1();
System.out.println();
ver2();
}
public static void ver1() {
Integer a = 128;
Integer b = 128;
if (a == b) {
System.out.println("Equal Object");
}
if (a != b) {
System.out.println("Different objects");
}
if (a.equals(b)) {
System.out.println("Meaningfully equal.");
}
}
public static void ver2() {
Integer i1 = 127;
Integer i2 = 127;
if (i1 == i2) {
System.out.println("Equal Object");
}
if (i1 != i2){
System.out.println("Different objects");
}
if (i1.equals(i2)){
System.out.println("Meaningfully equal");
}
}
}
Output:
[ver1 output]
Different objects
Meaningfully equal.
[ver2 output]
Equal Object
Meaningfully equal
Why the == and != testing produces different results for ver1() and ver2() for same number much less than the Integer.MAX_VALUE? Can it be concluded that == checking for numbers greater than 127 (for wrapper classes like Integer as shown in the code) is totally waste of time?
Integers are cached for values between -128 and 127 so Integer i = 127 will always return the same reference. Integer j = 128 will not necessarily do so. You will then need to use equals to test for equality of the underlying int.
This is part of the Java Language Specification:
If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.
But 2 calls to Integer j = 128 might return the same reference (not guaranteed):
Less memory-limited implementations might, for example, cache all char and short values, as well as int and long values in the range of -32K to +32K.
Because small integers are interned in Java, and you tried the numbers on different sides of the "smallness" limit.
There exist an Integer object cache from -128 and up to 127 by default. The upper border can be configured. The upper cache border can be controlled by VM option -XX:AutoBoxCacheMax=<size>
You are using this cache when you use the form:
Integer i1 = 127;
or
Integer i1 = Integer.valueOf(127);
But when you use
Integer i1 = new Integer(127);
then you're guaranteed to get a new uncached object. In the latter case both versions print out the same results. Using the cached versions they may differ.
Java caches integers from -128 to 127 That is why the objects ARE the same.
I think the == and != operators when dealing with primitives will work how you're currently using them, but with objects (Integer vs. int) you'll want to perform testing with .equals() method.
I'm not certain on this, but with objects the == will test if one object is the same object or not, while .equals() will perform testing that those two objects contain equivalence in value (or the method will need to be created/overridden) for custom objects.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Integer wrapper objects share the same instances only within the value 127?
I have copied the following program snippet from the Khalid Mughal SCJP, but I am unable to
understand the output.
public class RQ200_60 {
public static void main(String[] args) {
Integer i = -10;
Integer j = -10;
System.out.print(i==j); // output: true -- why true?
System.out.print(i.equals(j)); // output: true
Integer n = 128;
Integer m = 128;
System.out.print(n==m); // output: false
System.out.print(n.equals(m)); // output: true
}
}
The above program giving output true for the first print statement but it supposed to give false because it is reference comparison with == relational operator. But third print gives false and I don't understand this inconsistency.
Explanations are greatly appreciated!
In the first case, both the objects i and j are pointing to the same cached object. By default, the range between -128 and 127 are cached as Integer Object. We can increase the range using JVM arguments
The answers about caching are correct. However, if you go...
Integer i = new Integer(10);
Integer j = new Integer(10);
...then you avoid the caching and the results will be what you expected.
Integer objects may be cached for the ones that represent a value close to 0. (The specification for the implementation may tell you some details). This is presumably to save memory (values close to 0 are common, and it would waste a lot of memory to make a new object for every variable with the same value).
== checks whether two things are the same object; you may or may not have the same Integer object for any two given variables with the same value. You are not supposed to check with == because you are not supposed to care whether it is the same object; it is the value of an Integer that matters, not its identity.
Here in this case the Integer i and Integer j holding the integer values which are in range of integer, range of an Integer is -128 to 128, and Integer n and Integer m exceeds the range of Integer