Skip navigation

When we use the == operator, we are actually comparing two object references, to see if they point to the same object. We cannot compare, for example, two strings for equality, using the == operator. We must instead use the .equals method, which is a method inherited by all classes from java.lang.Object.

Ex. String Comparison

     String abc = "abc"; String def = "def";

// Bad way if ( (abc + def) == "abcdef" ) { ….. }

 

// Good way if ( (abc + def).equals("abcdef") ) { ..... }

Fortunately, even if you don't spot this one by looking at code on the screen, your compiler will. Most commonly, it will report an error message like this : "Can't convert xxx to boolean", where xxx is a Java type that you're assigning instead of comparing.

Accessing non-static member variables from static methods (such as main)

 

 

public class StaticDemo

      {

        public String my_member_variable = "somedata";

        public static void main (String args[])

        {

        // Access a non-static member from static method

                System.out.println ("This generates a compiler error" +

            my_member_variable );

        }

     }

 

 

 

Mistyping the name of a method when overriding

 

 

If you mistype the name, you're no longer overriding a method - you're creating an entirely new method, but with the same parameter and return type.

Filter Blog