General Features of the Java Programming Language Variables and Data Types Operators Expressions...

65
General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements

Transcript of General Features of the Java Programming Language Variables and Data Types Operators Expressions...

Page 1: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

General Features of theJava Programming Language

Variables and Data TypesOperators

ExpressionsControl Flow Statements

Page 2: 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

Page 3: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

Algorithm design• Pancakes

800g flower4 tsp sucker1 tsp salt12 eggs16 dl milk12 sp water

1. Pour the milk in a bowl2. Pour the water in the bowl3. Add the salt4. Add the sucker5. As long as there are eggs left

1. Take an egg2. Break the egg3. Put in the bowl

6. Add the flower7. Turn the dew

Page 4: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

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;

Robot.pourMilkInBowl(dlMilk); Robot.pourWaterInBowl(spWater); Robot.putSaltInBowl(tspSalt); Robot.putSugarInBowl(tspSugar); …

Variables are declared before they are used

The program is read sequentially from top to bottom

Page 5: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

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

Page 6: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

The “Hello World” Application

revisited

Page 7: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

Create a Java Source File

public class HelloWorld {public static void main(String[] args) {System.out.println("Hello World!");}

}

Page 8: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

Compile and Run

• Compile– javac HelloWorld.java

• One file named HelloWorld.class is created if the compilation is succeeds.

• Run– java HelloWorld

..\Java1\examples

Page 9: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

Writing, compiling and running a Java Program

Java Compiler

Java Interpreter

Java Source Java Bytecode

Compile

Run

<file>.java <file>.class

javac HelloWorld.java java HelloWorld

Created using NotePad

Page 10: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

10

Java Program Structure

public class MyProgram {

}

// comments about the class

class header

class body

Comments can be placed almost anywhere

This class is written in a file named: MyProgram.java

Page 11: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

11

Java Program Structure

public class MyProgram {

}

public static void main(String[] args) {

}

// comments about the class

// comments about the method

method headermethod body

Page 12: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

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 methodinformation provided to the method

(parameters)

Page 13: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

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,

…)

int total;

data type variable name

Page 14: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

Primitive and Reference Data Type

int x;x = 5;

x: 5

Point p1, p2;p1 = new Point();p2 = p1;

p1:

p2:

x: 0

y: 0Primitive Data

TypeReference Data Type

Page 15: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

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

Page 16: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

Reserved Words(Keywords)

abstract default if private throwboolean do implements protected throwsbreak double import public transientbyte else instanceof return trycase extends int short voidcatch final interface static volatilechar finally long super whileclass float native switchconst* for new synchronizedcontinue goto* package 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.

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.

Page 17: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

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

Page 18: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

Variable Scope

Page 19: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

Variables

• A variable can be given an initial value in the declaration

• 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

int sum = 0;int base = 32, max = 149;

Page 20: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

Assignment

• An assignment statement changes the value of a variable

• The assignment operator is the = sign

total = 55;

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

The expression on the right is evaluated and the result is stored in the variable on the left

Page 21: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

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

Page 22: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

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

Page 23: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

Numeric Primitive Types

• The difference between the various numeric primitive types is their size, and therefore the values they can store:

Type

byteshortintlong

floatdouble

Storage

8 bits16 bits32 bits64 bits

32 bits64 bits

Min Value

-128-32,768-2,147,483,648< -9 x 1018

+/- 3.4 x 1038 with 7 significant digits+/- 1.7 x 10308 with 15 significant digits

Max Value

12732,7672,147,483,647> 9 x 1018

Page 24: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

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'

Page 25: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

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

Page 26: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

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);

Page 27: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

27

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;

Page 28: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

28

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;

Page 29: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

29

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

count++++countcount----count

Operation

add 1add 1

subtract 1subtract 1

Value Used in Expression

old valuenew valueold valuenew value

Page 30: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

30

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

Page 31: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

31

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;

Page 32: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

32

Assignment Operators

• There are many assignment operators, including the following:

Operator

+=-=*=/=%=

Example

x += yx -= yx *= yx /= yx %= y

Equivalent To

x = x + yx = x - yx = x * yx = x / yx = x % y

Page 33: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

33

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);

Page 34: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

Relational operators

• > greater than

• >= greater than or equal to

• < less than

• <= less than or equal to

• == equal to

• != not equal to

Page 35: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

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.

Page 36: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

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

Page 37: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

37

The if Statement

• The if statement has the following syntax:

if (condition) statement;

if is a Javareserved word

The condition must be a boolean expression.It must evaluate to either true or false.

If the condition is true, the statement is executed.If it is false, the statement is skipped.

Page 38: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

38

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

Page 39: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

39

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++; }

Page 40: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

40

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 to which an else clause belongs

Page 41: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

Multiway Selection: Else if

• Sometime you want to select one option from several alternatives

if (conditon1)

statement1;

else if (condition2)

statement2;

else if (condition3)

statement3;

else

statement4;

conditon1evaluated

conditon2evaluated

conditon3evaluated

statement1

statement2

statement3

statement4

true

true

true

false

false

false

Page 42: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

Exampleint 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

Page 43: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

43

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 operates on two operands)

Page 44: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

44

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

Page 45: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

45

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

Page 46: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

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

Page 47: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

47

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 operatorslogical NOT has higher precedence than logical AND and logical OR

Page 48: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

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

Page 49: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

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

Page 50: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

50

The while Statement

• The while statement has the following syntax:

while (condition) statement;

while is areserved word

If the condition is true, the statement is executed.Then the condition is evaluated again.

The statement is executed repeatedly untilthe condition becomes false.

Page 51: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

while Loop Example

final int LIMIT = 5;int count = 1;

while (count <= LIMIT) {

System.out.println(count);

count += 1;

}

Output:

12345

Page 52: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

Logic of a while Loop

statement

true

conditionevaluated

false

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

Page 53: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

53

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

Page 54: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

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

Page 55: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

The do Statement

• The do statement has the following syntax:

do{ statement;} while (condition);

do andwhile arereserved

words

The statement is executed once initially,and then the condition is evaluated

The statement is executed repeatedlyuntil the condition becomes false

Page 56: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

do-while Example

final int LIMIT = 5;int count = 1;

do {

System.out.println(count);

count += 1;

} while (count <= LIMIT);

Output:

12345

Page 57: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

Comparing while and do

statement

true

conditionevaluated

false

while loop

true

conditionevaluated

statement

false

do loop

Page 58: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

The for Statement

• The for statement has the following syntax:

for (initialization; condition; increment) statement;

Reservedword

The initializationis executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed at the end of each iterationThe condition-statement-increment cycle is executed repeatedly

Page 59: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

for Example

final int LIMIT = 5;

for (int count = 1; count <= LIMIT; count++) {

System.out.println(count);}

Output:

12345

Page 60: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

The for Statement

• A for loop is functionally equivalent to the following while loop structure:

initialization;while (condition) { statement; increment;}

Page 61: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

Page 62: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

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

Page 63: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

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

Page 64: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

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

Page 65: General Features of the Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.

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