Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Data Structures Exploring the Java Collection Framework Maps

Broderic Crowe
Broderic Crowe
1,549 Points

= vs ==

Why does Craig assign the variable "count" to 0 with a single '='?

Example:

Integer count = 0; 

//more correct than?

Integer count == 0; 

I guess you could say I'm a little bit confused with which equals sign to use! Some clarity or examples would be sweet!

Broderic

3 Answers

In Java the '=' operator is used in assignment statements to set whatever is on the right side of the equals side as the value of whatever is on the left side of the equals sign.

An example of this would be assigning a value of "Bread" to a variable called "food" like below.

String food = "Bread";

On the contrary, the '==' operator is used to check the equality between whatever is on the left and right of it. This could be used, for example, in a conditional statement like an if statement.

if(food == "Bread") {
    //Random Code Goes Here!
}

I hope that this helped you out and I hope you are having a great day!

-Luke

Grigorij Schleifer
Grigorij Schleifer
10,364 Points

The “==” operator is actually checking to see if the an objects refer to the exact same memory location.

With the the "=" operator you assign an integer to the variable count.

Why Craig is doing == .... I have no clue ... :)

Rohit Tolawat
Rohit Tolawat
8,277 Points

Hello All, Some clarifications: Craig had done this in some of his examples, return x == 10; // Assuming x as an integer x == 10 checks the value of the variable x and compares it with 10. Returns true or false. The return type here is boolean.

return x = 10; // Assigns x to 10 Here, the return type would be integer.
In conclusion, = implies assignment ( From Right to Left) == checks for equality of values (It is a relational operator)