Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does java require a double equals sign?

Tags:

java

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.

like image 448
java Avatar asked May 16 '13 02:05

java


People also ask

Why we use double equal to in Java?

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.

Why are there double equal signs?

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.

What does 2 equal signs mean in Java?

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.

What does == mean in coding Java?

== (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.


2 Answers

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){
like image 155
Thilo Avatar answered Sep 20 '22 05:09

Thilo


= 

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.

like image 29
eyadMhanna Avatar answered Sep 24 '22 05:09

eyadMhanna