I am effectively trying to write a multiple-bit if-statement in binary. If val is true, I would like to return the correct value of x. However, if val is false, I would like to return all values of the array to be false.
This is effectively the same as checking all values within the array against the value of val. Why doesn't this work?
boolean[] ifStatement(bit0, bit1, bit2, bit3, val) {
boolean[] x = {bit0, bit1, bit2, bit3};
return (x && val);
}
In response to comments asking what I mean by the question, the following is a representation using an 8-bit AND gate in the program Logisim:
I am also aware that it is very easy to do the same thing using a for statement. My question is why is the example code not possible?
Thanks in advance.
The short answer is no. You have check each item. It'd be kind of nice if it did work, but there you have it.
There are, however, special classes like BitSet that provide special functionality for big collections of booleans. You might find one of these useful. Typically not worth the effort for short numbers of booleans, though.
boolean[] x = {bit0, bit1, bit2, bit3};
return (x && val);
Why doesn't this work?
Your proposed meaning of that expression matches the semantics of the standard map higher-order function in the FP paradigm. Interestingly enough, I am not aware of any actual FP language which would have its AND operator overloaded to mean map((applyPartial(AND, val), coll) when one of its operands is a collection.
But, constraining the discussion to Java, such a feature would be deeply incongruent with everything else in it. It would make a logical operator suddenly behave like a batch collection operator; there is nothing even remotely close to that in Java, which is meant to be as unsurprising to beginners as possible, and especially so to people already familiar with C.
BTW you should have at least picked & because && has short-circuiting semantics, something which makes no sense in your proposal.
An array is a type all its own, not a boolean. So you can't use logical operators on an array type.
From your question description, it sounds like you just want to check every value in the array against some baseline boolean. You can do that with a loop over all elements in the array, and if any of don't match up to the baseline, return false.
public boolean ifStatement(boolean base, boolean... values) {
for(boolean value : values) {
if(!(value && base)) {
return false;
}
}
return true;
}
EDIT: After your diagram explained a few things, it seems that a boolean array is the wrong data structure. Why not work with a byte directly? (8 bits = 1 byte)
public byte ifStatement(boolean val, byte value) {
return val ? value : (byte) 0x00;
}
You're either returning value or nothing in your example, so I believe that this would work better.
This doesn't work because the Java compiler doesn't interpret your wishes but adheres to its specification.
And the boolean operators only work with, well, booleans. Arrays of booleans aren't booleans.
Actually you don't need for loop / bitwise operators:
boolean []ifStatement(boolean b1, boolean b2, boolean b3, boolean b4, boolean val) {
if (!val) {
boolean []result = {false, false, false, false};
return result;
} else {
boolean []result = {b1, b2, b3, b4};
return result;
}
}
Related
I'm learning C++ and java and I've noticed how if you have a conditional, whatever code follows will be executed if the condition is true, even if you don't explicitly write == true
Consider the following very simple C++ code:
bool c_plus_plus_is_cool(){
return true;
}
int main(){
if (c_plus_plus_is_cool()) {
cout << "C++ is cool!";
}
return 0;
}
Q: What is the difference between
if (c_plus_plus_is_cool())
and if (c_plus_plus_is_cool() == true) ?
And is this also the case in other languages (like Java (where I've been writing ==true all this time...)) ?
The == operator returns a boolean.
If you already have a boolean, == true will be no different from the original boolean; there is no point in writing it.
Similarly, use the ! operator instead of == false.
One exception to this is C# nullable booleans, where == true will be false for null.
Both C++ and Java have the same behaviour in this point and in both languages the == true is just redundant noise.
If you use the verbose syntax in Java so far then this is your own private style. Even in Java this is not the commonly used and accepted/recommended style.
There is actually no difference other than syntactical bloat brought by == true.
In C/C++ and pretty much every language, if and while encapsulate blocks of code that will only be executed if a condition is true. Explicitly putting an == true into your condition statement is redundant but some programmers prefer it; it's basically a style choice and will not affect the behaviour or speed of your program.
They both are same. The language implements the conditions as follows:
When it encounters the if statement, please check whether the condition is true.
Now, when we say this, it obviously allows you to do == , which
the compiler/interpreter will deal it by saying, are the data types or value
equal? If yes then proceed further.
Refer the flowchart
The piece of code:
bool c_plus_plus_is_cool(){
return true;
}
int main(){
if (c_plus_plus_is_cool()) {
cout << "C++ is cool!";
}
return 0;
}
is same as:
int main(){
if (c_plus_plus_is_cool() == true) {
cout << "C++ is cool!";
}
return 0;
}
No difference when == true is in if or while (or something similar like for or ternary operator), especially if the left value is already of type bool, and in your case it is.
If you need to explicitly convert a value to bool, plain explicit conversion (bool(expr)) looks much better.
THE ONLY case when that strange comparison is reasonable is when the value on the left of == belongs to a class that has a comparison operator taking bool as a second argument (though that generally means bad design:)). But it is not the case, so, to my mind, such coding convention is absolutely useless and rather ugly.
The second one is a bad habit that will give wrong answers in other contexts:
int f() {
return 3;
}
if (f() == true)
std::cout << "Won't get here\n";
if (f())
std::cout << "Will get here\n";
In python, you can do
if(a!=b!=c)
How can you do the same thing in Java without having to separate them and write all the "&&" operators? I'm trying to check that all 10 elements are not equal, and I don't want to have to write the equality statement 45 times.
You cannot do that operation in Java. Note furthermore that if a, b, etc., are not primitives, then you should probably be using equals instead of == (or !=). The latter only check for object identity, not equality of values.
If you want to check whether 10 elements are all distinct, you can throw them into a Set implementation (such as HashSet) and check that the set contains 10 elements. Or better (thanks to #allonhadaya for the comment), check that each element was added. Here's a generic method that works for an arbitrary number of objects of arbitrary type:
public static <T> boolean areDistinct(T... elements) {
Set<T> set = new HashSet<T>();
for (T element : elements) {
if (!set.add(element)) {
return false;
}
}
return true;
}
If your elements are primitives (e.g., int), then you can write a non-generic version for the specific type.
Something wrong in your program, if you need to compare 45 variables.
Try to use arrays and cycles.
There's no such option in java (you cannot do such thing without using &&). Java is not Python
Honestly, no, there's no native way to do this in Java.
But, why don't we implement the syntactic sugar for Python's all method instead? With varargs, it's not difficult. It does have an O(n) runtime cost, though.
public static boolean all(Boolean... theBools) {
Boolean result = Boolean.TRUE;
for(Boolean b : theBools) {
if(null == b || !b) {
result = Boolean.FALSE;
break;
}
}
return result;
}
You can use it then like this:
if(YourClass.all(a, b, c, d, e, f, g, h, i, j)) {
// something to do if ALL of them are true
}
I agree that Set is probably the most efficient solution, but if you need to supply some kind of customization to the comparison, you could use something like...
Comparable[] values = new Comparable[]{1, 2, 3, 4, 5};
boolean matches = true;
for (int outter = 0; outter < values.length; outter++) {
for (int inner = outter + 1; inner < values.length; inner++) {
matches &= values[outter].compareTo(values[inner]) == 0;
}
}
System.out.println(matches);
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Integer wrapper class and == operator - where is behavior specified?
I known Java integer use cache in -127~128.
If
Integer i = 1;
Integer j = 1;
Integer m = 128;
Integer n = 128;
i == j // true
m == n // false
But I met a strange phenomenon.First,look at following snippet.
List<CustomerNotice> customerNotice = findByExample(example); // use Hibernate findByExample method
for(CustomerNotice n : customerNotice){
if(n.getConfirmStatus() == NoticeConfirmStatus.UNCONFIRMED.getValue()){
// do sth
}
}
public enum NoticeConfirmStatus{
UNCONFIRMED(1), //
CONFIRMED(2), //
FAILED_TO_CONFIRM(3); //
private final Integer value;
private NoticeConfirmStatus(Integer value) {
this.value = value;
}
public Integer getValue() {
return this.value;
}
}
public class CustomerNotice {
#Column(name = "CONFIRM_STATUS")
private Integer confirmStatus;
public Integer getConfirmStatus() {
return this.confirmStatus;
}
public void setConfirmStatus(Integer confirmStatus) {
this.confirmStatus = confirmStatus;
}
}
Although the if expression is not recommended, I think it will be return true,because n.getConfirmStatus()==1, but the result is false.I'm very confusing.
In addition, theList<CustomerNotice> customerNotice acquired by Hibernate findByExample method. Is there some Autoboxing or new operation when retrieve the resultset?
Thank you.
SHORT: (answers question)
If you want to compare Integers as the objects, you should use .equals:
i.equals(j);
m.equals(n);
With this, they should both return true. But if you really want to use ==, you need to get the primitive int value:
i.intValue() == j.intValue();
m.intValue() == j.intValue();
LONG: (explains answer)
The basis of this is that Objects are always stored separately in memory (except for some special cases like m=n), and to be compared properly, they need to be broken down into primitive types that can be compared successfully using ==.
Every Object has a .equals() method, which is inherited from Object as its superclass. However, it must be overridden to do a proper comparison. Integer overrides this method to compare to Integer objects successfully, while using == checks to see if both objects point to the same space in memory, and because two instances of an Object cannot point to the same space in memory, this will always return false.
However, as your code points out, there are some special cases that work, like these:
Your code uses a Integer i = 1, which is considered a "standard instance" and is able to be compared using ==.
If you set one Object equal to another using =, Java tells both objects to point to the same location in memory, which means that == will return true.
There are many others, but those are the two that come to mind and seem relevant.
You'll drive yourself crazy and waste a lot of time trying to figure out specific cases where this works or does not work. It depends on the implementation of code which isn't always visible to you.
The bottom line: never, ever, use == to compare Integer instances, period. As you have seen, it works sometimes, under some circumstances, and fails miserably the rest of the time. If you have a method that returns an Integer, then assign the value to an int, and then you can use == to compare that int to another int.
the question is simple, there is a functional equivalent of the famous iif in java?
For example:
IIf (vData = "S", True, False)
Thanks in advance.
vData.equals("S") ? true : false
or in this particular case obviously one could just write
vData.equals("S")
Yeah, the ternary op ? :
vData.equals("S") ? true : false
The main difference between the Java ternary operator and IIf is that IIf evaluates both the returned value and the unreturned value, while the ternary operator short-circuits and evaluates only the value returned. If there are side-effects to the evaluation, the two are not equivalent.
You can, of course, reimplement IIf as a static Java method. In that case, both parameters will be evaluated at call time, just as with IIf. But there is no builtin Java language feature that equates exactly to IIf.
public static <T> T iif(boolean test, T ifTrue, T ifFalse) {
return test ? ifTrue : ifFalse;
}
(Note that the ifTrue and ifFalse arguments must be of the same type in Java, either using the ternary operator or using this generic alternative.)
if is the same as the logical iff.
boolean result;
if (vData.equals("S"))
result = true;
else
result = false;
or
boolean result = vData.equals("S") ? true : false;
or
boolean result = vData.equals("S");
EDIT: However its quite likely you don't need a variable instead you can act on the result. e.g.
if (vData.equals("S")) {
// do something
} else {
// do something else
}
BTW it may be considered good practice to use
if ("S".equals(vData)) {
The difference being that is vData is null the first example will throw an exception whereas the second will be false. You should ask yourself which would you prefer to happen.
I know that we cant use assignment operator in if statements in java as we use in any other few languages.
that is
int a;
if(a = 1) { }
will give a compilation error.
but the following code works fine, how?
boolean b;
if(b = true) { }
EDIT : Is this the exception to rule that assignment cant be used in if statement.
Because the "result" of an assignment is the value assigned... so it's still a boolean expression in the second case. if expressions require the condition to be a boolean expression, which is satisfied by the second but not the first. Effectively, your two snippets are:
int a;
a = 1;
if (a) { }
and
boolean b;
b = true;
if (b) { }
Is it clear from that expansion that the second version will compile but not the first?
This is one reason not to do comparisons with true and false directly. So I would always just write if (b) instead of if (b == true) and if (!b) instead of if (b == false). You still get into problems with if (b == c) when b and c are boolean variables, admittedly - a typo there can cause an issue. I can't say it's ever happened to me though.
EDIT: Responding to your edit - assignments of all kinds can be used in if statements - and while loops etc, so long as the overall condition expression is boolean. For example, you might have:
String line;
while ((line = reader.readLine()) != null)
{
// Do something with a line
}
While I usually avoid side-effects in conditions, this particular idiom is often useful for the example shown above, or using InputStream.read. Basically it's "while the value I read is useful, use it."
For if you need an expression that evaluates to boolean. b = true evalueates to boolean but a = 1 evaluates to int as assignments always evaluate to the assigned values.
The reason the second code works okay is because it is assigning 'b' the value of true, and then comparing to see if b is true or false. The reason you can do this is because you can do assignment operators inside an if statement, AND you can compare against a boolean by itself. It would be the same as doing if(true).
In java, you don't have implicit casting. So non-boolean values or not automatically transformed to booleans.
In the first case, the result of the statements is an int, which is non-boolean, which will not work. The last case, the result is boolean, which can be evaluated in an if-statement.
The rule is not that "assignment can't be used in an if statement", but that "the condition in an if statement must be of type boolean". An assignment expression produces a value of the type being assigned, so Java only permits assignment in an if statement if you're assigning a boolean value.
This is a good reason why the style if (foo == true) should be avoided, and instead simply write if (foo).