
Programming – Lecture 3 Expressions (Chapter 3) • Primitive types • Aside: Context Free Grammars • Constants, variaBles • Identifiers • VariaBle declarations • Arithmetic expressions • Operator precedence • Assignment statements • Booleans The Art and Science of Java An Introduction ERIC S. ROBERTS to Computer Science C H A P T E R 3 Expressions “What’s twice eleven?” I said to Pooh. (“Twice what?” said Pooh to Me.) “I think that it ought to be twenty-two.” “Just what I think myself,” said Pooh. —A. A. Milne, Now We Are Six, 1927 3.1 Primitive data types 3.2 Constants and variables 3.3 Operators and operands 3.4 Assignment statements 3.5 Boolean expressions 3.6 Designing for change Chapter 3—Expressions Expressions in Java • The heart of the Add2Integers program from Chapter 2 is the line int total = n1 + n2; that performs the actual addition. • The n1 + n2 that appears to the right of the equal sign is an example of an expression, which specifies the operations involved in the computation. • An expression in Java consists of terms joined together by operators. • Each term must be one of the following: – A constant (such as 3.14159265 or "hello, world") – A variable name (such as n1, n2, or total) – A method calls that returns a values (such as readInt) – An expression enclosed in parentheses Expressions int total = n1 + n2; Expression: terms (n1,n2) operators (+) Term: – Literal, a.k.a. (unnamed) constant (3.14) – VariaBle, including named constants (n1, or PI, as in static final PI = 3.14 – Method call (Math.abs(n1)) – Expression enclosed in parentheses 4 Aside: Context-Free Grammar (CFG) Can specify syntax of a program (or parts of a program) as CFG As some other material, this is not fully covered in the book, but still part of the class content. For further reference, see e.g.: https://en.wikipedia.org/wiki/Context- free_grammar Definition: CFG CFG defined By 4-tuple G = (V, Σ, R, S) • V is a set of nonterminal characters or variables • Σ, the alphabet, is finite set of terminals • R, the set of (rewrite) rules or productions, is relation from V to (V∪Σ)* • S ∈ V is the start variable (or start symbol) Note: * is the Kleene Star. For any set X, X* denotes 0 or more instances of elements of X Definition: Language For any strings u, v ∈ (V∪Σ)*, u directly yields v (written u ⇒ v) if ∃(α, β) ∈ R with α ∈ V and u1, u2 ∈ (V∪Σ)* and u = u1αu2 and v = u1βu2. Thus, v is a result of applying the rule (α, β) to u. Language of grammar G = (V, Σ, R, S) is the set L(G) = {w ∈ Σ* : S ⇒* w} where ⇒* is reflexive transitive closure of ⇒ A language L is said to be a context-free language (CFL), if there exists a CFG G, such that L = L(G) Example: Well-Formed Parentheses G = (V, Σ, R, S) with • VariaBles V = { S } • AlphaBet Σ = { (, ) } • Productions R = { S → SS, S → (S), S → () } May also write R as S → SS | (S) | () S → SS | (S) | () The string (()()) is valid, i.e., in L(G). Proof: consider the derivation S ⇒ (S) ⇒ (SS) ⇒ (()S) ⇒ (()()) However, the string )( is not in L(G), since there is no derivation from S to )( Parse Trees May use parse trees as compact S representation for derivation / | \ Internal nodes are variaBles, Leafs are terminals ( S ) / \ S ⇒ (S) ⇒ (SS) ⇒ (()S) ⇒ (()()) S S is a derivation that follows from / \ / \ parse tree on right ( ) ( ) Recall: S → SS | (S) | () Example: Parenthesized Sums a + b, u, x + (y + z), ... G = (V, Σ, R, S) with • VariaBles V = { S, P, X } • AlphaBet Σ = { (, ), +, a, ..., z } • Productions: S → S + P | P P → ( S ) | X X → a | ... | z S → S + P | P S P → ( S ) | X / | \ X → a | ... | z 3 S + P / | \ | Parse tree for a + (B + c) + d:2 S + P X | / | \ | P ( S ) d Parsing done Bottom-up; | / | \ higher precedence results in X S + P 1 lower position in parse tree | | | a P X Parentheses evaluated first | | + is evaluated left-to-right X c (left-associative) | B Note on Notation Formally, set of productions is a relation Can write this in different ways: R = { (S, SS), (S, (S)), (S, ()) } S: SS S → SS, S → (S), S → () (S) () S → SS | (S) | () Java Lexical Grammar • Is a CFG • Variant of BNF (Backus-Naur Form) • Terminals are from Unicode character set • Translate into input symbols that, with whitespace and comments discarded, form terminal symBols (tokens) for Java Syntactic Grammar Example: Decimal Numerals • Want to prohiBit leading 0 (except in 0 itself), to avoid clash with Octal Numeral • Therefore, must Be 0 or Begin with non-zero • Allow underscores, But not at Beginning or end DecimalNumeral: Digit: 0 0 NonZeroDigit [Digits] NonZeroDigit NonZeroDigit Underscores Digits DigitOrUnderscore: NonZeroDigit: Digit (one of) _ 1 2 3 4 5 6 7 8 9 Underscores: Digits: _ {_} Digit Digit [DigitsAndUnderscores] Digit DigitsAndUnderscores: DigitOrUnderscore {DigitOrUnderscore} Note: [] denote 0 or 1 occurrence, {} denote 0 or more occurrences https://docs.oracle.com/javase/specs/jls/se8/html/jls-2.html Primitive Data Types • Although complex data values are represented using objects, Java defines a set of primitive types to represent simple data. • Of the eight primitive types available in Java, the programs in this text use only the following four: int This type is used to represent integers, which are whole numbers such as 17 or –53. double This type is used to represent numbers that include a decimal fraction, such as 3.14159265. In Java, such values are called floating-point numbers; the name double comes from the fact that the representation uses twice the minimum precision. boolean This type represents a logical value (true or false). char This type represents a single character and is described in Chapter 8. Primitive Types Data type characterized By set of values (domain) + set of operations Type Domain Common operations The arithmetic operators: byte 8-bit integers in the range –128 to 127 + add * multiply 16-bit integers in the range –32768 to 32767 - subtract / divide short % remainder 32-bit integers in the range The relational operators: int –2146483648 to 2146483647 == equal to != not equal 64-bit integers in the range < less than <= less or equal long –9223372036754775808 to 9223372036754775807 > greater than >= greater or equal 32-bit floating-point numbers in the range float ±1.4 x 10-45 to ±3.4028235 x 10-38 The arithmetic operators except % 64-bit floating-point numbers in the range The relational operators double ±4.39 x 10-322 to ±1.7976931348623157 x 10308 char 16-bit characters encoded using Unicode The relational operators The logical operators: boolean the values true and false && and || or ! not The relational operators: == equal to !=not equal 18 Bit-Wise Operators Integer data are encoded in Binary int x = 42; // x encoded as 0010 10102 int y = 15; // y encoded as 0000 11112 Bit-wise operators refer to Binary encodings AND: x & y = 10 // 0000 10102 OR: x | y = 47 // 0010 11112 Shift left: y << 2 = 60 // 0011 11002 Shift right: y >> 2 = 3 // 0000 00112 19 ABstract Data Types (ADTs) ADT = set of values + set of operations + specification Specification may Be informal prose and/or mathematical equations that must hold (e.g., commutative/distriButive/associative laws) ADT abstracts from implementation 20 ADTs in Java In Java, typically implement ADT as class See also Michael S. Jenkins, ABstract Data Types in Java, Computing Mcgraw-Hill, 1997 http://www.e-reading.ws/Bookreader.php/ 138175/ABstract_Data_Types_in_Java.pdf 21 Constants and Variables • The simplest terms that appear in expressions are constants and variables. The value of a constant does not change during the course of a program. A variable is a placeholder for a value that can be updated as the program runs. • The format of a constant depends on its type: – Integral constants consist of a string of digits, optionally preceded by a minus sign, as in 0, 42, -1, or 1000000. – Floating-point constants include a decimal point, as in 3.14159265 or 10.0. Floating-point constants can also be expressed in scientific notation by adding the letter E and an exponent after the digits of the number, so that 5.646E-8 represents the number 5.646 x 10-8. – The two constants of type boolean are true and false. – Character and string constants are discussed in detail in Chapter 8. For the moment, all you need to know is that a string constant consists of a sequence of characters enclosed in double quotation marks, such as "hello, world". Constants and Variables • The simplest terms that appear in expressions are constants and variables. The value of a constant does not change during the course of a program. A variable is a placeholder for a value that can be updated as the program runs. • A variable in Java is most easily envisioned as a box capable of storing a value. total 42 (contains an int) • Each variable has the following attributes: – A name, which enables you to differentiate one variable from another. – A type, which specifies what type of value the variable can contain. – A value, which represents the current contents of the variable. • The name and type of a variable are fixed. The value changes whenever you assign a new value to the variable. Identifiers • Must Begin with letter or underscore • Remaining characters must Be letters, digits, or underscores • Must not Be one of Java’s reserved words: abstract else interface super boolean extends long switch break false native synchronized byte final new this case finally null throw catch float package throws char for private transient class goto protected true const if public try continue implements return void default import short volatile do instanceof static while double int strictfp 24 Variable Declarations • In Java, you must declare a variable before you can use it.
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages46 Page
-
File Size-