r/javahelp • • Feb 27 '20

Homework Why is 17.0f is less than 4.567?

I am reading this OCJP exercise and there is a comparison as follows:

public classPrim { public static void main(String[] args) { int num1 = 12; float num2 = 17.8f boolean resultVal = num1 >= 12 && num2 < 4.567 || eJavaResult == true; System.out.println(returnVal); }}

N one of the explanation is :

boolean returnVal = (num1 >= 12 && num2 < 4.567) || eJavaResult == true;

My question is num2 should be less than 4.567 right ? But if the rest of the conditions are met so it returns true.

Hope someone can clarify my doubts. Tks.

0 Upvotes

17 comments sorted by

5

u/omykronbr Feb 27 '20

|| will return false if and only if both statements are false, otherwise, true. Any further explanation you need to review Boolean algebra, logical gates and truth table.

1

u/tangara888 Feb 27 '20

Your explanation is clear so my guess is correct then.

2

u/omykronbr Feb 27 '20

Yes, but the trick of the evaluation is to understand that the top level is an OR gate where one of the statement is always true, so the evaluation is "useless".

2

u/the_mailer_doraemon Feb 27 '20

It’s an OR operation which is symbolized as ||

2

u/tangara888 Feb 27 '20

Ok. Tks. So I have overlooked on Or. Guess I was trying to squeeze whatever time I can and rushed thru the exercise. Tks again for clarifying my doubts.

1

u/cscu090619 Feb 27 '20

Why would (num2 = 17.8f) be less than 4.567?

1

u/tangara888 Feb 27 '20

Why? I hope to know also.

2

u/cscu090619 Feb 27 '20

It’s not.

1

u/tangara888 Feb 27 '20

Then why it is returning true?

2

u/cscu090619 Feb 27 '20

Then eJavaResult must be set to true

1

u/tangara888 Feb 27 '20

Can you explain more cos I don’t understand what you mean

2

u/Soloem Feb 27 '20

The || is an OR operation.

If the left side happens to be false, it checks that the JavaResult is true.

Which it is, therefore the value is true. The num2 being less than has no bearing on this.

1

u/cscu090619 Feb 27 '20

Do a system.out.println(eJavaResult) and it should print true to output

1

u/tangara888 Feb 27 '20

But, I want to know why?

2

u/cscu090619 Feb 27 '20

The left hand side of || is false so then the right hand side of || is evaluated

3

u/the_mailer_doraemon Feb 27 '20

In an OR || statement, if at least one of the conditions is true, then the whole statement evaluates to True.

In an AND && statement, all the conditions must be true for the whole statement to be evaluated to True.

2

u/Mochi-Mo Feb 27 '20

You got a few answers here, but it seems like you're still confused. What exactly are you confused about?