EXPRESSIONS AND ASSIGNMENT CITS1001. Scope of this lecture Assignment statements Expressions 2.

Slides:



Advertisements
Similar presentations
© 2007 Lawrenceville Press Slide 1 Assignment Statement An assignment statement gives a value to a variable. Assignment can take several forms: x = 5;
Advertisements

L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Types and Arithmetic Operators
Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
Lecture 2 Introduction to C Programming
Introduction to C Programming
Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Introduction to Programming with Java, for Beginners Primitive Types Expressions Statements Variables Strings.
10-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
CMT Programming Software Applications
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
Data types and variables
Chapter 2 Data Types, Declarations, and Displays
JavaScript, Third Edition
Introduction to C Programming
Chapter 2 Data Types, Declarations, and Displays.
Objectives You should be able to describe: Data Types
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
VARIABLES AND TYPES CITS1001. Types in Java the eight primitive types the unlimited number of object types Values and References The Golden Rule Scope.
2440: 211 Interactive Web Programming Expressions & Operators.
Object-Oriented Programming Using C++ Third Edition Chapter 2 Evaluating C++ Expressions.
Chapter 3: Data Types and Operators JavaScript - Introductory.
Operators Using Java operators An operator takes one or more arguments and produces a new value. All operators produce a value from their.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CSC Programming I Lecture 5 August 30, 2002.
Assignment Statements Operator Precedence. ICS111-Java Programming Blanca Polo 2 Assignment, not Equals  An assignment statement changes the value of.
Knowledge Base C++ #include using std namespace; int main(){} return 0 ; cout
CPS120: Introduction to Computer Science Operations Lecture 9.
Lecture 2: Introduction to C Programming. OBJECTIVES In this lecture you will learn:  To use simple input and output statements.  The fundamental data.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
CSC 107 – Programming For Science. The Week’s Goal.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Computer Science 1620 boolean. Types so far: Integer char, short, int, long Floating Point float, double, long double String sequence of chars.
Operators Precedence - Operators with the highest precedence will be executed first. Page 54 of the book and Appendix B list C's operator precedence. Parenthesis.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
Operators A binary operator combines two values to get one result: x OP y where OP is any binary operators such as +, -, *, /, ==, !=, >, &&, or even =.
Chapter 4: Variables, Constants, and Arithmetic Operators Introduction to Programming with C++ Fourth Edition.
Copyright © Curt Hill The Assignment Operator and Statement The Most Common Statement you will use.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
1Object-Oriented Program Development Using C++ Built-in Data Types Data type –Range of values –Set of operations on those values Literal: refers to acceptable.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
What will each of the following lines print? System.out.println("number" ); number645 System.out.println("number" + (6 + 4)+ 5); number105 System.out.println(6.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
CompSci 230 S Programming Techniques
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Expressions An expression is a portion of a C++ statement that performs an evaluation of some kind Generally requires that a computation or data manipulation.
Multiple variables can be created in one declaration
Introduction to C++ Programming
Computing in COBOL: The Arithmetic Verbs and Intrinsic Functions
Expressions An expression is a portion of a C++ statement that performs an evaluation of some kind Generally requires that a computation or data manipulation.
Building Java Programs
Primitive Types and Expressions
Building Java Programs
Introduction to C Programming
Presentation transcript:

EXPRESSIONS AND ASSIGNMENT CITS1001

Scope of this lecture Assignment statements Expressions 2

Assignment Statements Values are stored into fields (and other variables) using assignment statements price = cost * 1.1; The expression on the RHS is evaluated, and the result is stored in the variable on the LHS A variable stores a single value at a time Any previous value is lost Statements in a sequence are performed one after another Each statement uses the context provided by previous statements 3

Sequence and Assignment int x, y, z; x = 10; y = 4; z = x + 2; x = y; z = x + 2; xyz time (execution order) xyz 446 final state computer memory 4

An expression is Java code that is evaluated to yield a value Every expression has a type and a value total = price + 10; Whenever a statement is executed, each expression is evaluated and replaced with its value The process of evaluating expressions and doing something with the resulting values is the fundamental process of computing 5 Expressions

Evaluation of Expressions A simple example int x; x = ; The first line creates a variable called x of type int The second line evaluates the expression 10+15, replaces it with its value ( 25 ), and assigns this value to x Evaluation of an expression may take several steps and require the cooperation of several objects double y; y = b1.getBalance() * b2.getBalance() * 0.05; 6

Types of Expression There are several types of expressions Literals and names Method invocations Object creations Compound expressions built up with operators Arithmetic operators Relational operators Logical operators 7

Literals Literals are values that are “hard wired” into the code 23, 10009, ‘a’, , 10e-5, 100e2, true In Java, the types int and double are dominant Any literal that does not use a decimal point is assumed to be of type int, and any literal that uses a decimal point (or scientific notation) is assumed to be a double The Java compiler will complain if you try to assign a value to a “smaller” type float f; f = 23.5; float f; f = 23.5; 8

Casting (an aside) If the programmer really wants to assign a double value to a float variable, then the compiler can be prevented from complaining by using a cast The number is simply truncated to fit the new type float f; f = (float) 23.5; This says to the compiler “I know this looks dumb, but I know what I want; just treat this number as a float rather than a double” 9

Names Names are the declared variables that are in scope; the expression has the value and the type currently associated with that variable the value in the shoebox, if it is a primitive type the reference in the shoebox, if it is a reference type For example, circle, price, total, mark, studentName, i 10

Method Invocations The calling of a non-void method of some object The value of the expression is the returned value The type of the expression is the return type of the method This method call is an expression (here b1 is an object in BankAccount) b1.getBalance() Its type is int, because the return type of the method is int Its value is the current value of b1’s balance You can use such an expression anywhere that an int is allowed But the compiler will complain if you violate this Type checking is a valuable aid to debugging! 11

Object Creations The construction of an object with new returns a reference to the newly-created object, so this is also an expression The expression new SimpleCanvas() returns a reference to a SimpleCanvas object, so it can be used anywhere that such a reference is valid 12

Compound Expressions A compound expression is obtained by combining one or more simple expressions with an operator is a compound expression, obtained by combining the literals 5 and 3 with the operator + The value of this expression is 8 The type of this expression is int 13

Classes of Operators Java has a large number of operators Arithmetic Operators Take numeric values and perform arithmetic on them, producing numeric answers Relational Operators Take numeric (or other) values and make logical tests of equality, inequality, etc, producing boolean answers Logical Operators Take boolean values and combine them using the rules of logic, producing boolean answers Miscellaneous Operators Other operators, acting on Strings, bit patterns, etc. 14

Arithmetic Operators We will concentrate on the arithmetic operators first PrecedenceOperatorOperationAssociation Unary plus Unary minus Right-to-left 2 */%*/% Multiplication Division Remainder Left-to-right Addition Subtraction Left-to-right 15

Association The association rules explain how to combine a sequence of operators of the same precedence Consider the expression 100 / 10 / 5 The / operator associates left-to-right, so the value is the same as (100 / 10) / 5 If it associated right-to-left, it would be 100 / (10 / 5) The association rules just follow normal mathematical usage, so there are no surprises 16

These behave (almost) as you would expect But what is 5 * * * 11 ? ExpressionValue * / * Arithmetic Operators

Precedence The compiler uses the precedence and association rules to determine the order of evaluation 5 * * * 11 becomes (5 * 6) + (3 * 2) (6 * 11) because * has a higher precedence than + or - The resulting expression is calculated left to right (((30 + 6) - 4) + 66) The programmer can use parentheses if a different order is required 18

Watch your types! Every expression has a type, which depends on the operators involved and the types of the operands In particular, the division operator / returns an int if both of its operands are int s So 7/5 yields 1 12/4 yields 3, as do 13/4 and 14/4 7.0/5 yields 1.4, as do 7/5.0 and 7.0/5.0, because the expression is a floating point number The integer is obtained by truncation 100/51 yields 1 19

Integer Division Java’s integer division is always a fertile source of difficult-to-trace bugs double d = 8 / 5; After this statement, the value of d is 1.0 and not 1.6! Why? First the expression 8 / 5 is evaluated, and as both arguments are ints, the answer is truncated to an int Then the value 1 is assigned to the double variable, and hence d has the value 1.0 This leads to some potentially confusing situations 2.0 / 3 * 6 is not equal to 2 / 3 *

The Remainder Operator The operator % returns the remainder in a division with two integer arguments An important Java idiom is the use of / and % together If someone is 7000 days old, then how old are they? 7000/365 years, plus 7000%365 days ExpressionValue 10 % % % 7 % % (7 % 4)1 21

Turn on the Code Pad by using the View menu and selecting Show Code Pad The Code Pad This is the Code Pad, which allows you to enter either expressions or statements and have them performed immediately

Enter any expression in order to have it immediately evaluated Here we discover that 15 % 11 has the value 4 and the type int Notice that the Code Pad knows you want to evaluate an expression because it has no semicolon 23 Evaluate an Expression

Relational Operators The six relational operators compare numeric values and return a boolean OperatorOperation a == bIs a equal to b? a != bIs a different to b? a > bIs a greater than b? a < bIs a less than b? a >= bIs a greater than or equal to b? a <= bIs a less than or equal to b? 24

Use of the Relational Operators Relational operators are crucial in allowing a program to choose among different courses of action depending on the results of calculations They are often used to determine a program’s flow of control, using if statements (and others) “if the balance is less than zero, then print out an overdraft statement” if (balance < 0) { // print out the overdraft statement } 25

Boolean expressions can be combined into compound expressions using operators for NOT, AND, and OR OperatorOperation a && bAre a and b both true? a || bIs at least one of a and b true? !a Is a false? 26 Logical Operators

Shortcut Evaluation Java uses shortcut evaluation of the logical operators As soon as it knows the final answer it stops calculating if (balance > || accountName.equals(“Kerry Packer”)) { // send grovelling letter } There are two relational tests, one on balance and the other on accountName, combined with an OR If the first test returns true, then the entire expression will be true regardless of the second test Thus Java saves time by not even bothering to do the second test Similarly for b1 && b2 If b1 is false, no need to evaluate b2 27