Top Banner
1 unit 2 Program Elements Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants operators and expressions data conversion basic programmin g concepts object oriented programmin g topics in computer science syllabus
43

Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

Dec 21, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

1unit 2

Program ElementsProgram Elements

We can now examine the core elements of programming (as implemented in Java)

We focuse on:• data types

• variable declaration and use, constants

• operators and expressions

• data conversion

basic programming

concepts

object oriented programming

topics in computer science

syllabus

Page 2: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

2unit 2

Data representationData representation

question: how to represent information in the computer, using the java language?

answer: java lets us represent information in 8 different ways

these representation formats are called data types

Page 3: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

3unit 2

Primitive Data TypesPrimitive Data Types

A data type is defined by a set of values and the operators you can perform on them

Each value stored in memory is associated with a particular data type; Java has several predefined types, called primitive data types

The following reserved words represent eight different primitive types:• byte, short, int, long • float, double• boolean • char

Page 4: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

4unit 2

IntegersIntegers

There are four separate integer primitive data types; they differ by the amount of memory used to store them

Type

byteshortintlong

Storage

8 bits16 bits32 bits64 bits

Min Value

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

Max Value

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

Page 5: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

5unit 2

reading from memoryreading from memory

00000001000000100000000000000111

:1תא

תא 4:

Page 6: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

6unit 2

Floating PointFloating Point

There are two floating point types:

Type

floatdouble

Storage

32 bits64 bits

ApproximateMin Value

-3.4 x 1038

-1.7 x 10308

ApproximateMax Value

3.4 x 1038

1.7 x 10308

Page 7: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

7unit 2

CharactersCharacters

A char value stores a single character from the Unicode character set

A character set is an ordered list of characters

The Unicode character set uses 16 bits per character, allowing for 65,536 unique characters

It is an international character set, containing symbols and characters from many world languages

Page 8: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

8unit 2

CharactersCharacters

The ASCII character set is still the basis for many other programming languages

ASCII is a subset of Unicode, including:

uppercase letterslowercase letterspunctuationdigitsspecial symbolscontrol characters

A B C …a b c …. , ; … 0 1 2 …& | \ …carriage return, tab, ...

Page 9: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

9unit 2

BooleanBoolean

A boolean value represents a true/false condition.

It can also be used to represent any two states, such as a light bulb being on or off

The reserved words true and false are the only valid values for a boolean type

how many bytes does this datatype use?

Page 10: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

10unit 2

VariablesVariables

A variable is an identifier (שם) that represents a storage in memory that holds a particular type of data

Variables must be declared before being used; the syntax of a variable declaration is:

data-type variable-name;

int total;

data typedata type variable namevariable name

Page 11: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

11unit 2

variables in memoryvariables in memory

00000001000000100000000000000111

:1תא

תא 4:

} total

Page 12: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

12unit 2

Details of variable declarationDetails of variable declaration

Multiple variables can be declared on the same line:

int total, count, sum;

Variables can be initialized (given an initial value) in the declaration:

int total = 0, count = 20;

double unitPrice = 57.25;

Page 13: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

13unit 2

Variables useVariables use

public static void main (String[] args) {

short weeks = 14;

int numberOfStudents = 120;

double averageFinalGrade = 78.6;

System.out.println(weeks);

System.out.println(numberOfStudents);

System.out.println(averageFinalGrade);

}

Page 14: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

14unit 2

ConstantsConstants

A constant is similar to a variable except that it keeps the same value throughout its existence;

Constants are specified using the reserved word final

It is better to use constants than literals because:• They make the code more readable by giving meaning to a

value

• They facilitate change because the value is only specified in one place

Q: assembler languages do not have constants; what do we do?

Page 15: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

15unit 2

Example - Constants useExample - Constants use

// Reads the radius of a circle and prints// its circumference and areaclass ConstantsExample { static final double PI = 3.1415927;

public static void main(String[] args) { double r, circumference, area;

System.out.println(“Enter radius: “); r = EasyInput.readDouble ();

circumference = 2*PI*r; area = PI*r*r; System.out.println(“Circumference: “ +circumference); System.out.println(“Area: “ + area); }}

Page 16: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

16unit 2

Assignment StatementsAssignment Statements

An assignment statement takes the following form:

variable-name = expression;

The expression is evaluated and the result is stored in the variable, overwriting the value currently stored in the variable

Page 17: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

17unit 2

Assignment Statements: exampleAssignment Statements: example

// Uses assignment to change a variable's value

public static void main (String[] args) {

int NumberOfStudents = 140;

System.out.println(“Students in 2001:”); System.out.println(NumberOfStudents);

NumberOfStudents = 170; System.out.println(" Students in 2000:”); System.out.println(NumberOfStudents); }

Page 18: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

18unit 2

OperatorsOperators

An operator is a mapping that maps one or more values to a single value

examples: +, -, *, / Java operators can be either:

• Unary operators - takes a single value (e.g., -)

• Binary operators - takes two values (e.g., +)

All Java binary operators are written in the infix notation:

operand1 operator operand2

Page 19: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

19unit 2

OperatorsOperators

arithmetic

increment and decrement

logical

assignment

conditional

Page 20: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

20unit 2

Arithmetic operatorsArithmetic operators

Java defines 5 arithmetic operators that are valid between every two numerical types

a + b add a and b a - b subtract b from a a * b multiply a and b a / b divide a by b a % b the remainder of dividing a by b

Page 21: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

21unit 2

5.0 / 2.0

5 / 2.0

5.0 / 2

5 / 2 2

5.0 / 2.0

5 / 2.0

5.0 / 2 2.5

5 / 2

5.0 / 2.0 2.5

5 / 2.0

5.0 / 2

5 / 2

5.0 / 2.0

5 / 2.0 2.5

5.0 / 2

5 / 2

Operators can act differently on different data types

5.0 / 2.0

5 / 2.0

5.0 / 2

5 / 2

Essentially these are different operators

OperatorsOperators

Page 22: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

22unit 2

ExpressionsExpressions

An expression can consist of a combination of operators and operands

Operands can be literal values, variables, or expressions by themselves

Examples of expressions: 4 + 5 x * 2.73 a - (7 - b) x

Page 23: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

23unit 2

Expression exampleExpression example

public static void main (String[] args) {

int numberOfBooks = 30; double bookPrice = 45.90; double totalPrice;

totalPrice = numberOfBooks * bookPrice;

System.out.println( “The total price is:”); System.out.println(totalPrice);

}

Page 24: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

24unit 2

Operator PrecedenceOperator Precedence

The order in which operands are evaluated in an expression is determined by a well-defined precedence hierarchy

Operators at the same level of precedence are evaluated according to their associativity (right to left or left to right)

Parentheses can be used to force precedence

Page 25: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

25unit 2

Operator PrecedenceOperator Precedence

Multiplication, division, and remainder have a higher precedence than addition and subtraction

Both groups associate left to right

Expression:

Order of evaluation:

Result:

5 + 12 / 5 - 10 % 3

43 21

6

Page 26: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

26unit 2

Operator PrecedenceOperator Precedence

What is the order of evaluation in the following expressions?

a + b + c + d + e1 432

a + b * c - d / e3 241

a / (b + c) - d % e2 341

a / (b * (c + (d - e)))4 123

Page 27: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

27unit 2

Assignment RevisitedAssignment Revisited

The assignment operator has a lower precedence than the arithmetic operators

First the expression on the right handFirst the expression on the right handside of the = operator is evaluatedside of the = operator is evaluated

Then the result is stored in theThen the result is stored in thevariable on the left hand sidevariable on the left hand side

answer = sum / 4 + MAX * lowest;

14 3 2

Page 28: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

28unit 2

Assignment RevisitedAssignment Revisited

The right and left hand sides of an assignment statement can contain the same variable

First, one is added to theFirst, one is added to theoriginal value of original value of countcount

Then the result is stored back into Then the result is stored back into countcount((overwriting the original valueoverwriting the original value))

count = count + 1;

Page 29: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

29unit 2

String ConcatenationString Concatenation

The ‘+’ operator between strings has the meaning of String concatenation

When we apply ‘+’ upon a String and a value of another type, that value is first converted into a String and the result is the concatenation of the two Strings

Page 30: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

30unit 2

String ConcatenationString Concatenation

public static void main(String[] args) { System.out.print(“The international “ + “dialing code”); System.out.println(“for Israel is “ + 972); }

Output:

The international dialog code for Israel is 972

Page 31: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

31unit 2

Data ConversionsData Conversions

Sometimes it is convenient to convert data from one type to another; e.g., we may want to treat an integer as a floating point value during a computation

Conversions must be handled carefully to avoid losing information:• Widening conversions are safest because they tend to go

from a specific data type to a general one (such as int to float)

• Narrowing conversions can lose information because they tend to go from a general data type to a more specific one (such as float to int)

Page 32: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

32unit 2

Data ConversionsData Conversions

In Java, data conversions can occur in three ways:

• Assignment conversion occurs when a value of one type is assigned to a variable of another; only widening conversions can happen via assignment

• Arithmetic promotion happens automatically when operators in expressions convert their operands

• Casting

Page 33: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

33unit 2

Data Conversions: castingData Conversions: casting

Casting is the most powerful, and dangerous, technique for conversion

Both widening and narrowing conversions can be accomplished by explicitly casting a value

To cast, the type is put in parentheses in front of the value being converted

int total, count;

result = (float) total / count;

Page 34: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

34unit 2

The Increment and Decrement OperatorsThe Increment and Decrement Operators

The increment operator (++) adds one to its integer or floating point operand

The decrement operator (--) subtracts one

The statement

count++;

is essentially equivalent to

count = count + 1;

Page 35: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

35unit 2

The Increment and Decrement OperatorsThe Increment and Decrement Operators

The increment and decrement operators can be applied in prefix (before the variable) or postfix (after the variable) form

When used alone in a statement, the prefix and postfix forms are basically equivalent. That is,

count++;

is equivalent to

++count;

Page 36: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

36unit 2

The Increment and Decrement OperatorsThe Increment and Decrement Operators

When used in a larger expression, the prefix and postfix forms have a different effect

In both cases the variable is incremented (decremented)

But the value used in the larger expression depends on the form

Expression

count++++countcount----count

Operation

add 1add 1

subtract 1subtract 1

Value of Expression

old valuenew valueold valuenew value

Page 37: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

37unit 2

The Increment and Decrement OperatorsThe Increment and Decrement Operators

If count currently contains 45, then

total = count++;

assigns 45 to total and 46 to count

If count currently contains 45, then

total = ++count;

assigns the value 46 to both total and count

Page 38: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

38unit 2

The Increment and Decrement OperatorsThe Increment and Decrement Operators

If sum contains 25, then the statement

System.out.println (sum++ + " " +

++sum + " " + sum + " " +

sum--);

prints the following result:

and sum contains after the line is complete25 27 27 27

26

Page 39: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

39unit 2

Assignment OperatorsAssignment Operators

Often we perform an operation on a variable, then store the result back into that variable

Java provides assignment operators that simplify that process

For example, the statement

sum += value;

is equivalent to

sum = sum + value;

Page 40: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

40unit 2

Assignment OperatorsAssignment Operators

There are many such assignment operators, always written as op= , such as:

Operator

+=-=*=/=%=

Example

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

Equivalent To

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

Page 41: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

41unit 2

Assignment OperatorsAssignment Operators

The right hand side of an assignment operator can be a complete expression

The entire right-hand expression is evaluated first, then combined with the additional operation

Therefore result /= (total-MIN) % n;

is equivalent to result = result /

((total-MIN) % n);

Page 42: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

42unit 2

How many different ways to doHow many different ways to do......

int x=0,y=0;

x=1; y=2;

int x=1;y=1;

x=2; y=2;

Page 43: Unit 2 1 Program Elements H We can now examine the core elements of programming (as implemented in Java) H We focuse on: data types variable declaration.

43unit 2

What you should be able to doWhat you should be able to do......

write programs which have variables perform simple arithmetic operations and store the

output value for further use