***** SWTJC STEM ***** Chapter 2-3 cg 29 Java Operators Recall Java’s programming components: Packages - Collection of classes (Programs) Classes - Collections.

Slides:



Advertisements
Similar presentations
Types and Arithmetic Operators
Advertisements

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.
1 Fundamental Data types Overview l Primitive Data Types l Variable declaration l Arithmetical Operations l Expressions l Assignment statement l Increment.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
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”
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Primitive Data Types There are exactly eight primitive data types in Java four of them represent integers: byte (class Byte), short (class Short), int.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Expressions An expression is a sequence of operands and operators that reduces to a single value expression operator operand An operator is a language-specific.
JavaScript, Third Edition
1 Expressions, Operators Expressions Operators and Precedence Reading for this class: L&L, 2.4.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Performing Computations C provides operators that can be applied to calculate expressions: example: tax is 8.5% of the total sale expression: tax =
Expressions, Data Conversion, and Input
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Primitive Data Types and Operations Identifiers, Variables, and Constants Primitive Data Types Byte, short, int, long, float, double, char, boolean Casting.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Numeric Types, Expressions, and Output ROBERT REAVES.
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
Operators Using Java operators An operator takes one or more arguments and produces a new value. All operators produce a value from their.
LESSON 6 – Arithmetic Operators
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Chapter 2: Using Data.
Java Software Solutions Lewis and Loftus Chapter 5 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. More Programming Constructs.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Assignment Statements Operator Precedence. ICS111-Java Programming Blanca Polo 2 Assignment, not Equals  An assignment statement changes the value of.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Mathematical Calculations in Java Mrs. G. Chapman.
November 1, 2015ICS102: Expressions & Assignment 1 Expressions and Assignment.
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.
Mathematical Calculations in Java Mrs. C. Furman.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
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.
1 Lecture 5 More Programming Constructs Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
Doing math In java.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
ECE 103 Engineering Programming Chapter 4 Operators Herbert G. Mayer, PSU CS Status 6/19/2015 Initial content copied verbatim from ECE 103 material developed.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
CSCI 1100/1202 January 18, Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions compute numeric.
ICS102 Lecture 1 : Expressions and Assignment King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer.
Expressions Version Topics Arithmetic expressions Conversions Operator precedence String class 2.
Data and Expressions. Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration.
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.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Expressions.
Chapter 7: Expressions and Assignment Statements
Lecture 3 Java Operators.
Expressions.
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Chapter 7: Expressions and Assignment Statements
Data Conversion & Scanner Class
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Type Conversion, Constants, and the String Object
Java Programming: From Problem Analysis to Program Design, 4e
Increment and Decrement
Lecture 3 Expressions Richard Gesick.
Numerical Data Types.
Arithmetic Expressions & Data Conversions
Expressions and Assignment
Data Types and Expressions
Data Types and Expressions
Arithmetic Expressions & Data Conversions
Data Types and Expressions
Presentation transcript:

***** SWTJC STEM ***** Chapter 2-3 cg 29 Java Operators Recall Java’s programming components: Packages - Collection of classes (Programs) Classes - Collections of data and methods that operate on data Methods - Collections of statements that operate on data Variables - Store data Constants - Store data that doesn’t change Literals - Explicit data like “Hello World”

***** SWTJC STEM ***** Expressions and Operators Expressions are segments of code that perform computations and return values. They are combinations of literals, variables, constants, and operators. An operator performs an action on variables, constants, and literals. Associated with an operator are one or two operands that receive the action of the operator. Unary operators act on only one operand. Example: -12, negation operator “-” Binary operators act on two operands. Example: , addition operator “+” Chapter 2-3 cg 29

***** SWTJC STEM ***** Chapter 2-3 cg 29 Unary Operators Unary operators support either prefix or postfix notation. Prefix notation means that the operator appears before its operand: operator operand Example:  - i, negation operator “-”  ++ i, shortcut increment operator “++“ Postfix notation means that the operator appears after its operand: operand operator Example:  i ++, shortcut increment operator “++“

***** SWTJC STEM ***** Chapter 2-3 cg 29 Binary Operators Binary operators use infix notation, which means that the operator appears between its operands: operand1 operator operand2 Examples: i + j a / b x += 10

***** SWTJC STEM ***** Chapter 2-3 cg 29 Basic Numeric Operators OperatorUseDescription ++op Promotes op to int if it's a byte, short, or char --opArithmetically negates op Unary Operators (op is an operand) Operator + - * / % Use op1 + op2 op1 - op2 op1 * op2 op1 / op2 op1 % op2 Description Adds op1 and op2 Subtracts op2 from op1 Multiplies op1 by op2 Divides op1 by op2 Computes the remainder of dividing op1 by op2 Binary Operators

***** SWTJC STEM ***** Chapter 2-3 cg 30 Numeric Operator Examples Declare Variables... int i = 37; int j = 42; double x = ; double y = 7.22; Adding... i + j is 79 x + y is Subtracting... i - j is -5 x - y is x - (-y) is Multiplying... i * j is 1554 x * y is Dividing... i / j is 0 (integer division implied) x / y is Computing the remainder... i % j is 37, j % i is 5 x % y is Mixing types...converts to double... j + y is i * x is

***** SWTJC STEM ***** Chapter 2-3 cg 30 Coding an expression - Examples Example: Coding expressions 1.int thisDecade = 2000; byte decadeLength = 10; int nextDecade = thisDecade + decadeLength;  byte decadeLength = 10; assigns the value 10 to a 8-bit byte variable named decadeLength.  int thisDecade = 2000; assigns the value 2000 to a 32-bit integer variable named thisDecade.  int nextDecade = thisDecade + decadeLength; assigns the value 2010 to a 32-bit integer variable named nextDecade.

***** SWTJC STEM ***** Chapter 2-3 cg 30 Coding an expression - Examples Examples: Expression coding continued... 2.float radius = 2.0f; float area = f * radius * radius;  float radius = 2.0f; assigns the value 2.0 to a 32-bit (single precision) floating point variable named radius.  float area = f * radius * radius; assigns the computed expression to a 32-bit (single precision) floating point variable named area.

***** SWTJC STEM ***** Chapter 2-3 cg 29 Shortcut Incr/Decr Operators Shortcut Increment/Decrement Operators OperatorUseDescription ++ (incr)op++ Increments operand op by 1; evaluates to the value of op before incrementing op ++ (incr)++op Increments operand op by 1; evaluates to the value of op after incrementing op -- (decr)op-- Decrements operand op by 1; evaluates to the value of op before decrementing op -- (decr)--op Decrements operand op by 1; evaluates to the value of op after decrementing op

Note: --i and i– (decrement) work similarly. ***** SWTJC STEM ***** Chapter 2-3 cg 29 Shortcut Incr/Decr Examples inewNum Before10Undeclared After11100 Postfix Operator Code... int i = 10; int newNum = 10 * (i++); i increments after *. Prefix Operator Code... int i = 10; int newNum = 10 * (++i); inewNum Before10Undeclared After11110 i increments before *.

***** SWTJC STEM ***** Chapter 2-3 cg 29 Shortcut Assignments Operators OperatorUseEquivalent to +=op1 += op2op1 = op1 + op2 -=op1 -= op2op1 = op1 - op2 *=op1 *= op2op1 = op1 * op2 /=op1 /= op2op1 = op1 / op2 %=op1 %= op2op1 = op1 % op2 Examples... iValue += 8; is the same as iValue = iValue + 8; jValue %= 5; is the same as jValue = jValue % 5;

***** SWTJC STEM ***** Chapter 2-3 cg 29 Shortcut Assignment Examples Assignment Addition Code: int i = 10; int newNum = 10; newNum += i; Same as newNum = newNum + i; newNum becomes 20. i remains 10. Assignment Division Code: int i = 10; int newNum = 10; newNum /= i; Same as newNum = newNum / i; newNum becomes 1. i remains 10.

***** SWTJC STEM ***** Chapter 2-3 cg 29 Character Operator Operator UseDescription + char1 + char2 string1 + string 2 Concatenates characters and strings Binary Operator A char/string variable holds character/string data, respectively. Char literals use apostrophes ‘s‘ and are single values. String literals use quotation marks “red leaf” and can hold more than one character (i.e., text). Concatenation “ties together” char/string variables and literals.

***** SWTJC STEM ***** Chapter 2-3 cg 29 Character Operator Examples Examples... char cValue = ‘s’; Declares a character variable cValue and assigns character s to it. String c1Value = “red”, c2Value = “bird”; Declares string variables c1Value and c2Value assigning strings “red” and “bird” to them respectively. System.out.println(c1Value + c2Value + cValue); Outputs string redbirds to the PC monitor, which is the concatenation of all three variables.

***** SWTJC STEM ***** Chapter 2-3 cg Creating Complex Assignments When creating complex assignment expressions, 1.How is the order of operations determined? 2.What if we mix data and variable types? Examples: int result = / 2;  Is the result 11 (+ first)? or 18 (/ first)? int result = 12 / 2 * 3;  Is the result 18 (/ first)? or 2 (* first)? float total = f; int count = 10; float result = total / count; // Mixed types?  Is result 10 (integer /)? or (float /)?

***** SWTJC STEM ***** Chapter 2-3 cg Order of Operations - Precedence Expressions are evaluated according to operator precedence. When operators of equal precedence occur together in an expression, association governs the order. Left-associative means operations are performed left-to- right. Binary operators, except the assignment operator, are left-associative. Right-associative means operations are performed right- to-left. Unary and assignment operators are right- associative.

***** SWTJC STEM ***** Chapter 2-3 cg Order of Operations - Precedence Precedence Level OperatorOperationAssociates ,-- unary plus unary minus shortcut R to L 2*/%*/% multiplication division modulus L to R addition subtraction concatenation L to R 4= +=,-=,... assignmentR to L

***** SWTJC STEM ***** Chapter 2-3 cg Order of Operations - Examples Given differing orders of precedence. result = / 2; // Divide first / higher precedence than + and result is 18. Precedence can be forced using parentheses. result = (14 + 8) / 2; // Add first + is forced first by parentheses and result is 11. Given the same order of precedence. result = 12 / 2 * 3; // Divide first / is first (L to R), then * and result is 18. Adding a unary operator -. result = 12 / -(-3 + 1) * 3; // Negation first - is first (R to L), then / (L to R), then * and result is 18.

***** SWTJC STEM ***** Chapter 2-3 cg Order of Operations - Assignment Given assignment operators. Assume int a = 1. 1.result = a + (a = 3); 1)Proceed L to R a = 1, then 1 + (a = 3). 2)Now do (a = 3) then result = 4. 2.result = (a = 3) + a; 1)Proceed L to R (a = 3) first, so a is now 3. 2)Now do a + a = so result is 6. 3.result = (a += 2 * a) + a 1)(a = * 1) + a. 2)(a = 3) + a = a + a = = 6.

***** SWTJC STEM ***** Chapter 2-3 cg Order of Operations - Incr/Decr Given increment/decrement operators. Assume int a = 5. 1.result = a + (--a) + a 1)Proceed L to R a = 5, then 5 + (--a) + a. 2)Now do a = a - 1= 4  a, then a  9 + a. 3)Finally, a = 4 and  result is result = a + (a--) + a 1)Proceed L to R a = 5, then 5 + (a--) + a. 2)Now do a = 10 + a, then do a = a - 1 = 4  a. 3)Finally 10 + a =  result is 14.

***** SWTJC STEM ***** Chapter 2-3 cg 32 Mixed Data/Variable Types Java is a strong typed language, meaning that all data and variables must be explicitly typed. Sometimes conversion is necessary. Recall float total = f; int count = 10; float result = total / count; // Mixed types? Care must be exercised or information can be lost. byte a = 20; // 1 byte in size int b = 2 * a ; // 4 bytes in size b can hold a; (1 byte) will fit in (4 bytes). int a = 2000; // 4 bytes in size byte b = 2 * a ; // 1 byte in size b cannot store a. ; (4 bytes) will not fit in (1 byte)!

***** SWTJC STEM ***** Chapter 2-3 cg 32 Mixed Data/Variable Types Conversions are of two types: 1.Widening conversions. Safest, does not lose information. Data conversion involves smaller to larger storage. doublefloat float, doublelong* long, float, doubleint int, long, float, doublechar int, long, float, doubleshort short, int, long, float, doublebyte ToFrom * Some precision (significant digits) could be lost!

***** SWTJC STEM ***** Chapter 2-3 cg 32 Mixed Data/Variable Types Conversions are of two types (continued): 2.Narrowing conversions. Likely to lose information. Avoid! Data conversion involves larger to smaller storage. byte, short, char, int, longfloat byte, short, char, intlong byte, short, charint byte, shortchar byte, charshort charbyte ToFrom byte, short, char, int, long, floatdouble

***** SWTJC STEM ***** Chapter 2-3 cg 32 Assignment Conversion Java conversions occur in three ways: 1.Assignment conversion Occurs when one type is assigned to another. Only widening conversions allowed. Is automatic. double money; int dollars = 1000; money = dollars; // int will fit in double OK - Widening conversion, done. double money = 1000; byte dollars; dollars = money; // double will not fit in int (max 255)! Not OK - Narrowing conversion, error!

***** SWTJC STEM ***** Chapter 2-3 cg 32 Arithmetic Promotion Java conversion occur in three ways (cont.): 2.Arithmetic promotion Occurs in expressions when operators need to widen (promote) data to complete. Only widening conversions allowed. Promotion is automatic when possible. float total = f, result; int count = 10; result = total / count; count promoted to float automatically. Floating point division used to calculate result. result is

***** SWTJC STEM ***** Chapter 2-3 cg 32 Casting - Forced Conversion Java conversion can occur in three ways: 3.Casting - Forcing the conversion Most general form of conversion. Unary operator specified by a data type in parentheses, (type) operand. Is not automatic. Programmer must specify. Example: float money = 8.75f; int dollars; dollars = (int) money; Casts money (float) to dollars (int). dollars is 8 money truncated (decimal portion dropped)

***** SWTJC STEM ***** Chapter 2-3 cg 32 Casting Continued Java conversion can occur in three ways: 3.(cont) Casting examples double result; int count = 10, total = 20; result = (double) total / count; total cast to double. count automatically promoted to double. Floating point division used. Quotient 2.0 stored in result as a double.

***** SWTJC STEM ***** Chapter 2-3 cg 32 Casting Continued Java conversion can occur in three ways: 3.(cont) Casting char variables char c = 'A'; // upper case A int ic; ic = (int) c; char c is cast as an int ic is 65. ic = 97; c = (char) ic; int ic is cast as char c = ‘a’, lower case a.