Programming Lecture 3

Similar documents
Programming Lecture 3

Programming Lecture 3

Programming Lecture 3

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

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

3. Java - Language Constructs I

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Operators and Expressions

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Full file at

1 Lexical Considerations

Lexical Considerations

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

Index COPYRIGHTED MATERIAL

Lexical Considerations

Introduction to Programming Using Java (98-388)

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

1 Shyam sir JAVA Notes

Decaf Language Reference Manual

IC Language Specification

UNIT- 3 Introduction to C++

Visual C# Instructor s Manual Table of Contents

Language Reference Manual simplicity

The MaSH Programming Language At the Statements Level

Program Fundamentals

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.

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

Java Notes. 10th ICSE. Saravanan Ganesh

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

This book is licensed under a Creative Commons Attribution 3.0 License

The PCAT Programming Language Reference Manual

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

Java Primer 1: Types, Classes and Operators

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

3. Java - Language Constructs I

Full file at

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

COMP 202 Java in one week

JAVA Programming Fundamentals

DEPARTMENT OF MATHS, MJ COLLEGE

Language Fundamentals Summary

A Short Summary of Javali

The SPL Programming Language Reference Manual

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

Principles of Programming Languages COMP251: Syntax and Grammars

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

CSC 1214: Object-Oriented Programming

Java Programming. Atul Prakash

Operators. Java operators are classified into three categories:

Typescript on LLVM Language Reference Manual

Java Programming Fundamentals. Visit for more.

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

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

Accelerating Information Technology Innovation

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

Language Reference Manual

FRAC: Language Reference Manual

Declaration and Memory

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

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

CS260 Intro to Java & Android 03.Java Language Basics

Table of Contents Preface Bare Necessities... 17

Basics of Java Programming

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

Values and Variables 1 / 30

Fundamental of Programming (C)

Fundamentals of Programming

Review of the C Programming Language for Principles of Operating Systems

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

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Maciej Sobieraj. Lecture 1

CMPT 125: Lecture 3 Data and Expressions

Chapter 2. Elementary Programming

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

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

LOON. Language Reference Manual THE LANGUAGE OF OBJECT NOTATION. Kyle Hughes, Jack Ricci, Chelci Houston-Borroughs, Niles Christensen, Habin Lee

Points To Remember for SCJP

A Simple Syntax-Directed Translator

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

The Arithmetic Operators

LECTURE 3 C++ Basics Part 2

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

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

Reserved Words and Identifiers

Decaf Language Reference

Java: framework overview and in-the-small features

Bits, Words, and Integers

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

Chapter 3: Operators, Expressions and Type Conversion

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

L-System Fractal Generator: Language Reference Manual

ECE 122 Engineering Problem Solving with Java

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

SECTION II: LANGUAGE BASICS

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

ARG! Language Reference Manual

Chapter 2: Using Data

Transcription:

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

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 The Art and Science of ERIC S. ROBERTS Java An Introduction to Computer Science 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 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.: https://en.wikipedia.org/wiki/context-free_grammar 4

Why You Should Care About CFGs 6.11.2017 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 6.11.2017 The Java Language Specification 6.11.2017 The Java Language Specification Next 3.11. Separators 3.12. Operators 4.2.1. Integral Types and Values 4.2.2. Integer Operations 4.2.3. Floating Point Types, Formats, and Values 4.2.4. Floating Point Operations 4.2.5. The boolean Type and boolean Values Bill Joy Guy Steele Daniel Smith 3. Lexical Structure The Java Language Specification 6.11.2017 6.6. Access Control 6.6.1. Determining Accessibility 6.6.2. Details on protected Access The Java Language Specification https://docs.oracle.com/javase/specs/jls/se9/html/index.html 6.11.2017 8.5.1. Static Member Type Declarations The Java Language Specification 12.4.1. When Initialization Occurs 12.4.2. Detailed Initialization Procedure 8.9. Enum Types 8.9.1. Enum Constants 8.9.2. Enum Body Declarations 8.9.3. Enum Members 11.1.1. The Kinds of Exceptions 11.1.2. The Causes of Exceptions 11.1.3. Asynchronous Exceptions 9.1.1. Interface Modifiers 9.1.1.1. abstract Interfaces 9.1.1.2. strictfp Interfaces 11.2. Compile Time Checking of Exceptions 11.2.1. Exception Analysis of Expressions 11.2.2. Exception Analysis of Statements 11.2.3. Exception Checking 9.1.2. Generic Interfaces and Type Parameters 9.1.3. Superinterfaces and Subinterfaces 9.1.4. Interface Body and Member Declarations 12.1. Java Virtual Machine Startup 12.1.1. Load the Class Test 12.1.2. Link Test: Verify, Prepare, (Optionally) Resolve 12.1.3. Initialize Test: Execute Initializers 12.1.4. Invoke Test.main 9.4.1. Inheritance and Overriding 9.4.1.1. Overriding (by Instance Methods) 9.4.1.2. Requirements in Overriding 9.4.1.3. Inheriting Methods with Override Equivalent Signatures 6.11.2017 5/15 The Java Language Specification https://docs.oracle.com/javase/specs/jls/se9/html/index.html 6.11.2017 6.11.2017 15.22.1. Integer Bitwise Operators &, ^, and 15.22.2. Boolean Logical Operators &, ^, and 15.12. Method Invocation Expressions 15.27.1. Lambda Parameters 15.27.2. Lambda Body 15.27.3. Type of a Lambda Expression 15.27.4. Run Time Evaluation of Lambda Expressions 15.28. Constant Expressions 16.1.1. Boolean Constant Expressions 16.1.2. Conditional And Operator && 16.1.3. Conditional Or Operator 16.1.4. Logical Complement Operator! 16.1.5. Conditional Operator? : 16.1.6. Conditional Operator? : 16.1.7. Other Expressions of Type boolean 16.1.8. Assignment Expressions 16.1.9. Operators ++ and -16.1.10. Other Expressions 15.14.1. Expression Names 15.14.2. Postfix Increment Operator ++ 15.14.3. Postfix Decrement Operator -- 15.15.1. Prefix Increment Operator ++ 15.15.2. Prefix Decrement Operator -15.15.3. Unary Plus Operator + 15.15.4. Unary Minus Operator 15.15.5. Bitwise Complement Operator ~ 15.15.6. Logical Complement Operator! 17.6. Word Tearing 17.7. Non Atomic Treatment of double and long 18. Type Inference 18.1. Concepts and Notation 18.1.1. Inference Variables 18.1.2. Constraint Formulas 18.1.3. Bounds 16.2. Definite Assignment and Statements 16.2.1. Empty Statements 16.2.2. Blocks 16.2.3. Local Class Declaration Statements 15.16. Cast Expressions https://docs.oracle.com/javase/specs/jls/se9/html/index.html 17.5.1. Semantics of final Fields 17.5.2. Reading final Fields During Construction 17.5.3. Subsequent Modification of final Fields 17.5.4. Write Protected Fields 16.1. Definite Assignment and Expressions 15.15. Unary Operators 9/15 The Java Language Specification https://docs.oracle.com/javase/specs/jls/se9/html/index.html 6.11.2017 18.2. Reduction 18.2.1. Expression Compatibility Constraints 10/15 The Java Language Specification 13/15 https://docs.oracle.com/javase/specs/jls/se9/html/index.html https://docs.oracle.com/javase/specs/jls/se9/html/index.html 6.11.2017 11/15 https://docs.oracle.com/javase/specs/jls/se9/html/index.html 12/15 The Java Language Specification 14.14 1. Enhanced for And Arrays 14.14 2. Enhanced for And Unboxing Conversion 14.15 1. The break Statement 14.16 1. The continue Statement 14.19 1. The synchronized Statement 14.20.1 1. Catching An Exception 14.20.2 1. Handling An Uncaught Exception With finally 14.21 1. Conditional Compilation 15.7.1 1. Left Hand Operand Is Evaluated First 15.7.1 2. Implicit Left Hand Operand In Operator Of Compound Assigment 15.7.1 3. Abrupt Completion of Evaluation of the Left Hand Operand 15.7.2 1. Evaluation of Operands Before Operation 15.7.4 1. Evaluation Order At Method Invocation 15.7.4 2. Abrupt Completion of Argument Expression 15.8.3 1. The this Expression 15.9.4 1. Evaluation Order and Out Of Memory Detection 15.10.2 1. Array Creation Evaluation 15.10.2 2. Multi Dimensional Array Creation 15.10.2 3. OutOfMemoryError and Dimension Expression Evaluation 15.10.4 1. Array Reference Is Evaluated First 15.10.4 2. Abrupt Completion of Array Reference Evaluation 15.10.4 3. null Array Reference 15.11.1 1. Static Binding for Field Access 15.11.1 2. Receiver Variable Is Irrelevant For static Field Access 15.11.2 1. The super Expression 15.12.2 1. Method Applicability 15.12.2 2. Return Type Not Considered During Method Selection 15.12.2 3. Choosing The Most Specific Method 15.12.4.1 1. Target References and static Methods 15.12.4.1 2. Evaluation Order During Method Invocation 15.12.4.4 1. Overriding and Method Invocation 15.12.4.4 2. Method Invocation Using super 15.12.4.5 1. Invoked Method Signature Has Different Erasure Than Compile Time Method Signature 15.17.3 1. Integer Remainder Operator 15.17.3 2. Floating Point Remainder Operator 15.18.1 1. String Concatenation 15.18.1 2. String Concatenation and Conditionals 15.20.2 1. The instanceof Operator 15.26.1 1. Simple Assignment To An Array Component 15.26.2 1. Compound Assignment To An Array Component 15.26.2 2. Value Of Left Hand Side Of Compound Assignment Is Saved Before Evaluation Of Right Hand Side 15.28 1. Constant Expressions 16 1. Definite Assignment Considers Structure of Statements and Expressions 16 2. Definite Assignment Does Not Consider Values of Expressions 16 3. Definite Unassignment 17.4 1. Incorrectly Synchronized Programs May Exhibit Surprising Behavior 17.4.5 1. Happens before Consistency 17.4.8 1. Happens before Consistency Is Not Sufficient 17.5 1. final Fields In The Java Memory Model 17.5 2. final Fields For Security 17.5.3 1. Aggressive Optimization of final Fields 17.6 1. Detection of Word Tearing 8.4.9 1. Overloading 8.4.9 2. Overloading, Overriding, and Hiding 8.8 1. Constructor Declarations 8.8.7 1. Constructor Bodies 8.8.7.1 1. Restrictions on Explicit Constructor Invocation Statements 8.8.7.1 2. Qualified Superclass Constructor Invocation 8.8.9 1. Default Constructors 8.8.9 2. Accessibility of Constructors v. Classes 8.8.10 1. Preventing Instantiation via Constructor Accessibility 8.9.2 1. Enum Body Declarations 8.9.2 2. Restriction On Enum Constant Self Reference 8.9.3 1. Iterating Over Enum Constants With An Enhanced for Loop 8.9.3 2. Switching Over Enum Constants 8.9.3 3. Enum Constants with Class Bodies 8.9.3 4. Multiple Enum Types 9.3 1. Ambiguous Inherited Fields 9.3 2. Multiply Inherited Fields 9.3.1 1. Forward Reference to a Field 9.4.2 1. Overloading an abstract Method Declaration 9.6.1 1. Annotation Type Declaration 9.6.1 2. Marker Annotation Type Declaration 9.6.1 3. Single Element Annotation Type Declarations 9.6.2 1. Annotation Type Declaration With Default Values 9.6.3 1. Ill formed Containing Annotation Type 9.6.3 2. Restricting Where Annotations May Repeat 9.6.3 3. A Repeatable Containing Annotation Type 9.7.1 1. Normal Annotations 9.7.2 1. Marker Annotations 9.7.3 1. Single Element Annotations 9.8 1. Functional Interfaces 9.8 2. Functional Interfaces and Erasure 9.8 3. Generic Functional Interfaces 9.9 1. Function Types 9.9 2. Generic Function Types 10.2 1. Declarations of Array Variables 10.2 2. Array Variables and Array Types 10.4 1. Array Access 10.5 1. ArrayStoreException 10.6 1. Array Initializers 10.7 1. Arrays Are Cloneable 10.7 2. Shared Subarrays After A Clone 10.8 1. Class Object Of Array 10.8 2. Array Class Objects Are Shared 11.2.3 1. Catching Checked Exceptions 11.3 1. Throwing and Catching Exceptions 12.4.1 1. Superclasses Are Initialized Before Subclasses 12.4.1 2. Only The Class That Declares static Field Is Initialized 12.4.1 3. Interface Initialization Does Not Initialize Superinterfaces 12.5 1. Evaluation of Instance Creation 12.5 2. Dynamic Dispatch During Instance Creation 13.4.4 1. Changing A Superclass 13.4.6 1. Changing A Class Body 13.4.6 2. Changing A Superclass 13.4.7 1. Changing Accessibility 13.4.8 1. Adding A Field Declaration 13.4.9 1. Changing A Variable To Be final 13.4.16 1. Changing A Method To Be abstract 13.4.17 1. Changing A Method To Be final 13.4.23 1. Adding An Overloaded Method 13.5.3 1. Deleting An Interface Member 13.5.6 1. Adding A Default Method 14.3 1. Local Class Declarations 14.7 1. Labels and Identifiers 14.11 1. Fall Through in the switch Statement 14.13 1. The do Statement 6.5.5.2 1. Qualified Type Names 6.5.6.1 1. Simple Expression Names 6.5.6.2 1. Qualified Expression Names 6.5.6.2 2. Qualifying an Expression with a Type Name 6.5.7.1 1. Simple Method Names 6.6 1. Access Control 6.6 2. Access to public Fields, Methods, and Constructors 6.6 3. Access to public and Non public Classes 6.6 4. Access to Package Access Fields, Methods, and Constructors 6.6 5. Access to private Fields, Methods, and Constructors 6.6.2 1. Access to protected Fields, Methods, and Constructors 6.7 1. Fully Qualified Names 6.7 2. Fully Qualified Names v. Canonical Name 7.4.2 1. Unnamed Package 7.5.1 1. Single Type Import 7.5.1 2. Duplicate Type Declarations 7.5.1 3. No Import of a Subpackage 7.5.1 4. Importing a Type Name that is also a Package Name 7.5.2 1. Type Import on Demand 7.6 1. Conflicting Top Level Type Declarations 7.6 2. Scope of Top Level Types 7.6 3. Fully Qualified Names 7.1.1 1. Resolution of requires transitive directives 8.1.1.1 1. Abstract Class Declaration 8.1.1.1 2. Abstract Class Declaration that Prohibits Subclasses 8.1.2 1. Mutually Recursive Type Variable Bounds 8.1.2 2. Nested Generic Classes 8.1.3 1. Inner Class Declarations and Static Members 8.1.3 2. Inner Class Declarations 8.1.4 1. Direct Superclasses and Subclasses 8.1.4 2. Superclasses and Subclasses 8.1.4 3. Class Depends on Itself 8.1.5 1. Illegal Superinterfaces 8.1.5 2. Superinterfaces 8.1.5 3. Illegal Multiple Inheritance of an Interface 8.1.5 3. Implementing Methods of a Superinterface 8.2 1. Use of Class Members 8.2 2. Inheritance of Class Members with Package Access 8.2 3. Inheritance of public and protected Class Members 8.2 4. Inheritance of private Class Members 8.2 5. Accessing Members of Inaccessible Classes 8.3 1. Multiply Inherited Fields 8.3 2. Re inheritance of Fields 8.3.1.1 1. static Fields 8.3.1.1 2. Hiding of Class Variables 8.3.1.1 3. Hiding of Instance Variables 8.3.1.3 1. Persistence of transient Fields 8.3.1.4 1. volatile Fields 8.3.2 1. Field Initialization 8.3.2 2. Forward Reference to a Class Variable 8.3.3 1. Restrictions on Field References 8.4.2 1. Override Equivalent Signatures 8.4.3.1 1. Abstract/Abstract Method Overriding 8.4.3.1 2. Abstract/Non Abstract Overriding 8.4.3.6 1. synchronized Monitors 8.4.3.6 2. synchronized Methods 8.4.6 1. Type Variables as Thrown Exception Types 8.4.8 1. Inheritance 8.4.8.1 1. Overriding 8.4.8.1 2. Overriding 8.4.8.2 1. Invocation of Hidden Class Methods 8.4.8.3 1. Covariant Return Types 8.4.8.3 2. Unchecked Warning from Return Type 8.4.8.3 3. Incorrect Overriding because of throws 8.4.8.3 4. Erasure Affects Overriding 3.10.5 1. String Literals 4.2.2 1. Integer Operations 4.2.4 1. Floating point Operations 4.3.1 1. Object Creation 4.3.1 2. Primitive and Reference Identity 4.4 1. Members of a Type Variable 4.5.1 1. Unbounded Wildcards 4.5.1 2. Bounded Wildcards 4.8 1. Raw Types 4.8 2. Raw Types and Inheritance 4.11 1. Usage of a Type 4.12.3 1. Different Kinds of Variables 4.12.4 1. Final Variables 4.12.5 1. Initial Values of Variables 4.12.6 1. Type of a Variable versus Class of an Object 5.0 1. Conversions at Compile Time and Run Time 5.0 2. Conversions In Various Contexts 5.1.2 1. Widening Primitive Conversion 5.1.3 1. Narrowing Primitive Conversion 5.1.3 2. Narrowing Primitive Conversions that lose information 5.2 1. Assignment for Primitive Types 5.2 2. Assignment for Reference Types 5.2 3. Assignment for Array Types 5.5 1. Casting for Reference Types 5.5 2. Casting for Array Types 5.5 3. Casting Incompatible Types at Run Time 5.6.1 1. Unary Numeric Promotion 5.6.2 1. Binary Numeric Promotion 6.1 1. Unique Package Names 6.1 2. Unique Module Names 6.1 3. Descriptive Class Names 6.1 4. Conventional Type Variable Names 6.3 1. Scope of Type Declarations 6.3 2. Scope of Local Variable Declarations 6.4 1. Attempted Shadowing Of A Local Variable 6.4.1 1. Shadowing of a Field Declaration by a Local Variable Declaration 6.4.1 2. Shadowing of a Type Declaration by Another Type Declaration 6.5.2 1. Reclassification of Contextually Ambiguous Names 17.5. final Field Semantics 16. Definite Assignment 15.14. Postfix Expressions List of Examples 17.4.1. Shared Variables 17.4.2. Actions 17.4.3. Programs and Program Order 17.4.4. Synchronization Order 17.4.5. Happens before Order 17.4.6. Executions 17.4.7. Well Formed Executions 17.4.8. Executions and Causality Requirements 17.4.9. Observable Behavior and Nonterminating Executions 15.27. Lambda Expressions 15.12.4.1. Compute Target Reference (If Necessary) 15.12.4.2. Evaluate Arguments 15.12.4.3. Check Accessibility of Type and Method 15.12.4.4. Locate Method to Invoke 15.12.4.5. Create Frame, Synchronize, Transfer Control 15.13.1. Compile Time Declaration of a Method Reference 15.13.2. Type of a Method Reference 15.13.3. Run Time Evaluation of Method References 18.5.2.1. Poly Method Invocation Compatibility 18.5.2.2. Additional Argument Constraints 18.5.3. Functional Interface Parameterization Inference 18.5.4. More Specific Method Inference 17.3. Sleep and Yield 17.4. Memory Model 15.26.1. Simple Assignment Operator = 15.26.2. Compound Assignment Operators 15.13. Method Reference Expressions 18.5.1. Invocation Applicability Inference 18.5.2. Invocation Type Inference 19. Syntax Index A. Limited License Grant 17.2.1. Wait 17.2.2. Notification 17.2.3. Interruptions 17.2.4. Interactions of Waits, Notification, and Interruption 15.26. Assignment Operators 15.12.3. Compile Time Step 3: Is the Chosen Method Appropriate? 15.12.4. Run Time Evaluation of Method Invocation 18.4. Resolution 18.5. Uses of Inference 17.1. Synchronization 17.2. Wait Sets and Notification 15.25.1. Boolean Conditional Expressions 15.25.2. Numeric Conditional Expressions 15.25.3. Reference Conditional Expressions 15.12.2.1. Identify Potentially Applicable Methods 15.12.2.2. Phase 1: Identify Matching Arity Methods Applicable by Strict Invocation 15.12.2.3. Phase 2: Identify Matching Arity Methods Applicable by Loose Invocation 15.12.2.4. Phase 3: Identify Methods Applicable by Variable Arity Invocation 15.12.2.5. Choosing the Most Specific Method 15.12.2.6. Method Invocation Type 18.3.1. Complementary Pairs of Bounds 18.3.2. Bounds Involving Capture Conversion 17. Threads and Locks 15.23. Conditional And Operator && 15.24. Conditional Or Operator 15.25. Conditional Operator? : 15.12.1. Compile Time Step 1: Determine Class or Interface to Search 15.12.2. Compile Time Step 2: Determine Method Signature The Java Language Specification 18.2.2. Type Compatibility Constraints 18.2.3. Subtyping Constraints 18.2.4. Type Equality Constraints 18.2.5. Checked Exception Constraints 16.2.12.1. Initialization Part of for Statement 16.2.12.2. Incrementation Part of for Statement 15.22. Bitwise and Logical Operators 15.11.1. Field Access Using a Primary 15.11.2. Accessing Superclass Members using super 8/15 18.3. Incorporation 16.3. Definite Assignment and Parameters 16.4. Definite Assignment and Array Initializers 16.5. Definite Assignment and Enum Constants 16.6. Definite Assignment and Anonymous Classes 16.7. Definite Assignment and Member Types 16.8. Definite Assignment and Static Initializers 16.9. Definite Assignment, Constructors, and Instance Initializers 15.21.1. Numerical Equality Operators == and!= 15.21.2. Boolean Equality Operators == and!= 15.21.3. Reference Equality Operators == and!= https://docs.oracle.com/javase/specs/jls/se9/html/index.html 6.11.2017 16.2.13. break, continue, return, and throw Statements 16.2.14. synchronized Statements 16.2.15. try Statements 15.20.1. Numerical Comparison Operators <, <=, >, and >= 15.20.2. Type Comparison Operator instanceof 15.21. Equality Operators 15.11. Field Access Expressions 15.8.1. Lexical Literals The Java Language Specification 15.19. Shift Operators 15.20. Relational Operators 15.9.5.1. Anonymous Constructors 15.7.1. Evaluate Left Hand Operand First 15.7.2. Evaluate Operands before Operation 15.7.3. Evaluation Respects Parentheses and Precedence 15.7.4. Argument Lists are Evaluated Left to Right 15.7.5. Evaluation Order for Other Expressions 15.8. Primary Expressions 7/15 16.2.4. Local Variable Declaration Statements 16.2.5. Labeled Statements 16.2.6. Expression Statements 16.2.7. if Statements 16.2.8. assert Statements 16.2.9. switch Statements 16.2.10. while Statements 16.2.11. do Statements 16.2.12. for Statements 15.18.1. String Concatenation Operator + 15.18.2. Additive Operators (+ and -) for Numeric Types 15.10.1. Array Creation Expressions 15.10.2. Run Time Evaluation of Array Creation Expressions 15.10.3. Array Access Expressions 15.10.4. Run Time Evaluation of Array Access Expressions https://docs.oracle.com/javase/specs/jls/se9/html/index.html The Java Language Specification 15.17.1. Multiplication Operator * 15.17.2. Division Operator / 15.17.3. Remainder Operator % 15.10. Array Creation and Access Expressions 14.20.3.1. Basic try with resources 14.20.3.2. Extended try with resources 15.1. Evaluation, Denotation, and Result 15.2. Forms of Expressions 15.3. Type of an Expression 15.4. FP strict Expressions 15.5. Expressions and Run Time Checks 15.6. Normal and Abrupt Completion of Evaluation 15.7. Evaluation Order https://docs.oracle.com/javase/specs/jls/se9/html/index.html 15.18. Additive Operators 15.9.1. Determining the Class being Instantiated 15.9.2. Determining Enclosing Instances 15.9.3. Choosing the Constructor and its Arguments 15.9.4. Run Time Evaluation of Class Instance Creation Expressions 15.9.5. Anonymous Class Declarations 6.11.2017 6/15 15.17. Multiplicative Operators 15.8.2. Class Literals 15.8.3. this 15.8.4. Qualified this 15.8.5. Parenthesized Expressions 15.9. Class Instance Creation Expressions 14.20.1. Execution of try catch 14.20.2. Execution of try finally and try catch finally 14.20.3. try with resources 14.21. Unreachable Statements 15. Expressions 14.1. Normal and Abrupt Completion of Statements 14.2. Blocks 12.2.1. The Loading Process https://docs.oracle.com/javase/specs/jls/se9/html/index.html 14.14.1.1. Initialization of for Statement 14.14.1.2. Iteration of for Statement 14.14.1.3. Abrupt Completion of for Statement 14.14.2. The enhanced for statement 14. Blocks and Statements 12.2. Loading of Classes and Interfaces 9.4.2. Overloading 9.4.3. Interface Method Body 14.14.1. The basic for Statement 14.15. The break Statement 14.16. The continue Statement 14.17. The return Statement 14.18. The throw Statement 14.19. The synchronized Statement 14.20. The try statement 13.5.1. public Interfaces 13.5.2. Superinterfaces 13.5.3. Interface Members 13.5.4. Interface Type Parameters 13.5.5. Field Declarations 13.5.6. Interface Method Declarations 13.5.7. Evolution of Annotation Types 12. Execution 9.3.1. Initialization of Fields in Interfaces 9.4. Method Declarations 14.13.1. Abrupt Completion of do Statement 14.14. The for Statement 13.5. Evolution of Interfaces 11.3. Run Time Handling of an Exception 9.2. Interface Members 9.3. Field (Constant) Declarations 14.12.1. Abrupt Completion of while Statement 14.13. The do Statement 13.4.1. abstract Classes 13.4.2. final Classes 13.4.3. public Classes 13.4.4. Superclasses and Superinterfaces 13.4.5. Class Type Parameters 13.4.6. Class Body and Member Declarations 13.4.7. Access to Members and Constructors 13.4.8. Field Declarations 13.4.9. final Fields and static Constant Variables 13.4.10. static Fields 13.4.11. transient Fields 13.4.12. Method and Constructor Declarations 13.4.13. Method and Constructor Type Parameters 13.4.14. Method and Constructor Formal Parameters 13.4.15. Method Result Type 13.4.16. abstract Methods 13.4.17. final Methods 13.4.18. native Methods 13.4.19. static Methods 13.4.20. synchronized Methods 13.4.21. Method and Constructor Throws 13.4.22. Method and Constructor Body 13.4.23. Method and Constructor Overloading 13.4.24. Method Overriding 13.4.25. Static Initializers 13.4.26. Evolution of Enums 11.1. The Kinds and Causes of Exceptions 9.1. Interface Declarations 14.10. The assert Statement 14.11. The switch Statement 14.12. The while Statement 13.1. The Form of a Binary 13.2. What Binary Compatibility Is and Is Not 13.3. Evolution of Packages and Modules 13.4. Evolution of Classes 11. Exceptions 9. Interfaces 14.9.1. The if then Statement 14.9.2. The if then else Statement 12.6.1. Implementing Finalization 12.6.2. Interaction with the Memory Model 13. Binary Compatibility 10.1. Array Types 10.2. Array Variables 10.3. Array Creation 10.4. Array Access 10.5. Array Store Exception 10.6. Array Initializers 10.7. Array Members 10.8. Class Objects for Arrays 10.9. An Array of Characters Is Not a String The Java Language Specification 14.4.1. Local Variable Declarators and Types 14.4.2. Execution of Local Variable Declarations 14.5. Statements 14.6. The Empty Statement 14.7. Labeled Statements 14.8. Expression Statements 14.9. The if Statement 12.7. Unloading of Classes and Interfaces 12.8. Program Exit 10. Arrays 4/15 14.3. Local Class Declarations 14.4. Local Variable Declaration Statements 12.5. Creation of New Class Instances 12.6. Finalization of Class Instances 9.8. Functional Interfaces 9.9. Function Types 8.8.7.1. Explicit Constructor Invocations 6.11.2017 12.3.1. Verification of the Binary Representation 12.3.2. Preparation of a Class or Interface Type 12.3.3. Resolution of Symbolic References 9.7.1. Normal Annotations 9.7.2. Marker Annotations 9.7.3. Single Element Annotations 9.7.4. Where Annotations May Appear 9.7.5. Multiple Annotations of the Same Type 8.8.8. Constructor Overloading 8.8.9. Default Constructor 8.8.10. Preventing Instantiation of a Class https://docs.oracle.com/javase/specs/jls/se9/html/index.html 12.4. Initialization of Classes and Interfaces 9.7. Annotations 8.8.1. Formal Parameters 8.8.2. Constructor Signature 8.8.3. Constructor Modifiers 8.8.4. Generic Constructors 8.8.5. Constructor Throws 8.8.6. The Type of a Constructor 8.8.7. Constructor Body 3/15 12.3. Linking of Classes and Interfaces 9.6.4.1. @Target 9.6.4.2. @Retention 9.6.4.3. @Inherited 9.6.4.4. @Override 9.6.4.5. @SuppressWarnings 9.6.4.6. @Deprecated 9.6.4.7. @SafeVarargs 9.6.4.8. @Repeatable 9.6.4.9. @FunctionalInterface 8.4.8.1. Overriding (by Instance Methods) 8.4.8.2. Hiding (by Class Methods) 8.4.8.3. Requirements in Overriding and Hiding 8.4.8.4. Inheriting Methods with Override Equivalent Signatures 8.4.9. Overloading 8.6. Instance Initializers 8.7. Static Initializers 8.8. Constructor Declarations 8.4.3.1. abstract Methods 8.4.3.2. static Methods 8.4.3.3. final Methods 8.4.3.4. native Methods 8.4.3.5. strictfp Methods 6.6.2.1. Access to a protected Member 6.6.2.2. Access to a protected Constructor 2/15 9.6.1. Annotation Type Elements 9.6.2. Defaults for Annotation Type Elements 9.6.3. Repeatable Annotation Types 9.6.4. Predefined Annotation Types 8.5. Member Type Declarations 8.4.1. Formal Parameters 8.4.2. Method Signature 8.4.3. Method Modifiers 6.5.7.1. Simple Method Names 9.5. Member Type Declarations 9.6. Annotation Types 8.4.3.6. synchronized Methods 8.4. Method Declarations 6.5.7. Meaning of Method Names 5.1.1. Identity Conversion 5.1.2. Widening Primitive Conversion 5.1.3. Narrowing Primitive Conversion https://docs.oracle.com/javase/specs/jls/se9/html/index.html 8.4.4. Generic Methods 8.4.5. Method Result 8.4.6. Method Throws 8.4.7. Method Body 8.4.8. Inheritance, Overriding, and Hiding 8.3.1.1. static Fields 8.3.1.2. final Fields 8.3.1.3. transient Fields 8.3.1.4. volatile Fields 8.3.2. Field Initialization 8.3.3. Restrictions on Field References in Initializers 6.5.6.1. Simple Expression Names 6.5.6.2. Qualified Expression Names 5.1. Kinds of Conversion 1/15 8.3.1. Field Modifiers 6.5.5.1. Simple Type Names 6.5.5.2. Qualified Type Names 6.5.6. 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 6.5.4.1. Simple PackageOrTypeNames 6.5.4.2. Qualified PackageOrTypeNames 6.5.5. Meaning of Type Names 4.12.1. Variables of Primitive Type 4.12.2. Variables of Reference Type 4.12.3. Kinds of Variables 4.12.4. final Variables 4.12.5. Initial Values of Variables 4.12.6. Types, Classes, and Interfaces https://docs.oracle.com/javase/specs/jls/se9/html/index.html 8.1.1.1. abstract Classes 8.1.1.2. final Classes 8.1.1.3. strictfp Classes 8.1.2. Generic Classes and Type Parameters 8.1.3. Inner Classes and Enclosing Instances 8.1.4. Superclasses and Subclasses 8.1.5. Superinterfaces 8.1.6. Class Body and Member Declarations 6.5.3.1. Simple Package Names 6.5.3.2. Qualified Package Names 6.5.4. Meaning of PackageOrTypeNames 4.11. Where Types Are Used 4.12. Variables 2.1. Context Free Grammars 2.2. The Lexical Grammar 2.3. The Syntactic Grammar 2.4. Grammar Notation 8.1.1. Class Modifiers 6.5.1. Syntactic Classification of a Name According to Context 6.5.2. Reclassification of Contextually Ambiguous Names 6.5.3. Meaning of Module Names and Package Names 4.10.1. Subtyping among Primitive Types 4.10.2. Subtyping among Class and Interface Types 4.10.3. Subtyping among Array Types 4.10.4. 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 4.5.1. Type Arguments of Parameterized Types 4.5.2. Members and Constructors of Parameterized Types 2. Grammars 7.7.1. Dependences 7.7.2. Exported and Opened Packages 7.7.3. Service Consumption 7.7.4. Service Provision 7.7.5. Unnamed Modules 7.7.6. Observability of a Module 8. Classes 6.4.1. Shadowing 6.4.2. Obscuring 4.6. Type Erasure 4.7. Reifiable Types 4.8. Raw Types 4.9. Intersection Types 4.10. Subtyping 1. Introduction 7.5.1. Single Type Import Declarations 7.5.2. Type Import on Demand Declarations 7.5.3. Single Static Import Declarations 7.5.4. 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 2017 08 07 Table of Contents 7.5. Import Declarations 6. Names 4.3.1. Objects 4.3.2. The Class Object 4.3.3. The Class String 4.3.4. When Reference Types Are the Same Legal Notice 7.4.1. Named Packages 7.4.2. Unnamed Packages 7.4.3. Package Observability and Visibility 5.6.1. Unary Numeric Promotion 5.6.2. 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 5.1.7. Boxing Conversion 5.1.8. Unboxing Conversion 5.1.9. Unchecked Conversion 5.1.10. Capture Conversion 5.1.11. String Conversion 5.1.12. Forbidden Conversions 5.1.13. Value Set Conversion 4. Types, Values, and Variables Java SE 9 Edition 6.11.2017 5.1.6.1. Allowed Narrowing Reference Conversion 5.1.6.2. Checked and Unchecked Narrowing Reference Conversions 5.1.6.3. Narrowing Reference Conversions at Run Time 3.10.1. Integer Literals 3.10.2. Floating Point Literals 3.10.3. Boolean Literals 3.10.4. Character Literals 3.10.5. String Literals 3.10.6. Escape Sequences for Character and String Literals 3.10.7. The Null Literal The Java Language Specification 6.11.2017 The Java Language Specification 5.1.4. Widening and Narrowing Primitive Conversion 5.1.5. Widening Reference Conversion 5.1.6. Narrowing Reference Conversion 3.6. White Space 3.7. Comments 3.8. Identifiers 3.9. Keywords 3.10. Literals Java SE > Java SE Specifications > Java Language Specification Next Chapter 1. Introduction Legal Notice 14/15 https://docs.oracle.com/javase/specs/jls/se9/html/index.html 15/15 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. https://docs.oracle.com/javase/specs/jls/se9/html/jls-2.html#jls-2.1 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

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

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

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

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

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

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

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

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

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 https://en.wikipedia.org/wiki/pumping_lemma_for_context-free_languages 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

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

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

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 https://docs.oracle.com/javase/specs/jls/se9/html/jls-2.html#jls-2.4 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

DecimalNumeral: 0 NonZeroDigit [Digits] NonZeroDigit Underscores Digits NonZeroDigit: (one of) 1 2 3 4 5 6 7 8 9 Digits: Digit Digit [DigitsAndUnderscores] Digit Digit: 0 NonZeroDigit DigitOrUnderscore: Digit _ Underscores: _ {_} DigitsAndUnderscores: DigitOrUnderscore {DigitOrUnderscore} https://docs.oracle.com/javase/specs/jls/se9/html/jls-3.html#jls-decimalnumeral 22

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 call that returns a value (such as readint) An expression enclosed in parentheses 23

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

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 boolean char 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. This type represents a logical value (true or false). This type represents a single character and is described in Chapter 8. 25

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 127 16-bit integers in the range 32768 to 32767 32-bit integers in the range 2146483648 to 2146483647 64-bit integers in the range 9223372036754775808 to 9223372036754775807 32-bit floating-point numbers in the range ±1.4 x 10-45 to ±3.4028235 x 10-38 64-bit floating-point numbers in the range ±4.39 x 10-322 to ±1.7976931348623157 x 10 308 16-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

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

The Structure of Memory The fundamental unit of memory inside a computer is called a bit, which is a contraction of the words binary digit. A bit can be in either of two states, usually denoted as 0 and 1. The hardware structure of a computer combines individual bits into larger units. In most modern architectures, the smallest unit on which the hardware operates is a sequence of eight consecutive bits called a byte. The following diagram shows a byte containing a combination of 0s and 1s: 0 0 1 0 1 0 1 0 Numbers are stored in still larger units that consist of multiple bytes. The unit that represents the most common integer size on a particular hardware is called a word. Because machines have different architectures, the number of bytes in a word may vary from machine to machine.

Binary Notation Bytes and words can be used to represent integers of different sizes by interpreting the bits as a number in binary notation. Binary notation is similar to decimal notation but uses a different base. Decimal numbers use 10 as their base, which means that each digit counts for ten times as much as the digit to its right. Binary notation uses base 2, which means that each position counts for twice as much, as follows: 0 0 1 0 1 0 1 0 The next The digit next The gives digit rightmost gives digit And so on... the number the number of is 4s. the of units 2s. place. 0 x 1 = 0 1 x 2 = 2 0 x 4 = 0 1 x 8 = 8 0 x 16 = 0 1 x 32 = 32 0 x 64 = 0 0 x 128 = 0 42

Numbers and Bases The calculation at the end of the preceding slide makes it clear that the binary representation 00101010 is equivalent to the number 42. When it is important to distinguish the base, the text uses a small subscript, like this: 00101010 2 = 42 10 Although it is useful to be able to convert a number from one base to another, it is important to remember that the number remains the same. What changes is how you write it down. The number 42 is what you get if you count how many stars are in the pattern at the right. The number is the same whether you write it in English as forty-two, in decimal as 42, or in binary as 00101010. Numbers do not have bases; representations do.

Octal and Hexadecimal Notation Because binary notation tends to get rather long, computer scientists often prefer octal (base 8) or hexadecimal (base 16) notation instead. Octal notation uses eight digits: 0 to 7. Hexadecimal notation uses sixteen digits: 0 to 9, followed by the letters A through F to indicate the values 10 to 15. The following diagrams show how the number forty-two appears in both octal and hexadecimal notation: octal 5 2 2 x 1 = 2 5 x 8 = 40 42 hexadecimal 2 A 10 x 1 = 10 02 x 16 = 32 42 The advantage of using either octal or hexadecimal notation is that doing so makes it easy to translate the number back to individual bits because you can convert each digit separately.

Exercises: Number Bases What is the decimal value for each of the following numbers? 10001 2 177 8 AD 16 1 0 0 0 1 1 7 7 17 127 173 1 x 1 = 1 7 x 1 = 7 13 x 1 = 13 0 x 2 = 0 7 x 8 = 56 10 x 16 = 160 0 x 4 = 0 1 x 64 = 64 173 0 x 8 = 0 127 1 x 16 = 1 1 1 0 0 1 0 1 017 1 1 1 1 1 1 1 0 As part of a code to identify the file type, every Java class file begins with the following sixteen bits: How would you express that number in hexadecimal notation? 1 1 0 0 1 0 1 0 1 1 1 1 1 1 1 0 A F E CAFE 16 A D

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 https://docs.oracle.com/javase/specs/jls/se9/html/jls-4.html#jls-4.2 33

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

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 35

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 36

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". 37

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 Each variable has the following attributes: (contains an int) 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. 38

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

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 https://en.wikipedia.org/wiki/naming_convention_(programming) http://www.oracle.com/technetwork/java/codeconventions-135099.html#367 40

Variable Declarations In Java, you must declare a variable before you can use it. The declaration establishes the name and type of the variable and, in most cases, specifies the initial value as well. The most common form of a variable declaration is type name = value; where type is the name of a Java primitive type or class, name is an identifier that indicates the name of the variable, and value is an expression specifying the initial value. Most declarations appear as statements in the body of a method definition. Variables declared in this way are called local variables and are accessible only inside that method. Variables may also be declared as part of a class. These are called instance variables and are covered in Chapter 6. 41

Operators and Operands As in most languages, Java programs specify computation in the form of arithmetic expressions that closely resemble expressions in mathematics. The most common operators in Java are the ones that specify arithmetic computation: + Addition Subtraction * Multiplication / Division % Remainder Operators in Java usually appear between two subexpressions, which are called its operands. Operators that take two operands are called binary operators. The - operator can also appear as a unary operator, as in the expression -x, which denotes the negative of x. 42

Division and Type Casts Whenever you apply a binary operator to numeric values in Java, the result will be of type int if both operands are of type int, but will be a double if either operand is a double. This rule has important consequences in the case of division. For example, the expression 14 / 5 seems as if it should have the value 2.8, but because both operands are of type int, Java computes an integer result by throwing away the fractional part. The result is therefore 2. If you want to obtain the mathematically correct result, you need to convert at least one operand to a double, as in (double) 14 / 5 The conversion is accomplished by means of a type cast, which consists of a type name in parentheses. 43

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

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

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

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

The Pitfalls of Integer Division Consider the following Java statements, which are intended to convert 100 Celsius temperature to its Fahrenheit equivalent: double c = 100; double f = 9 / 5 * c + 32; The computation consists of evaluating the following expression: The problem arises from the fact that both 9 and 5 are of type int, which means that the result is also an int. 9 / 5 * c 132 + 32 1 100 9 / 5 * c + 32 48

The Pitfalls of Integer Division You can fix this problem by converting the fraction to a double, either by inserting decimal points or by using a type cast: double c = 100; double f = (double) 9 / 5 * c + 32; The computation now looks like this: 212.0 180.0 1.8 9.0 (double) 9 / 5 * c + 32 49

The Remainder Operator The only arithmetic operator that has no direct mathematical counterpart is %, which applies only to integer operands and computes the remainder when the first divided by the second: 14 % 5 returns 4 14 % 7 returns 0 7 % 14 returns 7 The result of the % operator make intuitive sense only if both operands are positive. The examples in this book do not depend on knowing how % works with negative numbers. The remainder operator turns out to be useful in a surprising number of programming applications and is well worth a bit of study. 50

Precedence If an expression contains more than one operator, Java uses precedence rules to determine the order of evaluation. The arithmetic operators have the following relative precedence: unary - (type cast) * / % + - highest lowest Thus, Java evaluates unary - operators and type casts first, then the operators *, /, and %, and then the operators + and -. Precedence applies only when two operands compete for the same operator. If the operators are independent, Java evaluates expressions from left to right. Parentheses may be used to change the order of operations. 51

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 + 2 + 3 * 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 + 1 + 1E100 + -1E100 == (1 + 1E100) + -1E100!= 1 + (1E100 + -1E100) false + true + "" == (false + true) + ""!= false + (true + "") 1E100/true bound to left +, not to right + See also http://introcs.cs.princeton.edu/java/11precedence/ 52

[http://introcs.cs.princeton.edu/java/11precedence/] 53

[http://introcs.cs.princeton.edu/java/11precedence/] 54

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: 2 + 3 * (4 + 5) == 2 + (3 * (4 + 5)) Once expression is fully parenthesized, don't need to consider precedence and associativity any more. 55

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

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 0 + 2 3. Computing sum yields 2 57

Exercise: Precedence Evaluation 42 32 0 0 4 32 3 30 8 (( ( 1 + 2 ) % 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

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

Assignments variable = expression; Shorthand assignment: variable op= expression; variable++; Post-increment --variable; Pre-decrement 60

Assignment Statements You can change the value of a variable in your program by using an assignment statement, which has the general form: variable = expression; The effect of an assignment statement is to compute the value of the expression on the right side of the equal sign and assign that value to the variable that appears on the left. Thus, the assignment statement total = total + value; adds together the current values of the variables total and value and then stores that sum back in the variable total. When you assign a new value to a variable, the old value of that variable is lost. 61

Shorthand Assignments Statements such as total = total + value; are so common that Java allows the following shorthand form: total += value; The general form of a shorthand assignment is variable op= expression; where op is any of Java s binary operators. The effect of this statement is the same as variable = variable op (expression); For example, the following statement multiplies salary by 2. salary *= 2; 62

Increment and Decrement Operators Another important shorthand form that appears frequently in Java programs is the increment operator, which is most commonly written immediately after a variable, like this: x++; The effect of this statement is to add one to the value of x, which means that this statement is equivalent to x += 1; or in an even longer form x = x + 1; The -- operator (which is called the decrement operator) is similar but subtracts one instead of adding one. The ++ and -- operators are more complicated than shown here, but it makes sense to defer the details until Chapter 11. 63

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 (1791-1871) Relational operators producing Booleans: < <= == >= >!= 64

Boolean Expressions George Boole (1791-1871) In many ways, the most important primitive type in Java is boolean, even though it is by far the simplest. The only values in the boolean domain are true and false, but these are exactly the values you need if you want your program to make decisions. The name boolean comes from the English mathematician George Boole who in 1854 wrote a book entitled An Investigation into the Laws of Thought, on Which are Founded the Mathematical Theories of Logic and Probabilities. That book introduced a system of logic that has come to be known as Boolean algebra, which is the foundation for the boolean data type. 65