NdVO.blog.br

Learning Java

I'm working on a Java project without any previous experience with it. Here are some things about Java that are not obvious for people comming from other programming languages.

Strings are objects

Not everything in Java is an object. Primitive types aren't. There is no primitive type for strings though. This may seem like a mere curiosity, but it is actually very important. First of all single quotes create chars - a primitive type - while double create strings. Chars are single chars that you can use to build lists of chars. Second, as Strings are objects and the equality operator checks for the memmory address of objects, two String objects will not be interpreted as "==" to each other.

Let me demonstrate this. In Java the following will return False:


      boolean testString(){
        return "Testing" == "Testing";
      }
      

This code would be equivalent to the following PHP code:


      function testString(){
        $first = new stdClass;
        $second = new stdClass;
        $first->text = "test";
        $second->text = "test";
        return $first === $second;
      }
      

As you can see, the contents of the text attribute are simply irrelevant for the return value of the function. The "===" operator in PHP is simply checking if the two objects are the same. That is the same thing the "==" operator does for objects in Java, and strings are objects.