When are the appropriate times to use double equals signs?
Though they both use "=", "=" and "'==" are completely different and have different meanings.
You use the single = when you're assigning a value to a variable.
means x is assigned the value of 5.
You use double == when you're asking whether a variable is equal to something.
x == 5
means is x equal to 5? It's a yes/no statement also called a boolean. You would use this in an if statement.
if(x==5), do something
means do something if and only if x is equal to exactly five.
It wouldn't make sense to say if(x=5).
while(x=5), do something
means do something while x is equal to five (usually you change the value of x at some point or the loop will go on forever, eventually crashing your page or worse)
Likewise you wouldn't use while (x==5).
== is used to compare the references if you are using strings. Before that you need to know what is string literal and string Object.
In java strings are immutable.
There are two methods of declaring strings:
1) String Literal
2) String object
1)** String Literal:**
String literal is declared like an ordinary java variable.
String s="ABC", s1="ABC"; //String literal
Whenever String literal like s and s1 is declared in an program ,Java Virtual machine (JVM) checks the "String pool", if the content is already resent in the pool then memory is not again allocated for the new string instead of it, reference of the string having same content is returned. So, This optimizes the use of memory.
s ans s1 will point to same memory location.
2) String Object:
String object is one which is declared using new keyword. The above concept is not used with the string objects i.e. even if two string objects have same content then too different memory locations are given them.
String s3=new String("ABC"); //String Object
String s4=new String("ABC");
So, s3 and s4 will occupy different memory locations.
So, now if you do
if(s==s1) // returns true as s and s1 points to same memory location.
but if you do as follows:
returns false as both occupy different memory locations.
For more Details on Java String pool Example Refer following link:
It looks like you're new here. If you want to get involved, click one of these buttons!