0% found this document useful (0 votes)
25 views22 pages

Slide Set Two - Operators, Expressions, and Casting

The document discusses Java operators including assignment, arithmetic, relational, increment, and decrement operators. It provides examples of using various operators and explains operator precedence. Key topics covered include data types, primitive types, equality checks, and unary operators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views22 pages

Slide Set Two - Operators, Expressions, and Casting

The document discusses Java operators including assignment, arithmetic, relational, increment, and decrement operators. It provides examples of using various operators and explains operator precedence. Key topics covered include data types, primitive types, equality checks, and unary operators.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Software and Information Systems Testing

INFO6066

Operators, Expressions, and


Type Casting in Java

INFO6066
Software and Information Systems Testing

Recap: What is a Data Type?

• A data type is a how a computer language represents the various


types of numbers and text characters we use in our physical world.
• Some primitive data type examples from Java:
• char: Represents a single character: ‘a’,’-’…
• int: uses 32 bits to represent a whole number 1,2,3…
• double: uses 64 bits to represent a real or floating point number
such as 25.243
• boolean: uses 8 bits to represent a value of either ‘true’ or ‘false’

INFO6066
Software and Information Systems Testing
Recap: Primitive Data Types in Java

• Primitive data types are the only things in Java that are not
objects (T!)
• primitives don’t have any methods associated with them.
Object data types like Strings do have methods.
• Are eight primitive data types in Java(T!).
• See if you can list them all before looking at the next slide!

INFO6066
Software and Information Systems Testing
Primitives Data Types in Java (T!)

• 6 numeric data types • 2 Non-numeric types


• 4 integer types • char (16 bit)
– byte (8 bits) • Will hold a Unicode
– short (16 bits) value for any single
– int (32 bits) character
– long(64 bits)
• boolean (8 bit)
• 2 floating point
– Holds values of true or
– float (32 bit) false.
– double (64 bit)

INFO6066
Software and Information Systems Testing

The Assignment Operator =


• Assignment Operator: =
• = DOES NOT mean “equal to” as it does in mathematics.
• It means “is assigned to” or “gets”. (Hint: say “gets” to avoid confusion)
• used to assign a data value to a variable in memory.
• Any statement that contains the ‘=‘ operator is an assignment statement. It
means some data is being stored in memory.
• Any mathematical expression on the right side is completed first, and the
answer is then assigned to the variable on the left side.
• Example: int cost = 25 + 40; //addition is done first…
• means the variable cost gets the value of 65 placed in it.
• A Java statement to calculate a total price with GST looks like this:
double totalPrice = cost * GST_RATE + cost;

INFO6066
Software and Information Systems Testing

Arithmetic Operators
• +, -, *, /, and %.
• Are called binary operators because they appear between two operands
(values).
• Example: myValue = 3 + 6;
• “add 3 to 6 and assign the result to the variable myValue”.
• Q. What is ‘%’ used for?
• A. it is the modulus division operator. This returns the remainder from a
division operation, rather than the quotient.
• Example : 5 / 2 returns a value of 2 (remember, integer division in Java
truncates the decimal portion!), with 1 as the remainder
• 5 % 2 (read as “5 mod 2” )will return a value of 1, which is the remainder
of the division operation.

INFO6066
Software and Information Systems Testing

Modulus Division (T!)


• Q. What is modulus division useful for?
• A. one common use is to determine if a value is odd or even by doing a
modulus division by 2 on the test value.
• The answer of a modulus division operation is the REMAINDER value from
a regular division operation. (T!)
• Example : 6 % 2 returns a value of 0, so we know it’s even
• 5 % 2 returns a value of 1, so we know it’s an odd value.
• Code would look like this:

if(inputValue % 2 ==0) //note the “==“ operator here…


{
System.out.println(“The value “ + inputValue + “ is an even
number…”);
}//end if
INFO6066
Software and Information Systems Testing

Operator Precedence
• Q: What value does result get? int result = 14 – 10 / 2;
• A: 9 Were you expecting 2?
• The above expression contains three operators: =, -, /
• Q: How does Java decide which operation to perform 1st, 2nd, etc.?
• A: Operator precedence
Operator Precedence
• Similar to BEDMAS rule in arithmetic:
() Highest
– Brackets, Exponents, (Division, Multiplication),
(Addition, Subtraction) */%

• But, Java doesn’t have an operator for + - (add, sub)


= Lowest
exponents and Java does have other
operators not represented in BEDMAS
• Click below to learn more about operator precedence in Java:
– http://download.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

INFO6066
Software and Information Systems Testing

Equality Operator (==) Gotcha!

• REMEMBER: the ‘=‘ sign is the ASSIGNMENT operator in Java.


• If we want to test to see if two values are equal to each other then we use
the equality operator “==“
• if(amount1 == amount2)
System.out.print(“They’re equal”);
• For inequality tests, we use the !=
• if(amount1 != amount2)
System.out.print(“Values not equal”);
• What operation happens here?
if (myAge = DRINKING_AGE)
• This would be a syntax or compile error, because you are actually trying to
do an assignment operation inside an ‘if’ condition statement, and Java
cannot resolve this to a boolean value.

INFO6066
Software and Information Systems Testing

Unary Operators: (+ and -)


(positive and negative signs)

• + and - used to indicate positive or negative.


• Are called unary operators because they take only one operand (fancy
word for a value)
• By default, a numeric literal value is assumed to be positive, so you don’t
need to do this:
count = +15;
Just do this : count = 15;
• If you want to assign a negative value to a literal, then you do this:
count = -15;

INFO6066
Software and Information Systems Testing

Unary Operators:
Increment ++ and Decrement --

• ++ :the increment operator is used to add one to a variable


• -- :the decrement operator is used to subtract one from a
variable
• Commonly used to control loop counter variables

example: for(int count = 0; count <5; count++)

• The ++ increments the variable count by 1 after each iteration


of the loop.

INFO6066
Software and Information Systems Testing

Increment ++ and
Decrement – continued…

• These two operators can be used in two different ways; in


pre-increment (or prefix) mode or in post-increment (or postfix) mode. The
difference is subtle.
• Post-increment mode is the most commonly seen usage, and involves
placing the operator AFTER the variable. This means that the variable is not
incremented until after it has been used in the statement.
• Example: int number1 = 5;
int number2 = number1 ++;
• The value that gets assigned to variable number2 is 5, and AFTER this
assignment operation is done, Java then increments the value of number1
to 6.

INFO6066
Software and Information Systems Testing

Increment Operator…
Using pre-increment mode

• Same example from previous slide, but now we do the increment operation
in pre-increment mode.
• When using pre-increment mode, the increment operation is done first,
before the assignment operation is carried out.
• Example: int number1 = 5;
int number2 = ++number1 ;

Here the value of number1 is first incremented to 6, and then it is assigned


to the variable number2.
• So, the value assigned to number2 is 6, not 5, which is different to what
happened on the previous slide.

INFO6066
Software and Information Systems Testing

Increment Operator Example


public class IncrementExample
{
public static void main(String[] args)
{
int count1 = 15;
int count2 = 15;
int count3 = 15;
System.out.println("The value of count1 is " + count1);
System.out.println("The value of count2 is " + count2++);
System.out.println("The value of count2 is " + count2);
System.out.println("The value of count3 is " + ++count3);
int num1 = 15;
int num3 = num1++ + ++num1;
System.out.println(“value of num3 is “ + num3);
}
}
Q.What will the final value of count3 be when it is printed out?
A. Code it and find out! INFO6066
Software and Information Systems Testing

Relational Operators recap…


• Used when doing greater than or less than comparisons between data
values
• == means “is equal to”
• > greater than
• >= greater than or equal to
• < less than
• <= less than or equal to
• These operators are usually found in loops and conditional (branching)
statements like an “if” statement.
if (yourAge > 50)
{
System.out.println(“Yep! You’re old!”);
}

INFO6066
Software and Information Systems Testing

Shortcut Assignment Operators or op= Operators


• Consider this code: int number1 = 5;
number1= number1 + 5;
• Q. What value gets stored in variable number1? Answer: 10
• Consider this code: int number1 = 5;
number1 +=5;
• What value gets stored in variable number1? Answer: 10
• Result is exactly the same.

• The += is called a “shortcut assignment operator”.


• += adds the operand value on the right side to the variable on the
left side.
• It’s just a shorter way of coding “add this value to this variable”

INFO6066
Software and Information Systems Testing

Shortcut Assignment Operators


• Other shortcut assignment operators are:
-= *= /= %=
• Ex: int j = 5;
j *= 2; //same as j = j * 2…multiply j by 2 and assign it to j
• Value of j is now 10
• j -=2; //same as j = j - 2
• Value of j is now 8
• j /=2; // same as j = j / 2…divide j by 2 and assign it to j
• Value of j is now 4
• j %=3; //same as j = j%3 …do 4 mod 3 and assign it to j
• Value of j is now 1

INFO6066
Software and Information Systems Testing

Mixing Data Types in Expressions


• You can assign a value of a data type with a smaller capacity to a variable
of a data type with more capacity
Ex: short value1 = 123; // short is a 16 bit data type
int value2= value1; // This is okay…a short is 16 bits and will
//easily fit into the 32 bit space of an int
• Unless you use explicit (explicit means you have to tell Java to do it by
writing a line of code) “type casting” you can’t assign a value of more
capacity to a variable with less capacity.
Ex: double value3 = 3.25;
int value4 = value3;// This is NOT okay
//and will cause a compiler error, because Java does not
//want to stuff a 64 bit double value into a 32 bit int space.

INFO6066
Software and Information Systems Testing

Type Casting
• Converts a value of one data type into a value of another data type (T!)
• NOTE: it is the value stored in the variable that gets converted, and not the variable
itself.
• You can cast from larger capacity to smaller capacity data types, but you have to
tell Java explicitly to do this.
• Ex: double money = 20.35;
int change = (int) money; //put the data type you want to cast it to
//in brackets in front of the variable.
• Q. Now, if your are converting a double to an int, what value gets stored in variable
change?
• A. the value stored in change will be 20. The decimal portion will be truncated by
the casting operation.
• Casting a value to a lower capacity data type can result in a loss of precision (i.e.
truncated decimal portion), or it can result in an overflow error if you exceed the
maximum value of the lower capacity data type.

INFO6066
Software and Information Systems Testing
When is a Explicit Casting Required?
Cast from: double float long int short char byte
to double -
Decreasing Precision

to float (float) -

to long (long) (long) -

to int (int) (int) (int) -

to short (short) (short) (short) (short) - (short)

to char (char) (char) (char) (char) (char) -

to byte (byte) (byte) (byte) (byte) (byte) (byte) -

This diagram shows which type conversions require cast operators

INFO6066
Software and Information Systems Testing

Example of an Overflow error from casting


• Here is an example of an overflow type of error caused by type casting,
which occurs if a data type’s upper limit value is exceeded.

byte numOne = 0; // 8 bit type, largest value it can hold is 127

int numTwo = 128;


//now cast numTwo’s value to a byte and assign it to numOne
numOne = (byte) numTwo;
System.out.println(“Value of numOne is “ + numOne);
• Q. what value gets stored in numOne and printed out?
• A. a value of -128 is stored. This happens because 128 is too large for a
byte data type, so it “overflows” and “wraps around” to its other end. Try
coding this, and put in values of 129, 130, and 131.

INFO6066
Software and Information Systems Testing
Useful Application of Casting: truncating to two decimals.
• When doing currency calculations using doubles, such as calculating sales
tax amounts, our final answers often have an excessive number of decimal
places.
• Ex. double price holds a value of 99.95345322356.
• We want to have it hold just 99.95.
• Step 1) multiply it by 100 to get 9995.345322356
double tempPrice = price * 100;
• Step 2) now cast this to an int and store it in a temp variable…
int tempPrice2 = (int)tempPrice; //this cuts off the decimals
//and assigns 9995
• Step 3) divide the int tempPrice2 by 100.0 (Q. why use 100.0 and not just
100?) and assign it back to the variable price
price = tempPrice2 /100.0; //this stores 99.95 into price

INFO6066

You might also like