Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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 '='?


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!


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!


Grigorij Schleifer
Grigorij Schleifer
10,365 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)