Programming Lecture 3

Size: px
Start display at page:

Download "Programming Lecture 3"

Transcription

1 Five-Minute Review 1. What is a variable? 2. What is a class? An object? 3. What is a package? 4. What is a method? A constructor? 5. What is an object variable? 1

2 Programming Lecture 3 Expressions etc. (Chapter 3) Aside: Context Free Grammars Expressions Primitive types Aside: representing integers Constants, variables Identifiers Variable declarations Arithmetic expressions Operator precedence Assignment statements Booleans 2

3 Aside: Context-Free Grammars (CFGs) 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.: 4

4 Why You Should Care About CFGs The Java Language Specification Table of Contents 1. Introduction 1.1. Organization of the Specification 1.2. Example Programs 1.3. Notation 1.4. Relationship to Predefined Classes and Interfaces 1.5. Feedback 1.6. References 2. Grammars 2.1. Context-Free Grammars 2.2. The Lexical Grammar 2.3. The Syntactic Grammar 2.4. Grammar Notation... The Java Language Specification The Java Language Specification The Java Language Specification Next Separators Operators Integral Types and Values Integer Operations Floating Point Types, Formats, and Values Floating Point Operations The boolean Type and boolean Values Bill Joy Guy Steele Daniel Smith 3. Lexical Structure The Java Language Specification Access Control Determining Accessibility Details on protected Access The Java Language Specification Static Member Type Declarations The Java Language Specification When Initialization Occurs Detailed Initialization Procedure 8.9. Enum Types Enum Constants Enum Body Declarations Enum Members The Kinds of Exceptions The Causes of Exceptions Asynchronous Exceptions Interface Modifiers abstract Interfaces strictfp Interfaces Compile Time Checking of Exceptions Exception Analysis of Expressions Exception Analysis of Statements Exception Checking Generic Interfaces and Type Parameters Superinterfaces and Subinterfaces Interface Body and Member Declarations Java Virtual Machine Startup Load the Class Test Link Test: Verify, Prepare, (Optionally) Resolve Initialize Test: Execute Initializers Invoke Test.main Inheritance and Overriding Overriding (by Instance Methods) Requirements in Overriding Inheriting Methods with Override Equivalent Signatures /15 The Java Language Specification Integer Bitwise Operators &, ^, and Boolean Logical Operators &, ^, and Method Invocation Expressions Lambda Parameters Lambda Body Type of a Lambda Expression Run Time Evaluation of Lambda Expressions Constant Expressions Boolean Constant Expressions Conditional And Operator && Conditional Or Operator Logical Complement Operator! Conditional Operator? : Conditional Operator? : Other Expressions of Type boolean Assignment Expressions Operators ++ and Other Expressions Expression Names Postfix Increment Operator Postfix Decrement Operator Prefix Increment Operator Prefix Decrement Operator Unary Plus Operator Unary Minus Operator Bitwise Complement Operator ~ Logical Complement Operator! Word Tearing Non Atomic Treatment of double and long 18. Type Inference Concepts and Notation Inference Variables Constraint Formulas Bounds Definite Assignment and Statements Empty Statements Blocks Local Class Declaration Statements Cast Expressions Semantics of final Fields Reading final Fields During Construction Subsequent Modification of final Fields Write Protected Fields Definite Assignment and Expressions Unary Operators 9/15 The Java Language Specification Reduction Expression Compatibility Constraints 10/15 The Java Language Specification 13/ / /15 The Java Language Specification Enhanced for And Arrays Enhanced for And Unboxing Conversion The break Statement The continue Statement The synchronized Statement Catching An Exception Handling An Uncaught Exception With finally Conditional Compilation Left Hand Operand Is Evaluated First Implicit Left Hand Operand In Operator Of Compound Assigment Abrupt Completion of Evaluation of the Left Hand Operand Evaluation of Operands Before Operation Evaluation Order At Method Invocation Abrupt Completion of Argument Expression The this Expression Evaluation Order and Out Of Memory Detection Array Creation Evaluation Multi Dimensional Array Creation OutOfMemoryError and Dimension Expression Evaluation Array Reference Is Evaluated First Abrupt Completion of Array Reference Evaluation null Array Reference Static Binding for Field Access Receiver Variable Is Irrelevant For static Field Access The super Expression Method Applicability Return Type Not Considered During Method Selection Choosing The Most Specific Method Target References and static Methods Evaluation Order During Method Invocation Overriding and Method Invocation Method Invocation Using super Invoked Method Signature Has Different Erasure Than Compile Time Method Signature Integer Remainder Operator Floating Point Remainder Operator String Concatenation String Concatenation and Conditionals The instanceof Operator Simple Assignment To An Array Component Compound Assignment To An Array Component Value Of Left Hand Side Of Compound Assignment Is Saved Before Evaluation Of Right Hand Side Constant Expressions Definite Assignment Considers Structure of Statements and Expressions Definite Assignment Does Not Consider Values of Expressions Definite Unassignment Incorrectly Synchronized Programs May Exhibit Surprising Behavior Happens before Consistency Happens before Consistency Is Not Sufficient final Fields In The Java Memory Model final Fields For Security Aggressive Optimization of final Fields Detection of Word Tearing Overloading Overloading, Overriding, and Hiding Constructor Declarations Constructor Bodies Restrictions on Explicit Constructor Invocation Statements Qualified Superclass Constructor Invocation Default Constructors Accessibility of Constructors v. Classes Preventing Instantiation via Constructor Accessibility Enum Body Declarations Restriction On Enum Constant Self Reference Iterating Over Enum Constants With An Enhanced for Loop Switching Over Enum Constants Enum Constants with Class Bodies Multiple Enum Types Ambiguous Inherited Fields Multiply Inherited Fields Forward Reference to a Field Overloading an abstract Method Declaration Annotation Type Declaration Marker Annotation Type Declaration Single Element Annotation Type Declarations Annotation Type Declaration With Default Values Ill formed Containing Annotation Type Restricting Where Annotations May Repeat A Repeatable Containing Annotation Type Normal Annotations Marker Annotations Single Element Annotations Functional Interfaces Functional Interfaces and Erasure Generic Functional Interfaces Function Types Generic Function Types Declarations of Array Variables Array Variables and Array Types Array Access ArrayStoreException Array Initializers Arrays Are Cloneable Shared Subarrays After A Clone Class Object Of Array Array Class Objects Are Shared Catching Checked Exceptions Throwing and Catching Exceptions Superclasses Are Initialized Before Subclasses Only The Class That Declares static Field Is Initialized Interface Initialization Does Not Initialize Superinterfaces Evaluation of Instance Creation Dynamic Dispatch During Instance Creation Changing A Superclass Changing A Class Body Changing A Superclass Changing Accessibility Adding A Field Declaration Changing A Variable To Be final Changing A Method To Be abstract Changing A Method To Be final Adding An Overloaded Method Deleting An Interface Member Adding A Default Method Local Class Declarations Labels and Identifiers Fall Through in the switch Statement The do Statement Qualified Type Names Simple Expression Names Qualified Expression Names Qualifying an Expression with a Type Name Simple Method Names Access Control Access to public Fields, Methods, and Constructors Access to public and Non public Classes Access to Package Access Fields, Methods, and Constructors Access to private Fields, Methods, and Constructors Access to protected Fields, Methods, and Constructors Fully Qualified Names Fully Qualified Names v. Canonical Name Unnamed Package Single Type Import Duplicate Type Declarations No Import of a Subpackage Importing a Type Name that is also a Package Name Type Import on Demand Conflicting Top Level Type Declarations Scope of Top Level Types Fully Qualified Names Resolution of requires transitive directives Abstract Class Declaration Abstract Class Declaration that Prohibits Subclasses Mutually Recursive Type Variable Bounds Nested Generic Classes Inner Class Declarations and Static Members Inner Class Declarations Direct Superclasses and Subclasses Superclasses and Subclasses Class Depends on Itself Illegal Superinterfaces Superinterfaces Illegal Multiple Inheritance of an Interface Implementing Methods of a Superinterface Use of Class Members Inheritance of Class Members with Package Access Inheritance of public and protected Class Members Inheritance of private Class Members Accessing Members of Inaccessible Classes Multiply Inherited Fields Re inheritance of Fields static Fields Hiding of Class Variables Hiding of Instance Variables Persistence of transient Fields volatile Fields Field Initialization Forward Reference to a Class Variable Restrictions on Field References Override Equivalent Signatures Abstract/Abstract Method Overriding Abstract/Non Abstract Overriding synchronized Monitors synchronized Methods Type Variables as Thrown Exception Types Inheritance Overriding Overriding Invocation of Hidden Class Methods Covariant Return Types Unchecked Warning from Return Type Incorrect Overriding because of throws Erasure Affects Overriding String Literals Integer Operations Floating point Operations Object Creation Primitive and Reference Identity Members of a Type Variable Unbounded Wildcards Bounded Wildcards Raw Types Raw Types and Inheritance Usage of a Type Different Kinds of Variables Final Variables Initial Values of Variables Type of a Variable versus Class of an Object Conversions at Compile Time and Run Time Conversions In Various Contexts Widening Primitive Conversion Narrowing Primitive Conversion Narrowing Primitive Conversions that lose information Assignment for Primitive Types Assignment for Reference Types Assignment for Array Types Casting for Reference Types Casting for Array Types Casting Incompatible Types at Run Time Unary Numeric Promotion Binary Numeric Promotion Unique Package Names Unique Module Names Descriptive Class Names Conventional Type Variable Names Scope of Type Declarations Scope of Local Variable Declarations Attempted Shadowing Of A Local Variable Shadowing of a Field Declaration by a Local Variable Declaration Shadowing of a Type Declaration by Another Type Declaration Reclassification of Contextually Ambiguous Names final Field Semantics 16. Definite Assignment Postfix Expressions List of Examples Shared Variables Actions Programs and Program Order Synchronization Order Happens before Order Executions Well Formed Executions Executions and Causality Requirements Observable Behavior and Nonterminating Executions Lambda Expressions Compute Target Reference (If Necessary) Evaluate Arguments Check Accessibility of Type and Method Locate Method to Invoke Create Frame, Synchronize, Transfer Control Compile Time Declaration of a Method Reference Type of a Method Reference Run Time Evaluation of Method References Poly Method Invocation Compatibility Additional Argument Constraints Functional Interface Parameterization Inference More Specific Method Inference Sleep and Yield Memory Model Simple Assignment Operator = Compound Assignment Operators Method Reference Expressions Invocation Applicability Inference Invocation Type Inference 19. Syntax Index A. Limited License Grant Wait Notification Interruptions Interactions of Waits, Notification, and Interruption Assignment Operators Compile Time Step 3: Is the Chosen Method Appropriate? Run Time Evaluation of Method Invocation Resolution Uses of Inference Synchronization Wait Sets and Notification Boolean Conditional Expressions Numeric Conditional Expressions Reference Conditional Expressions Identify Potentially Applicable Methods Phase 1: Identify Matching Arity Methods Applicable by Strict Invocation Phase 2: Identify Matching Arity Methods Applicable by Loose Invocation Phase 3: Identify Methods Applicable by Variable Arity Invocation Choosing the Most Specific Method Method Invocation Type Complementary Pairs of Bounds Bounds Involving Capture Conversion 17. Threads and Locks Conditional And Operator && Conditional Or Operator Conditional Operator? : Compile Time Step 1: Determine Class or Interface to Search Compile Time Step 2: Determine Method Signature The Java Language Specification Type Compatibility Constraints Subtyping Constraints Type Equality Constraints Checked Exception Constraints Initialization Part of for Statement Incrementation Part of for Statement Bitwise and Logical Operators Field Access Using a Primary Accessing Superclass Members using super 8/ Incorporation Definite Assignment and Parameters Definite Assignment and Array Initializers Definite Assignment and Enum Constants Definite Assignment and Anonymous Classes Definite Assignment and Member Types Definite Assignment and Static Initializers Definite Assignment, Constructors, and Instance Initializers Numerical Equality Operators == and!= Boolean Equality Operators == and!= Reference Equality Operators == and!= break, continue, return, and throw Statements synchronized Statements try Statements Numerical Comparison Operators <, <=, >, and >= Type Comparison Operator instanceof Equality Operators Field Access Expressions Lexical Literals The Java Language Specification Shift Operators Relational Operators Anonymous Constructors Evaluate Left Hand Operand First Evaluate Operands before Operation Evaluation Respects Parentheses and Precedence Argument Lists are Evaluated Left to Right Evaluation Order for Other Expressions Primary Expressions 7/ Local Variable Declaration Statements Labeled Statements Expression Statements if Statements assert Statements switch Statements while Statements do Statements for Statements String Concatenation Operator Additive Operators (+ and -) for Numeric Types Array Creation Expressions Run Time Evaluation of Array Creation Expressions Array Access Expressions Run Time Evaluation of Array Access Expressions The Java Language Specification Multiplication Operator * Division Operator / Remainder Operator % Array Creation and Access Expressions Basic try with resources Extended try with resources Evaluation, Denotation, and Result Forms of Expressions Type of an Expression FP strict Expressions Expressions and Run Time Checks Normal and Abrupt Completion of Evaluation Evaluation Order Additive Operators Determining the Class being Instantiated Determining Enclosing Instances Choosing the Constructor and its Arguments Run Time Evaluation of Class Instance Creation Expressions Anonymous Class Declarations / Multiplicative Operators Class Literals this Qualified this Parenthesized Expressions Class Instance Creation Expressions Execution of try catch Execution of try finally and try catch finally try with resources Unreachable Statements 15. Expressions Normal and Abrupt Completion of Statements Blocks The Loading Process Initialization of for Statement Iteration of for Statement Abrupt Completion of for Statement The enhanced for statement 14. Blocks and Statements Loading of Classes and Interfaces Overloading Interface Method Body The basic for Statement The break Statement The continue Statement The return Statement The throw Statement The synchronized Statement The try statement public Interfaces Superinterfaces Interface Members Interface Type Parameters Field Declarations Interface Method Declarations Evolution of Annotation Types 12. Execution Initialization of Fields in Interfaces 9.4. Method Declarations Abrupt Completion of do Statement The for Statement Evolution of Interfaces Run Time Handling of an Exception 9.2. Interface Members 9.3. Field (Constant) Declarations Abrupt Completion of while Statement The do Statement abstract Classes final Classes public Classes Superclasses and Superinterfaces Class Type Parameters Class Body and Member Declarations Access to Members and Constructors Field Declarations final Fields and static Constant Variables static Fields transient Fields Method and Constructor Declarations Method and Constructor Type Parameters Method and Constructor Formal Parameters Method Result Type abstract Methods final Methods native Methods static Methods synchronized Methods Method and Constructor Throws Method and Constructor Body Method and Constructor Overloading Method Overriding Static Initializers Evolution of Enums The Kinds and Causes of Exceptions 9.1. Interface Declarations The assert Statement The switch Statement The while Statement The Form of a Binary What Binary Compatibility Is and Is Not Evolution of Packages and Modules Evolution of Classes 11. Exceptions 9. Interfaces The if then Statement The if then else Statement Implementing Finalization Interaction with the Memory Model 13. Binary Compatibility Array Types Array Variables Array Creation Array Access Array Store Exception Array Initializers Array Members Class Objects for Arrays An Array of Characters Is Not a String The Java Language Specification Local Variable Declarators and Types Execution of Local Variable Declarations Statements The Empty Statement Labeled Statements Expression Statements The if Statement Unloading of Classes and Interfaces Program Exit 10. Arrays 4/ Local Class Declarations Local Variable Declaration Statements Creation of New Class Instances Finalization of Class Instances 9.8. Functional Interfaces 9.9. Function Types Explicit Constructor Invocations Verification of the Binary Representation Preparation of a Class or Interface Type Resolution of Symbolic References Normal Annotations Marker Annotations Single Element Annotations Where Annotations May Appear Multiple Annotations of the Same Type Constructor Overloading Default Constructor Preventing Instantiation of a Class Initialization of Classes and Interfaces 9.7. Annotations Formal Parameters Constructor Signature Constructor Modifiers Generic Constructors Constructor Throws The Type of a Constructor Constructor Body 3/ Linking of Classes and Interfaces Overriding (by Instance Methods) Hiding (by Class Methods) Requirements in Overriding and Hiding Inheriting Methods with Override Equivalent Signatures Overloading 8.6. Instance Initializers 8.7. Static Initializers 8.8. Constructor Declarations abstract Methods static Methods final Methods native Methods strictfp Methods Access to a protected Member Access to a protected Constructor 2/ Annotation Type Elements Defaults for Annotation Type Elements Repeatable Annotation Types Predefined Annotation Types 8.5. Member Type Declarations Formal Parameters Method Signature Method Modifiers Simple Method Names 9.5. Member Type Declarations 9.6. Annotation Types synchronized Methods 8.4. Method Declarations Meaning of Method Names Identity Conversion Widening Primitive Conversion Narrowing Primitive Conversion Generic Methods Method Result Method Throws Method Body Inheritance, Overriding, and Hiding static Fields final Fields transient Fields volatile Fields Field Initialization Restrictions on Field References in Initializers Simple Expression Names Qualified Expression Names 5.1. Kinds of Conversion 1/ Field Modifiers Simple Type Names Qualified Type Names Meaning of Expression Names 5. Conversions and Contexts 3.1. Unicode 3.2. Lexical Translations 3.3. Unicode Escapes 3.4. Line Terminators 3.5. Input Elements and Tokens 8.2. Class Members 8.3. Field Declarations Simple PackageOrTypeNames Qualified PackageOrTypeNames Meaning of Type Names Variables of Primitive Type Variables of Reference Type Kinds of Variables final Variables Initial Values of Variables Types, Classes, and Interfaces abstract Classes final Classes strictfp Classes Generic Classes and Type Parameters Inner Classes and Enclosing Instances Superclasses and Subclasses Superinterfaces Class Body and Member Declarations Simple Package Names Qualified Package Names Meaning of PackageOrTypeNames Where Types Are Used Variables 2.1. Context Free Grammars 2.2. The Lexical Grammar 2.3. The Syntactic Grammar 2.4. Grammar Notation Class Modifiers Syntactic Classification of a Name According to Context Reclassification of Contextually Ambiguous Names Meaning of Module Names and Package Names Subtyping among Primitive Types Subtyping among Class and Interface Types Subtyping among Array Types Least Upper Bound 1.1. Organization of the Specification 1.2. Example Programs 1.3. Notation 1.4. Relationship to Predefined Classes and Interfaces 1.5. Feedback 1.6. References 8.1. Class Declarations 6.5. Determining the Meaning of a Name Type Arguments of Parameterized Types Members and Constructors of Parameterized Types 2. Grammars Dependences Exported and Opened Packages Service Consumption Service Provision Unnamed Modules Observability of a Module 8. Classes Shadowing Obscuring 4.6. Type Erasure 4.7. Reifiable Types 4.8. Raw Types 4.9. Intersection Types Subtyping 1. Introduction Single Type Import Declarations Type Import on Demand Declarations Single Static Import Declarations Static Import on Demand Declarations 7.6. Top Level Type Declarations 7.7. Module Declarations 6.1. Declarations 6.2. Names and Identifiers 6.3. Scope of a Declaration 6.4. Shadowing and Obscuring 4.4. Type Variables 4.5. Parameterized Types Table of Contents 7.5. Import Declarations 6. Names Objects The Class Object The Class String When Reference Types Are the Same Legal Notice Named Packages Unnamed Packages Package Observability and Visibility Unary Numeric Promotion Binary Numeric Promotion 4.3. Reference Types and Values Gilad Bracha Alex Buckley 7.1. Package Members 7.2. Host Support for Modules and Packages 7.3. Compilation Units 7.4. Package Declarations 5.2. Assignment Contexts 5.3. Invocation Contexts 5.4. String Contexts 5.5. Casting Contexts 5.6. Numeric Contexts 4.1. The Kinds of Types and Values 4.2. Primitive Types and Values James Gosling The Java Language Specification 6.7. Fully Qualified Names and Canonical Names 7. Packages and Modules Boxing Conversion Unboxing Conversion Unchecked Conversion Capture Conversion String Conversion Forbidden Conversions Value Set Conversion 4. Types, Values, and Variables Java SE 9 Edition Allowed Narrowing Reference Conversion Checked and Unchecked Narrowing Reference Conversions Narrowing Reference Conversions at Run Time Integer Literals Floating Point Literals Boolean Literals Character Literals String Literals Escape Sequences for Character and String Literals The Null Literal The Java Language Specification The Java Language Specification Widening and Narrowing Primitive Conversion Widening Reference Conversion Narrowing Reference Conversion 3.6. White Space 3.7. Comments 3.8. Identifiers 3.9. Keywords Literals Java SE > Java SE Specifications > Java Language Specification Next Chapter 1. Introduction Legal Notice 14/ /15 5

5 Context-Free Grammars (CFGs) From the Java Language Standard, Sec. 2.1: A context-free grammar consists of a number of productions. Each production has an abstract symbol called a nonterminal as its left-hand side, and a sequence of one or more nonterminal and terminal symbols as its right-hand side. For each grammar, the terminal symbols are drawn from a specified alphabet. Starting from a sentence consisting of a single distinguished nonterminal, called the goal symbol, a given context-free grammar specifies a language, namely, the set of possible sequences of terminal symbols that can result from repeatedly replacing any nonterminal in the sequence with a right-hand side of a production for which the nonterminal is the left-hand side. 6

6 Context-Free Grammars (CFGs) Formally: 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/goal symbol) Note: * is the Kleene Star. For any set X, X* denotes 0 or more instances of elements of X. Example: { 0, 1 }* = { ε, 0, 1, 00, 01, 10, 11, 000,... }, where ε denotes the empty string 7

7 Language of CFG For any strings u, v (V Σ)*, u directly yields v (written u v) if (α, β) R with α V and u 1, u 2 (V Σ)* and u = u 1 αu 2 and v = u 1 βu 2. 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 8

8 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) () 9

9 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 )( 10

10 Trees in CS Our trees grow downwards! R: Root I: Internal node L: Leaf Typically, root is an internal node (when not?) R / \ L I L / \ I I / \ / \ L L L L 11

11 Parse Trees May use parse trees as compact representation for derivation. Internal nodes are variables, Leafs are terminals. S (S) (SS) (()S) (()()) is a derivation that follows from parse tree on right. S / \ ( S ) / \ S S / \ / \ ( ) ( ) Recall: S SS (S) () 12

12 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 13

13 S S + P P P ( S ) X X a... z Parse tree for a + (b + c) + d: Parsing done bottom-up; lower position in parse tree is parsed/evaluated earlier Parentheses evaluated first + is evaluated left-to-right (left-associative) 3 2 S / \ S + P / \ S + P X / \ P ( S ) d / \ X S + P 1 a P X X b c 14

14 Note on Notation Formally, set of productions is a relation Can write this in different ways: Set notation: R = { (S, SS), (S, (S)), (S, ()) } Verbose arrow notation: S SS, S (S), S () Compact arrow notation: S SS (S) () Multiline notation: S: SS (S) () 15

15 Context-Free Languages L is a context-free language (CFL), if there exists a CFG G, such that L = L(G) Example: Is L 2 = { a n b n : n N } context-free? Yes, L 2 = L( ( { S }, { a, b }, { (S, asb), (S, ε) }, S ) ) Example: Is L 3 = { a n b n c n : n N } context-free? No, there is no CFG G with L 3 = L(G). Proof: see 16

16 So, is Java context free? No. CFGs don't address, e.g., variable declarations/bindings. But CFGs make the syntax precise, which is important both for programmers and parsers. 17

17 Backus-Naur Form (BNF) BNF is another notation for CFGs Close to compact arrow notation Use "::=" instead of arrow, "<...>" for variables Well-formed parentheses example in BNF: <S> ::= <S><S> (<S>) () 18

18 Extended Backus-Naur Form (EBNF) Typically puts terminals into quotes (" or ') Typically no "<...>" for variables [X] denotes 0 or 1 occurrences of X S ::= a [b] c abbreviates S ::= a c a b c {X} denotes 0 or more occurrences of X S ::= a {b} c abbreviates S ::= a T c, T ::= b T ε (X) defines a group S ::= a (b c) d abbreviates S ::= a b d a c d 19

19 Java Lexical Grammar Is a CFG Terminals are from Unicode character set Translate into input symbols that, with whitespace and comments discarded, form terminal symbols (tokens) for Java Syntactic Grammar Notation is variant of EBNF See also 20

20 Example: Java 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 21

21 DecimalNumeral: 0 NonZeroDigit [Digits] NonZeroDigit Underscores Digits NonZeroDigit: (one of) Digits: Digit Digit [DigitsAndUnderscores] Digit Digit: 0 NonZeroDigit DigitOrUnderscore: Digit _ Underscores: _ {_} DigitsAndUnderscores: DigitOrUnderscore {DigitOrUnderscore} 22

22 Expressions int total = n1 + n2; Expression: consists of terms (n1,n2), or operands, joined by operators (+, *, =,...) Term: Literal, a.k.a. (unnamed) constant (3.14) Variable (n1), including named constants (PI, as in static final PI = 3.14) Method call (Math.abs(n1)) Expression enclosed in parentheses 24

23 Primitive Types Data type: set of values (domain) + set of operators Type byte short int long float double char boolean Domain 8-bit integers in the range 128 to bit integers in the range to bit integers in the range to bit integers in the range to bit floating-point numbers in the range 1.4 x to x bit floating-point numbers in the range 4.39 x to x bit characters encoded using Unicode the values true and false Common operators The arithmetic operators: + add * multiply - subtract / divide % remainder The relational operators: == equal to!= not equal < less than <= > greater than >= less or equal greater or equal The arithmetic operators except % The relational operators The relational operators and +, -,... The logical operators: && and or! not The relational operators: == equal to!= not equal 26

24 Numbers This is covered further in Ch. 7 Decimal, binary, octal, hexadecimal notation In Java: = = 52 8 = 2A 16 K, M, G, T Decimal: 10 3, 10 6, 10 9, Binary: 2 10, 2 20, 2 30, 2 40 Prefix "0"/"0x" means octal/hex literal , 0x

25 Aside: Encoding Integers Computers represent integers in w bits x i { 0, 1 } X = x w-1 x w-2... x 1 x 0 For unsigned int's, X encodes value B2U(X) = w 1 x i 2 i i=0 For signed int's, X encodes This is two's complement encoding B2T(X) = x w 1 2 w 1 + w 2 x i 2 i i=0 Sign bit In Java: w = 8 (byte), 16 (short/char), 32 (int), or 64 (long) In Java, all integral types are signed, except for char See also 33

26 Bit-Wise Operators byte x = 42; // x encoded as byte y = 15; // y encoded as byte z = -16; // z encoded as Bit-wise operators refer to binary encodings AND: x & y = 10 // OR: x y = 47 // Shift left: y << 2 = 60 // Arithmetic shift right: y >> 2 = 3 // z >> 2 = -4 // Logical shift right: y >>> 2 = 3 // z >>> 2 = 60 // More on bit-wise operators in Lecture 7 34

27 Abstract Data Types (ADTs) ADT = set of variables + 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 35

28 ADTs in Java In Java, typically implement ADT as class See also Michael S. Jenkins, Abstract Data Types in Java, Computing Mcgraw-Hill, /Abstract_Data_Types_in_Java.pdf 36

29 Identifiers Identifier: name of variable, class, method etc. Must begin with letter or underscore Remaining characters must be letters, digits, or underscores Must not be one of Java's reserved words: 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 39

30 Coding Advice Naming Conventions Classes: UpperCamelCaseNouns Methods: lowercamelcaseverbs Constants: UPPER_CASE Variables: lowercamelcase Avoid single-character variable names, except for "temporary" ones: integers: i, j, k... char's: c, d, e... Try to use English names: e.g., use counter instead of zaehler See also

31 Variable Variations Local variable: declared within method Instance variable (or non-static field): declared as part of a class (without static), one per object Class variables (or static field): declared as part of class (with static), only one for class 44

32 Scoping Scope: part of program where variable is visible Scope of local variables: from declaration until end of enclosing block (sequence of statements enclosed in braces, see Lec. 4) Shadowing (or hiding): multiple variables of same name have overlapping scope. In Java: local variables shadow fields (useful e.g. for setters, see later) no shadowing of local variables (local variable names must be unique within method, unlike e.g. for functions in C) 45

33 Operators and Operands Binary operators take two operands +, -, /, *, ==, <, >, &&,, &,, ^, <<, >>,... Unary operators take one operand +, -, ++, --,! Ternary operator takes three operands? : 46

34 Type Casts int op int int int op double double double op double double double c = 100; double f = 9 / 5 * c + 32; Casting: (type) expression double f = (double) 9 / 5 * c + 32; 47

35 Aside: Expression Evaluation Different operators may be ordered by precedence: An operand between operators of different precedence is bound to operator of higher precedence * has higher precedence than * 4 == 2 + (3 * 4)!= (2 + 3) * 4 3 bound to *, not to + Operators of same precedence level ordered by associativity: + is left-associative, operands between +'s bound to left E E100 == (1 + 1E100) + -1E100!= 1 + (1E E100) false + true + "" == (false + true) + ""!= false + (true + "") 1E100/true bound to left +, not to right + See also 52

36 [ 53

37 [ 54

38 Aside: Expression Evaluation Precendence and associativity... govern which operands belong to which operator imply paren's can be overridden by paren's Precedence, associativity and paren's tell us how to construct a fully parenthesized expression, which makes all bindings of operands to operators explicit: * (4 + 5) == 2 + (3 * (4 + 5)) Once expression is fully parenthesized, don't need to consider precedence and associativity any more. 55

39 Aside: Expression Evaluation To perform an operation, we first evaluate operands, then apply operator to results. (Special case: short-circuit evaluation for &&, see later) Do this recursively: if evaluating an operand entails performing an operation, the same rule applies again. Operands of operator ordered by evaluation direction: Java evaluates left-to-right (undefined in C or C++!) This matters when operand evaluation has side effects (such as assigning new values to variables) With i initially 0: i + 2 * ++i == 2 Wait a minute... * has higher precedence than +, but operands of * are evaluated after left operand of +? Explanation: evaluation direction, see next slide 56

40 Aside: Expression Evaluation What happens exactly: Fully parenthesized expression: i + (2 * (++i)) We thus have a sum with 2 operands. To compute sum, we first evaluate the left operand, then evaluate the right operand, then compute the sum of both. 1. Evaluating left operand i yields 0 + (2 * (++i)) 2. Right operand 2 * (++i) is a product, with again 2 operands thus recursively apply left-to-right rule: 1. Left operand 2 of product is already evaluated: 0 + (2 * (++i)) 2. Evaluating right operand ++i of product sets i to 1 (pre-increment), and yields 0 + (2 * 1) 3. Computing product yields Computing sum yields 2 57

41 Exercise: Precedence Evaluation (( ( ) % 3 ) * 4 ) + ( ( 5 * 6 ) / 7 )* ( 8 % 9 )) + 10 To get started: we have a sum (root of parse tree), whose left operand is another sum, whose left operand is a product, whose left operand is a modulo operation, whose left operand is the sum "1 + 2". 58

42 Coding Advice Naming, Paren's Use meaningful variable names Don't use "magic numbers", use named constants instead Add paren's if precedence may not be obvious Example: Replace help me == read && that!= thing by help ((me == read) && (that!= thing)) 59

43 Assignments variable = expression; Shorthand assignment: variable op= expression; variable =op expression; Pre-increment ++variable; ++x; equivalent to x += 1; Post-increment variable++; x++; equivalent to x =+ 1; int x = 0; x += 1.0; is equivalent to int x = 0; x = (int) (x + 1.0); Omitting the (int) cast would result in an error 60

44 Assignment Expressions Assignments are also expressions, with assignment operator (=, +=, etc.) Left operand must be an L-Value, i.e., something that points to a storage location, i.e., a variable Value of assignment expression is assigned value int x, y = (x = 1) + (y = 2) + (x += 3); results in x = 4, y = 7 Coding advice: don t use shorthand assignments (including pre/post-increment etc.) as expressions Bad: y = x++; Good: x++; y = x; 61

45 Booleans Boolean values: true, false Logical operators on Booleans: && These short-circuit: right operand evaluated only when needed Other logical operators on Booleans: ==!=! & ^ These don't short-circuit George Boole ( ) Relational operators producing Booleans: < <= == >= >!= 65

46 Coding Advice Don't confuse "=" and "==" if (oneflag = otherflag) {... } If you really mean this, write instead: oneflag = otherflag; if (oneflag) { }... But what was probably meant: if (oneflag == otherflag) { }... 71

47 Summary Expressions = terms + operators Primitive data types: int, double,... Simplest terms: constants, variables Declarations: type name = value; Expression evaluation: paren's, precedence, associativity and (in Java) left-to-right evaluation Assignments: variable = expression; Relational operators produce Booleans Can operate on Booleans 72

Programming Lecture 3

Programming Lecture 3 Five-Minute Review 1. What is a variable? 2. What is a class? An object? 3. What is a package? 4. What is a method? A constructor? 5. What is an object variable? 1 Programming Lecture 3 Expressions etc.

More information

Programming Lecture 3

Programming Lecture 3 Five-Minute Review 1. What is a variable? 2. What is a class? An object? 3. What is a package? 4. What is a method? A constructor? 5. What is an object variable? 1 Programming Lecture 3 Expressions etc.

More information

Programming Lecture 3

Programming Lecture 3 Programming Lecture 3 Expressions (Chapter 3) Primitive types Aside: Context Free Grammars Constants, variables Identifiers Variable declarations Arithmetic expressions Operator precedence Assignment statements

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Operators and Expressions

Operators and Expressions Operators and Expressions Conversions. Widening and Narrowing Primitive Conversions Widening and Narrowing Reference Conversions Conversions up the type hierarchy are called widening reference conversions

More information

3. Java - Language Constructs I

3. Java - Language Constructs I Educational Objectives 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations, Evaluation of Expressions, Type Conversions You know the basic blocks

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

IC Language Specification

IC Language Specification CS 301 Spring 2016 IC Language Specification The IC Language For the implementation project, you will build a compiler for an object-oriented language called IC (for Irish Coffee 1 ), which is essentially

More information

1 Lexical Considerations

1 Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a

More information

Index COPYRIGHTED MATERIAL

Index COPYRIGHTED MATERIAL Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

More information

The PCAT Programming Language Reference Manual

The PCAT Programming Language Reference Manual The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University September 27, 1995 (revised October 15, 2002) 1 Introduction The PCAT language

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p.

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p. Preface p. xix Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p. 5 Java Applets and Applications p. 5

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information

The MaSH Programming Language At the Statements Level

The MaSH Programming Language At the Statements Level The MaSH Programming Language At the Statements Level Andrew Rock School of Information and Communication Technology Griffith University Nathan, Queensland, 4111, Australia a.rock@griffith.edu.au June

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

Decaf Language Reference Manual

Decaf Language Reference Manual Decaf Language Reference Manual C. R. Ramakrishnan Department of Computer Science SUNY at Stony Brook Stony Brook, NY 11794-4400 cram@cs.stonybrook.edu February 12, 2012 Decaf is a small object oriented

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University CS5000: Foundations of Programming Mingon Kang, PhD Computer Science, Kennesaw State University Overview of Source Code Components Comments Library declaration Classes Functions Variables Comments Can

More information

Java Primer 1: Types, Classes and Operators

Java Primer 1: Types, Classes and Operators Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,

More information

This book is licensed under a Creative Commons Attribution 3.0 License

This book is licensed under a Creative Commons Attribution 3.0 License 6. Syntax Learning objectives: syntax and semantics syntax diagrams and EBNF describe context-free grammars terminal and nonterminal symbols productions definition of EBNF by itself parse tree grammars

More information

A Short Summary of Javali

A Short Summary of Javali A Short Summary of Javali October 15, 2015 1 Introduction Javali is a simple language based on ideas found in languages like C++ or Java. Its purpose is to serve as the source language for a simple compiler

More information

The SPL Programming Language Reference Manual

The SPL Programming Language Reference Manual The SPL Programming Language Reference Manual Leonidas Fegaras University of Texas at Arlington Arlington, TX 76019 fegaras@cse.uta.edu February 27, 2018 1 Introduction The SPL language is a Small Programming

More information

Operators. Java operators are classified into three categories:

Operators. Java operators are classified into three categories: Operators Operators are symbols that perform arithmetic and logical operations on operands and provide a meaningful result. Operands are data values (variables or constants) which are involved in operations.

More information

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17 List of Programs xxv List of Figures xxix List of Tables xxxiii Preface to second version xxxv PART 1 Structured Programming 1 1 Getting started 3 1.1 Programming 3 1.2 Editing source code 5 Source code

More information

Language Reference Manual simplicity

Language Reference Manual simplicity Language Reference Manual simplicity Course: COMS S4115 Professor: Dr. Stephen Edwards TA: Graham Gobieski Date: July 20, 2016 Group members Rui Gu rg2970 Adam Hadar anh2130 Zachary Moffitt znm2104 Suzanna

More information

LECTURE 3 C++ Basics Part 2

LECTURE 3 C++ Basics Part 2 LECTURE 3 C++ Basics Part 2 OVERVIEW Operators Type Conversions OPERATORS Operators are special built-in symbols that have functionality, and work on operands. Operators are actually functions that use

More information

Language Fundamentals Summary

Language Fundamentals Summary Language Fundamentals Summary Claudia Niederée, Joachim W. Schmidt, Michael Skusa Software Systems Institute Object-oriented Analysis and Design 1999/2000 c.niederee@tu-harburg.de http://www.sts.tu-harburg.de

More information

IPCoreL. Phillip Duane Douglas, Jr. 11/3/2010

IPCoreL. Phillip Duane Douglas, Jr. 11/3/2010 IPCoreL Programming Language Reference Manual Phillip Duane Douglas, Jr. 11/3/2010 The IPCoreL Programming Language Reference Manual provides concise information about the grammar, syntax, semantics, and

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

Visual C# Instructor s Manual Table of Contents

Visual C# Instructor s Manual Table of Contents Visual C# 2005 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

COMP 202 Java in one week

COMP 202 Java in one week COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of

More information

Basics of Java Programming

Basics of Java Programming Basics of Java Programming Lecture 2 COP 3252 Summer 2017 May 16, 2017 Components of a Java Program statements - A statement is some action or sequence of actions, given as a command in code. A statement

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

Review of the C Programming Language for Principles of Operating Systems

Review of the C Programming Language for Principles of Operating Systems Review of the C Programming Language for Principles of Operating Systems Prof. James L. Frankel Harvard University Version of 7:26 PM 4-Sep-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights

More information

3. Java - Language Constructs I

3. Java - Language Constructs I Names and Identifiers A program (that is, a class) needs a name public class SudokuSolver {... 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations,

More information

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos. Lecture 2: Variables and Operators AITI Nigeria Summer 2012 University of Lagos. Agenda Variables Types Naming Assignment Data Types Type casting Operators Declaring Variables in Java type name; Variables

More information

CMPT 125: Lecture 3 Data and Expressions

CMPT 125: Lecture 3 Data and Expressions CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1 Character Strings A character string is an object in Java,

More information

Chapter 3: Operators, Expressions and Type Conversion

Chapter 3: Operators, Expressions and Type Conversion 101 Chapter 3 Operators, Expressions and Type Conversion Chapter 3: Operators, Expressions and Type Conversion Objectives To use basic arithmetic operators. To use increment and decrement operators. To

More information

Operators. Lecture 3 COP 3014 Spring January 16, 2018

Operators. Lecture 3 COP 3014 Spring January 16, 2018 Operators Lecture 3 COP 3014 Spring 2018 January 16, 2018 Operators Special built-in symbols that have functionality, and work on operands operand an input to an operator Arity - how many operands an operator

More information

Java enum, casts, and others (Select portions of Chapters 4 & 5)

Java enum, casts, and others (Select portions of Chapters 4 & 5) Enum or enumerates types Java enum, casts, and others (Select portions of Chapters 4 & 5) Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The

More information

Accelerating Information Technology Innovation

Accelerating Information Technology Innovation Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lesson 02 Variables and Operators Agenda Variables Types Naming Assignment Data Types Type casting Operators

More information

Casting -Allows a narrowing assignment by asking the Java compiler to "trust us"

Casting -Allows a narrowing assignment by asking the Java compiler to trust us Primitives Integral types: int, short, long, char, byte Floating point types: double, float Boolean types: boolean -passed by value (copied when returned or passed as actual parameters) Arithmetic Operators:

More information

Java Notes. 10th ICSE. Saravanan Ganesh

Java Notes. 10th ICSE. Saravanan Ganesh Java Notes 10th ICSE Saravanan Ganesh 13 Java Character Set Character set is a set of valid characters that a language can recognise A character represents any letter, digit or any other sign Java uses

More information

Decaf Language Reference

Decaf Language Reference Decaf Language Reference Mike Lam, James Madison University Fall 2016 1 Introduction Decaf is an imperative language similar to Java or C, but is greatly simplified compared to those languages. It will

More information

Java Programming. Atul Prakash

Java Programming. Atul Prakash Java Programming Atul Prakash Java Language Fundamentals The language syntax is similar to C/ C++ If you know C/C++, you will have no trouble understanding Java s syntax If you don't, it will be easier

More information

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

Unit-II Programming and Problem Solving (BE1/4 CSE-2) Unit-II Programming and Problem Solving (BE1/4 CSE-2) Problem Solving: Algorithm: It is a part of the plan for the computer program. An algorithm is an effective procedure for solving a problem in a finite

More information

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

The Sun s Java Certification and its Possible Role in the Joint Teaching Material The Sun s Java Certification and its Possible Role in the Joint Teaching Material Nataša Ibrajter Faculty of Science Department of Mathematics and Informatics Novi Sad 1 Contents Kinds of Sun Certified

More information

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE CS313D: ADVANCED PROGRAMMING LANGUAGE Computer Science department Lecture 2 : C# Language Basics Lecture Contents 2 The C# language First program Variables and constants Input/output Expressions and casting

More information

FRAC: Language Reference Manual

FRAC: Language Reference Manual FRAC: Language Reference Manual Justin Chiang jc4127 Kunal Kamath kak2211 Calvin Li ctl2124 Anne Zhang az2350 1. Introduction FRAC is a domain-specific programming language that enables the programmer

More information

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 2 Professional Program: Data Administration and Management JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1) AGENDA

More information

Language Reference Manual

Language Reference Manual Programming Languages and Translators Language Reference Manual ART: Animation Rendering Tool Brett Jervey - baj2125 Gedion Metaferia - gym2103 Natan Kibret - nfk2105 Soul Joshi - srj2120 October 26, 2016

More information

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics Java Programming, Sixth Edition 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional

More information

Table of Contents Preface Bare Necessities... 17

Table of Contents Preface Bare Necessities... 17 Table of Contents Preface... 13 What this book is about?... 13 Who is this book for?... 14 What to read next?... 14 Personages... 14 Style conventions... 15 More information... 15 Bare Necessities... 17

More information

Principles of Programming Languages COMP251: Syntax and Grammars

Principles of Programming Languages COMP251: Syntax and Grammars Principles of Programming Languages COMP251: Syntax and Grammars Prof. Dekai Wu Department of Computer Science and Engineering The Hong Kong University of Science and Technology Hong Kong, China Fall 2007

More information

Review of the C Programming Language

Review of the C Programming Language Review of the C Programming Language Prof. James L. Frankel Harvard University Version of 11:55 AM 22-Apr-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights reserved. Reference Manual for the

More information

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( ) Sir Muhammad Naveed Arslan Ahmed Shaad (1163135 ) Muhammad Bilal ( 1163122 ) www.techo786.wordpress.com CHAPTER: 2 NOTES:- VARIABLES AND OPERATORS The given Questions can also be attempted as Long Questions.

More information

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and The Arithmetic Operators The arithmetic operators refer to the standard mathematical operators: addition, subtraction, multiplication, division and modulus. Op. Use Description + x + y adds x and y x y

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

The Arithmetic Operators

The Arithmetic Operators The Arithmetic Operators The arithmetic operators refer to the standard mathematical operators: addition, subtraction, multiplication, division and modulus. Examples: Op. Use Description + x + y adds x

More information

Points To Remember for SCJP

Points To Remember for SCJP Points To Remember for SCJP www.techfaq360.com The datatype in a switch statement must be convertible to int, i.e., only byte, short, char and int can be used in a switch statement, and the range of the

More information

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things. A Appendix Grammar There is no worse danger for a teacher than to teach words instead of things. Marc Block Introduction keywords lexical conventions programs expressions statements declarations declarators

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 3 - Constants, Variables, Data Types, And Operations Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline C Program Data types Variables

More information

L-System Fractal Generator: Language Reference Manual

L-System Fractal Generator: Language Reference Manual L-System Fractal Generator: Language Reference Manual Michael Eng, Jervis Muindi, Timothy Sun Contents 1 Program Definition 3 2 Lexical Conventions 3 2.1 Comments...............................................

More information

Types, Values and Variables (Chapter 4, JLS)

Types, Values and Variables (Chapter 4, JLS) Lecture Notes CS 141 Winter 2005 Craig A. Rich Types, Values and Variables (Chapter 4, JLS) Primitive Types Values Representation boolean {false, true} 1-bit (possibly padded to 1 byte) Numeric Types Integral

More information

SEMANTIC ANALYSIS TYPES AND DECLARATIONS

SEMANTIC ANALYSIS TYPES AND DECLARATIONS SEMANTIC ANALYSIS CS 403: Type Checking Stefan D. Bruda Winter 2015 Parsing only verifies that the program consists of tokens arranged in a syntactically valid combination now we move to check whether

More information

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements Programming Languages Third Edition Chapter 9 Control I Expressions and Statements Objectives Understand expressions Understand conditional statements and guards Understand loops and variation on WHILE

More information

Declaration and Memory

Declaration and Memory Declaration and Memory With the declaration int width; the compiler will set aside a 4-byte (32-bit) block of memory (see right) The compiler has a symbol table, which will have an entry such as Identifier

More information

Full file at

Full file at Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional

More information

Introduction. Assessment Test. Part I The Programmer s Exam 1

Introduction. Assessment Test. Part I The Programmer s Exam 1 4276FM.fm Page ix Thursday, October 2, 2003 11:22 AM at a Glance Introduction Assessment Test xix xxv Part I The Programmer s Exam 1 Chapter 1 Language Fundamentals 3 Chapter 2 Operators and Assignments

More information

Typescript on LLVM Language Reference Manual

Typescript on LLVM Language Reference Manual Typescript on LLVM Language Reference Manual Ratheet Pandya UNI: rp2707 COMS 4115 H01 (CVN) 1. Introduction 2. Lexical Conventions 2.1 Tokens 2.2 Comments 2.3 Identifiers 2.4 Reserved Keywords 2.5 String

More information

SECTION II: LANGUAGE BASICS

SECTION II: LANGUAGE BASICS Chapter 5 SECTION II: LANGUAGE BASICS Operators Chapter 04: Basic Fundamentals demonstrated declaring and initializing variables. This chapter depicts how to do something with them, using operators. Operators

More information

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,

More information

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic BIT 3383 Java Programming Sem 1 Session 2011/12 Chapter 2 JAVA basic Objective: After this lesson, you should be able to: declare, initialize and use variables according to Java programming language guidelines

More information

Java: framework overview and in-the-small features

Java: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: framework overview and in-the-small features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

Java Overview An introduction to the Java Programming Language

Java Overview An introduction to the Java Programming Language Java Overview An introduction to the Java Programming Language Produced by: Eamonn de Leastar (edeleastar@wit.ie) Dr. Siobhan Drohan (sdrohan@wit.ie) Department of Computing and Mathematics http://www.wit.ie/

More information

Sprite an animation manipulation language Language Reference Manual

Sprite an animation manipulation language Language Reference Manual Sprite an animation manipulation language Language Reference Manual Team Leader Dave Smith Team Members Dan Benamy John Morales Monica Ranadive Table of Contents A. Introduction...3 B. Lexical Conventions...3

More information

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence Data and Variables Data Types Expressions Operators Precedence String Concatenation Variables Declaration Assignment Shorthand operators Review class All code in a java file is written in a class public

More information

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9

Character Set. The character set of C represents alphabet, digit or any symbol used to represent information. Digits 0, 1, 2, 3, 9 Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Uppercase Alphabets Lowercase Alphabets Character Set A, B, C, Y, Z a, b, c, y, z Digits

More information

The Decaf Language. 1 Lexical considerations

The Decaf Language. 1 Lexical considerations The Decaf Language In this course, we will write a compiler for a simple object-oriented programming language called Decaf. Decaf is a strongly-typed, object-oriented language with support for inheritance

More information

A Quick Tour p. 1 Getting Started p. 1 Variables p. 3 Comments in Code p. 6 Named Constants p. 6 Unicode Characters p. 8 Flow of Control p.

A Quick Tour p. 1 Getting Started p. 1 Variables p. 3 Comments in Code p. 6 Named Constants p. 6 Unicode Characters p. 8 Flow of Control p. A Quick Tour p. 1 Getting Started p. 1 Variables p. 3 Comments in Code p. 6 Named Constants p. 6 Unicode Characters p. 8 Flow of Control p. 9 Classes and Objects p. 11 Creating Objects p. 12 Static or

More information

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. Today! Build HelloWorld yourself in BlueJ and Eclipse. Look at all the Java keywords. Primitive Types. HelloWorld in BlueJ 1. Find BlueJ in the start menu, but start the Select VM program instead (you

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

An overview of Java, Data types and variables

An overview of Java, Data types and variables An overview of Java, Data types and variables Lecture 2 from (UNIT IV) Prepared by Mrs. K.M. Sanghavi 1 2 Hello World // HelloWorld.java: Hello World program import java.lang.*; class HelloWorld { public

More information

COMP-421 Compiler Design. Presented by Dr Ioanna Dionysiou

COMP-421 Compiler Design. Presented by Dr Ioanna Dionysiou COMP-421 Compiler Design Presented by Dr Ioanna Dionysiou Administrative! Any questions about the syllabus?! Course Material available at www.cs.unic.ac.cy/ioanna! Next time reading assignment [ALSU07]

More information

Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 Advance mode: Auto

Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 Advance mode: Auto CS 170 Java Programming 1 Expressions Slide 1 CS 170 Java Programming 1 Expressions Duration: 00:00:41 What is an expression? Expression Vocabulary Any combination of operators and operands which, when

More information

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003 Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 Java Programs A Java program contains at least one class definition. public class Hello { public static void

More information

A Java program contains at least one class definition.

A Java program contains at least one class definition. Java Programs Identifiers Objects and Types COMS W1007 Introduction to Computer Science Christopher Conway 29 May 2003 A Java program contains at least one class definition. public class Hello { public

More information

A Simple Syntax-Directed Translator

A Simple Syntax-Directed Translator Chapter 2 A Simple Syntax-Directed Translator 1-1 Introduction The analysis phase of a compiler breaks up a source program into constituent pieces and produces an internal representation for it, called

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information