Java Lecture 2

Review so far
  1. ML is a functional language. Its key concepts:
    1. values and expressions
    2. identifiers bound to values
    3. functions that took input and computed an output
  2. Java is an imperative language. Its key concepts:
    1. statements, executed one after the other (e.g., commands)
    2. named variables, that can contain a value (of a certain type)
    3. functions and procedures (both also called methods)
      1. these group statements
      2. functions also return a result, but procedures don't
The central idea of imperative languages: The assignment statement
  1. Purpose: to assign a new value to a variable
  2. Syntax: VarName = Some_Expression ;
  3. The variable VarName gets assigned the value resulting from evaluating Some_Expression
  4. Remember, a variable acts as a location
    1. The location can only hold one value, so:
    2. The old value gets thrown away (forever!)
    3. The new value gets written in
Structure of a Java Program
  1. (See slides with this lecture)
  2. All procedures must be in some class (or "module")
  3. A Java program begins at a procedure (or "method") called main
  4. main is declared as "public static void"
    1. public means it is accessible outside the current class (main needs to be!)
    2. static means that this is the only definition (don't worry about this for now)
    3. void means that it is a procedure, rather than a function (that is, it returns nothing, which is kind of what "void" means)
  5. The class name that contains main is the name of the resulting program
    1. You should name your program file "classname.java", where classname is the name of the class containing main
    2. That way, when you compile it (by doing javac classname.java) you get a file classname.class as a result, and they match up
    3. Finally, you run the program by doing java classname
More on variables, values, and types
  1. In ML, the values were typed. You didn't tell ML what type an identifier referred to, ML told you!
  2. In Java, you have to tell it what type of value a variable will hold
  3. So you declare variables to be certain types
  4. Unlike ML, that variable cannot hold any other type of value. It does not change.
  5. The way you declare an integer variable is:
    1. int VarName = 3;
  6. So the type name is given, and then the variable name, and finally an initial value
  7. Actually, there are four different "integer" types in Java: byte, short, int, long
    1. Each stores a different range of integer values (-128 to +127 for the byte type)
  8. Real values in Java have two different types: double and float
    1. We will assume that we always use double
  9. Also have the boolean type and the char (character) type, and String, as we have seen
Examples 1, 2, 3, and 4; and the sample runs.