IT 114: Introduction to Java
Class 8
Topics
Review
New Material
Homework 3
Homework 3 is due this Sunday at 11:59 PM.
You will find the assignment here.
If you have a problem or a question, make a post on the Class Discussion Area.
Review
Expressions
- There are many different ways that we can get a value inside our code
- The value can be a literal
- The value can also be held inside a
variable
- Or we can calculate the value using
operators
- Each of these is an
expression
- An expression is anything in Java that can be turned into a value
- At the moment you only know three types of expressions in Java
- Literals
- Variables
- Calculations using operators
- There is a fourth expression type that we will meet in a future class
Evaluating an Expression
- The Java compiler processes the code statement by statement
- Each expression in a statement must be turned into a value
- This has to be done before the compiler can produce the bytecodes for the statement
- Turning an expression into a value is called
evaluation
- Consider the following calculation
(4 + x) / (4 - y)
- The operations inside the two parentheses must be evaluated first
- Then we can divide the two values
- So we have three separate evaluations of operators
- Evaluation of
(4 + x)
- Evaluation of
(4 - y)
- Division of the results
- Using this technique you can build up very complicated expressions
- This poses no problems to the compiler
- It just finds the lowest level expressions and evaluates them
- Then it moves up to the next level
- And performs the operations specified there
Precedence
- Consider the following expression
3 + 2 * 4
- This expression has two operators
- Which operation should be done first?
- If we do addition first we get
3 + 2 = 5
5 * 4 = 20
- But if we do multiplication first we get
2 * 4 = 8
3 + 8 = 11
- Java uses rules of
precedence
in situations like this
- The rules of precedence tell the compiler which operator to apply first
- Operators with higher precedence are used before operators of lower precedence
- For arithmetic operators there are two orders of precedence
- Operators that deal with multiplication and division
have the higher order of precedence
- Operators that deal with addition and subtraction
have a lower order of precedence
- Parentheses always overrule the order of precedence
- If you are ever in doubt about how the compiler will evaluate an expression ...
- use parentheses
Escape Sequences
- There are a few unusual characters that require special treatment
- Because they cannot be written inside a string in the normal way
- There is a character called
newline
that makes the output go down to the next line
- This is the character you get when you hit Enter on a PC
- Or Return on a Mac
- But this won't work inside a
string literal
- If you want to use these or other troublesome characters
you have to use an
escape sequence
- An escape sequence is a set of two characters
- The first of which is a backslash, \
- Here is a list
Sequence | Represents |
\t | tab character |
\n | new line character |
\" | double quote |
\\ | backslash |
Control Structures
- When the interpreter run a script it goes through the code statement by statement
- The order in which it executes the statements is call the
flow of control
- Or the
path of execution
- Control structures allow the interpreter to take different paths through the code
- There are two types of control structures in Java
- Loops
- Branches or Conditionals
Loops
- There are two kinds of loops in Java
- Loops controlled by counting
- Loops controlled by some condition
- Loops controlled by counting are sometimes called
definite loops
- Loops controlled by a condition are sometimes called
indefinite loops
- All loops are composed of two parts
- A loop header
- A loop body
- The loop header
is a single line at the top of the loop
- It controls how many times the loop runs
- The loop body
are the statements that are executed with each pass through the loop
- Each pass through the loop body is an
iteration
Code Blocks
- The loop body is an example of a
code block
- Code blocks are a group of statements that are only executed under
certain conditions
- In Java code blocks are contained between
left curly brace, {
- And a right curly brace, }
- Every { must be followed by a matching
}
- Or you will get an error
- You should indent the statements inside a code block
- The compiler won't care
- But it will make your code more readable
- And readable code is easier to fix when you get an error
The ++ and -- Operators
- ++ adds 1 the value of the variable it is placed
next too
- -- subtracts 1 from its variable
- Adding 1 to the value of a variable is called
incrementing
- Subtracting 1 from the value of a variable is called
decrementing
Order of Precedence for ++ and --
- Here is how the ++ and -- fit into the precedence hierarchy
Description | Operators |
unary operators |
––
–
|
multiplicative operators |
/
%
|
additive operators |
– |
assignment operators |
+=
*=
%=
|
New Material
The for
loop
Initializing the Loop Variable
- The first statement in the loop header
initializes
a variable that controls the loop
- It is called the
loop variable
- Also known at the
control variable
- This variable must be an integer
- Because it counts how many times the loop body is run
- The initialization gives the loop variable it's first value
- Which is often 0 or 1
- Here is an example
int i = 1;
- This variable can have any name you want
- But it is traditional to use i,
j or k
- This statement is only executed once
- And that happens before entering the loop
The Loop Test
- The second statement in the loop header determines how many
times the loop runs
- It is a
boolean expression
which test the loop variable
- As long as this expression is true the loop will run
- A
for
loop stops when the test becomes false
- Usually the expression is true as long as the loop variable
is less than some value
- Here is an example
i <= 5;
The Loop Update Statement
- If the loop variable does not change, the loop will go on forever
- The update statement makes sure this does not happen
- The this statement changes the value of the control variable
- This happens after the statements in the loop body have been run
- But before the loop test is run
- The most common update is to add 1 to the loop variable
- Usually this is done using the ++
operator
- Here is an example
i++
The for
Loop in Action
- Here is the flow chart for a
for
loop
- First we give the control variable its starting value
- This happens only once
- Then the loop test is run
- If the loop returns true all the statement in the loop body are run
- After the last statement in the loop body, the update statement is run
- Then we run the loop test again
- If the result is true, we run the statements in the loop body again
- If not, we jump out of the loop
- And run the first statement after the loop
for
Loop Patterns
- The three statements in the loop header can be written many ways
- But some patterns are more common than others
- The most common
for
loop pattern is the following
for (int VARIABLE_NAME = 1; VARIABLE_NAME <= LIMIT; VARIABLE_NAME++) {
STATEMENT;
...
}
- This loop starts with the control variable set to 1
- And executes the statements contained in the loop body
LIMIT times
- The following code
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ") ;
}
- Will produce this output
1 2 3 4 5 6 7 8 9 10
- Sometimes it is more convenient to start counting from 0 instead of one
- Here is the pattern
for (int VARIABLE_NAME = 0; VARIABLE_NAME < LIMIT; VARIABLE_NAME++) {
STATEMENT;
...
}
- There are two differences between this pattern and the previous one
- The loop variable is initialized to 0 instead of 1
- And the loop test uses <
instead of <=
Decreasing Loops
Using the Loop Variable Only for Counting
- The primary purpose of the loop variable is determine how many times the loop runs
- But often we use the value of the loop variable in the loop body
- Here is an example
public class Squares {
public static void main(String[ ] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i + " squared = " + (i * i) ) ;
}
}
}
- Running this program we get
$ java Squares
1 squared = 1
2 squared = 4
3 squared = 9
4 squared = 16
5 squared = 25
- But sometimes you don't use the value of the loop variable
- Here is an example
public class GoSox {
public static void main(String[ ] args) {
for (int i = 1; i <= 5; i++){
System.out.println("Go Sox!");
}
}
}
- This is what we get when we run it
$ java GoSox
Go Sox!
Go Sox!
Go Sox!
Go Sox!
Go Sox!
Indenting Java Code
- Look at the code above
- There are three sets of curly braces
- The line after each { is indented
- That is to make it obvious to the reader that a new code block has begun
- I did not have to do this
javac
does not require it
- As long as a Java program is correct the compiler will not complain
- But compilers aren't the only ones looking at Java source code files
- People have to read them too
- Two types of people have to read Java programs
- The people who write them
- The people who maintain them
- Compare the code above
public class GoSox {
public static void main(String[ ] args) {
for (int i = 1; i <= 5; i++){
System.out.println("Go Sox!");
}
}
}
- With this
public class GoSox2 {public static void main(String[ ] args) {for (int i = 1; i <= 5; i++){System.out.println("Go Sox!");}}}
javac
will compile both
- And they both produce the same output
- But which one would you rather read?
- Or debug if it did not compile?
Class Quiz
Attendance