Java, making comparisons: operators greater than (>), less than (<), greater equal (>=), less equal (<=), equal (==) and different (!=)


What makes you choose a channel or another on TV?
What makes you choose between a blonde or brunette? Or man and woman? Or both, if you're emo?

Why learn Java, not Haskell?

Whatever the reasons, everyone goes through a stage: a comparison.



In Java, we make a comparison when it returns 'true'', 'false' or gives error.
And Java got an error, my friend, is why you missed something. It's your fault.

These operators, along with the conditional (which we'll see shortly) and the mathematical operations, already saw, are alphabet-like in Java.
These are the basics, but the issues are essential.
This article is very short and easy to understand.

Perhaps you already know the meaning of all these symbols, then you go forward and make a program that shows all tests:

import java.util.Scanner;

public class Comparing {
    public static void main(String [] args) {
        float num1, num2;
        Scanner input = new Scanner(System.in);
        
        System.out.print("Enter the first number:");
        num1 = input.nextFloat();
        System.out.print("Enter the second number:");
        num2 = input.nextFloat ();
        
        System.out.printf("%.2f > %.2f -> %s\n", num1, num2, num1 > num2);
        System.out.printf("%.2f >= %.2f -> %s\n", num1, num2, num1 > = num2);
        System.out.printf("%.2f < %.2f -> %s\n", num1, num2, num1 < num2);
        System.out.printf("%.2f <= %.2f -> %s\n", num1, num2, num1 <= num2);
        System.out.printf("%.2f == %.2f -> %s\n", num1, num2, num1 == num2);
        System.out.printf("%.2f != %.2f -> %s\n", num1, num2, num1 != Num2);
    }
}


Greater than: >

a > b -> returns 'true' if 'a' is greater than 'b' and 'false' if is less

Less than: <

a < b -> returns 'true' if 'a' is less than 'b' and 'false' if greater

Greater than or equal to:> =

a >= b -> returns 'true' if 'a' is greater than or equal to 'b' and 'false' if is less

Less than or equal to: <=

a <= b -> returns 'true' if 'a' is less than or equal to 'b' and 'false' if greater

Equality Comparison: ==

a == b -> returns 'true' if 'a' is equal to b, and false otherwise

Comparison of denial: !=

the! = b -> returns 'true' if 'a' is different from b, and false otherwise



PS: Note the difference between
a == b
and
a = b

The first comparison is a TEST! It's like a pro Java question: "'a' is equal to 'b'?"
The second is an assertion, ie, 'a' will receive the value of 'b'! In this case the Java always returns the last value, in which case it is 'b'.

If it were a = b = c, he would return 'c'.

No comments: