Choose Between Good And Evil

From Huben's Wiki
Jump to: navigation, search

Gandalf nazgul.jpg

Today we must face the difference between good and evil, between truth and falsity. We must learn to reason about them, lest we fall into error. The human sage George Boole was the great master in whose footsteps we follow.

We shall view the slides (1-12) that accompany the Book Of The Humans, pages 154 to 160.

Objects are difficult creatures: we cannot truly compare them with inequality operators such as ==, >= and the like. For objects, those operators compare only the memory addresses of the objects. This has at least two uses:

  • compare with null to see if a variable points of an object allocated with new.
  • compare the address of two objects to see if they are the same object.

But usually, we will want to compare objects by their contents. For class String, there are a few useful tricks.

  • For strings s1 and s2, you can see if they are equal with s1.equals(s2).
  • You can find the length of a string with s1.length.
  • You can get any character in position n with s1.charAt(n).

For this code, figure out the values of the character and boolean variables a to l. Remember, for String == is not the same as .equals().

String s1 = "abcde";
String s2 = "elbereth";
String s3 = s1;
String s4 = s1 + "";

char a = s1.charAt(4);
char b = s2.charAt(3);
char c = s2.charAt(2);
boolean d = a == b;
boolean e = a != c;
boolean f = b == c;
boolean g = s1 == s2;
boolean h = s1 == s3;
boolean i = s1 == s4;
boolean j = s1.equals(s2);
boolean k = s1.equals(s3);
boolean l = s1.equals(s4);

Now make a test program that prints out each. Test programs only need a class with a main(). Did you get them right? Why or why not?

Personal tools