December 29, 2003

Java Tidbits

Quick, take this true/false quiz and test your Java(tm) knowledge:

1. Private members can only be accessed by the object which owns them.

2. The contents of a finally block are guaranteed to run.

Everybody knows that both of these are true, right?

Actually each of these is false. In the first case, this program shows that objects can twiddle with private members of other objects of the same class:

class PrivateMember {
   private int i; 
   public PrivateMember() { 
      i = 2;
   public void printI() {
      System.out.println("i is: "+i);
   public void messWithI(PrivateMember t) {
      t.i *= 2;
   public static void main (String args[]) {
      PrivateMember sub = new PrivateMember();
      PrivateMember obj = new PrivateMember();

and this program shows that finally blocks don't run if the JVM exits:

class TryCatch {
   public static void main (String args[]) {
      try {
         System.out.println("in try");
         throw new Exception();
      } catch (Exception e) {
         System.out.println("in catch");
      } finally {
         System.out.println("in finally");
Posted by moore at December 29, 2003 08:04 PM
© Moore Consulting, 2003-2006