views:

128

answers:

5
  public class Test {
        public static void main(String[] args){
            if (5.0 > 5) // (5.0<5) for both case it is going to else
                System.out.println("5.0 is greater than 5");
            else 
                System.out.println("else part always comes here");
                     /*another sample*/
            if (5.0 == 5) 
                System.out.println("equals");
            else 
                System.out.println("not equal");
        }
    }

can any one explain the first "if statement" why it always come to else part

second else part prints "equals "

+2  A: 

The opposite of "less than" is not "greater than". It is "greater than or equal to", which is true in this case.

Ignacio Vazquez-Abrams
+1  A: 

Because 5.0 is not less than 5. It is equal to 5. So the 5.0 < 5 is false.

Jaymz
5.0>5 is also coming as false
Anbu
That's because 5.0 is not greater than 5. It is equal, and only equal, to 5. It is neither greater than nor less than. 5.0 == 5. Fact.
Jaymz
+1  A: 

It always goes to the else part because 5.0 is not less than 5. It is the same value.

Jonno
Why is everyone saying "less than". Are you just reading other people's answers and saying the same thing they said? The first person who said "less than" is wrong. The Java operator ">" means greater than, not less than.
Gnarly
@Gnarly - Perhaps I should have said less than or equal to, denoting the exact opposite of >. As the value is NOT greater, then it has to be one of the other 2 possibilities, which both route to the else. Nobody is confusing the meaning of >.
Jonno
+1  A: 

5.0 is not greater than 5; they're equal. Therefore it will resort to the else because the if statement does not return true.

Gnarly
how it is true for both the case 5.0>5 and 5.0 < 5
Anbu
It's not. It's false for both cases.
Jack Leow
+3  A: 

You're testing whether or not (5.0 < 5) or (5.0 > 5). Since (5.0 == 5) then that means it's not less then 5 (false) and not greater then 5 (false). So both (5.0 < 5) and (5.0 > 5) will return false and you will always hit the else statement.

If you did the following (which is what you did in the second half):

if (5.0 == 5)
    System.out.println("5.0 is equal to 5");
else 
    System.out.println("else part always comes here");

Then you will no longer hit the else statement (as you saw in the second half of your question).

spdaley