float, int equality in Java

I saw a strange thing tonight. I was checking primitive types in Java. I was trying float, int equality to see when the “==” equality fails. It is supposed to be values over 2^23.

Guess what? It never fails.

When we try a equality check like;

aFloat == aInt

Java casts int to float first then executes the equality check.

aFloat == (float)aInt

Switching left values to right values of equality operator does not change this behaviour. This is the reference to this situation.

The following code exemplifies the situation.

public static void main(String[] args) {
	float f = 99_000_021;
	int i = 99_000_021;
	if(i == f) {
		System.out.println("int value:"+ i + 
			" and float value:"+ f + " are EQUAL!");

Output is as follows:
int value:99000021 and float value:9.9000024E7 are EQUAL!


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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s