Comparing Values:

Assignment Statement: a single equal sign.  For example, x = 5;
Comparing (Equal) Statement: a set of double equal signs.  For example, 10 == 10;
Comparing (NOT EQUAL): For example, 12
!= 10;

Comparing Floating-Point Numbers

Consider this code
    double r = Math.sqrt(2);
    double d =
r * r - 2;
    if (
d == 0)      //
don't use == to compare floating-point numbers

       System.out.println("sqrt(2)squared minus 2 is 0");

    else

       System.out.println("sqrt(2)squared minus 2 is not 0, but " + d);

It prints:
    sqrt(2)squared minus 2 is not 0 but 4.440892098500626E-16

   final double EPSILON = 1E-14;

   if (Math.abs(x - y) <= EPSILON)

      // x is approximately equal to y

Comparing Strings

  if (input == "Y") // WRONG!!!

  if (input.equals("Y"))

public class Tester
{
   public static void main(String [] args)
   {
	String myname = "Fredrick";
	String hisname = myname.substring(0,4);
	String nickname = "Fred";
	
	System.out.println("Test by == ");
	if( hisname == "Fred" )            //This result is wrong!!!
	System.out.println("his name is Fred.");
	else
	System.out.println("his name is not Fred. \n");
	
	if( nickname == "Fred" )
	System.out.println("his nickname is Fred.\n");
	else
	System.out.println("his nickname is not Fred. \n");
	
	System.out.println("Test by equals method ");
	if(hisname.equals("Fred"))
	System.out.println("his name is Fred.\n");
	else
	System.out.println("his name is not Fred.\n");
	
	if(nickname.equals("Fred"))
	System.out.println("his nickname is Fred.\n");
	else
	System.out.println("his nickname is not Fred. \n");
   }
}

  if (input.equalsIgnoreCase("Y"))

Comparing Objects

 

Testing for null


What is the value of s.length() if s is

  1. the empty string ""?

  2. the string " " containing a space?

  3. null?

   Answer: (a) 0; (b) 1; (c) an exception is thrown.


Which of the following comparisons are syntactically incorrect?
Which of them are syntactically correct, but logically questionable?

String a = "1";

String b = "one";

double x = 1;

double y = 3 * (1.0 / 3);

  1. a == "1"     use equals method

  2. a == null

  3. a.equals("")

  4. a == b       use equals method

  5. a == x       type not match

  6. x == y       round off error

  7. x - y == null   type not match

  8. x.equals(y)     no equals method for double type

Answer: Syntactically incorrect: e, g, h. Logically questionable:  a, d, f.