Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java counter-intuitive code

Tags:

java

I remember reading a book named:

Java Puzzlers Traps, Pitfalls, and Corner Cases

that described odd behavior in Java code. Stuff that look completely innocent but in actuality perform something completely different than the obvious. One example was:

(EDIT: This post is NOT a discussion on this particular example. This was the first example on the book I mentioned. I am asking for other oddities you might have encountered.)

Can this code be used to identify if a number is odd or not?

public static boolean isOdd(int i) {

    return i % 2 == 1;

}

And the answer is of course NO. If you plug a negative number into it you get the wrong answer when the number is odd. The correct answer was:

public static boolean isOdd(int i) {

    return i % 2 != 0;

}

Now my question is what are the weirdest, most counter intuitive piece of Java code you came across? (I know it's not really a question, maybe I should post this as a community wiki, please advice on that as well)


1 Answers

One I blogged about recently, given the following two classes:

public class Base
{
   Base() {
       preProcess();
   }

   void preProcess() {}
}


public class Derived extends Base
{
   public String whenAmISet = "set when declared";

   @Override void preProcess()
   {
       whenAmISet = "set in preProcess()";
   }
}

what do you think the value of whenAmISet will be when a new Derived object is created?

Given the following simple main class:

public class Main
{
   public static void main(String[] args)
   {
       Derived d = new Derived();
       System.out.println( d.whenAmISet );
   }
}

most people said it looks like the output should be "set in preProcess()" because the Base constructor calls that method, but it isn't. The Derived class members are initialized after the call to the preProcess() method in the Base constructor, which overwrites the value set in preProcess().

The Creation of New Class Instances section of the JLS gives a very detailed explanation of the sequence of events that takes place when objects are created.

like image 97
Adrian Thompson Phillips Avatar answered Dec 12 '25 04:12

Adrian Thompson Phillips



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!