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.
equals() is a built-in function in java that compares this object to the specified object. The result is true if and only if the argument is not null and is a Double object that contains the same double value as this object. It returns false if both the objects are not same.
In programming, the equals sign (=) is used for equality and copying. For example, if x = 0 means "if X is equal to zero;" however x = 0 means "copy the value zero into the variable X." Double equals signs (==) means equals to in C. For example, if (x == 0) means if X is equal to zero.
Notice that ONE equal sign is used to "assign" a value, but TWO equal signs are used to check to see if numerical values are equal to one another. Relational operators always yield a true or false result.
== (equal to) Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true. != (not equal to) Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With