WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

Similar documents
Chapter 3: Operators, Expressions and Type Conversion

CS313D: ADVANCED PROGRAMMING LANGUAGE

Unit 3. Operators. School of Science and Technology INTRODUCTION

Declaration and Memory

Operators. Java operators are classified into three categories:

A variable is a name for a location in memory A variable must be declared

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

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

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

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

Java Primer 1: Types, Classes and Operators

Chapter 12 Variables and Operators

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Add Subtract Multiply Divide

Full file at

Basics of Java Programming

Chapter 2: Using Data

CMPT 125: Lecture 3 Data and Expressions

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

COMP Primitive and Class Types. Yi Hong May 14, 2015

Chapter 4: Basic C Operators

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

CT 229 Java Syntax Continued

Data Types and Variables in C language

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

CGS 3066: Spring 2015 JavaScript Reference

EXPRESSIONS AND ASSIGNMENT CITS1001

Operators in C. Staff Incharge: S.Sasirekha

CIS 110: Introduction to Computer Programming

GO - OPERATORS. This tutorial will explain the arithmetic, relational, logical, bitwise, assignment and other operators one by one.

ECE 122 Engineering Problem Solving with Java

Operators. Java Primer Operators-1 Scott MacKenzie = 2. (b) (a)

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

Language Reference Manual

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Lexical Considerations

Lexical Considerations

Language Reference Manual simplicity

1 Lexical Considerations

Chapter 12 Variables and Operators

Petros: A Multi-purpose Text File Manipulation Language

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

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

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

The Arithmetic Operators

Week 4 Lecture 1. Expressions and Functions

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

Review of the C Programming Language for Principles of Operating Systems

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Types and Expressions. Chapter 3

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

Lecture 3 Operators MIT AITI

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Expressions and Casting

CS106X Handout 03 Autumn 2012 September 24 th, 2012 Getting Started

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

Programming with Java

SECTION II: LANGUAGE BASICS

Variables and Operators 2/20/01 Lecture #

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

C: How to Program. Week /Mar/05

Reserved Words and Identifiers

TED Language Reference Manual

GridLang: Grid Based Game Development Language Language Reference Manual. Programming Language and Translators - Spring 2017 Prof.

Full file at C How to Program, 6/e Multiple Choice Test Bank

Outline. Performing Computations. Outline (cont) Expressions in C. Some Expression Formats. Types for Operands

UNIT- 3 Introduction to C++

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Program Elements -- Introduction

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Introduction to Programming Using Java (98-388)

Constants and Variables

egrapher Language Reference Manual

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

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

A Java program contains at least one class definition.

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

FRAC: Language Reference Manual

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Angela Z: A Language that facilitate the Matrix wise operations Language Reference Manual

QUIZ: What value is stored in a after this

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

Primitive Types. Four integer types: Two floating-point types: One character type: One boolean type: byte short int (most common) long

Department of Computer Science

Ordinary Differential Equation Solver Language (ODESL) Reference Manual

More Programming Constructs -- Introduction

Pace University. Fundamental Concepts of CS121 1

corgi Language Reference Manual COMS W4115

Fundamental of Programming (C)

Operators and Expressions

Learning Language. Reference Manual. George Liao (gkl2104) Joseanibal Colon Ramos (jc2373) Stephen Robinson (sar2120) Huabiao Xu(hx2104)

Variables and literals

Object-Oriented Programming

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Introduction to Visual Basic and Visual C++ Arithmetic Expression. Arithmetic Expression. Using Arithmetic Expression. Lesson 4.

Program Fundamentals

Mr. Monroe s Guide to Mastering Java Syntax

Transcription:

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS OPERATORS Review: Data values can appear as literals or be stored in variables/constants Data values can be returned by method calls Operators: special symbols that operate on their operands and return a result. Data values can be combined into expression using operators Eg. 12 * 2 is an expression that returns 24. o The operator is * o The operands are 12 and 2 o The result is 24 Expressions evaluate to a single value. This value must have a data type The resulting data type depends on the data types of the operands What do we use expression for? Arithmetic - mathematic calculations String manipulation - combining/changing strings Assignment - '=' is also an operator Comparison - these kinds of expression return the Boolean values Operator precedence list: a list that decides which operator operates first. THE ASSIGNMENT OPERATOR Assignment statement: an expression that is terminated by a ';' 1. The assignment operator has the LOWEST PRECENDENCE of all operators, because the RHS must be fully evaluated before it can be stored. 2. Assignment operators returns whatever value is on the RHS. ARITHMETIC OPERATORS Operation Operator Example expression Return value Addition + 1 + 2 3 Subtraction - 1-2 -1 Multiplication * 1.5 * 2.0 3.0 Division / 1.0 / 2.0 1 / 2 0.5 0 Remainder % 7 % 3 1

Integer division VS floating-point division If BOTH operands are integers the operation is integer division Return value = truncated integer If ONE operand is a double, and the other is an integer the operation is floating-point division A copy of the integer's value is AUTO-PROMOTED to a double Return value = double type If BOTH operands are integers you can CAST one operand to double and the auto-promotion of the other operand will cause floating-point division '++' and '--' The following statements are equivalent if they appear as standalone statements: count = count + 1; ++count; count++; Pre-increment Post-increment count = count - 1; --count; count--; Pre-decrement Post-decrement For x = 1 and y = 2; Expression Return value x after y after Explanation x + ++y 4 1 3 y is incremented from 2 to 3, y is added to x. x + y++ 3 1 3 y is added to x, which is returned, then y is incremented from 2 to 3 x + --y 2 1 1 y is decremented from 2 to 1, y is added to x. x + y-- 3 1 1 y is added to x, which is returned, then y is decremented by 1. Note: don't use post-increment and post-decrement when writing code, because they get confusing. But understand them in other code.

COMPOUND OPERATORS Using compound operator total += number total -= number total *= number total /= number total %= number Long equivalent total = total + number total = total - number total = total * number total = total / number total = total % number Compound operators are often used for accumulating a sum/string THE MATH CLASS The Math class: contains many mathematical functions, such trigonometry, absolute, exponential and roots Eg. Math.floor(pi); //returns 3.0 1. The Math class is always available in Java code a. The math class is in a package in the Java Class Library (java.lang). b. THE MATH CLASS NEVER NEEDS TO BE "IMPORTED" (neither does the String class) 2. The Math class prevents instantiation of math objects a. It can be invoked on the Class itself b. Math is 'static', it's in the application driver. OPERATOR PRECENDENCE BODMAS: Brackets, Orders, Division, Multiplication, Addition, Subtraction Parentheses can be nested - the expression within the INNERMOST level of parenthesis is evaluated first. The following operators have equal precedence: Division and multiplication Addition and subtraction The leftmost operator has the highest precedence EXCEPTION - the assignment operator associated from right to left. Good style - programmers use parentheses to explicitly and completely specify the order of operations. Why? The programmer doesn't have to remember the operator precedence rules.

EQUALITY AND RELATIONAL OPERATORS Equality and relational operators: operate on numeric and String operands, and return Boolean results. Ordering of numeric values: We can establish relativity between values because we assume an ordering of value This is self-evident. Ordering of String values: String values are compared by right-padding the shorter values with spaces to make the comparative values the same length Then, a left-to-right character-by-character comparison is made It is based on the characters' Unicode integer value Space has the lowest Unicode integer value Unicode ordering: Space < 1 < 2 < 3 < A < B < C < < a < b < c < Case-sensitivity: 'A' and 'a' are not the same. Punctuation characters are placed unpredictably between the digits and numbers Eg. "abcdefghij" compared to "abcd" 1. Right-pad the shorter value: "abcdefghij" VS "abcd " 2. Character-by-character comparison: "a" vs "a", "b" vs "b", "C" vs "c" - "C" is smaller, therefore "abcdefghij" is the smaller value. Control structure conditions: Structures that control the sequence in which statements are executed rely on Boolean expressions, called conditions to decide which statement to execute next. Operator Java symbol Equality == Inequality!= Relational: Less than Less than or equal to More than More than or equal to < <= > >= Precedence: Relational (<, >) come before '==' and '!=' When comparing two floating-point values, it is best to allow for small inaccuracies. double d1 = 1.23, d2 = 3.45; double delta = 0.00000001; mywindow.writeoutline((d2 - d1) < delta); //false

Equality and Inequality with Strings: String s1 = "dog", s2; s2 = mywindow.readin(); //assume user types in 'dog' mywindow.writeoutline("s1 == s2: "+(s1 == s2)); //false Problem: both String variables, s1 and s2, are set with the same value. However, Java judged them unequal String is a reference type, not a primitive type When two string variables are compared with the equality/inequality operators, Java asks the question: "are they stored at the same location in memory or not?" Instead of "are they the same value?" STRING VALUES CANNOT BE COMPARED WITH THE '==' / '!=' OPERATORS Side notes about reference types: A reference variable's value is actually an address to its value, not the value itself. If you set two variables in code with the same String value, the Java compiler will only store it once and reference it twice Relational operators with Strings: Java will syntactically prevent relational operators from taking String operands. o You cannot run the expression: "abcd" < "ABCD"; Instead, we use some functions from the String class String s1 = "dog", s2, s3 = "dog", s4 = "dogs!"; s2 = mywindow.readin(); //assume user types in 'dog' Function Explanation Return value s1.equals(s2) s1 == s2 true!s1.equals(s2) Not (s1 == s2) false s1.equalsignorecase(s3) Compares s1 and s3, ignoring case considerations. True s1.compareto(s4) Compares s1 and s4, lexicographically*. Returns the difference of the two character values. It is negative, because s1 is smaller than s4. -2 (negative value) s4.compareto(s1) s1.compareto(s2) Returns a positive value, because s4 is bigger than s1 Returns 0, because both values are equal 2 (positive value) 0

s1.comparetoignorecase(s3) Compares s1 and s3 lexicographically, but ignore the case differences. 32 (positive value) LOGICAL OPERATORS Operator Java symbol Not! And && Or Precendence:! < && < Truth tables: Not B1!B1 True False False True And B1 B2 B1 && B2 True True True True False False False True False False False False Or B1 B2 B1 B2 True True True True False True False True True False False False Example of combinations:

Write an expression that tells you whether a value is in the range of 50 and 100, called inrangetest. int low = 50, high = 100; int testvalue1 = 99, testvalue2 = 101; boolean inrangetest1, inrangetest2; inrangetest1 = testvalue1 >= low && testvalue1 <= high; inrangetest2 = testvalue2 >= low && testvalue2 <= high; Short circuiting: The '&&' and ' ' operates are short circuit operators. This means that o For '&&', if the left-hand operand is false, then the right-hand operand is not evaluated, and the return value is automatically false. o For ' ', if the left-hand operand is true, then the right-hand operand is not evaluated, and the return value is automatically true. Some programmers use short-circuiting to invoke/not invoke a method call, depending on the left-hand operand. Redundant syntax: Boolean expressions that look like this myboolean == true; myboolean == false; Should be coded like this myboolean;!myboolean; OPERATOR PRECEDENCE The four different types of operators are: 1. Arithmetic (+, -, /, %, *) 2. Relational (<, >) 3. Equality, inequality (=,!=) 4. Logical (&&,,!) Precedence: Arithmetic < Relational < Equality/Inequality < Logical EXPRESSIONS AND STATEMENTS Expression: any syntactically legal combination of variables, constants, literals, method calls and operators that evaluate to a single value. All expressions return this single value, therefore it has a data type The data type is determined by the types of the expression's terms There are 3 types of Java statements: 1. Expression statements: assignments, pre/post increment/decrement, method calls, and object instantiation expressions, which are turned into statements by terminating them with a semi-colon

2. Declaration statements: tell Java the name of a storage location and the type of data that will be stored there. 3. Control flow statements: employ decision-making and looping to conditionally execute particular blocks of code. Statement block: 0 or more statements that are Terminated with semi-colons Enclosed in braces { } Syntactically, statement blocks can appear anywhere a single statement can appear Statement blocks can be nested inside other statement blocks SCOPE Scope: the scope of a variable is all the code that can access it There are 3 levels of variable scope: 1. Class level: a. Variables declared in a class, but outside of any methods b. The scope is the entire class, including the methods. 2. Method level (local scope): a. Variables declared inside a method b. The scope is from the variable's declaration statement until the closing brace of the method, including any nested statement blocks. 3. Block level (block scope): a. Variables declared in a block b. The scope is from the variable's declaration statement until the closing brace of the block, including any nested statement blocks. Control flow statements: use statement blocks extensively to delimit sequences of statements that should or should not be executed (decisions / if statements), or should be repeatedly executed (loops / for / while) Usually, statements are executed from top to bottom However, control flow statements break up the flow of execution by employing, eg. decisionmaking and looping, Allows your program to conditionally execute particular blocks of code. Lifetime: the time a variable exists in memory It is possible for variables to be alive, but temporarily out of scope Scope is a static concept, but lifetime is a dynamic concept.