Download for statement

Document related concepts

Falcon (programming language) wikipedia , lookup

ALGOL 68 wikipedia , lookup

Java (programming language) wikipedia , lookup

Scala (programming language) wikipedia , lookup

JavaScript syntax wikipedia , lookup

Indentation style wikipedia , lookup

Relational model wikipedia , lookup

Go (programming language) wikipedia , lookup

Java performance wikipedia , lookup

Java syntax wikipedia , lookup

Java ConcurrentMap wikipedia , lookup

Structured programming wikipedia , lookup

Monitor (synchronization) wikipedia , lookup

CAL Actor Language wikipedia , lookup

One-pass compiler wikipedia , lookup

C Sharp (programming language) wikipedia , lookup

?: wikipedia , lookup

For loop wikipedia , lookup

C Sharp syntax wikipedia , lookup

C syntax wikipedia , lookup

Transcript
General Features of the
Java Programming Language
Variables and Data Types
Operators
Expressions
Control Flow Statements
Programming
• Programming consists of two steps:
• design (the architects)
• coding (the construction workers)
• Programming requires:
• a programming language to express your ideas
• a set of tools to design, edit, and debug your code
• either
– a compiler to translate your programs to machine code
– a machine to run the executable code
• or
– an interpreter to translate and execute your program
Algorithm design
• Pancakes
800g flower
4 tsp sucker
1 tsp salt
12 eggs
16 dl milk
12 sp water
1.
2.
3.
4.
5.
Pour the milk in a bowl
Pour the water in the bowl
Add the salt
Add the sucker
As long as there are eggs left
1. Take an egg
2. Break the egg
3. Put in the bowl
6. Add the flower
7. Turn the dew
Coding
• A Java program for a Pancake Robot
…
double kiloFlower = 0.8;
int tspSugar = 4;
int tspSalt = 1;
int noEggs = 12;
int dlMilk = 16;
int spWater = 12;
Variables are declared before they are used
Robot.pourMilkInBowl(dlMilk);
Robot.pourWaterInBowl(spWater);
Robot.putSaltInBowl(tspSalt);
Robot.putSugarInBowl(tspSugar);
…
The program is read sequentially from top to bottom
Coding
…
Robot.putSugarInBowl(tspSugar);
While (noEggs > 0)
{
NoEggs = NoEggs -1;
Robot.breakEgg();
Robot.putEggInBowl();
}
Robot.putFlowerInBowl(kiloFlower);
Robot.turnDew();
…
Making decisions
based on logical expressions
The “Hello World” Application
revisited
Create a Java Source File
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Compile and Run
• Compile
– javac HelloWorld.java
• One file named HelloWorld.class is
created if the compilation is succeeds.
• Run
– java HelloWorld
..\Java1\examples
Writing, compiling and running a
Java Program
Java
Compiler
javac HelloWorld.java
Java
Interpreter
java HelloWorld
Java Source
Java Bytecode
<file>.java
<file>.class
Created using NotePad
Java Program Structure
//
comments about the class
public class MyProgram {
class header
class body
Comments can be placed almost anywhere
}
This class is written in a file named: MyProgram.java
10
Java Program Structure
//
comments about the class
public class MyProgram {
//
comments about the method
public static void main(String[] args) {
method body
method header
}
}
11
System.out
• The System.out object represents a
destination to which we can send output
System.out.println(“Hello World. Some would write first");
object
method
information provided to the method
(parameters)
Variables
• Variable is a name for a location in memory
• 2 types of variables
– Primitive
– Reference
• Variables must have a type
• Variables must have a name
– Starts with a letter, underscore (_), or dollar sign ($)
– Cannot be a reserved word (public, void, static, int,
…)
data type
variable name
int total;
Primitive and Reference Data Type
Point p1, p2;
p1 = new Point();
p2 = p1;
int x;
x = 5;
x:
5
Primitive Data
Type
p1:
p2:
x: 0
y: 0
Reference Data Type
Variable Names
• Java refers to a variable's value by its name.
• General Rule
– Must be Legal Java identifier
– Must not be a keyword or a boolean literal
– Must not be the same name as another
variable in the same scope
• Convention:
– Variable names begin with a lowercase letter
• isEmpty, isVisible, count, in
– Class names begin with an uppercase letter
• Count
Reserved Words
(Keywords)
abstract
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
throw
protected
throws
public
transient
return
try
short
void
static
volatile
super
while
switch
synchronized
this
Don't worry about what all
these words mean or do, but be
aware that you cannot use
them for other purposes like
variable names.
Variable Scope
• The block of code within which the variable is
accessible and determines when the variable is
created and destroyed.
• The location of the variable declaration within
your program establishes its scope
• Variable Scope:
–
–
–
–
Member variable
Local variable
Method parameter
Exception-handler parameter
Variable Scope
Variables
• A variable can be given an initial value in
the declaration
int sum = 0;
int base = 32, max = 149;
• When a variable is not initialized, the value
of that variable is unknown.
When a variable is referenced in a program, its current value is
used
Assignment
• An assignment statement changes the
value of a variable
• The assignment operator is the = sign
total = 55;
The expression on the right is evaluated and the result is stored in
the variable on the left
The value that was in total is overwritten
You can assign only a value to a variable that is consistent with
the variable's declared type
Constants
• A constant is an identifier that is similar to a variable
except that it holds one value while the program is active
• The compiler will issue an error if you try to change the
value of a constant during execution
• In Java, we use the final modifier to declare a
constant
final int MIN_HEIGHT = 69;
• Constants:
– give names to otherwise unclear literal values
– facilitate updates of values used throughout a
program
– prevent inadvertent attempts to change a value
Primitive types
• There are exactly eight primitive data types in Java
• Four of them represent integers:
– byte, short, int, long
• Two of them represent floating point numbers:
– float, double
• One of them represents characters:
– char
• And one of them represents boolean values:
– boolean
Numeric Primitive Types
• The difference between the various
numeric primitive types is their size, and
therefore the values they can store:
Type
Storage
Min Value
Max Value
byte
short
int
long
8 bits
16 bits
32 bits
64 bits
-128
-32,768
-2,147,483,648
< -9 x 1018
127
32,767
2,147,483,647
> 9 x 1018
float
double
32 bits
64 bits
+/- 3.4 x 1038 with 7 significant digits
+/- 1.7 x 10308 with 15 significant digits
Non-numeric Primitive Types
• A boolean value represents a true or false
condition
• A char variable stores a single character from
the Unicode character set
– Character literals are delimited by single quotes:
'a'
'X'
'7'
'$'
','
'\n'
Arithmetic Expressions
• An expression is a combination of one or
more operands and their operators
• Arithmetic expressions compute numeric
results and make use of the arithmetic
operators:
Addition
Subtraction
Multiplication
Division
Remainder
+
*
/
%
If either or both operands associated with an arithmetic operator
are floating point, the result is a floating point
Operator Precedence
• Operators can be combined into complex expressions
result
=
total + count / max - offset;
• Operators have a well-defined precedence which
determines the order in which they are evaluated
• Multiplication, division, and remainder are evaluated prior
to addition, subtraction, and string concatenation
• Arithmetic operators with the same precedence are
evaluated from left to right
• Parentheses can be used to force the evaluation order
result
=
(total + (count / max)) - offset;
result
=
(total + count) / (max – offset);
Increment and Decrement
• The increment and decrement operators are arithmetic
and operate on one operand
• The increment operator (++) adds one to its operand
• The decrement operator (--) subtracts one from its
operand
• The statement count++;
is functionally equivalent to count = count + 1;
27
Increment and Decrement
• The increment and decrement operators can be applied
in prefix form (before the operand) or postfix form (after
the operand)
• When used alone in a statement, the prefix and postfix
forms are functionally equivalent. That is,
count++;
is equivalent to
++count;
28
Increment and Decrement
• When used in a larger expression, the prefix and postfix
forms have different effects
• In both cases the variable is incremented (decremented)
• But the value used in the larger expression depends on
the form used:
Expression
Operation
Value Used in Expression
count++
++count
count---count
add 1
add 1
subtract 1
subtract 1
old value
new value
old value
new value
29
Increment and Decrement
• If count currently contains 45, then the statement
total = count++;
assigns 45 to total and 46 to count
• If count currently contains 45, then the statement
total = ++count;
assigns the value 46 to both total and count
30
Assignment Operators
• Often we perform an operation on a variable,
and then store the result back into that variable
• Java provides assignment operators to simplify
that process
• For example, the statement
num += count;
is equivalent to
num = num + count;
31
Assignment Operators
• There are many assignment operators,
including the following:
Operator
+=
-=
*=
/=
%=
Example
x
x
x
x
x
+=
-=
*=
/=
%=
y
y
y
y
y
Equivalent To
x
x
x
x
x
=
=
=
=
=
x
x
x
x
x
+
*
/
%
y
y
y
y
y
32
Assignment Operators
• The right hand side of an assignment operator can be a
complex expression
• The entire right-hand expression is evaluated first, then
the result is combined with the original variable
• Therefore
result /= (total-MIN) % num;
is equivalent to
result = result / ((total-MIN) % num);
33
Relational operators
•
•
•
•
•
•
>
>=
<
<=
==
!=
greater than
greater than or equal to
less than
less than or equal to
equal to
not equal to
Conditional Test
• Conditional test is an expression that
results in a boolean value.
– Uses relational operators
• If we have the statement int x = 3; the
conditional test (x >= 2) evaluates to
true.
Conditional Statements
• A conditional statement lets us choose which statement
will be executed next by using a conditional test
• Therefore they are sometimes called selection statements
• Conditional statements give us the power to make basic
decisions
• Java's conditional statements are
– the if statement
– the if-else statement
– the switch statement
The if Statement
• The if statement has the following syntax:
if is a Java
reserved word
The condition must be a boolean expression.
It must evaluate to either true or false.
if (condition)
statement;
If the condition is true, the statement is executed.
If it is false, the statement is skipped.
37
The if-else Statement
• An else clause can be added to an if
statement to make an if-else statement
if ( condition )
statement1;
else
statement2;
If the condition is true, statement1 is executed; if the
condition is false, statement2 is executed
One or the other will be executed, but not both
38
Block Statements
• Several statements can be grouped together into a block
statement
• A block is delimited by braces : { … }
• A block statement can be used wherever a statement is
called for by the Java syntax
• Example:
if (guess == answer) {
System.out.println(“You guessed correct!”);
correct++;
} else {
System.out.println(“You guessed wrong.”);
wrong++;
39
}
Nested if Statements
• The statement executed as a result of an if
statement or else clause could be another if
statement
• These are called nested if statements
• An else clause is matched to the last
unmatched if (no matter what the indentation
implies!)
• Braces can be used to specify the if statement
40
to which an else clause belongs
Multiway Selection: Else if
• Sometime you want to select one option
from several alternatives
true
conditon1
evaluated
if (conditon1)
statement1;
else if (condition2)
statement2;
else if (condition3)
statement3;
else
statement4;
statement1
false
conditon2
evaluated
true
statement2
false
conditon3
evaluated
false
statement4
true
statement3
Example
int income = 350000;
System.out.println(“You are “);
if (income < 200000){
System.out.println (“poor”);
}
else if (income < 400000){
System.out.println (“not so poor”);
}
else if (income < 600000){
System.out.println (“rich”);
}
else {
System.out.println (“ very rich”);
}
Output:
You are not so poor
Logical Operators
• Boolean expressions can use the following logical
operators:
!
&&
||
Logical NOT
Logical AND
Logical OR
• They all take boolean operands and produce boolean
results
• Logical NOT is a unary operator (it operates on one
operand)
• Logical AND and logical OR are binary operators (each
43
operates on two operands)
Logical NOT
• The logical NOT operation is also called logical
negation or logical complement
• If some boolean condition a is true, then !a is
false; if a is false, then !a is true
• Logical expressions can be shown using truth
tables
a
!a
true
false
false
true
44
Logical AND and Logical OR
• The logical AND expression
a && b
is true if both a and b are true, and false
otherwise
• The logical OR expression
a || b
is true if a or b or both are true, and false
otherwise
45
Truth Tables
• A truth table shows the possible true/false
combinations of the terms
• Since && and || each have two operands, there
are four possible combinations of conditions a
and b
a
b
a && b
a || b
true
true
true
true
true
false
false
true
false
true
false
true
false
false
false
false
Logical Operators
• Conditions can use logical operators to
form complex expressions
if ((total < MAX+5) && !found)
System.out.println ("Processing…");
Logical operators have precedence relationships among
themselves and with other operators
all logical operators have lower precedence than the relational
or arithmetic operators
logical NOT has higher precedence than logical AND and
47
logical OR
Short Circuited Operators
• The processing of logical AND and logical OR is
“short-circuited”
• If the left operand is sufficient to determine the
result, the right operand is not evaluated
if (count != 0 && total/count > MAX)
System.out.println ("Testing…");
This type of processing must be used carefully
Repetition Statements
• Repetition statements allow us to execute a statement
multiple times
• Often they are referred to as loops
• Like conditional statements, they are controlled by
boolean expressions
• Java has three kinds of repetition statements:
– the while loop
– the do loop
– the for loop
• The programmer should choose the right kind of loop for
the situation
The while Statement
• The while statement has the following
syntax:
while is a
reserved word
while (condition)
statement;
If the condition is true, the statement is executed.
Then the condition is evaluated again.
The statement is executed repeatedly until
the condition becomes false.
50
while Loop Example
final int LIMIT = 5;
int count = 1;
Output:
while (count <= LIMIT) {
System.out.println(count);
count += 1;
}
1
2
3
4
5
Logic of a while Loop
condition
evaluated
true
false
statement
Note that if the condition of a while statement is false
initially, the statement is never executed. Therefore, the
body of a while loop will execute zero or more times
Infinite Loops
• The body of a while loop eventually must make
the condition false
• If not, it is an infinite loop, which will execute
until the user interrupts the program
• This is a common logical error
• You should always double check to ensure that
your loops will terminate normally
53
Nested Loops
• Similar to nested if statements, loops can
be nested as well
• That is, the body of a loop can contain
another loop
• Each time through the outer loop, the inner
loop goes through its full set of iterations
The do Statement
• The do statement has the following syntax:
do and
while are
reserved
words
do{
statement;
} while (condition);
The statement is executed once initially,
and then the condition is evaluated
The statement is executed repeatedly
until the condition becomes false
do-while Example
final int LIMIT = 5;
int count = 1;
Output:
do {
System.out.println(count);
count += 1;
} while (count <= LIMIT);
1
2
3
4
5
Comparing while and do
while loop
do loop
statement
condition
evaluated
true
true
false
condition
evaluated
statement
false
The for Statement
• The for statement has the following
syntax:
Reserved
word
The initialization
is executed once
before the loop begins
The statement is
executed until the
condition becomes false
for (initialization; condition; increment)
statement;
The increment portion is executed at the end of each iteration
The condition-statement-increment cycle is executed repeatedly
for Example
final int LIMIT = 5;
for (int count = 1; count <= LIMIT; count++) {
System.out.println(count);
}
Output:
1
2
3
4
5
The for Statement
• A for loop is functionally equivalent to the
following while loop structure:
initialization;
while (condition) {
statement;
increment;
}
Logic of a for loop
initialization
condition
evaluated
true
statement
increment
false
The for Statement
• Like a while loop, the condition of a for
statement is tested prior to executing the
loop body
• Therefore, the body of a for loop will
execute zero or more times
• It is well suited for executing a loop a
specific number of times that can be
determined in advance
The for Statement
• Each expression in the header of a for loop is optional
– If the initialization is left out, no initialization is
performed
– If the condition is left out, it is always considered to
be true, and therefore creates an infinite loop
– If the increment is left out, no increment operation is
performed
• Both semi-colons are always required in the for loop
header
Choosing a Loop Structure
• When you can’t determine how many times you
want to execute the loop body, use a while
statement or a do statement
– If it might be zero or more times, use a while
statement
– If it will be at least once, use a do statement
• If you can determine how many times you want
to execute the loop body, use a for statement
Summary
• Variables and types
– int count
• Assignments
– count = 55
• Arithmetic expressions
– result = count/5 + max
• Control flow
–
–
–
–
if – then – else
while – do
do –while
for