43
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

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

  • View
    215

  • Download
    2

Embed Size (px)

Citation preview

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

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

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

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

5unit 2

reading from memoryreading from memory

00000001000000100000000000000111

:1תא

תא 4:

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

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

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, ...

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?

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

11unit 2

variables in memoryvariables in memory

00000001000000100000000000000111

:1תא

תא 4:

} total

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;

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

}

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?

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

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

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

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

19unit 2

OperatorsOperators

arithmetic

increment and decrement

logical

assignment

conditional

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

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

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

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

}

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

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

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

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

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;

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

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

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)

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

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;

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;

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;

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

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

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

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;

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

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

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;

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