Lecture 5

CSC120: Programming I - Spring 2002
Prof. Christian A. Duncan
csc120@mail.cs.miami.edu

Announcements

String Class

Although Strings are objects of a class and not a primitive data type like int or double, they are treated specially in Java. And since they are very useful, it is important that we understand them as early as possible.

The phrase "Hello World!" is a String literal (constant). In your first program, you simply did:
System.out.println("Hello World!"); and did not directly use the String. But like other variables, you could make the phrase a variable and use it in outputing the message:

    String greeting = "Hello World!";
    System.out.println(greeting);
One useful feature for Strings is concatenation, combining two strings. Here is another way to print out the message from above:
    // One way
    String greeting = "Hello ";
    String name = "World";
    String message = greeting + name;
    System.out.println(message);

    // Or simply
    System.out.println(greeting + name);
One other advantage is concatenating using variables as well:
    String name = "Christian";
    int dollars = 1000;
    System.out.println(name + " has " + dollars + " dollars in his pocket.");
    System.out.println(name + " has $" + dollars + " in his pocket.");
    // DANGER! DANGER!  Be careful (the following do not behave the same way!)
    System.out.println("Counting " + 1 + 2);
    System.out.println(1 + 2 + " and counting ");
The "command" println(...) is a method associated with a class called PrintWriter. The class String also has methods associated with it. The book goes over some of these in Section 2.2 (page 82), to be helpful we shall cover some of these methods as well and show how to use them.
int length() Returns the length of the string
boolean equals(String otherString) Tests if two strings are equal
String toUpperCase() Returns a new String with all characters in old string in upper case.
char charAt(int position) Returns the character at the current position. Counting starts at 0!
String substring(int start) Returns the subString starting at the given position start
String substring(int start, int end) Returns the substring starting at start and ending just before end
int indexOf(char c) Returns the index in the string of the first occurrence of the character c or -1 if the character does not exist.
Here are some samples (the comments indicate the value)
   String message = "Fun with strings";
   // positions      0123456789012345
   int length = message.length();                  // Returns 16
   System.out.println(length);                     // Prints 16
   String shout = message.toUpperCase();
   System.out.println(shout);                      // "FUN WITH STRINGS"
   System.out.println(message.substring(9));       // "strings"
   System.out.println(message.substring(2,6));     // "n wi"
   System.out.println(message.indexOf(' '));       // Prints 3
   System.out.println(message.indexOf('z'));       // Prints -1

As another example, let us see how to get the first word in a text. What changes do you need to make to get the second word?

   String text = "Hello there world";
   int spaceAt = text.indexOf(' ');   // spaceAt == 5
   String firstWord = text.substring(0,spaceAt);

Conditional execution

In programming, it is very important to make decisions based on certain conditions. So far, all of our programs execute consecutively. Conditionals allow us to write programs that do one of two (or even more) things. Conditional execution is one of the fundamental elements of programming without it the computer (and your program) would always do the same thing over and over again.
If I am over 60, I will retire otherwise (else) I'll keep working.
The same applies for the Java programming language:
public class Retire {
   public static void main(String[] args) {
      System.out.println("How old are you?");
      int age = SavitchIn.readLineInt();
      if (age > 60) 
	 System.out.println("Time to retire!");
      else
         System.out.println("Keep working");
      System.out.println("Good bye!");
   }
}
The format for the (if-else) is as follows:
   if (boolean-expression)  statement 
   else statement
Notice the above takes exactly one statement for the then and else portions. For multiple statements, we can simplify it to the following:
   if (boolean-expression) {
      multiple-statements
   }
   else {
      multiple-statements
   }
The else portion is also optional. It can be removed completely.

Compound Statements:
The statements between an opening brace { and a matching closing brace } form what is called a compound statement. This compound statement then is, in itself, a statement.

Boolean Expressions

Boolean expressions come in many forms. Here are just a few of them.
   x == 3   // Tests if the variable x equals 3
   x != 3   // Exact opposite
   x >  3, x >= 3, x <  3, x <= 3, (x+y) < (a+b), ...
These expressions evaluate to either true or false depending on the condition. The expression (x==3) is true if x is equal to 3 and false otherwise. Sometimes we don't just have one "condition". For example, if I am older than 50 and rich, I'll retire early. There is one way to do this:
   if (myAge > 50) {
      if (myMoney >= 1000000) {
         System.out.println("I'm retiring early!");
      }
   }
There is a better way:
   if ((myAge > 50) && (myMoney >= 1000000)) {
      System.out.println("I'm retiring early!");
   }
The && is called a logical and operator. The expression ((A)&&(B)) returns true only if both (A) AND (B) are true. The three logical operators you should be concerned with now are: Here are a few examples.
   int x = 2;
   int y = 4;
   if ((x < 3) && (y > 0)) {
      System.out.println("Should be printed");
   }
   if ((x < 3) && (y > 4)) {
      System.out.println("Should NOT be printed.  Why?");
   }
   if ((x < 3) || (y > 4)) {
      System.out.println("Shoud be printed.  Why?");
   }
   if (!((x < 3) || (y > 4))) {
      System.out.println("Shoud NOT be printed.  Why?");
   }

Watch Out: Comparing Strings

If you want to compare two strings the "==" operator will NOT work properly. Later, we shall learn why, but for now you use the equals() method from the String class. For example,
   System.out.println("Who are you?");
   String name = SavitchIn.readLine();
   if (name.equals("Christian")) {
      System.out.println("Great!  I hoped it was you.");
   }

Multi-branch Statements

Many times you will also want to check several possible situations for one variable (or expression).

   System.out.println("What kind of computer should I get?");
   if (myMoney >= 1000000) {
      System.out.println("I am a millionaire.  Let's buy a supercomputer!");
   } else if (myMoney >= 100000) {
      System.out.println("Well, I'll just buy a nice Dell system.");
   } else if (myMoney >= 1000) {
      System.out.println("Ok, maybe I'll just find a used Dell.");
   } else {
      System.out.println("Hmmm, where's that old Atari system of mine.");
   }
In this case, the algorithm prints out one of several different values depending on the value of the variable (myMoney). Notice, that even if I have $1,000,000, the output does not produce multiple lines of output. However, if I remove the "else" words, it would. Why is this?

Switch Statement

There are a few "shortcuts" and conveniences that you as a Java programmer must recognize and may choose to use. The first one dealing with conditionals is the switch statement.

Imagine creating a menu driven program for example. There are (at least) two ways to do this, the old fashioned way and the switch way.

   System.out.println("Please enter an option (1-3)");
   int option = SavitchIn.readLineInt();
   
   if (option == 1) {
      System.out.println("You entered option 1");
      System.out.println("I will restart your computer now");
   }
   if (option == 2) {
      System.out.println("You entered option 2");
      System.out.println("I will reformat your hard disk now");
   }
   if (option == 3) {
      System.out.println("You entered option 3");
      System.out.println("Your computer will self destruct... now");
   }
   else {
      System.out.println("Hey, buddy, follow directions next time!");
   }

   // Or the following way...
   switch (option) {
      case 1:   
         System.out.println("You entered option 1");
         System.out.println("I will restart your computer now");
         break;
      case 2:
         System.out.println("You entered option 2");
         System.out.println("I will reformat your hard disk now");
         break;
      case 3:
         System.out.println("You entered option 3");
         System.out.println("Your computer will now self destruct");
         break;
      default:
         System.out.println("Hey, buddy! Follow directions next time");
   }
The way it works should be straightforward (almost). It takes the value of "option" and if it is a 0, it performs the actions after the case 0. If it is a 1, it performs the actions after the case 1, etc. The one tricky part is that it starts executing commands after the case and continues to the end of the switch or until it encounters a break.

The book covers this topic fairly well so use it as a better reference. The key pitfall to avoid here is forgetting the break statement when needed. For example, if the first break was commented out and the user entered a 1, the system would print out the following (Why?):

    You entered option 1
    I will restart your computer now
    You entered option 2
    I will reformat your hard disk now
The second rule is that the values in the case statements must be constants or literals. Basically, think of it as numbers or letters. The following are invalid examples:
   // INVALID (can't use anything but primitives)
   String name = SavitchIn.readLine();

   switch (name) {
   case "Alex":
   case "Christian":
   case "Duncan":
       System.out.println("Yes?");
       break;
   default:
       System.out.println("Who are you?");
   }

   // INVALID (can't use variables in the case statements)
   char letter1 = 'Q';
   char letter2 = 'W';
   char opt = SavitchIn.readLineNonwhiteChar();

   switch (opt) {
   case letter1:
      System.out.println("Q entered");
      break;
   case letter2:
      System.out.println("W entered");
      break;
   }

Conditional Operator

Quick shortcut tip for everybody. It isn't something you need or even really should use that often but you do need to be able to recognize it.
   if (a > b)
      max = a;
   else
      max = b;

   // Or
   max = (a > b) ? a : b;
The format is: (boolean-expression) ? expression : expression

There are things to remember about this expression. The value in the two expressions has to be of the same type. In the following example, the first statement works and the second one does not.

   double grade;
   char letter;
   grade = SavitchIn.readLineDouble();

   letter = (grade > 90) ? 'A' : 'B';      // WORKS
   letter = (grade >= 60) ? "PASS" : 'F';  // WON'T COMPILE