Lecture notes

advertisement
CT 229
Java Syntax Continued
29/09/2006
CT229
Lab Assignments
 One Week Extension for Lab Assignment 1. Due Date: Oct 8th
 Before submission make sure that the name of each .java file matches
the name given in the assignment sheet!!!!
 Remember: Electronic Submission @
http://ecrg-vlab01.it.nuigalway.ie/uploader/Submissions.html
or
email: edward.scully@nuigalway.ie
 Where does Eclipse put my .java files????
– By default Eclipse will put your .java files in your F:\ drive.
– Look in your F:\My Documents\workspace\<name of project>
29/09/2006
CT229
1
Tutorials
 Tutorial Commence next week.
 Tutorials 1hr/Week
–
–
–
–
BE(EE)
BE(E&CE)
BSc(IT)
BSc(P&A)
29/09/2006
Tues AC213 (12-1)
Tues AC213 (12-1)
Thurs IT203 (12-1)
Thurs IT203 (12-1)
CT229
2
Review of Last Week
 Difference between an operand and an operator
 Operators can be classified as unary, binary or ternary
 Operator Types
– Arithmetic (+, -, etc.)
– Relational (>, >=, etc)
– Boolean (&&, ||, ^, etc)
• Difference between (&& and &) and (|| and |)
– Assignment Operators (*=, +=, etc)
– Bitwise Operators
• Bitwise AND(&) OR(|) XOR(^) Complement (~)
• Bitwise Shift (>>, >>>, <<)
 NEXT: Precedence and Associativity
29/09/2006
CT229
3
Precedence and Associativity
 It is possible to combine multiple arithmetic operations in
one statement
– int answer = 1 + 2 + 3 + 4 + 5;
– The value of answer is obviously 15
 However, if you use different operators on the same line it's
not always clear what the result will be.
– int answer = 1 - 2 * 3 - 4 + 5;
– Is answer equal to -2? You might think so if you just calculate
from left to right.
– According to Java answer is -4
–Why?
29/09/2006
CT229
4
Precedence and Associativity
int answer = 1 - 2 * 3 - 4 + 5;
 Java derived a value of -4 because it performs all
multiplications before it performs any additions or
subtractions.
 You can think of the calculation Java did as being:
int answer = 1 – (2 * 3) - 4 + 5;
 This is an issue of precedence.
 In Java the * operator has a higher precedence than the – or
+ arithmetic operators
29/09/2006
CT229
5
Precedence and Associativity
 Precedence determines the order in which operators act in an
expression with more than one operator.
 The Operator Precedence Table gives the precedence rating
for each operator, the lower the number indicating higher
precedence
– For example, in the example on the previous slide the *
operator will have a lower precedence number than the + or operator
29/09/2006
CT229
6
Full Precedence & Associativity Table
Prec.
Operators
() [] .
1
2
! ~ ++ -- +(unary) -(unary)
~(unary) (type-cast)
* / %
3
+ 4
<< >> >>>
5
< <= > >= instanceof
6
== !=
7
&
8
^
9
10 |
11 &&
12 ||
13 ?:
14 = += -= *= /= %=
&= ^= |= <<= >>=
29/09/2006
CT229
Associativity
Left to right
Right to left
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Right to left
Right to left
7
An Example of Precedence
Example
int num1 = 2;
The value of num5 is 17
int num2 = 3;
int num3 = 4;
int num4 = 3;
int num5 = num1 += num2 * num3 + num4;
System.out.println(“The value of num5 is ” + num5);
29/09/2006
CT229
8
Precedence and Associativity
 What happens when the operations in an expression all
have the same precedence rating?
 The associativity rule specifies the correct order.
Associativity Rule
Unary and Assignment:
Others:
e.g.:
29/09/2006
right-to-left
left-to-right
x + y + z is evaluated as (x + y) + z
x + y - z is evaluated as (x + y) - z
CT229
9
Precedence and Associativity
 Consider the following:
a-b+c
• Precedence Ranking is equal
• The associativity rule dictates (left to right), that is b will be
subtracted from a before it is added to c
– a * b / c (Again this is evaluated left to right)
 Parentheses have highest level of Precedence. For example,
if I wanted b and c to be summed first in the above equation
I could write it as:
a – (b + c)
29/09/2006
CT229
10
Full Precedence & Associativity Table
Prec.
Operators
() [] .
1
2
! ~ ++ -- +(unary) -(unary)
~(unary) (type-cast)
* / %
3
+ 4
<< >> >>>
5
< <= > >= instanceof
6
== !=
7
&
8
^
9
10 |
11 &&
12 ||
13 ?:
14 = += -= *= /= %=
&= ^= |= <<= >>=
29/09/2006
CT229
Associativity
Left to right
Right to left
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Right to left
Right to left
11
Precedence and Associativity
Example:
int x =5;
int y = 2;
x += y *= 10;
System.out.println(x);
29/09/2006
What is the answer?
CT229
12
Full Precedence & Associativity Table
Prec.
Operators
() [] .
1
2
! ~ ++ -- +(unary) -(unary)
~(unary) (type-cast)
* / %
3
+ 4
<< >> >>>
5
< <= > >= instanceof
6
== !=
7
&
8
^
9
10 |
11 &&
12 ||
13 ?:
14 = += -= *= /= %=
&= ^= |= <<= >>=
29/09/2006
CT229
Associativity
Left to right
Right to left
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Right to left
Right to left
13
Precedence and Associativity
Example:
int x =5;
int y = 2;
x += y *= 10;
The answer is 25
System.out.println(x);
2 *= 10 => 20
5 += 20 => 25
*= and += are assignment
operators. Therefore the
Associativity rule dictates that the
expression be evaluated from right
to left
29/09/2006
CT229
14
Flow of Control in Java Program
 When Java Program Run:
– Statements in main() executed in sequence
– Program ends at last statement in main(), or at System.exit()
(which can appear anywhere in code)
 System.exit(n);
– n = 0 -> normal successful completion
– n != 0 -> indicates error to operating system
 Along the way, control structures and method calls change
flow of control
– Conditions for program ending stay the same
29/09/2006
CT229
15
Statement Blocks and Empty Statements
 Empty Statement:
– Semi-colon on its own, or empty { }
– Considered a statement by compiler; does nothing
– Avoid stray semi-colons in code!
 Statement Blocks
– Anywhere you can have a single statement in Java, you can write a
compound statement instead
– Block of statements between { }
if (condition)
{
action1;
action2;
}
 Compound statements are statements that contain lists of
statements enclosed in braces "{ statements }"
– Compound statements can be decision/loop structure
29/09/2006
CT229
16
Decisions – ‘if’ Statements
 Basic if statement:
if (condition)
{
action;
}
– condition: an expression that evaluates to a boolean
– action: an executable statement
 if/else:
– Specifies alternative action if condition false
if (condition)
{
action_if_true;
}
else
{
action_if_false;
}
29/09/2006
CT229
17
Decisions – ‘if’ Statements
 if/else if
if (condition1)
{
action_if_condition1_true;
}
else if (condition2)
{
action_if_condition1_true;
}
else
{
action_if_all_conditions_false;
}
29/09/2006
CT229
18
Decisions – ‘if’ Statements
Note:
‘if’ statements should always use braces {}. Avoid the
following error-prone form:
if (condition)
if (condition)
action;
{
action;
}
AVOID
Note:
Java differs from C and C++ because an if takes a boolean
expression and not a numeric one.
29/09/2006
CT229
19
Decisions: if “ladder”
 Avoids excessive indentation of complex nested ifs
if (mark < 0 || mark > 100)
{
System.out.println("ERROR: mark is invalid\n");
}
else if
{
grade
}
else if
{
grade
}
else if
{
grade
}
else if
{
grade
}
else
{
grade
}
(mark < 40.0)
= 'F';
(mark < 55.0)
= 'D';
(mark < 70.0)
= 'C';
(mark < 85.0)
= 'B';
= 'A';
29/09/2006
CT229
20
switch
 Multiple decision structure:
– carry out different actions corresponding to
different values of an integer-type variable
int choice;
/* user enters 1, 2, 3, or 4 for choice */
switch (choice)
{
case 1:
doActionOne();
break;
case 2:
doActionTwo();
break;
Examples:
- Switch.java
- MonthSwitch.java
// done if choice == 1
// don't do next stmt
// if choice == 2
case 3:
case 4:
doActionTwoThreeFour(); // if choice == 2,3,4
break;
}
default:
displayError();
29/09/2006
// all other cases
CT229
21
Repetition: while
 while:
– Repeat a statement/block while a condition is true
– Useful when we don't know in advance how many times to
repeat (for used more often when we do know)
– Format
while (condition)
{
action;
}
29/09/2006
CT229
22
Repetition - While
int count = 1;
while (count < 5)
{
System.out.println("Count is: " + count);
count++;
}
Count is: 1
Count is: 2
Count is: 3
Count is: 4
29/09/2006
CT229
23
Repetition - do/while
 do/while:
– Like while, but condition tested after action first done
– Action guaranteed to be executed at least once
– Useful when action initialises variable used in condition
– Format:
do
{
action;
} while (condition);
29/09/2006
CT229
24
Repetition – do/while
int count = 1;
do
{
System.out.println("Count is: " + count);
count++;
}
while (count < 5);
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Examples:
- DoWhileExample2.java
29/09/2006
CT229
25
Repetition: for
 Used to repeat block of code specified number of times
– Useful when number of repetitions known
1: Initialise
– E.g. print 10 lines
2: Test
for (i = 0 ; i < 10 ; i++) {
3: Increment
System.out.println("Line " + i);
}
– Initialise control variable: once, at very start of loop
– Test: every time, before executing loop body
– Increment: every time, after loop body, before next test
 All sections of for header are optional
– Leave in “;”
– E.g. no initialisation required; endless loop; no increment
29/09/2006
CT229
26
For: Notes
 Initialise Section:
– Can declare the control variable: for (int x=10; x>5; x--)
– Scope of variable is until end of loop
 Test Section:
– If testing (variable == value) ensure variable does not miss
the exact value, particularly with float/double
– Using >= or <= may be safer
 Increment Section:
– Can increment, decrement, add 7, whatever…
– For clarity, use combined assignment operator (x += 7)
29/09/2006
CT229
27
Download