Category Archives: java

A Preference for Flexibility

I came upon this example in an otherwise very good book. One example tried to test a main method by passing arguments:

String[] args = new String[2];
args[0] = "param1";
args[1] = "param2";
MainApplication.main(args);

Whenever I write in this kind of code, I always prefer to create an array instead:

List<String> list = new ArrayList<String>();
list.add("param1");
list.add("param2");
MainApplication.main(list.toArray(new String[list.size()]);

It’s a bit more verbose, but I find it offers a lot more flexibility as adding new parameters is simply a matter of adding a new element to the list. In the first example, adding a new parameter requires two steps : 1) modify the size of the array and 2) initialize an element of the array to the desired value.

I do whatever I can to remove a step, as small as it seems.

Modifying all the indexes is also a lot less fun when you need to add an element at index 0. And of course you’ll eventually copy/paste one line of the array and forget to modify either the size of the array or the index.

Using a list is a small improvement but in the long run, small things make the code a lot more maintainable.

PS : a friend noted that if you already use Google Collections (now Guava), you can get even more elegant code with

list = Lists.newArrayList("param1", "param2")

Dear Java, Please Let Me Work

I had to read the content of a file for a ruby project. This is how I did it:

def read_file_content(filename)
  File.read(filename)
end

Simple enough, right?

Then for some reason I thought about how I would have to the same in Java:

public String readFileContent(String filename) {
  try {
    BufferedReader reader = new BufferedReader(new FileReader(filename));
    StringBuilder buffer = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      buffer.append(line);
    }
    return buffer.toString();
  } catch (IOException e) {
    return "";
  }
}

Need I really explain why I prefer Ruby these days? Even if you remove the try/catch clause and rethrow the exception, that’s still a lot of code compared to a single line of ruby. I am also aware that it is possible to write the same Java code in a single line using Apache’s commons-io (IOUtils.toString(InputStream) – but still, why are the base Java libraries so verbose for file manipulation?

I still like Java, but I’m impress by the compactness of Ruby. It just works as it should. Sometimes working in Java it seems I’m just smashing the keyboard instead of getting actual work done.

Java Brainteasers

I had lunch with a few colleagues yesterday and we started talking about obscure stuff. Among other things we talked about:

  • the initial default size of a hashmap, which is a power of 2 (16) in HashMap but a prime number (11) in Hashtable in java 1.6 (possible explanation, see the ‘Tip’ section)
  • the strictfp keyword, which can be used to ensure that floating point numbers behave the same on all hardware.
  • the volatile keyword, which seems to have a slightly different behavior since 1.5. I did not find anything from Sun about this, but I found some references indicating that something might actually have changed… Basically it seems that writing to a volatile variable synchronizes all cached copies of variables with the main memory, not just the volatile variable itself. I must admit this one was totally new to me.

Anyway that reminded me about Java Puzzlers, a book about obscure features of Java in the form of puzzles. I decided to go through the book again to see if I would gain anything. Although many puzzles show how things can go hairy while using really bad code, a few bits of knowledge can always be useful. Here is a few of the things I learned (or re-learned) while skimming through the book:

Weird behavior of Math.abs
The absolute value is not always positive!
Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE

Unicode considered evil (at least problematic in comments)
Unicode characters in comments can cause problems. Consider the following comment:
/*
Test files are located in \utest\samples
*/

The file will not compile because the java compiler tries to convert \utest to a Unicode character (I saw this in a real project once)

Escape regex
I learned that Pattern.quote() can be used to automatically escape a literal string as a regular expression.
System.out.println(Pattern.quote(".")) will print \Q.\E

This method was added in Java 5.

Recursive array printing
I also learned about the Array.deepToString() method, which can output the content of multi-dimensional arrays. This method was also added in 1.5.
int[][] array = new int[][] {{1, 2, 3}, {4, 5}};

System.out.println(array); => [[I@1ad086a
System.out.println(Arrays.deepToString(array)); => [[1, 2, 3], [4, 5]]

Ternary operator madness
And finally the behavior of the ternary operator (? :) was changed in 1.5. Consider the following statement:
boolean b = true; // or false, doesn't matter
List list = b ? new ArrayList() : new Vector();

In 1.5, the code compiles fine.
In 1.4, I get an error ‘Incompatible conditional operand types ArrayList and Vector‘.
Before 1.5, both values returned by the ternary operator must have a shared ancestor other than Object. In 1.5 the requirement was relaxed – any common ancestor is fine, and since all classes inherit from Object you can return two completely unrelated classes.

Now why would you want to do something like this?
Object o = b ? new ArrayList() : new JButton();

Don’t ask me, I’m just the messenger…