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