Some remarks about Java

Posted Thursday, September 21, 2006

Filed under: ,

I was told that Java was a strict and robust language. I found some inconsistencies and awkward behaviours...

For instance, getting the length from an array and a string are slightly different:
array.length() //array.length is a property
string.length //string.length is a method

I haven't used this much yet, but the passing of arguments to a function by reference or value is... let's say surprising.
Passing by reference : funtionName(String args[]) {...
Passing by value : funtionName(String[] args) {...

I also had trouble comparing strings. I wanted to be able to perform an action when the user entered "o" (as a string).
When printed to the console, my user-entered string had a length of exactly one and contained the character "o". No wacky \n or \r remained, all was fine and dandy yet this was evaluated as false.
The solution was to compare the first character.
if (myString == "o") //returns false even when myString = "o"
if (myString.charAt(0) == 'o') //returns true

Weird huh?

What took me some time to grok was that dividing two integers and storing the resulting value in a float returned 0.
To get the appropriate result, one has to use on-the-fly typecasting.
int a = 5, b = 2;
float c = a/b; //c = 2.0
float c = (float) a / (float) b; //c = 2.5

Who will, in the light of these code samples, affirm unwaveringly that Java doesn't have it's own quirks?

Comments disabled because of spammers.

No comments yet

Technorati Profile