Symbols

Ruby symbols are so regularly used but are mystic to the amatuer developer. There’re several explanations what they are and how they should be used. To me, they are String constants, whose value is the name of the constant itself. Therefore :something contains the value “something” and cannot be changed.

This is preferred over using “something” in Ruby directly because unlike Java it doesn’t have a String pool and using “something” over and over creates separate String objects in memory. As such, symbols are useful if a particular String is repeatedly used in your application. Now go read again about the confusing stuff about being able to to_i and being an instance of a Symbol class. It should make a little bit more sense.

Ruby on Rails

Its somewhat amusing for me to be working on RoR. First I don’t really know the langauge, even though it OO it’s cryptic enough to a Java programmer. Second I’m literally amused by its syntax, such as:


return true unless read_fragment(name)

when_fragment_expired 'fragname', 20.seconds.from_now do
end

Also things like gem (Ruby, Gem, get is just as clever as the way Java Beans and Jakarta project relate to Java itself. Anyway, here’s a vid to tell you it’s the end of JARs…

http://www.youtube.com/watch?v=PQbuyKUaKFo

IE renders web page bigger than FF

If for an unknown reason your Internet Explorer seems to show things bigger than Firefox, and you’ve checked that it’s not the Text Size, it may be because of your screen DPI settings. The most obvious symptom is when images in IE appear larger and low quality (jagged edges) due to the enlargement.

If so, open your Display Properties, choose “Advanced” under the “Settings” tab. The view here might vary by display card, but look out for an option for DPI settings. For my case I was having 120dpi instead of 96dpi. Once I changed it back and restarted the machine IE was doing fine. However doing so makes my other screen fonts too small on the high-res monitor.

To fix that you’ll have to manuall adjust the fonts in the Display Properties again. I was too lazy so I switched back to 120dpi again, and stayed with the IE tab plugin…

Static methods in Inner classes

Hit this seldom seen compilation error while writing inner classes.


public class OuterClass {
	public class InnerClass {
		public static void InnerStaticMethod() {
		}
	}
}

This is what the compiler said:

The method InnerStaticMethod cannot be declared static; static methods can only be declared in a static or top level type

Java don’t like inner classes to have static methods, unless the inner class is static. A static inner class means you can instantiate the inner class without an enclosing outer class instance. One quick way to fix this situation is below, but note that you lose access to the outer class instance variables. InnerClass may also be instantiated without an OuterClass by new OuterClass.InnerClass(). Of course this can be prevented by limiting the access of the inner class.


public class OuterClass {
	public static class InnerClass {
		public static void InnerStaticMethod() {
		}
	}
}

Similarly, when the inner class is non-static, static member variables are not allowed. But static finals are permissible.

Breaking nested for loops

Not a question so common, but one that everyone will hit along the path of coding: breaking out of a nested for loop. A normal break will just take you out of the inner for loop.


System.out.println("before");
for (int i=0;i<3;i++) {
  for (int j=0;j<3;j++) {
    System.out.println("inside inner loop");
    break;
  }
  System.out.println("after inner loop"); // this will be printed
}
System.out.println("after everything");

To break out of the outer loop directly, label the outer loop using a... label. Then specify the label of the loop you'd like to break out of. You can name the label anything, as long as it's unique within its scope. It also works if you have higher levels of nesting -- by labelling the correct for loops you'll be able to break out of it correctly.


System.out.println("before");
outer: for (int i=0;i<3;i++) {
  for (int j=0;j<3;j++) {
    System.out.println("inside inner loop");
    break outer;
  }
  System.out.println("after inner loop"); // this won't be printed
}
System.out.println("after everything");

Ubuntu

Flipped open the Wired magazine at a bookstore just now, and saw Ubuntu listed as one of the “Ways to ditch DRM”. Guess it’s another prompt for me to shift to the new OS. Been experiencing Ubuntu for the past few weeks and I felt that it’s a good OS for a Unix newbie like me.

I’ve already downloaded a copy of the OS itself, and phishie also gave me the free CD they sent him today. So now I’ll just have to backup my current stuff, pop the OS in and hope that there’s sufficient support for the hardware on my laptop…

Java Virtual Hosting

I had a client recently who wanted a functional website built. By functional I meant he cared more about the features of his site than the design. Due to the site requirements and manpower issues on my side I initially recommended a Java web host. However as I started out in search of one, I soon realize that it was more challenging than I perceived.

Firstly, there were few Java web hosts. Despite being free to implement, there were many more PHP and ASP web hosts. Several blogs reasoned that there was difficulty supporting it, such as sharing JVM instances and Tomcat restarting.

Secondly, many of those Java web hosts I found did not come cheap. Due to the abovementioned reason those that do support it charge higher for it. There were some that were cheap, but those had shared instances or did not really know how to maintain a servlet engine. Some don’t allow restarts.

Thirdly, there isn’t that much demand in Java virtual hosting. This also added to the cost factor. Projects small enough will usually go for PHP or alternative technologies that are easier to implement, manage and have cheaper virtual hosting solutions. Projects big enough to use Java would have purchased their own boxes to deal with it.

Given these factors I would probably switch the project to PHP or not take it at all than to risk an unstable deployment.

Anonymous Inner Class Constructors

Have been writing anonymous inner class for many years, when I suddenly hit a question today while writing a quick dirty test class. I needed to initialize stuff within the anon inner class, but how?

Found this link to teach me how to do that — just by using braces { }.

Musings of Laurie

Solved my problem, but had me thinking. I can’t call super() to call the parent constructor, what if I do not want to override the default constructor? After an hour of thinking, I realized the answer was right there too. To declare the anon inner class I have already specified which constructor to call before the declaration of the anon inner class, like this:


// i'm calling the JButton(String) constructor
new JButton("asd") {
  {
    // override constructor
  }
};

Certification doesn’t mean you know and remember everything!

Autoboxing

In Java SE 5, autoboxing was introduced to automatically convert between primitives and primitive wrappers. Primitives means basic types such as int, short, long, etc. Corresponding wrappers are Integer, Short, Long, and… nope, no Etc. To understand this, let’s look at the interaction between primitive and their wrappers before SE 5.


int originalInt = 3;

// convert primitive 3 to wrapper
Integer intWrapper = new Integer(originalInt);

// convert wrapper to primitive
int intPrimitive = intWrapper.intValue();

// store primitive in ArrayList
ArrayList list = new ArrayList();
list.add(new Integer(3));

// retrieve primitive in ArrayList
Integer wrapped = (Integer)list.get(0);
int unwrapped = wrapped.intValue();

// short-cut to retrieve primitive, less readable
int fastUnwrap = ((Integer)list.get(0)).intValue();

As shown above, a common usage of wrappers is when you need to store primitives as Objects. The ArrayList accepts an Object to be added, so it cannot add an int directly. However, we can make use of an Integer wrapper to put the number into the ArrayList, and take it out subsequently.

With SE 5, Java automatically generates necessary code to convert between primitives and wrappers during compilation. Let’s look at the new way with Autoboxing.


int originalInt = 3;

// convert primitive 3 to wrapper - Java will auto-convert
Integer intWrapper = originalInt;

// convert wrapper to primitive - Java will auto-convert
int intPrimitive = intWrapper;

// store primitive in ArrayList - generics added
ArrayList list = new ArrayList();
list.add(3);

// retrieve primitive in ArrayList
int unwrapped = list.get(0);

As you can see, all the scenarios have been simplified. Adding generics allows direct adding and retrieval of primitive types without any casting or wrapping. Despite being a useful convenient feature, programmers who pick up SE 5 directly without knowledge of the old way may not understand the rationale or even find it confusing (especially the ArrayList). Comparing and understanding the differences between the above code snippets will help in understanding Autoboxing.