JAVA Equals Alternative [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I was just wondering if there was an alternative to the following operator:
if (f == 0){
System.out.print("");
} else if (i %2 == 1){
System.out.print("; ");
}
To be clearer, I would like an alternative way of writing the if statement's "==" and the else if statement's %2 == 1.
Thanks.

System.out.print(f!=0 && i%2==1 ? "; " : "");
Instead of the modulo you can flag out all bits of i except the last one by a bitwise and.
The alternative to i%2 is i&1.

In java 7 you can compare like this
int result = Integer.compare(f, 10);
Description of the method
public static int compare(int x,
int y)
Compares two int values numerically. The value returned is identical to what would be returned by:
Integer.valueOf(x).compareTo(Integer.valueOf(y))
Parameters:
x - the first int to compare
y - the second int to compare
Returns:
the value 0 if x == y; a value less than 0 if x < y; and a value greater than 0 if x > y
Since: 1.7
Taken from official document
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#compare%28int,%20int%29
and In java 6
int result = Double.compare(f, 10);
Description of the method
compare
public static int compare(double d1,
double d2)
Compares the two specified double values. The sign of the integer value returned is the same as that of the integer that would be returned by the call:
new Double(d1).compareTo(new Double(d2))
Parameters:
d1 - the first double to compare
d2 - the second double to compare
Returns:
the value 0 if d1 is numerically equal to d2; a value less than 0 if d1 is numerically less than d2; and a value greater than 0 if d1 is numerically greater than d2.
Since:
1.4
Taken fropm official docs
http://docs.oracle.com/javase/6/docs/api/java/lang/Double.html#compare%28double,%20double%29
you can use any of the approach according to your requirements
I have tested both of them
see my tested solution
for java 6 http://ideone.com/56dm1T
for java 7 http://ideone.com/mEjt6W

Equals operator == compares references in the case of objects and actual values in the case of primitive types.
A scenario where this operator can be replaced with equals(Object obj) is when the wrapper objects of primitive types are used.
So, if there are two int, a and b, and you obtain their wrappers with:
Integer objA = Integer.valueOf(a);
Integer objB = Integer.valueOf(b);
a == b gives the same result as objA.equals(objB).

Related

For what value of i does while (i == i + 1) {} loop forever?

I ran cross this puzzler from an advanced programming course at a UK university exam.
Consider the following loop, in which i is, so far, undeclared:
while (i == i + 1) {}
Find the definition of i, that precedes this loop, such that the while loop
continues for ever.
The next question, which asked the same question for this code snippet:
while (i != i) {}
was obvious to me. Of course in this other situation it is NaN but I am really stuck on the prior one. Does this have to do with overflow? What would cause such a loop to loop for ever in Java?
First of all, since the while (i == i + 1) {} loop doesn't change the value of i, making this loop infinite is equivalent to choosing a value of i that satisfies i == i + 1.
There are many such values:
Let's start with the "exotic" ones:
double i = Double.POSITIVE_INFINITY;
or
double i = Double.NEGATIVE_INFINITY;
The reason for these values satisfying i == i + 1 is stated in JLS 15.18.2. Additive Operators (+ and -) for Numeric Types:
The sum of an infinity and a finite value is equal to the infinite operand.
This is not surprising, since adding a finite value to an infinite value should result in an infinite value.
That said, most of the values of i that satisfy i == i + 1 are simply large double (or float) values:
For example:
double i = Double.MAX_VALUE;
or
double i = 1000000000000000000.0;
or
float i = 1000000000000000000.0f;
The double and float types have limited precision, so if you take a large enough double or float value, adding 1 to it will result in the same value.
These puzzles are described in detail in the "Java Puzzlers: Traps, Pitfalls, and Corner Cases" book by Joshua Bloch and Neal Gafter.
double i = Double.POSITIVE_INFINITY;
while (i == i + 1) {}
or:
double i = 1.0e40;
while (i == i + 1) {}
both will result in an infinite loop, because adding 1 to a floating-point value that is sufficiently large will not change the value, because it doesn't "bridge the gap" to its successor1.
A note about the second puzzle (for future readers):
double i = Double.NaN;
while (i != i) {}
also results in an infinite loop, because NaN is not equal to any floating-point value, including itself 2.
1 - Java Puzzlers: Traps, Pitfalls, and Corner Cases (chapter 4 - Loopy Puzzlers).
2 - JLS §15.21.1
double i = Double.POSITIVE_INFINITY;
Just an idea: what about booleans?
bool i = TRUE;
Isn't this a case where i + 1 == i?

When does Integer != 1 come true [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
This is classical, but writing to Google did not give me hits.
My code:
Integer i = ..; // Sth is put from database.
if (i != 1) {
// do sth
} else {
// do not.
}
Case:
I know that this comparison is not correct java and I should compare:
if (i.intValue != 1) {}
or
if(!i.equals(1)) {}
but my code had the first one and I seem to get the true from somewhere, where the Integer is not 1 and when it is 1 there comes false.
Question:
What is happening there around?
but my code had the first one and I seem to get the true from somewhere, where the Integer is not 1 and when it is 1 there comes false.
If I understand your issue correctly, the following might explain the behavior:
Integer i = 1;
Integer j = new Integer(1);
Integer k = Integer.valueOf(1);
System.out.println(i == j); // false
System.out.println(i == k); // true
In other words, you can get both true or false when comparing with 1 depending on how the Integer was constructed. Integer.valueOf will reuse objects while new Integer will not.
If you indeed did the comparison with an integer literal (or with an int) then any Integer should be automatically unboxed by the compiler, and you should never get any surprises.
The compiler changes :
if (i != 1)
to
if(i.intValue()!=1)
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.
See this link
if (i != 1) , if (i.intValue != 1) and if(!i.equals(1)) are all equal and will return the same value. The compiler will automatically unbox i, turning it into a primitive int.

Why is Float.MIN_VALUE in Java a positive value? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
What do you think Float.MIN_VALUE equals to?
The next code explains where my last 5 hours went to, trying solving a bug.
public static void main(String[] args) {
compareToZero(Float.MIN_VALUE); // Out = true false false
compareToZero(Float.MAX_VALUE); // Out = true false false
System.out.println("Float minimum " + Float.MIN_VALUE); // Out = 1.4E-45
System.out.println("Float maximum " + Float.MAX_VALUE); // Out = 3.4028235E38
}
private static void compareToZero(float value1) {
System.out.print((value1 > 0) + " ");
System.out.print((value1 < 0) + " ");
System.out.print((value1 == 0) + "\n");
}
I didn't imagined that minimum value of float will be a positive value... Can't find any use for it.
Per the documentation for Float.MIN_VALUE:
A constant holding the smallest positive nonzero value of type float, 2-149. It is equal to the hexadecimal floating-point literal 0x0.000002P-126f and also equal to Float.intBitsToFloat(0x1).
While the name is debatable as the "true minimum value" of a float is -Float.MAX_VALUE, I suspect MIN_VALUE was chosen for consistency with the other numeric types. Using the names MIN_RANGE_VALUE and MAX_RANGE_VALUE (or similar) might have made the difference more clear.
To understand why this is the "minimum value" requires understanding a little bit about how Java (or IEEE-754) floating point values work. With this insight, after reading the documentation, it is clear that Float.MIN_VALUE is the minimum non-zero value representable by the mantissa and exponent components of a float. Or, the smallest positive value a float can represent.
The "true minimum value" is -Float.MAX_VALUE because Float.MAX_VALUE represents the maximum value that the mantissa and exponent components of a float can represent. Since the sign for a float is stored as a discrete bit, this range limit is the same for both positive and negative numbers.
This differs from how integers work in Java (and on most CPUs): they are encoded using two's complement. (Some computer systems used a discrete sign bit, which is called "one's complement", which then has two integer values of zero: 0 and -0!)
Happy researching!

What does this recursion method do? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
This is the code that I have a problem wit understanding. I know so far that this code here passes in int a and int b. Then it checks if int b is equal to 0 and if it is then it returns 1. Then it checks if b is 1 and if so then it returns int a. But I dont get the last part of this code. Its something with recursion but I dont get it.
public static int mystery(int a, int b) {
if(b == 0) {
return 1;
else if(b==1) {
return a;
return a * mystery(a,b-1);
This code looks like that for exponentiation where a is the base and b is the exponent. So in the case of b = 0, obviously, the answer would be 1 by the rules of exponentiation. When b = 1, then return a because a ^ 1 = a. Otherwise, use multiplication to get the result recursively where the base case for recursion is b = 1 (b = 0 condition will not be the base case if b > 0). By the way, you need to put proper parenthesis on the code for it to compile (the curly braces need to be closed).
i.e.,
public static int mystery(int a, int b) {
if(b == 0) {
return 1;
} else if(b==1) {
return a;
}
return a * mystery(a,b-1);
}
e.g.,
mystery(2, 6) returns 64 as the result.
Run it on paper:
mystery(10, 20)
b == 0 (false) b == 1 (false) so return 10 * mystery(10, 19)
mystery(10, 19)
boils down to return 10 * mystery(10, 18)
and so on.
Try with different values e.g. mystery(20, 10) mystery(5,5);

java == for Integer [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Inconsistent behavior on java's ==
Integer wrapper objects share the same instances only within the value 127?
I have found the following == behaviour for Integer objects and I fail to understand it. (I am well aware that one should use equals for such comparisons, but I am studying for OCPJP...)
On short, == works as expected for 1000, but not for 10.
The former fragment of code is:
Integer i1 = 1000;
Integer i2 = 1000;
if(i1 != i2) System.out.println("different objects");
if(i1.equals(i2)) System.out.println("meaningfully equal");
and it behaves as one would expect:
different objects
meaningfully equal
The latter though:
Integer i3 = 10;
Integer i4 = 10;
if(i3 == i4) System.out.println("same object");
if(i3.equals(i4)) System.out.println("meaningfully equal");
has the following output:
same object
meaningfully equal
Can someone please explain why this is happening?
Since Java 5, wrapper class caching was introduced. The following is an examination of the cache created by an inner class, IntegerCache, located in the Integer cache. For example, the following code will create a cache:
Integer myNumber = 10
or
Integer myNumber = Integer.valueOf(10);
256 Integer objects are created in the range of -128 to 127 which are all stored in an Integer array. This caching functionality can be seen by looking at the inner class, IntegerCache, which is found in Integer:
So when creating an object using Integer.valueOf or directly assigning a value to an Integer within the range of -128 to 127 the same object will be returned. Therefore, consider the following example:
Integer i = 100;
Integer p = 100;
if (i == p)
System.out.println("i and p are the same.");
if (i != p)
System.out.println("i and p are different.");
if(i.equals(p))
System.out.println("i and p contain the same value.");
The output is:
i and p are the same.
i and p contain the same value.
It is important to note that object i and p only equate to true because they are the same object, the comparison is not based on the value, it is based on object equality. If Integer i and p are outside the range of -128 or 127 the cache is not used, therefore new objects are created. When doing a comparison for value always use the “.equals” method. It is also important to note that instantiating an Integer does not create this caching.
Remember that “==” is always used for object equality, it has not been overloaded for comparing unboxed values
See Integer wrapper objects share the same instances only within the value 127?. The Integer class keeps shared static instances around for common values.

Categories