I was chatting with a professor (mentor and friend) from my University in Honduras. He was telling me that now the University became a “Javaschool”: a university were programming is taught using Java. This lead me to think of a couple of common mistakes that students might commit, since they don’t understand what is happening behind the scenes. Here is an example:
String patito = “javaschool”;
if (patito == “javaschool”){
//will never enter here
}
if (patito.equals(“javaschool”)){
//always enter here
}
The difference between using a == and equals method is that the operators == compares references to the object. Since “javaschool” is an object (even if you may see it as a value), it doesn’t reference the same object as patito. That is why the first if is always false. To compare or find out, if a String object has the value “javashool”, they will need to use the method equals.
They will make the above mistake, due to them learning to program using primitives like boolean, int, double, float, etc. Which is natural to conclude that everything in Java, works like comparing primitives, when is not the case.
int x = 90;
if (x == 90){
//woohoo! we are in
}
In the above example, int is not an object, but a primitive. A primitive is just a block of memory, no methods or others stuff. Just the value and a way to reference that block in memory containing the value.
If you need to read more about equals and == in Java, I recommend you go here. And if you want to read more about primitives, you can go here.
A personal blog where I write about my current projects, work and interests. The posts are a reflection on my current self, varying over time, since change is the only constant.
Welcome to G To The Square, my thoughts on ICT, Business and Life... in a Square.