Cs211 01 Java Basics
Cs211 01 Java Basics
1
Outline
2
What is programming?
Computers are extremely fast, precise, and dumb
Procedural Object-Oriented
• Describe the process that solves the • Describe the di erent pieces
problem (objects) of the problem, and how
they interact
• Separate the data from the
operations on that data • Separate interactions between
objects and internal representation
• Unit of programming is the function
(note, this is not functional • Unit of programming is the object
programming) (class)
4
ff
Procedural vs Object Oriented
Example: ATM
Procedural Object-Oriented
Possible functions Possible objects
• withdraw() • Customer
• deposit() • Account
• transfer() • Bank
5
What is Java?
• Five principles
1. Simple, Object-Oriented, Familiar
4. Fast
6
What is Java?
Portability
The development environment for Java has two parts: the Java compiler and the
Java interpreter / virtual machine (VM)
• Compiler
• Processes Java source code (.java les)
• Generates bytecode (not machine code) in a separate .class le
• Virtual machine
• Processes bytecode (.class les)
• Executes (runs) the program
7
fi
fi
fi
What is Java?
"Why have a separate compilation step?"
Compiled code is almost always much faster than "interpreted" code. At the
time, features like "Just-in-time" (JIT) compilation, faster garbage collection, and
various optimizations either didn't exist, or weren't good enough for consumer
use
Java's approach was to let programmers write in a high level language, compile
to an intermediate language (IL) and create interpreters (or JVMs) for this IL on
various hardware platforms
This way, you compile your source code once, and can run the program on
any* platform that has the JVM. Java calls this approach "write once, run
anywhere."
8
Java Editions
The JDK acronym zoo
• The tools for building Java programs are distributed as a Java Development Kit
(JDK), of which there are many "editions"
• Java Standard Edition (J2SE): The most common JDK for client-side standalone
applications, and what we use in this class
• Java Micro Edition (J2ME): Used for developing applications for mobile devices such
as cell phones (pre-smartphone)
10
Java Program Structure
Basics of syntax
• What does a class block look like? (Things below in [ ]'s are optional)
[Class documentation]
[package statement]
[import statement(s)]
[interface statement(s)]
[class de nition(s)]
main method class de nition
11
fi
fi
Java Program Structure
Example
/* A simple Java program. These comments should be for documenting
what this class (program) does at a high level.
*/
/* an import statement */
import java.lang.*;
/* the main function is the code that runs when this class is
executed
*/
public static void main(String[] args){
/* prints the message "Hello World!" */
System.out.println("Hello World!");
}
} 12
Java Program Structure
Java program = Comments + Tokens + whitespace
• Multi-line comments, start with /* and end with */ and indicate anything in between is a
comment:
• Javadoc comments, start with /** and end with */ and indicate specially formatted comments
that can be used to automatically generate documentation with the javadoc tool. (Examples later)
13
Java Program Structure
De ning terms: tokens
• Reserved words / keywords: things that have special meaning to the compiler (if, for,
class)
14
fi
fi
fi
Reserved words / keywords
tokens:keywords
Keywords have special meaning to the compiler. They can never be used as
identi ers. Some are not currently used, but are reserved for future use
(const, goto)
abstract assert boolean break byte
case catch char class const
continue default do double else
extends final finally float for
goto if implements import instanceof
int interface long native new
package private protected public return
short static strictfp super switch
synchronized this throw throws transient
try void volatile while enum
15
fi
Identifiers
tokens:identi ers
The "proper nouns" of programming
Identi ers are programmer chosen names used for classes, methods, variables, objects,
packages…
There are a few rules about what can be a valid identi er:
• Class names start with upper case letters, and should be inter-cap (StudentGrade)
• Variable names start with lower case letters, and should be inter-cap
(assignmentList)
• Method names start with lower case letters, and should be inter-cap
(calculateTotal)
• Names of constants are often written in all caps, replacing spaces with underscores
(MAX_PRICE)
17
fi
Literals
tokens:literals
18
Operators
tokens:operators
An operator is a token (usually a symbol, but not always!) that takes one or more
arguments, called operands, and…operates on them to produce a result
• Arithmetic operators
• Assignment operators
• Increment/decrement operators
• Relational operators
• Logical operators
19
Arithmetic operators
Tokens:operators:arithmetic
Arithmetic operators commonly work with numerical values (think calculator buttons).
They include
Order of operations:
• Multiplication *
1. Parentheses
• Division /
2. Multiplication, Division,
• Addition + and Mod (from left to right)
• Subtraction -
3. Addition and Subtraction
• Modulus % (the remainder of dividing the LHS by the RHS) (left to right)
Arithmetic operators can be unary (one operand), binary (two), or ternary (three)
20
Assignment Operators
tokens:operators:assignment
op1 = op2
Assigns the value of op2 (usually an expression) to op1 (always a variable). In addition
to the simple assignment operator, there are also compound assignment operators
that are shortcuts for common operations
op1 += op2
is equivalent to
op1 = op1 + op2
Compound assignment operators exist for all the arithmetic operations plus a few
more
21
Increment/Decrement operators
tokens:operators:increment/decrement
"Increase the value of this variable by 1" is such a common operation that it has
its own operator: ++op
However, there is some subtlety here! Since ++op is an expression (it evaluates
to a value), what should it evaluate to? Two options: the value of op after being
incremented (++op) OR the value of op before it was incremented (op++). This
will be particularly useful when we work with loops and arrays.
The above are called pre x (++op) and post x (opp++) increment operators.
Decrement operators also exist (--op and op--), and just reduce the value
by 1 rather than increasing
22
fi
fi
Relational Operators (comparison operators)
tokens:operators:relational
NOTE! NOT
the same as
ASSIGNMENT!
23
Order of operations:
Logical Operators 1. Negation (!)
tokens:operators:logical 2. Logical AND (&&)
3. Logical OR (||)
All the ways of gluing binary (true or false) values together
Example
Operator Returns true if "Short circuits"?
expression
&& op1 && op2 Both op1 and op2 are true Yes, rst false operand
|| op1 || op2 Either op1 or op2 is true Yes, rst true operand
! !op op is false No
24
fi
fi
Short-circuit evaluation
tokens:operators:logical
The rst part of the expression is much simpler to compute than the second part. If the rst part is
false, the overall expression will be false, and we can save time by not computing the second
part. Java evaluates && and || from left to right, stopping (short-circuiting) when the result is found.
However, when Java short-circuits an expression, sometimes the implications aren't so obvious.
Consider this expression:
( b < 5 || (++b / 2) > 10 )
What happens when b is greater than 5? What happens when b is less than 5? What will be the
value of b after this expression?
25
fi
fi
Operator Precedence
"Order of operations" when mixing di erent kinds of operators
A single expression can mix all of the di erent kinds of operators together. It is
best practice to use parentheses whenever things might get confusing, but Java
does have a set precedence among the di erent operators:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
26
ff
ff
ff
Separators
tokens:separators
Name Symbol
Usage: Parentheses ()
• Grouping operations together Braces {}
• Changing the default order-of-operations
Brackets []
• Ending / separating distinct computations
Semicolon ;
• "Accessing data and methods"**
Comma ,
Period .
27
Variables and Data Types
28
Variables
Declaring variables
Variables are named memory locations that can be assigned a value. The "name" of the
variable is an identi er. Useful for storing partial results for large/complex computations, or
for storing "state" within an object**.
• Data type - describes what kind of values the variable can hold (REQUIRED)
• Variable name - unique identi er for this memory location (REQUIRED)
• Comment - describes the purpose, limits, and use of the variable (optional)
29
fi
fi
Variables
Initializing variables
30
fi
Variables
Three di erent kinds of variables
31
ff
ff
Data types
Keyword Description Size/format
Unlike some other languages Integral numbers
(Python), Java requires the byte Byte-length integer 8-bit two's complement
programmer to give the type of data short Short integer 16-bit two's complement
a variable can hold explicitly. The
int Integer 32-bit two's complement
reason for this is that it makes for
Long integer 64-bit two's complement
much much faster code. long
Real numbers
Data types in Java can be split into float Single precision oating point 32-bit IEEE 754
two kinds: primitive types and double Double precision oating point 64-bit IEEE 754
reference types**. Each data type is Other types
stored in memory with a speci c
char 16-bit Unicode character
format.
boolean true or false
32
fl
fl
fi
Data type literals
Di erent data types have di erent literal formats (so Java knows how to
interpret literal values in your code)
• Integer: numbers without a decimal • Float: ends with the character 'f'
point float foo = 123.45f;
int foo = 12345;
• Long: ends with the character 'L'
• Double: numbers with a decimal long foo = 12345L;
point
double foo = 123.45; • Character: a single letter in single
quotes
char foo = 'a';
33
ff
ff
Data types
Notes
34
Default values
char '\u0000'
boolean false
35
Expressions
Terminology
36
Statements
Terminology
There are three kinds of statements in Java • Null statements (weird but necessary)
• Expression statements (computing things) • Assignment operations
• Declaration statements (creating/naming • Any use of ++ or --
things)
• Method calls
• Control ow statements (deciding where
to go next) • Object creation expressions**
37
fi
fl
fl
Statements
Examples
double aValue; //declaration statement;
aValue = 8933.234; //assignment statement
aValue++; //increment statement
System.out.println(aValue); //method call statement
Integer integerObject = new Integer(4); //object creation statement
38
fl
Scope and Lifetime of variables
• The scope of a variable is the region of a program within which the variable
can be referred to by its simple name.
• Scope also determines when the system allocates and clears memory for the
variable
• A block de nes a scope. Each time you create a block of code, you are
creating a new, possibly nested scope.
• Objects declared in the outer block will be visible to code within the inner
block, from the declaration down. (The reverse is not true)
39
fi
Scope and Lifetime of variables
Continued
• Variables are accessible when their scope is rst entered, and inaccessible
after their scope is left*. A variable that has "gone out of scope" will not retain
the value it previously stored.
• The lifetime of a variable is con ned to its scope. For most local variables,
this means the enclosing block of code.
• You cannot declare a local variable in an inner block to have the same name
(identi er) as a variable declared in an enclosing block. You can do this with
class/instance variables (called variable shadowing), which can lead to some
very di cult to debug problems!
40
fi
ffi
fi
fi
Blocks
Terminology
41
Type conversion
• Integer arithmetic yields results of type int unless at least one of the operands is
of type long
Conversion of a narrower data type to a broader data type is (usually) done without
loss of information, while conversion the other way round may cause loss of
information. The compiler will issue an error message if a conversion will result in
information loss, or if the types cannot be converted.
42
Type conversion
Examples
int i = 10;
double d = 3.14;
d = i; //OK! d will be 10.0 after conversion
i = d; //Not OK without an explicit cast, data will be lost
i = (int)d; //Accepted by compiler because of explicit cast
Explicit type casting syntax:
(<cast-to-type>)<variable or literal value>
float f = 3.5f; //types match
int x = (int)2.7; //explicit cast
f = (float)2.9; //explicit cast
float y = 98; //narrow (int) to broad (float)
byte b = (byte)2; //explicit cast
float z = y+b; //narrow to broad (98.0f + (byte)2) becomes (98.0f+2.0f)
b = (byte)z; //explicit cast
43
Control Flow
44
Control flow
(Also called " ow control")
• if statements
if (condition) {
//do something
}
45
fl
Control flow
if statement examples
if ((x>1) && (a+b == c)) {
System.out.println(a+b);
}
/* Note the conditional expression short-circuit: if (x>1) is false, then
Java knows it doesn't need to check (a+b == c). */
if(x>=0){
System.out.println(x);
} else {
System.out.println(-x);
}
if(x<1){
System.out.println("x is too small");
} else if(x>5){
System.out.println("x is too large");
}
46
Control flow
switch statement
if(x == 0){ switch(x) {
System.out.println("zero"); case 0:
} else if(x==1){ System.out.println("zero");
System.out.println("one"); break;
} else if(x==2){ case 1:
System.out.println("two"); System.out.println("one");
} else if(x==3){ break;
System.out.println("three"); case 2:
} else { System.out.println("two");
System.out.println("zero"); break;
} case 3:
System.out.println("three");
break;
default:
System.out.println("many");
}
47
While loops
// a while loop will continue "as long as" the condition is true
int x = 0;
while (x<5){
x++;
System.out.println(x);
}
48
For loops
Syntax
49
For loops
Compared to while loops
for (initializer; condition; update){
//do something
}
// same as:
initializer;
while(condition){
//do something
update;
}
50
For loops
Compared with Python
//Java
for (int i=0; i<arr.length; i++){
System.out.println(arr[i]);
}
#Python
for i in range(len(L)):
print(L[I])
51
For-each style loops
52
Additional control flow statements
There are other ways to exit a loop without waiting for the condition to be false:
• break
Breaks out of the current loop altogether, and resumes executing after the end of
the loop
• continue
Breaks out of the current iteration of the loop, but continues on the next iteration
(skips any code after this statement within the loop block)
• return
Returns from the current method call immediately, and as a side-e ect breaks
out of any currently executing loop
53
ff