Java Lecture 3

Methods: procedures and functions
  1. We have already talked about the main procedure, and functions
  2. Java (and the book) call the procedures and functions that are in a class the methods of that class
  3. So, when you read methods, think procedures and functions
  4. The form of a method definition is
    1. <modifiers> <type> Name ( <type> Param1, <type> Param2, ... )
      {
         <statement>;
         ...
         <statement>;
      }
      where the things in <brackets> stand for legal words or statements for that thing
  5. We have already seen two modifiers, namely public and static
    1. public means "visible (usable) outside of this class"
    2. static means "this is the only definition"
    3. main must be public and static
    4. for a while, all our methods will be static
  6. We have also seen two types, int and void
    1. All procedures have a type of void
  7. We have seen three statements, procedure calls, variable declarations, and assignments
  8. As with ML, each parameter has a type, but the type name comes before the parameter name
Choosing between statements to execute
  1. In ML, we had the if-then-else expression, which chose between two expressions, evaluated one of them, and returned a value (in ML, virtually everything returned a value)
  2. In Java we have the if-else statement, which chooses between two statements to execute
    1. It does not return a value
    2. It just controls the execution of statements
    3. We call this a control statement
  3. The form of the if-else statement is:
    1. if ( <boolean expression> ) 
         <true-statement>;
      else
         <false-statement>;
      where <boolean-expression> is some expression that results in true or false, and <true-statement> is the statement to do if the expression was true, and <false-statement> is the statement to do if the expression was false
  4. Note that there is no "then" keyword -- just the true-statement
What if we want to choose between a group of statements?
  1. Well, Java provides a way to group statements together
  2. Just put curly braces {} around the group of statements
  3. The curly braces make that group a compound statement
  4. It can go anywhere a single statement can go
  5. So, we can do the if-else statement like:
    1. if ( <boolean-expression> )
      {
         <statements>;
      }
      else
      {
         <statements>;
      }
Examples 1, 2, and 3; and the sample runs.