= and == difference in If statement Java - java

I am facing something strange here. Please help me understand if I am missing something. My if condition was supposed to be:
if(configuredPdf == true)
But by mistake I had written:
if(configuredPdf = true)
And my Eclipse compiler does not ask me to correct it. Then I assume there is no compile time or checked exception. So:
(configuredPdf = true)
Returns a boolean?

Yes, configuredPdf = true assigns true to your variable and returns true. Therefore if (configuredPdf = true) is a valid syntax even though it's usually a bug.
It's safer to use if (configuredPdf) to avoid this kind of typo.

An assignment is an expression which returns the value you assigned. e.g. a = b = true will assign true to a and b.
The reason boolean type was added was to avoid this sort of bug. In C for example you can write
if (a = 1)
and anything non-negative is true.
While you can still make a mistake with boolean types, instead of writing
if (a == true)
if (b == false)
you can write
if (a)
if (!b)
A more common example is
for(String line; ((line = br.readLine()) != null;) {
// process the line.
}

An assignment expression's result is always the value that was assigned, including when assigning to a boolean. This is covered by JLS§15.26:
At run time, the result of the assignment expression is the value of the variable after the assignment has occurred.
So yes, configuredPdf = true assigns true to configuredPdf, and the result of that expression is true.
Similarly, x = y = 5; assigns 5 to y, and the result of y = 5 is 5, which is then assigned to x.
Fundamentally, what you wanted was:
if (configuredPdf)
There's never any need to compare a boolean variable with true or false, just use the if (theVariable) (for comparing with true) or if (!theVariable) (for comparing with false). Getting in that habit will protect you from inadvertent assignment.
The only time actually comparing boolean values is useful is when they're both variables, e.g. if (thisFlag == thatFlag) or if (thisFlag != thatFlag).
To avoid accidental assignment in that situation, either:
Use a linter that checks for this
"double bang" the first flag:
if (!!thisFlag == thatFlag)
...although as you pointed out if you can accidentally type = instead of ==, presumably you can accidentally type ! instead of !! :-)
Use an old C idiom (this is what I use):
if (!thisFlag == !thatFlag)

What is happening is when the compiler comes to the if condition in your code, it assigns 'configuredpdf' to be true. Thus the condition
if(configuredpdf = true)
Becomes true and the loop executes successfully. However, the problem arises when we DON'T want this loop to be true. At that time when, for a given input, the compiler parses the if condition, it forcibly becomes true and executes the code written in if condition executes even if the data entered does not agreeing. That is why you will find that your code has a bug at the if condition.

configuredPdf must be a boolean for if(configuredPdf = true) to compile.
configuredPdf = true will assign true to configuredPdf and thus if will succeed.

Related

Comparing an int initialization with a boolean operator for an if statement parameter

I've declared ints skyB and day, and written this line:
if (skyB == true || (day=1) != true) {
System.out.print("example text");
}
Am I correct in assuming that the code will properly execute the argument given these parameters? I'm specifically unsure about whether or not the (day="1") would be properly detected as false, given the instance that the objects input was indeed a false.
minimal reproducable example(not including main method or packages):
int skyB = false;
int day =2;
if (skyB == true || (day =1) != true) {
System.out.print("example text"); }
The simple answer: this isn't C++
You cannot assign numeric value to boolean fields. In Java, the only two valid values are true and false. Therefore, you cannot assign integer values to a boolean variable.
For your boolean expressions to be valid, your variables skyB and day must be boolean data types
boolean skyB = false
boolean day = true
if (!skyB || day) {
System.out.print("example text");
}
The boolean fields are evaluated without the need to compare them to true or false. The expression !skyB (read "not skyB") evaluates to false. So this is the equivalent to skyB == false. Since that portion evaluates to true (skyB is equal to false), the second part of the expression is skipped and the System.out.print() is called. If the value of skyB was changed to true, the variable day would then be evaluated and the if-statement would be executed if the value of that variable equals true (which it is).
Alternatively, you could build boolean expressions using numeric values. How? Simple. Any mathematical expression is evaluated the same. For example:
int x = 5;
int y = 3;
if (x > y) {
System.out.println("x is greater than y");
}
Basically... The logic of what you are trying to do (the way I understood it) is correct, but your implementation was not. You cannnot mix boolean fields and numeric values. It is simply not allowed in Java.
Now, to your question...
boolean skyB = false; // this must be boolean, not int
int day =2; // this is fine
if (skyB || day == 1) {
System.out.print("example text");
}
Should produce the desired outcome. In plain English, the above is read:
If skyB is false OR is day one, print "example test"
If either part of the expression fails to evaluate to true (i.e. if skyB is true and day variable is any value other than one), it will not print anything.
UPDATE:
Even if this answer has been accepted and upvoted, I would like to include some information about boolean expressions for the benefit of new developers that might be struggling with this concept.
What is a Boolean Expression?
According to Oracle documentation, "A Boolean expression is a logical statement that is either TRUE or FALSE." These expressions take a few different forms. For example,
Boolean literals
if (true) {...}
Although there is no real reason for such if-statement, the above is a valid expression. "If true, do the stuff inside the curly braces." This means that the stuff inside will always execute (making it the same as not having the "if". However, this is the basis for understanding the rest.
Boolean variables
boolean isBlue = false;
if (isBlue) {...}
In the above case, the Boolean expression is the variable itself. The expectation is that, if the variable value evaluates to true, the stuff inside the curly braces will be executed. Since the value is false, it won't be executed. The above "if" is the more accepted short form of
boolean isBlue = false;
if (isBlue == true) {...}
So, since the left hand (variable) value of this evaluation is false and the right side is true, the complete expression evaluates to false. Therefore, the stuff inside curly braces won't be executed (false does not equals true). However
boolean isBlue = false;
if(!isBlue == true){...}
Negating a boolean variable toggles it's value. In this case, the isBlue variable holds the value of false. The "not" operator toggles its value to true. Since true == true evaluates to true (true equals true is a true expression), the stuff inside curly braces is executed.
Functions that yield a boolean value
public boolean isSkyBlue() {
return true; // sorry for the over simplification
}
...
if (isSkyBlue()) {...}
This is nothing more than an advance form of what I have shown already. In this case, the method "computes" the boolean value to be returned. Since boolean values are expressions onto themselves, it is valid to insert a method call such as the one illustrated above inside the parentheses. The stuff inside curly braces will execute so long the function returns true.
Comparison operations
I included the following example already:
int x = 5;
int y = 3;
if (x > y) {
System.out.println("x is greater than y");
}
Any type of comparison operation will yield true or false. Therefore, these comparison operations are boolean expressions. This also includes the result of overridden Object#equals(Object) method. For example:
String s = "Hello";
if (s.equals("Hello")) {...}
As a side note, objects in Java should be compared using an overridden equals() method, and not using the double-equals operator (unless you are only interested in comparing the object references (address) to be equal.

Resultset.getBoolean()) not returning true for if condition - row has value

Resultset.getBoolean()) not returning true, when value is there.
I'm trying to use a if condition so if there is row value in "fldplayersalary" then enter condition, however it keeps going to else. I have put a breakpoint and there is value for fldplayersalary (15583 for example).
Can someone explain why the .getBoolean is not returning true, because there is definitely a field "fldplayersalary" in table and data also. I've attached a screenshot of MySQL database
image of sql table
ResultSet r = stm.executeQuery("select * from tblmember");
//1-int,2-string,3-string,
while(r.next())
{
if(r.getBoolean("fldplayersalary") == true)
{
System.out.println("Player - 11 fields");
int id = r.getInt("fldmemberid");
String first = r.getString("fldfirstname");
String last = r.getString("fldlastname");
String email = r.getString("fldemail");
String mob = r.getString("fldmobile");
String gender = r.getString("fldgender");
String dob = r.getString("flddob");
String debut = r.getString("flddebut");
String recruited = r.getString("fldrecruitedfrom");
int salary = r.getInt("fldplayersalary");
int team = r.getInt("fldteamid");
Player pp = new Player(id, first, last, email, mob, gender, dob, debut, recruited, salary, team);
plist.add(pp);
}
.getBoolean is for reading boolean values, hence the name.
You seem to believe that the concept of truthy/falsy is universal. It isn't. First, adjust your thinking, then this becomes much simpler.
'truthy'/'falsy' is the notion that all expressions, if forcibly interpreted as a boolean, always report one of those two values. Many programming languages and environments are completely truthy/falsy, such as javascript and python.
However, java is not. In java, true is true, false is false, and nothing else is:
String x = "true";
if (x) {}
simply fails to compile in java, as x is neither the boolean value true nor the boolean value false (specifically, the type of the expression x isn't boolean, and the compiler immediately calls it at that point and flags an error). You appear to be so used to languages that have this complicated definition of what is considered 'true' (truthy) and what is considered 'false' (falsy), such as 'lists are truthy unless empty, null and undefined are falsy, numbers are truthy unless 0 or NaN, strings are truthy unless empty, nobody can remember if the string "false" or "0" is truthy or falsy, objects are truthy unless they override an operator method to say they are falsy, even a boolean wrapper wrapping the value 'false' ends up being truthy because of that, yadayada'. Hopefully you now also know why truthy/falsy is not universally applied: It's quite confusing at times. Java doesn't engage in it; java doesn't ever guess what you intended when you pass a non-boolean to a thing where only booleans are allowed. It just errors and demands you perform an operation that explicitly resolves to a boolean value, such as a < b or a.foo() where foo() has boolean as return type, etc.
Now that you know such systems exist, it should be obvious that the meaning of getBoolean is not 'act like python or javascript and do the usual: if null or 0 or empty or (yeah this is where truthy/falsy gets tricky doesnt it? Is the string "Non" falsy?)'.
What you're presumably looking for is either:
if (r.isNull("fldplayersalary")) {
or possibly:
if (r.getInt("fldplayersalary") != 0) {
Note that .getInt returns 0 if the value stored for that row is NULL, hence, if fldplayersalary is NULL, or it is set to 0, that if would not trigger, otherwise, it would, which sounds like what you wanted.

Why does java require a double equals sign?

Why does java require a double equals sign (==) when comparing Integers in a if statement?
For example
if(x = 3.141)
System.out.println("x is equal to pi.");
is incorrect, it should be
if(x == 3.141)
System.out.println("x is equal to pi.");
I know that "==" is used to compare integers and "=" is used to set an integer value, but why in a if statement does this remain true?
Is it even allowed to assign a variable a value in an if statement (or initiate a new variable)?
Is there any reason anyone would ever want to assign a variable a new value inside an if statement (if so please provide an example)?
This seems like a question that should already have an answer, but I was unable to find one on here or using google, if this is a duplicate question please tell me and I will remove it immediately.
Wouldn't it be confusing if = sometimes did assignment, and sometimes comparison, depending in which context you used it?
That sounds like a bad idea, and would introduce errors.
Plus, the current syntax is compatible with C and C++, so a lot of people are familiar with it.
Is there any reason anyone would ever want to assine a variable a new value inside of an if statement (if so please provide an example)?
It's quite common in while loops:
int b;
while ((b=in.read()) != -1){
=
is used for assignment.
==
is used for comparison.
Is it even allowed to assign a variable a value in an if statement (or initiate a new variable)?
yes it is allowed.
Note what error message you get for if (x = 3.141); it is a type error (cannot convert from double to boolean).
The assignment's type is the type of its both sides; if the type of the assignment is boolean (if (x = true), or even if (x = a.equals(b))), then it is legal to write.
So since it is legal to assign a value to a boolean in the condition, you'd have to use == for comparison.
Is it even allowed to assine a variable a value in an if statement (or initiate a new variable)?
Yes. A common idiom for doing this is:
String line = null;
while ( (line = in.readLine()) != null ) {
// do work
}
In the loop, line is assigned a value and then compared to null. I can't think of an example with ints; it certainly wouldn't be clear there.
History of programming languages 101:
Fortran uses = for both.
Algol introduced := for assignment and used = for comparison. This was required to resolve a grammar ambiguity.
Pascal followed suit.
PL/1 did not.
I can't speak for B or BCPL but by the time we got C it was = for assignment and == for comparison, again to resolve a grammar ambiguity
C++ followed C
Java followed C++ in many respects including this one.
The grammar ambiguity arises because of allowing assignments in expressions. Contrary to your assertion, if (x = true) is legal in Java if x is of type boolean.
== is the identity comparator, which works for both objects and primitives. It answers the question "are the two things the same thing".
= is the assignment operator. It sets the value of the left side to the right side.
Things can turn buggy when using your example with booleans:
boolean b;
if (b = true) // This compiles, but is a bug, because it sets b, not tests it
While other types won't compile with this syntax, boolean and Boolean do, so that's why the following pattern is advised:
if (b)
you can absolutely assign a variable in an if statement. also, that's just the way it works: = always is assignment, and == is always comparison.
So..
= is assignment, and == is comparison, and it is always like this, no matter where they are used.
And assignment is different with "declaration". An assignment statement has its return value, while a declaration doesn't. So you can't write boolean a = false in the () of if statement, but you can write a = false when a has been declared before.
Not all assignments are legal. For example:
int index;
if (index = str.indexOf("something")) {
...
}
It's not legal, because String.indexOf(String) returns an int, while if requires a boolean.
Also, there is a huge difference between "legal" and "making sense".
int index;
if ((index = str.indexOf("something")) != -1) {
...
}
It is legal, as != operation returns a boolean, and it makes sense, as I do want to check if the str contains a substring "something";
However,
int index;
boolean flag;
if ( flag = ((index = str.indexOf("something")) != -1) ) {
...
}
is also legal, as the statement as last returns a boolean; but it DOESN'T make sense, because the != statement already returns a boolean.

Why does my if condition not accept an integer in java?

Currently I'm using:
int a=10;
if(a=20)
printf("TRUE");
else
printf("false");
Which prints, in C, the value TRUE.
But in case of java:
int a=10;
if(a=20)
System.out.println("TRUE");
else
System.out.println("FALSE");
I'll get a compile time error about an incompatible type.
The reason for that is that in C there is no specific type boolean - instead any non-0 integer evaluates to a boolean "true". Thus in your C code:
if(a=20)
a is assigned the value 20, which is non-0 - and the condition is evaluated as true
In java, there's a fundamental type boolean and the value of the conditional inside if must be of this type.
a=20
in Java assigns 20 to a and returns the final result of evaluation as integer value 20, however type boolean is expected - hence you're getting a compile-time error about the incompatible types.
If you want to do a comparison of a with 20, however, you need to use == operator both in C and Java:
if(a == 20)
This will compile in both C and Java and print FALSE in both languages.
You need to replace = with ==.
= is an assignment operator
int a=10;
if(a==20){
System.out.println("TRUE");}
else{
System.out.println("FALSE");}
This should work fine.
Edit:
In C, the returned integer value of the assignment (in this case 20) is a positive int, which evaluates to true.
In java, a boolean is expected.
(See the more thorough answer provided by Aleks G)
A single = is an assignment. If you want to test for equality, you use the double == in both C and Java.
It should be evident that you're doing the wrong thing, even in the C version, since you set a to 10 and then, on "comparing" it to 20, you get a true value. I'm not aware of any mathematical systems where 10 and 20 are considered equal :-)
What happens in your C case is that the assignment actually "returns" a value as well.
The statement:
if (a = 20) ...
is equivalent to:
a = 20;
if (a) ...
so it first sets a to 20, then uses that as the if condition. Since 0 is false and anything else is true, the body of the if is executed.
A good compiler (like gcc) will actually warn you of what you're doing so that you don't get caught out by these little things. Some people also use the trick of putting constants first:
if (20 == a) ...
so that, if you mistakenly use assignment, it's a syntax error. But I find that sort of code ugly, especially since I mostly use those good compilers mentioned above :-)
The reason you get an error in Java is because it's much more strict on what you can do with assignments. By that, I mean there is no automatic conversion from int to boolean as with C. So this code refuses to compile, producing an error:
class Test {
static public void main(String[] args) {
int a = 10;
if (a = 20)
System.out.println ("true");
}
}
But you can still get burnt with something like this:
class Test {
static public void main(String[] args) {
boolean a = false;
if (a = true)
System.out.println ("true");
}
}
Because that assignment is of a boolean value inside the if, it doesn't cause a compilation error due to the wrong type. However, since it prints true, it's still not what you wanted.
Bottom line, go back an re-read that first paragraph. = is assignment, == is equality checking.
Use the == to test the condition instead of =. That way, you are assigning 20 to a and not testing for a condition.
if (a==20) ... or
System.out.println(a==20);
value of a=20 is 20. You should use == operator.
for comparison you should use ==
if(a==20) instead of a=20, which is assignment

"Invalid assignment" error from == operator

I was trying to write a simple method:
boolean validate(MyObject o)
{
// propertyA && propertyB are not primitive types.
return o.getPropertyA() == null && o.getPropertyB() == null;
}
And got a strange error on the == null part:
Syntax error on token ==. Invalid
assignment operator.
Maybe my Java is rusty after a season in PLSQL. So I tried a simpler example:
Integer i = 4;
i == null;
// compile error: Syntax error on token ==. Invalid assignment operator.
Integer i2 = 4;
if (i == null); //No problem
How can this be?
I'm using jdk160_05.
To clarify: I'm not trying to assign anything, just do an && operation between two boolean values. I don't want to do this:
if (o.propertyA() == null && o.propertyB() == null) { return true; }
else { return false; }
== is not an assignment operator, it's a boolean equality operator, see:
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.21.2
If you want to set i to null use the simple assignment operator =:
i = null;
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.26.1
If you want to check that i is null then you need to use the == operator
if (i == null)
I don't think you are confusing assignment and equality comparison. I think your compiler is just giving you a confusing error message. This program:
Integer i = 4;
i ==null;
should give an error something like this:
Program.java:8: not a statement
i ==null;
Your first program should compile correctly. Perhaps there is some invisible unicode character in the text that is confusing the compiler. Try deleting the entire function and typing it in again.
I think I see your problem. I'm sorry the other answers don't address it.
So, Java has this idea that is shared by some other languages that just because something is a valid expression doesn't mean that that thing, by itself, is a valid statement.
For example, this code will complain similarly:
Integer i = 4;
i+3; // this line gives a compilation error
And yet obviously I can use i+3 (go unboxing!) elsewhere to mean "7":
System.out.println(i+3); // this is fine
It gets a bit confusing because unlike some languages that have this expression/statement distinction, java allows you to use any method call - whether it returns a value or not - as a statement. However, most java operators do not - by themselves - form a valid statement.
Likewise, this fails to compile:
Integer i = 4;
i; // this line gives a compilation error
For the full gory details, see http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#32588
In PL/SQL, assigning a value to a variable is done with the := operator. Comparing two values is done with =.
In Java, assigning a value to a variable is done with the = operator. Comparing two values is done with ==, or a .equals() method in some cases.
You can do things like this:
x = i==null;
This will test if i is null and if so, the value true will be assigned to x (assuming that x is a boolean).

Categories