sophiekoonin / JavaDecaf

A Compiler for JavaDecaf - MSc Computer Science project 2015
0 stars 1 forks source link

In Java Decaf, == should be good to compare Strings #21

Open sergutsan opened 8 years ago

sergutsan commented 8 years ago

In Java,the == operator is not good to compare String as it only operates on simple types: primitives and pointers. Objects must be compared using .equals(), which may or may not be equivalent to comparing the pointers with == depending on the case.

In the particular case of String, which is an immutable class since Java 2, this means that == and .equals() are sometimes equivalent and sometimes not in a way that is quite confusing, especially for novices.

s1 = "Some string";
s2 = s1
s3 = new String("Some string");
s4 = "Some string";
s5 = new String(s1);

In this example, all strings are equal in the .equals() sense but not in the == sense.

It would be great if Java Decaf could hide this complexity from learners until they have some understanding of data types and move on to Java.

sergutsan commented 8 years ago

So the goal would be to detect when == is comparing two Strings and change it for .equals.

If it makes it easier, changing == for .equals() for all objects is probably OK too, not only Strings (but ideally, only Strings).