Java Operators

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 28

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”
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: 8 + 15, addition operator “+”
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
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
Basic Numeric Operators
Unary Operators (op is an operand)
Operator Use Description
Promotes op to int if it's a byte, short, or
+ +op
char
- -op Arithmetically negates op

Binary Operators
Operator Use Description

+ op1 + op2 Adds op1 and op2


- op1 - op2 Subtracts op2 from op1
* op1 * op2 Multiplies op1 by op2

/ op1 / op2 Divides op1 by op2

% op1 % op2 Computes the remainder of dividing op1 by op2


Numeric Operator Examples

Declare Variables... Multiplying...


int i = 37; i * j is 1554
int j = 42; x * y is 198.3695
double x = 27.475; Dividing...
double y = 7.22; i / j is 0 (integer division
Adding... implied)
i + j is 79 x / y is 3.8054...
x + y is 34.695 Computing the remainder...
Subtracting... i % j is 37 , j % i is 5
i - j is -5 x % y is 5.815
x - y is 20.255 Mixing types...converts to
x - (-y) is 34.695 double...
j + y is 49.22
i * x is 1016.58
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.
Coding an expression - Examples

• Examples: Expression coding continued . . .


2. float radius = 2.0f;
float area = 3.14159f * radius * radius;
 float radius = 2.0f;
assigns the value 2.0 to a 32-bit (single
precision) floating point variable named radius.
 float area = 3.14159f * radius * radius;
assigns the computed expression to a 32-bit
(single precision) floating point variable named
area.
Shortcut Incr/Decr Operators

Shortcut Increment/Decrement Operators

Operator Use Description


Increments operand op by 1; evaluates to the
++ (incr) op++
value of op before incrementing op
Increments operand op by 1; evaluates to the
++ (incr) ++op
value of op after incrementing op
Decrements operand op by 1; evaluates to the
-- (decr) op--
value of op before decrementing op
Decrements operand op by 1; evaluates to the
-- (decr) --op
value of op after decrementing op
Shortcut Incr/Decr Examples

Postfix Operator Code... Prefix Operator Code...


int i = 10; int i = 10;
int newNum = 10 * (i++); int newNum = 10 * (++i);
i newNum i newNum
Before 10 Undeclared Before 10 Undeclared
After 11 100 After 11 110
i increments after *. i increments before *.

Note: --i and i– (decrement) work similarly.


Shortcut Assignments Operators

Operator Use Equivalent to

+= op1 += op2 op1 = op1 + op2

-= op1 -= op2 op1 = op1 - op2

*= op1 *= op2 op1 = op1 * op2

/= op1 /= op2 op1 = op1 / op2

%= op1 %= op2 op1 = op1 % op2

Examples . . .
iValue += 8; is the same as iValue = iValue + 8;
jValue %= 5; is the same as jValue = jValue % 5;
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.
Character Operator
Binary Operator
Operator Use Description

char1 + char2
+ Concatenates characters and strings
string1 + string 2

• 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.
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.
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 = 14 + 8 / 2;
 Is the result 11 (+ first)? or 18 (/ first)?
• int result = 12 / 2 * 3;
 Is the result 18 (/ first)? or 2 (* first)?
• float total = 100.46f;
int count = 10;
float result = total / count; // Mixed types?
 Is result 10 (integer /)? or 10.046 (float /)?
***** SWTJC STEM ***** 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.

Chapter 2-3 cg 29-31


Order of Operations - Precedence

Precedence Operator Operation Associates


Level
1 + unary plus R to L
- unary minus
++,-- shortcut
2 * multiplication L to R
/ division
% modulus
3 + addition L to R
- subtraction
+ concatenation
4 = assignment R to L
+=,-=,...
Order of Operations - Examples

• Given differing orders of precedence.


• result = 14 + 8 / 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.
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 1 + 3 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 = 3 + 3 so result is 6.
3. result = (a += 2 * a) + a
1) (a = 1 + 2 * 1) + a.
2) (a = 3) + a = a + a = 3 + 3 = 6.
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 5 + 4 + a  9 + a.
3) Finally, a = 4 and 9 + 4  result is 13.
2. result = a + (a--) + a
1) Proceed L to R a = 5, then 5 + (a--) + a.
2) Now do 5 + 5 + a = 10 + a, then do a = a - 1 = 4  a.
3) Finally 10 + a = 10 + 4  result is 14.
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 = 100.46f;
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)!
Mixed Data/Variable Types

• Conversions are of two types:


1. Widening conversions.
• Safest, does not lose information.
• Data conversion involves smaller to larger storage.
From To
byte short, int, long, float, double
short int, long, float, double
char int, long, float, double
int long, float, double
long* float, double
float double
* Some precision (significant digits) could be lost!
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.
From To
byte char
short byte, char
char byte, short
int byte, short, char
long byte, short, char, int
float byte, short, char, int, long
double byte, short, char, int, long, float
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!
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 = 100.46f, result;
int count = 10;
result = total / count;
count promoted to float automatically.
Floating point division used to calculate result.
result is 1.0046.
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)
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.
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.

You might also like