That's my while loop, and the question is, how can i get a true condition?
s and t are Integer variables
while (s<=t && s>=t && s!=t )
EDIT
tl;dr the original question stated:
s and t are int variables (and OP commented they are not Integer variables)
Never!
s and t are int variables, so when s == t the third operand will fail, when s != t one of the first two operands will fail.
Possible, but unlikely, if they are declared as volatile int s, t; in a multi-threaded application.
EDIT
Question has been modified. Now s and t are Integer variables, which makes the answers referring to Integer objects more relevant.
By boxing the primitive value in an object:
Integer s = new Integer(5);
Integer t = new Integer(5);
boolean rslt = (s <= t && s >= t && s != t);
System.out.println("Result = " + rslt);
The rslt boolean here will indeed evaluate to true.
However, the following would return false:
s <= t && s >= t && !s.equals(t)
it is because in Java, for objects, == means that it is indeed the same instance, while equals is left up to be implemented by every class and typically means that the core values of the compared objects are the same -- while not necessarily being the same class instance (AKA object). The > and < for boxed primitives are evaluated agaist the primitive value, however == is checking the object identity.
It actually is possible:
public class EqualsTest
{
public static void main(String[] args)
{
Integer x = new Integer(Integer.parseInt(args[0]));
Integer y = new Integer(Integer.parseInt(args[1]));
if(x <= y && y <= x && y !=x)
{
System.out.println("equal");
}
else
{
System.out.println("not equal");
}
}
}
Compiling this and running it with two equal integer arguments produces:
$ java EqualsTest 5 5
equal
The reason that this works is due to autoboxing and the fact that, for objects, == only checks whether or not the references are the same (which, in the case above, they are not).
Never man, no way.
s<=t && s>=t returns true if s == t, and s == t && s != t returns false forever.
You cant the only way first two conditions result true is when s is equal to t and the third conditions negates this fact.
Hence i dont think its possible
If the two values are accessible by multiple threads (either static, or members variables of an object shared between multiple threads), you could do this:
Thread 1:
s = 1; // 1
t = 1; // 2
t = 2; // 5
Thread 2:
This is equivalent to your expression but easier to label.
boolean result = s <= t; // 3
if(result) {
result = s >= t; // 4
}
if(result) {
result = s != t; // 6
}
Assuming everything happens in the order given by the commented numbers, then at the end of thread 2's code, result will be true.
So, thread 1 sets s and t to be equal, then thread 2 checks that they're equal, then thread 1 sets them to be not equal, then thread 2 checks that they're not equal.
There are more complicated situations where this could be true, but this is the simplest one I could think of.
Related
I am making a Hash Table in java.
In searching function, I am doing some comparison in IF statement. but it is not doing any comparison.
here's is some part of my code.
while (table[pos]!=null) {
if (table[pos]==key) {
System.out.println("SEARCH "+key+" at INDEX "+home);
return;
}
else {pos=h(home+p(i));
i++;
}
}
System.out.println("Failed to find "+key+".");
return;
}
It doesn't work even when table[pos] and key are the same!
but I add very simple assigning variable to another one. It work! I don't know why it works. I wanna know it xD
while (table[pos]!=null) {
int x = table[pos];
if (x==key) {
System.out.println("SEARCH "+key+" at INDEX "+home);
return;
}
else {pos=h(home+p(i));
i++;
}
}
System.out.println("Failed to find "+key+".");
return;
}
Well, if table[pos] and key are both Integer (and table[pos] must be a reference type, since you are comparing it to null in the while statement), they should be compared with equals, not with ==, since two different Integer objects may have the same int value.
When you assign table[pos] to the int variable x, it is un-boxed to a primitive value.
Now, when you compare the int x to the Integer key, the key is also un-boxed to an int, and int comparison works with ==.
This can be demonstrated by the following short example:
Integer i1 = 300;
Integer i2 = 300;
System.out.println (i1 == i2);
int i3 = i1;
System.out.println (i3 == i2);
which outputs:
false
true
The code code would be:
while (table[pos] != null) {
if (table[pos].equals(key)) {
System.out.println("SEARCH "+key+" at INDEX "+home);
return;
} else {
pos = h(home + p(i));
i++;
}
}
System.out.println("Failed to find "+key+".");
When comparing two objects with ==, you check if both of these references point to the same place in the memory, while using == with primitives simply checks if values are the same. To correctly check equation of values inside two Integers you should use equals() method.
In your second example you used unboxing from Integer to int so it checked values as you expected it to do. In the first one you compared if both values point to the same place in memory.
Actually the correct way is to use both just like HashMap does for example, this way we will always be sure. This is for example how HashMap does it internally:
if(((k = first.key) == key || (key != null && key.equals(k)))) ...
So in your case it would be:
if ((table[pos] == key) || (key != null && (table[pos].equals(key)))) {
Say I have a list of many primitive variables:
final int a = 3;
final int b = 4;
final int c = 4;
final int d = 4;
final int e = 4;
What's an idiomatic way to make sure they all hold the same value? The obvious way is simply
if (a == b && a == c && a == d && a == e) // ...
But I think this is error prone and hard to read, especially when the variables have proper names, unlike my example.
if ( numCategories == numTypes && numCategories == numColours
&& numCategories == numStyles && numCategories == numPrices) // ...
It would be nice if we could do the comparison like this:
if (a == b == c == d == e)
but obviously a == b resolves to a boolean so we can't compare that to c.
Is there a library function in the JDK or another utility library with maybe a signature somewhat like this?
static boolean areEqual(int... numbers)
then we could use it like so:
if (areEqual(a, b, c, d, e)) //...
I could easily write a function like this myself, but why reinvent the wheel if you don't have to?
Maybe there's another idiomatic way to accomplish this that I'm missing.
Using Streams, you can take advantage of some convenient methods to achieve your goal.
You can use Stream's or IntStream's distinct() combined with count() to find the number of unique elements:
For int variables:
if (IntStream.of(a,b,c,d,e).distinct().count() == 1) {
}
For reference type variables:
if (Stream.of(a,b,c,d,e).distinct().count() == 1) {
}
Another way, which is probably less efficient (but I'll keep it here since it's the first thing I thought about) is creating a Stream of all the elements you want to compare and then collecting them into a Set and checking the size of the Set is 1 (since Set doesn't allow duplicates) :
if (IntStream.of(a,b,c,d,e).boxed().collect(Collectors.toSet()).size() == 1) {
}
or
if (Stream.of(a,b,c,d,e).collect(Collectors.toSet()).size() == 1) {
}
for general Objects.
A naive option is to build methods that receives all the variables as varargs and compare them one after other. If one of them is different you will get false
public static boolean areEqual(int...nums)
{
for (int i = 0 ; i < nums.length - 1 ; ++i) {
if (nums[i] != nums[i + 1]) {
return false;
}
}
return true;
}
Uses
if (areEqual(a, b, c, d, e))
I like this approach. There's no auto-boxing and no magic numbers.
As per the documentation, it's also short-circuiting so therefore potentially more efficient than other methods. More importantly, it's very easy to read.
IntStream.of(a, b, c, d).allMatch(x -> x == e);
Credit to saka1029.
This is some of my current code:
Class usedCoords contains:
public List<Integer> USEDX = new ArrayList<Integer>();
main function contains:
if(fX % gridX == 0 && fZ % gridZ == 0 && ALPHA != 0 && usedcoords.USEDX == fX) { }
Note I also done: usedCoords usedcoords = new usedCoords();, that is why I named it usedcoords.
My main task is that I want to make the usedcoords.USEDX == fX possible. Currently I will get an error because fX is an integer. USEDX has integers as well so how do check that the any integer in USEDX is equal to fX?
Thanks in advance.
Use List#contains() -- and it's more readable and conventional not to have variable names start with an uppercase unless they are constants:
if (fX % gridX == 0 && fZ % gridZ == 0 && alpha != 0 && usedcoords.usedX.contains(fX)) {
...
}
The int variable fX will be automatically boxed into the Integer type by the compiler.
USEDX has integers as well so how do check that the any integer in USEDX is equal to fX?
By calling List.contains(Object) which returns true if this list contains the specified element. Something like,
if (USEDX.contains(fx)) {
// ...
}
For efficiency-sake, you may use Hashtable<Integer> instead of List because it requires O(1) (constant) time to search for a value.
This question already has answers here:
Does Java evaluate remaining conditions after boolean result is known?
(7 answers)
Closed 7 years ago.
Does java calculate the second condition in ( test1 || test2 ) if the first one is true ?
I use Optional and I have something like that :
if (!opt.isPresent() || opt.get() == currentPlayer.getSelectedRegion())
and there will be a problem if the first test is true and java compute the second test.
If first condition is true second condition is not evaluated.
If first condition is false also second condition is evaluated.
That's why you can write a code like the following without a NullPointerException
if (str == null || str.length() == 0) {
// do something
}
The operator | (instead of || ) will evaluated both conditions
So the code
if (str == null | str.length() == 0) {
// do something
}
can generate a NullPointerException if str is null
Does java calculate the second condition in ( test1 || test2 ) if the first one is true ?
No. Boolean or will short-circuit, the first true is sufficient to make the expression true. No further conditions will be evaluated after that.
If you use the || and &&, rather than the | and &, Java will not bother to evaluate the right-hand operand.
No, java short-cut operators, the second argument is not evaluated if the first is. Ore more formal:
for x || y, y is only evaluated if x is false; and
for x && y, x is only evaluated if y is true.
This will increase performance and can be both useful and tricky:
usefull: to prevent you from doing things such that an error is thrown. The most typical example is the null check:
if(x != null && x.someTest())
this will prevent .someTest being called if x is null.
tricky: the problematic aspect can be if you call a method that does not only return something, but changes state as well. For instance:
public class Foo {
private int checked = 0;
bool someCondition () {
return (checked % 2) == 0;
}
bool neverChecked () {
checked++;
return checked == 1;
}
}
if you now call:
if(foo.someCondition() || foo.neverChecked());
this is one of the main reasons it is adviseable to keep "getters" (thinks that calculate things of an object), and "setters" (things that modify the state of an object), clearly separated. From the moment you start mixing, one can get complicated behavior in some circumstances.
it can be the intention that you always increment checked, but it will only if .someCondition happens to be false.
I am facing difficulty in comparing two double values using == and !=.
I have created 6 double variables and trying to compare in If condition.
double a,b,c,d,e,f;
if((a==b||c==d||e==f))
{
//My code here in case of true condition
}
else if ((a!=b||c!=d||e!=f))
{
//My code here in case false condition
}
Though my condition is a and b are equal control is going to else if part
So I have tried a.equals(b) for equal condition, Which is working fine for me.
My query here is how can I check a not equal b. I have searched the web but I found only to use != but somehow this is not working for me.
If you're using a double (the primitive type) then a and b must not be equal.
double a = 1.0;
double b = 1.0;
System.out.println(a == b);
If .equals() works you're probably using the object wrapper type Double. Also, the equivalent of != with .equals() is
!a.equals(b)
Edit
Also,
else if ((a!=b||c!=d||e!=f))
{
//My code here in case false condition
}
(Unless I'm missing something) should just be
else
{
//My code here in case false condition
}
if you really want invert your test conditions and test again,
else if (!(a==b||c==d||e==f))
Or use De Morgan's Laws
else if (a != b && c != d && e != f)
You can use
!a.equals(b) || !c.equals(d) || !e.equals(f)
Well with double data type you can use
==,!= (you should try to use these first.. )