Why does my if condition not accept an integer in java? - 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

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.

= and == difference in If statement 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.

Java: boolean in println (boolean ? "print true":"print false") [duplicate]

This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 9 years ago.
I came across this syntax:
System.out.println(boolean_variable ? "print true": "print false");
What is this syntax with two dots : called?
Where can I find info about it?
Does it work just for booleans or is it implemented in other different ways?
? : is the conditional operator. (It's not just the : part - the whole of the method argument is one usage of the conditional operator in your example.)
It's often called the ternary operator, but that's just an aspect of its nature - having three operands - rather than its name. If another ternary operator is ever introduced into Java, the term will become ambiguous. It's called the conditional operator because it has a condition (the first operand) which then determines which of the other two operands is evaluated.
The first operand is evaluated, and then either the second or the third operand is evaluated based on whether the first operand is true or false... and that ends up as the result of the operator.
So something like this:
int x = condition() ? result1() : result2();
is roughly equivalent to:
int x;
if (condition()) {
x = result1();
} else {
x = result2();
}
It's important that it doesn't evaluate the other operand. So for example, this is fine:
String text = getSomeStringReferenceWhichMightBeNull();
int usefulCharacters = text == null ? 0 : text.length();
It's the conditional operator, often called ternary operator because it has 3 operands: An example would be:
int foo = 10;
int bar = foo > 5 ? 1 : 2; // will be 1
int baz = foo > 15 ? 3 : 4; // will be 4
So, if the boolean expression evaluates to true, it will return the first value (before the colon), else the second value (after the colon).
You can read the specifics in the Java Language Specification, Chapter 15.25 Conditional Operator ?
It's a ternary operator, meaning that instead of having two operands like many other operators, it has three. Wikipedia on Ternary Operation and how it's used in Java. What it boils down to: the boolean operation (or just a variable) is evaluated. If it evaluates to true, the operator returns the value / executes the code before the :, otherwise the one after it.
That's an if statement.
What's to the left of ? is the condition, what's between the ? and : is the result if the condition is true, and what's to the right of : is the result if the condition is false.
This is ternary operator (http://en.wikipedia.org/wiki/?:). It can be used anywhere when you need a small if expression.
For your questions:
The ?: (both characters together) are called conditional operator (or ternary operator). Only both together will work.
Search for java ternery operator
It only works for boolean
In principle the ternery operator is a shortened if/else. The boolean will be the condition to the if, the part between ? and : is the if branch and the part after this is the else branch.
Please note that the return type of the conditional operator is determined by the first branch.
It's the ternary operator and it works with booleans. It can be used as a shorthand for if-else in some cases, but shouldn't be used for too complicated things as it can be difficult to read.
An example would be assigning value to a variable depending on a condition:
String message = doOperation() ? "Success" : "Error occurred";
System.out.println(message);
In this case, if doOperation returns a boolean telling whether it succeeded or not, the message to be shown can be assigned on a single line.
Please note that this example does not represent good programming practices.
Its ternary operator.
The ternary operator or ?, is a shorthand if else statement. It can be used to evaluate an expression and return one of two operands depending on the result of the expression.
boolean b = true;
String s = ( b == true ? "True" : "False" );
This will set the value of the String s according to the value of the boolean b. This could be written using an if else statement like this:
boolean b = true;
String s;
if(b == true){
s = "True";
}else{
s = "False";
}
Its a short form of if-else statement.
It works in this way
(yourCondition ? STATEMENT1 : STATEMENT2)
The compiler checks for the condition.
IF it returns TRUE then STATEMENT1 will be executed.
ELSE STATEMENT2 will be executed.
The question mark followed by a colon (two dots) is a ternary operator usually called inline if.
In this case it returns a string depending on the value of boolean_variable.
http://en.wikipedia.org/wiki/%3F:
See here. The ternary operator is similar to an if expression but differs in that it is an expression - it has a return value, while if expressions don't. Sometimes you want to use it to make your code a little less cluttered.

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.

"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