3. Java - Language Constructs I Convention for class names: use - - PowerPoint PPT Presentation

3 java language constructs i
SMART_READER_LITE
LIVE PREVIEW

3. Java - Language Constructs I Convention for class names: use - - PowerPoint PPT Presentation

Names and Identifiers A program (that is, a class) needs a name public class SudokuSolver { ... 3. Java - Language Constructs I Convention for class names: use CamelCase Words are combined into one word, each starting with a capital letter


slide-1
SLIDE 1
  • 3. Java - Language Constructs I

Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations, Evaluation of Expressions, Type Conversions

62

Names and Identifiers

A program (that is, a class) needs a name

public class SudokuSolver { ...

Convention for class names: use CamelCase → Words are combined into one word, each starting with a capital letter Allowed names for “entities” in a program: Names begin with a letter or _ or $ Then, sequence of letters, numbers or _ or $

63

Names - what is allowed

_myName TheCure __AN$WE4_1S_42__ $bling$ me@home 49ers side-swipe Ph.D’s strictfp ?!

64

Keywords

The following words are already used by the language and cannot be used as names:

abstract continue for new switch assert default goto package synchronized boolean do if private this break double implements protected throw byte else import public throws case enum instanceof return transient catch extends int short try char final interface static void class finally long strictfp volatile const float native super while

65

slide-2
SLIDE 2

Variables and Constants

Variables are buckets for a value Have a data type and a name The data type determines what kind of values are allowed in the variable

23 int x 42 int y 0.0f float f ’a’ char c

Declaration in Java:

int x = 23, y = 42; float f; char c = ’a’;

Initialization

66

Constants

Keyword final The value of the variable can be set exactly once Example

final int maxSize = 100;

Hint: Always use final, unless the value actually needs to change

  • ver time.

67

Standard Types

Data Type Definition Value Range Initial Value byte 8-bit integer −128, . . . , 127 short 16-bit integer −32′768, . . . , 32′767 int 32-bit integer −231, . . . , 231 − 1 long 64-bit integer −263, . . . , 263 − 1 0L float 32-bit floating point ±1.4E−45, . . . , ±3.4E+38 0.0f double 64-bit floating point ±4.9E−324, . . . , ±1.7E+308 0.0d boolean logical value true, false false char unicode-16 character ’\u0000’,. . . ,’a’,’b’,. . . ,’\uFFFF’ ’\u0000’ String string ∞ null

68

Types and Memory Usage

Reminder: Memory cells contain 1 Byte = 8 bit

byte

boolean

short, char int, float long, double

69

slide-3
SLIDE 3

Literals: Integer Numbers

Type int (or short, byte)

12 : value 12

  • 3 : value −3

Type long

25_872_224L : value 25′872′224

Hint: Underscores between digits are allowed!

70

Literals: Floating Point Numbers

are different from integers by providing decimal comma

1.0 : type double, value 1 1.27f : type float, value 1.27

and / or exponent.

1e3 : type double, value 1000 1.23e-7 : type double, value 1.23 · 10−7 1.23e-7f : type float, value 1.23 · 10−7

1.23e-7f

integer part fractional part exponent

71

Literals: Characters and Strings

Individual characters:

’a’ : Type char, value 97

Strings:

"Hello There!" : Type String "a" : Type String

Mind: Characters and Strings are two different things!

72

Character: In ASCII Table

73

slide-4
SLIDE 4

Value Assignment

In pseudo code: x ← value In Java: x = value

Copies a value into variable x

value value x

(copy)

“=” is the assignment operator and not a comparison! Therefore, int y = 42 is both a declaration + an assignment.

74

Value Assignment

Examples

int a = 3; double b; b = 3.141; int c = a = 0; String name = "Inf";

A nested assignment: The expression a = 0 stores the value 0 into variable a. and then returns the value

75

Arithmetic Binary Operators

Infix notation: x op y with the following operators

  • p: + − ∗ / %

modulo Precedence: Multiplication, division, and modulo first, then addition and subtraction Associativity: Evaluation from left to right

76

Arithmetic Binary Operators

Division x / y: Integer division if x and y are integer. Division x / y: Floating-point division if x or y is a floating-poing number! Examples Integer division and modulo

5 / 3

evaluates to 1

−5 / 3

evaluates to −1

5 % 3

evaluates to 2

−5 % 3

evaluates to −2

77

slide-5
SLIDE 5

Arithmetic Assignment

x = x + y

  • x += y

Analogous for −, ∗, /, % Examples:

x −= 3; // x = x − 3 name += "x" // name = name + "x" num ∗= 2; // num = num ∗ 2

78

Arithmetic Unary Operators

Prefix notation: + x or − x Precedence: Unary operators bind stronger than binary operators Examples Assuming x is 3

2 ∗ −x

evaluates to −6

−x − +1

evaluates to −4

79

Increment/Decrement Operators

Increment operators ++x and x++ have the same effect:

x ← x + 1.But different return values:

Prefix operator ++x returns the new value:

a = ++x; ⇐ ⇒ x = x + 1; a = x;

Postfix operator x++ returns the old value:

a = x++; ⇐ ⇒ temp = x; x = x + 1; a= temp;

Precedence: Increment and decrement operators bind stronger than unary operators Analogous for x−− and −−x.

80

Increment/Decrement Operators

Examples Assuming x is initially set to 2

y = ++x ∗ 3

evaluates to: x is 3 and y is 9

y = x++ ∗ 3

evaluates to: x is 3 and y is 6

81

slide-6
SLIDE 6

Expressions

represent computations are either primary

  • r composed . . .

. . . from other expressions, using operators are statically typed Analogy: Construction kit

82

Expressions

Examples primary: “−4.1d” or “x” or "Hi" composed: “x + y” or “f ∗ 2.1f” The type of “12 ∗ 2.1f” is float

83

Celsius to Fahrenheit

public class Main { public static void main(String[] args) { Out.print("Celsius: "); int celsius = In.readInt(); float fahrenheit = 9 * celsius / 5 + 32; Out.println("Fahrenheit: " + fahrenheit); } }

Example: 15◦ Celsius are 59◦ Fahrenheit

84

Celsius to Fahrenheit - Analysis

9 * celsius / 5 + 32

Arithmetic expression, contains three literals, one variable, three operator symbols Where are the brackets in this expression?

85

slide-7
SLIDE 7

Rule 1: Precedence

Multiplicative operators (*, /, %) have a higher precedence ("bind stronger") than additive operators (+, -). Example

9 * celsius / 5 + 32

means

(9 * celsius / 5) + 32

86

Rule 2: Associativity

Arithmetic operators (*, /, %, +, -) are left-associative: in case of the same precedence, the evaluation happens from left to right. Example

9 * celsius / 5 + 32

means

((9 * celsius) / 5) + 32

87

Rule 3: Arity

Unary operators +, - before binary operators +, -. Example

9 * celsius / + 5 + 32

means

9 * celsius / (+5) + 32

88

Bracketing

Any expression can be bracketed unambiguously using the associativities precedences arities (number of operands)

  • f the involved operators.

89

slide-8
SLIDE 8

Expression Trees

Bracketing leads to an expression tree

(((9 * celsius) / 5) + 32)

+ / * 9 celsius 5 32

90

Evaluation Order

“From leafs to the root” in the expression tree

9 * celsius / 5 + 32

+ / * 9 celsius 5 32

91

Expression Trees – Notation

Usual notation: root on top

9 * celsius / 5 + 32

+ / * 9 celsius 5 32

92

Type System

Java festures a static type system: All types must be declared If possible, the compiler checks the typing . . . . . . otherwise it’s checked at run-time Advantages of a static type system Fail-fast Bugs in the program are often found already by the compiler Understandable code

93

slide-9
SLIDE 9

Type errors

Example

int pi_ish; float pi = 3.14f; pi_ish = pi;

Compiler error:

./Root/Main.java:12: error: incompatible types: possible lossy conversion from float to int pi_ish = pi; ^

94

Explicit Type Conversion

Example

int pi_ish; float pi = 3.14f; pi_ish = (int) pi;

Explicit type conversion using casts (type) Statically type-correct, compiler is happy Run-time behavior: depends on the situation

Here: loss of precision: 3.14 ⇒ 3

Can crash a program at run-time

95

Type Conversion - Visually for Integer Numbers

byte short int long

explicit cast implicit conversion

Potential loss of information when casting explicitly, because less memory available to represent the number

96

Mixed Expressions, Conversion

Floating point numbers are more general than integers. In mixed expressions integers are converted to floating point numbers.

9 * celsius / 5 + 32

97

slide-10
SLIDE 10

Type Conversions for Binary Operations

Numeric operands in a binary operation are being converted according to the following rules:

If both operands have the same type, no conversion will happen If one operand is double, the other operand is converted to double as well If one operand is float, the other operand is converted to float as well If one operand is long, the other operand is converted to long as well Otherwise: Both operands are being converted to int

98

  • 4. Efficiency of algorithms

Efficiency of Algorithms, Random Access Machine Model, Function Growth, Asymptotics [Cormen et al, Kap. 2.2,3,4.2-4.4 | Ottman/Widmayer, Kap. 1.1]

99

Efficiency of Algorithms

Goals Quantify the runtime behavior of an algorithm independent of the machine. Compare efficiency of algorithms. Understand dependece on the input size.

100

Technology Model

Random Access Machine (RAM) Execution model: instructions are executed one after the other (on

  • ne processor core).

Memory model: constant access time. Fundamental operations: computations (+,−,·,...) comparisons, assignment / copy, flow control (jumps) Unit cost model: fundamental operations provide a cost of 1. Data types: fundamental types like size-limited integer or floating point number.

101

slide-11
SLIDE 11

Size of the Input Data

Typical: number of input objects (of fundamental type). Sometimes: number bits for a reasonable / cost-effective representation of the data.

102

Asymptotic behavior

An exact running time can normally not be predicted even for small input data. We consider the asymptotic behavior of the algorithm. And ignore all constant factors. Example An operation with cost 20 is no worse than one with cost 1 Linear growth with gradient 5 is as good as linear growth with gradient 1.

103

4.2 Function growth

O, Θ, Ω [Cormen et al, Kap. 3; Ottman/Widmayer, Kap. 1.1]

104

Superficially

Use the asymptotic notation to specify the execution time of algorithms. We write Θ(n2) and mean that the algorithm behaves for large n like

n2: when the problem size is doubled, the execution time multiplies

by four.

105

slide-12
SLIDE 12

More precise: asymptotic upper bound

provided: a function g : ◆ → ❘. Definition:

O(g) = {f : ◆ → ❘| ∃c > 0, n0 ∈ ◆ : 0 ≤ f(n) ≤ c · g(n) ∀n ≥ n0}

Notation:

O(g(n)) := O(g(·)) = O(g).

106

Graphic

g(n) = n2 f ∈ O(g) h ∈ O(g) n

107

Examples

O(g) = {f : ◆ → ❘| ∃c > 0, n0 ∈ ◆ : 0 ≤ f(n) ≤ c · g(n) ∀n ≥ n0} f(n) f ∈ O(?)

Example

3n + 4 O(n) c = 4, n0 = 4 2n O(n) c = 2, n0 = 0 n2 + 100n O(n2) c = 2, n0 = 100 n + √n O(n) c = 2, n0 = 1

108

Property

f1 ∈ O(g), f2 ∈ O(g) ⇒ f1 + f2 ∈ O(g)

109

slide-13
SLIDE 13

Converse: asymptotic lower bound

Given: a function g : ◆ → ❘. Definition:

Ω(g) = {f : ◆ → ❘| ∃c > 0, n0 ∈ ◆ : 0 ≤ c · g(n) ≤ f(n) ∀n ≥ n0}

110

Example

g(n) = n f ∈ Ω(g) h ∈ Ω(g) n0

111

Asymptotic tight bound

Given: function g : ◆ → ❘. Definition:

Θ(g) := Ω(g) ∩ O(g).

Simple, closed form: exercise.

112

Example

g(n) = n2 f ∈ Θ(n2) h(n) = 0.5 · n2

113

slide-14
SLIDE 14

Notions of Growth

O(1)

bounded array access

O(log log n)

double logarithmic interpolated binary sorted sort

O(log n)

logarithmic binary sorted search

O(√n)

like the square root naive prime number test

O(n)

linear unsorted naive search

O(n log n)

superlinear / loglinear good sorting algorithms

O(n2)

quadratic simple sort algorithms

O(nc)

polynomial matrix multiply

O(2n)

exponential Travelling Salesman Dynamic Programming

O(n!)

factorial Travelling Salesman naively

114

Small n

2 3 4 5 6 20 40 60 ln n n n2 n4 2n

115

Larger n

5 10 15 20 0.2 0.4 0.6 0.8 1 ·106 log n n n2 n4 2n

116

“Large” n

20 40 60 80 100 0.2 0.4 0.6 0.8 1 ·1020 log n n n2 n4 2n

117

slide-15
SLIDE 15

Logarithms

10 20 30 40 50 200 400 600 800 1,000 n n2 n3/2 log n n log n

118

Time Consumption

Assumption 1 Operation = 1µs.

problem size

1 100 10000 106 109 log2 n 1µs 7µs 13µs 20µs 30µs n 1µs 100µs 1/100s 1s 17 minutes n log2 n 1µs 700µs 13/100µs 20s 8.5 hours n2 1µs 1/100s 1.7 minutes 11.5 days 317 centuries 2n 1µs 1014 centuries ≈ ∞ ≈ ∞ ≈ ∞

119

A good strategy?

... Then I simply buy a new machine If today I can solve a problem of size n, then with a 10 or 100 times faster machine I can solve ...

Komplexität (speed ×10) (speed ×100)

log2 n n → n10 n → n100 n n → 10 · n n → 100 · n n2 n → 3.16 · n n → 10 · n 2n n → n + 3.32 n → n + 6.64

120

Examples

n ∈ O(n2) correct, but too imprecise: n ∈ O(n) and even n ∈ Θ(n). 3n2 ∈ O(2n2) correct but uncommon:

Omit constants: 3n2 ∈ O(n2).

2n2 ∈ O(n) is wrong: 2n2

cn = 2 cn → n→∞ ∞ !

O(n) ⊆ O(n2) is correct Θ(n) ⊆ Θ(n2) is wrong n ∈ Ω(n2) ⊃ Θ(n2)

121

slide-16
SLIDE 16

Useful Tool

Theorem Let f, g : ◆ → ❘+ be two functions, then it holds that

1 limn→∞

f(n) g(n) = 0 ⇒ f ∈ O(g), O(f) O(g).

2 limn→∞

f(n) g(n) = C > 0 (C constant) ⇒ f ∈ Θ(g).

3

f(n) g(n) → n→∞ ∞ ⇒ g ∈ O(f), O(g) O(f).

122

About the Notation

Common notation

f = O(g)

should be read as f ∈ O(g). Clearly it holds that

f1 = O(g), f2 = O(g)⇒f1 = f2!

Beispiel

n = O(n2), n2 = O(n2) but naturally n = n2.

123

Algorithms, Programs and Execution Time

Program: concrete implementation of an algorithm. Execution time of the program: measurable value on a concrete

  • machine. Can be bounded from above and below.

Beispiel

3GHz computer. Maximal number of operations per cycle (e.g. 8). ⇒ lower bound. A single operations does never take longer than a day ⇒ upper bound.

From an asymptotic point of view the bounds coincide.

124

Complexity

Complexity of a problem P: minimal (asymptotic) costs over all algorithms A that solve P. Complexity of the single-digit multiplication of two numbers with n digits is Ω(n) and O(nlog3 2) (Karatsuba Ofman). Example: Problem Complexity

O(n) O(n) O(n2) ↑ ↑ ↑

Algorithm Costs2

3n − 4 O(n) Θ(n2) ↓

  • Program

Execution time

Θ(n) O(n) Θ(n2)

2Number funamental operations 125