简体   繁体   中英

Whats the difference between = and == in java?

我知道==意味着等于,但我无法弄清楚=意味着什么。

A single = is assignment. A value is assigned to a variable.

int a = 1; // <-- assign 1 to a.

JLS-15.26.1. Simple Assignment Operator = says (in part)

A compile-time error occurs if the type of the right-hand operand cannot be converted to the type of the variable by assignment conversion ( §5.2 ).

The == is the equality operator, JLS-15.21. Equality Operators says (in part),

The operators == (equal to) and != (not equal to) are called the equality operators .

= means assignment operator which assigns the value on its right to the operand on its left whereas == (Equal to) means equality check.

Say, you want to assign 1 into a variable i , so you have to write:

i = 1;

But if you want to check whether the value of i is 1 or not, you have to check:

if (i == 1) {
//do something
} else {
// do something else
}

= is the assignment operator. Eg, a = 5 means assigning the value of 5 to the variable a .

the operator "=" assign the value to a certain instance

an operator "==" means a certain instance has a value of something

example

  x = 2; //It means x is 2
  x == 2; //means x has a value of 2

= is the assignment operator which is used to assign a value to a variable, property or fields. While == is used to check a condition for example in a if condition

int houseAddress = 1; 

This means that the variable houseAddress is given the value of 1, so you can think of this as the address of the house is equal to 1;

if(houseAddress == 1){
//do something
}

This code is saying whether houseAddress is equal to 1 this would return TRUE or FALSE in this case we know that houseAddress is 1 so it return TRUE.

Hope this helps its missing a few technical detail which might confuse you so its missed out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM