SEARCH W7R

Friday, January 06, 2012

Java Syntax: == V.S. equals()

In java there are two main ways of determining if two variables are equivalent, but they do not work in the same way. You may now be wondering, what is the difference? Let's start with the "==" (equals-equals or double equals).

CODE:
//the code expresses a correct use of "==". (comparing two integers)
int numDogs=5; //number of dogs someone has if(numDogs==1){    System.out.println("You have 1 dog like Brian"); } else if(numDogs==0){    System.out.println("You have no dogs? That is o.k!"); } else if(numDogs>2){    System.out.println("Wow, you have a lot of dogs!"); }
The two integers being compared are 5 and 1. (1st IF condition)
The two integers being compared are 5 and 0 (2nd IF condition)


The double equals ("==") is used to compare PRIMITIVE DATA TYPES. Primitive data types include: 
int, double, float, long, char, array (int[]  or double[] ect.)


Primative data types DO NOT include:
String, ArrayList, List, Line, ect. 


If you are familiar with java you may recognize that the NON-primitive data types are (class) instance variables. Classes are more intricate than primitive variables because they contain a combination of primitive variablex embedded into one body, the class.

If you needed to compare two different instances (an instance variable is a single copy of a class, think of them as variables), you would need to use....
The equals()


Example CODE: (Strings are instances of the String class)
String name1 = "Tommy";
String name2 = "Jason";
String name3 = "Tommy";
if(name1.equals(name2)){
   System.out.println("name1 and name2 are the same name.");
} else if(name1.equals(name3)){
   System.out.println("name1 and name3 are the same name.");

}
"name1  and name3 are the same name" would be printed to the console.



Example of misuse of "==" (BELOW) : Using "==" with Strings and other instances of classes 


CODE:
String name1 = "Tommy";
String name2 = "Jason";
if(name1==(name2)){
   System.out.println("name1 and name2 are the same name.");
} 
The print statement should not be printed. The intention was to compare the two Strings (instances of String class), but instead you just checked if the instance was of the same class.
"==" can be used with instance variables (classes) to compare whether they are instances of the same class (such as two Strings like in the last example). Or "==" can determine the equivalence of two primitive data types, such as integers (such as in first example)

No comments: