Java Puzzler : They just find me !!


Couple of days back I wrote a piece of code which was behaving in an unexpected manner. I was confused what was happening. Take a look at the sample code below and predict its behavior

package com.shekhar;

public class JavaPuzzler {

	public static void main(String[] args) {
		JavaPuzzler javaPuzzler = new JavaPuzzler();
		javaPuzzler.doSth();
	}

	public void doSth() {
		float f = 1.2f;
		if (f >= 1.0) {
			f = 0.9999999999999f;
		}
		InnerClass innerClass = new InnerClass(f);
		System.out.println(innerClass.getValue());
	}

	private class InnerClass {

		private float value;

		public InnerClass(float value) {
			if (value >= 1.0f) {
				throw new IllegalArgumentException(
						"Value can't be greater than 1.0f");
			}

			this.value = value;
		}

		public float getValue() {
			return value;
		}
	}
}

My initial expectation was that I would get value 0.9999999999999f as answer.Try it and find the answer. Share your answer and reasoning in comments.

7 thoughts on “Java Puzzler : They just find me !!

  1. Michael Paap

    Hello Shekhar,

    to show, what has to be shown, this code would be enough:

    public class JavaPuzzler {
    public static void main(String[] args) {
    System.out.println(0.9999999999999f == 1.0);
    }
    }

    This behaviour is a result of the binary representation of floats: The fact that the value range of float in Java is from ±1,4E−45 to ±3,4E+38 does not mean, that there are really distinct float values for every possible value in this range. And the difference betwean two adjacent float values is different in different areas of the range of float. In your example 0.9999999999999f and 1.0 are mapped to the same float value.

    Greetings,
    Michael

    Reply
  2. johnwaterwood

    Always nice to alert people for this, but I agree with Michael that you could have trimmed the code a little.

    I was initially looking for some weird interaction between inner classes, but that was totally irrelevant.

    Reply
  3. foofoo

    Not a puzzler really. You can go through this link to know more about why these calculations are made the way they are -> http://floating-point-gui.de/basic/

    Whatever you do, do not make such calculations (using float / double) on programs that involve transactions involving real money or something equally critical.

    Anyway, you are wiser now.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s