Lecture 4

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

Announcements

Basic math operations

Computers were first developed to perform calculations. For example, one of the first computers ever built was used for calculating missile trajectories for the army. These calculations are called operations. There are many operations available to the programmer. We will begin with a simple set of operators, we are all familiar with using:
   int x = 2;
   int y = 12;
   int z = x + y*3 - 5;
   System.out.print("z = " + z);
This batch of code produces the following output:
   z = 33
As in math, the order of operations performed depends on the operations. Multiplications and divisions have higher priority and are done before additions and subtractions. This order is determined by precedence rules. See page 71 (Section 2.1) for the basic precedence rules which are the same as mathematical rules. Parentheses "(...)" also work to determine the precedence. Therefore, changing line 3 to
   int z = (x + y)*3 - 5;
produces the following output
  z = 37
Division needs to be looked at closer because of how it is treated with respect to integers. The value of z in the following code fragment is 3 and not 3.33333! Because z is an integer.
   int x = 10;
   int z = x/3;
To get 3.33333 you would need to use double and/or type cast the value.
   int x = 10;
   double z = (double)x/3.0;
The mod operator (%) is another special operator. It is used to get the remainder when performing divisions. For exampe, the value of remainder in this fragment is 1.
   int numerator = 10;
   int denominator = 3;
   int quotient = numerator/denominator;
   int remainder = numerator % denominator;
The book discusses the mod operator more and gives some useful tricks. For example, the mod operator is useful for testing if a number is even or odd. How?

Math Shortcuts

There are a few other "shortcuts" as well. Many times we will want to increase (decrease) the value of a variable by some amount.
   x = x + 3;
   y = y - 2;
   z = z * x;
To save some trouble, we are allowed to use the following equivalent statements:
   x += 3;   // Same as x = x + 3;
   y -= 2;   // Same as y = y - 2;
   z *= x;   // Same as z = z * x;
To provide further convenience (and confusion to the beginner), many times you will want to increment (or decrement) the value of a variable by only one unit. The "++" and "--" operators allow for this. Note there is no "**" or "//" operators. The following three statements are all (about) the same:
   x = x + 1;
   x += 1;
   x++;

   y = y - 1;
   y -= 1;
   y--;
Note: there is a difference between x++ and ++x! Chapter 2 (page 78) discusses it but try to avoid situations where the difference actually matters. To see the difference, check out what happens here...
    int x, y;
    x = 2;
    y = x++;
    System.out.println("x = " + x + 
                       ", y = " + y);

    x = 2;
    y = ++x;
    System.out.println("x = " + x + 
                       ", y = " + y);

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 money = 1000;
    System.out.println(name + " has " + money + " dollars in his pocket.");
    System.out.println(name + " has $" + money + " in his pocket.");
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 how to use them.
length()
Returns the length of the string
equals(String otherString)
Tests if two strings are equal
toUpperCase()
Returns a new string with all characters in old string in upper case.
charAt(int position)
Returns the character at the current position. Counting starts at 0.
substring(int start)
Returns the substring starting at the given position start
substring(int start, int end)
Returns the substring starting at start and ending just before end
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);                    // "Fun with strings"!?!
   System.out.println(message.substring(9));       // "strings"
   System.out.println(message.substring(2,6));     // "n wi"
Given time we shall also mention escape characters in class. Otherwise, see the book Section 2.2 for info on this problem. It is not critical, but a very useful tool to know.

Input and Output

Input and output is somewhat involved in Java. In particular, input is extremely involved as it is typically given. Fortunately, the book circumvents this problem by writing a class which handles basic input operations for you.

Output

As mentioned in Lecture 3, there are two main easy methods for output: print() and println(). The difference is that println() adds a return (newline) at the end of printing the String and print() does not. You attach the expression System.out because the method is associated with the object System.out. We will talk about what this means later in the course.
   System.out.print("One");
   System.out.print("Two");
   System.out.println("Three");
   // Outputs: 
   // OneTwoThree
   System.out.println("One");
   System.out.println("Two");
   System.out.println("Three");
   // Output:
   // One
   // Two
   // Three

Input

General input is certainly much more tricky. However, we have the book to thank for making life easier. The author defines a class called SavitchIn which provides methods for us to use in receiving various types of input. This is described in the section 2.3 of the book. Note, for those of you without the book, I will give a short explanation in class and will also provide example programs on the course page for your benefit.

To use a method, you simply use the statement: SavitchIn.methodName()

   int age;
   age = SavitchIn.readLineInt();
   double distance;
   distance = SavitchIn.readLineDouble();
   char letter;
   letter = SavitchIn.readLineNonwhiteChar(); // Ignores whitespace
   String wholeLine;
   wholeLine = SavitchIn.readLine();  // Reads in an entire line as a string
I will try and compile a list and give some examples on the course page.