CSIT111 Lecture 4
CSIT111 Lecture 4
1
The concept of data types
• The main objective of a program is to manipulate various
data: whole numbers, real numbers, characters, words,…
numberOfEmployees = 5 … 20 … 300 – can be only a whole number
temperature = -12.5 … 0.0 … 36.6 … 95.4 – can be a real number
grade = ‘F’ … ‘P’ … ‘C’ … ‘D’ – can only be a character
doorIsLocked = yes … no – can only be “yes” or “no”
city = Canberra … London … New York – can be a word, or two words
- Numbers can be added, multiplied, or subtracted, but how can these
operations be extended to characters and words?
- Algebra defines simple rules how numbers can be compared, but
how to compare words or sentences?
- How to define and store complex data such as contact details,
timetable, weather, …?
- How can this diversity of values be efficiently stored in
memory and correctly processed?
2
The concept of data types
3
Fundamental data types
very small whole Min value = -128
byte 8 bits Max value = 127
numbers
16 bits whole numbers Min value = -32768
short
Max value = 32767
Min value = -2147483648
int 32 bits big whole numbers Max value = 2147483647
https://www.youtube.com/watch?v=kYUrqdUyEpI
5
Default data types
• Although Java has four data types (byte, short, int, long)
to represent integer numbers there is no any performance
advantage in using byte, or short
• All arithmetic operations are carried out by JVM with int
precision. The default type for integers should be int
• byte, or short are mostly useful when you need to save
memory, or in some special cases (to be discussed later)
• There is no any performance advantage in using float
instead of double. Math methods work with double type
• Java compiler uses double as a default type to represent
real numbers. Use double by default for real numbers
double x = 7.35; // OK because 7.35 is double by default
float y = 7.35; // compilation error: loss of precision
float y = 7.35F; // OK, 7.35 is explicitly set to float
6
Data types of literals
• When you declare a variable you specify its data type. The
specified data type reflects all properties of the variable.
• When you use a literal in your program, how can the
compiler guess what its data type is
23 – is it int or long?
12.75 – is it float or double?
• To avoid confusion, you should attach suffixes to literals
float y = 4.37F; // F indicates float data type
long a = 37654L; // L indicates long data type
• In some cases you may need to attach prefixes to literals
int x = 101; // 101 is a decimal value
int y = 0b101; // 0b is a prefix for binary values
// 0b101 is equal to 5 in decimal
7
Arithmetic operators
• Although basic arithmetic operators are defined using the
same set of symbols ( + - * / ) their operation is a bit
different for integer and floating-point types
Example:
int a = 7, b= 2, c;
c = a / b; // this is integer division: c = 3
float x = 7.0F, y= 2.0F, z;
z = x / y; // this is floating point division: z = 3.5
A 65 0000000001000001
12
Mixed type expressions
What is the data type of the rvalue produced by an
expression if it contains operands of different data types?
Example: 2 * 12.25 - how is it processed by JVM ?
13
Data type conversion
• Operands of different types must be converted to a
common data type before they can be processed by JVM
- Widening : conversion to a data type with higher precision
- Narrowing: conversion to a data type with lower precision
• Java compiler does widening conversion automatically
wage = 2 * 14.8; /* 2 is auto converted to 2.0 */
14
Conversion between numeric types
char No precision loss Widening conversion
Precision or range loss Narrowing conversion
float double
• You can use explicit type cast where loss of precision is acceptable
float measuredSpeed = 60.75F; // narrow 60.75 to a float
int carSpeed = (int)measuredSpeed; // carSpeed = 60
char ch = (char)n1; // ch = 'A' (65 is Unicode of A)
char ct = (char)n2; // ? (-65 is not a Unicode)
15
Expressions with auto conversion
int a = 1, b = 2;
short sa = 1, sb = 2;
long la = 1L, lb = 2L;
float fa = 1.0F, fb = 2.0F;
double da = 1.0, db = 2.0;
16
Expressions with auto conversion
• Sometimes even simple arithmetic operations may be confusing
Example:
byte a = 5, b;
b = a + 1; <- ???
It should work, but this statement results in a compilation error
error: possible loss of precision Why?
18
Overflow and precision limits
• Eight fundamental Java data types allows the programmers to
process efficiently a wide spectrum of data. However…
1. Even careful selection of data types for your program doesn't
guarantee that the result will always be right
Example:
double result = 10.0/3.0; // 3.33333333…
Even the most accurate data type may not have precision sufficient for
some numbers
2. JVM doesn't check if integer values go over the range
Example:
byte x = 129; // compilation error
// javac checks the range when possible
int y1 = 129, y2 = -127;
byte z = (byte)y2; // No error, but z = -127
z = (byte)( y2 – 2); // No error, but z = 127
19
Overflow
• Arithmetic expressions may produce incorrect
values when data bits propagate into the sign bit
Example:
byte result, num1 = 65, num2=67;
result = (byte)(num1 + num2);
print( result ); // is it 132 ?
0 1 0 0 0 0 0 1
No errors
+ 0 1 0 0 0 0 1 1 reported
1 1
A carry bit =1
turns the result 1 0 0 0 0 1 0 0 -> -124
into negative
20
Arithmetic operators
• Besides + - * /, Java has 40 other built-in operators
• Remainder %
Example: You have 43 tires in stock. A client usually needs a set of
4 new tires. How many tires will be left presuming that all
clients order 4 tires?
int tiersLeft = inStock % 4; // the remainder is 3
Remainder is a leftover after integer division
• Remainder is defined for floating numbers too
Example: You have 21.5 kilograms of baking flour. Each day you use
1.7 kilograms of flour. How many times does 1.7 go into
21.5 and how much will be left over?
double leftOver = 21.5 % 1.7; // the remainder is 1.1
21
Arithmetic operators
Operations x = x + 1 and x = x – 1 are used so
frequently that Java defines special operators for them
• Increment operator ++ (increase by 1)
• Pre-increment Example: ++counter
increment happens before the value to be used
• Post-increment Example: counter++
increment happens after the value is used
23
Compound assignment operator
assignment compound assignment
sum = sum + number; sum += number;
product = product * number; product *= number;
Syntax:
variable op= expression;
Meaning:
variable = variable op expression
Examples:
count += 2; // count = count + 2;
sum += 2+3; // sum = sum + (2+3)
stock -= quantity; // stock = stock – quantity
power *= 2.71; // power = power * 2.71
div /= power+20.0; // div = div/(power+20.0)
rem %= d; // rem = rem % d
24
Evaluation of complex expressions
Calculate the value of the following expression
-2 * -3/(4%5 + 6) + 4
25
Arithmetic operator precedence
Operators Associativity
function calls , (operations in brackets) left to right
pre++, pre--, unary -, (type_cast) right to left
*, /, % left to right
+ , - left to right
= , += , -= , *= , /= , %= right to left
Examples:
result = (15-6) * (3+11);
result = (float)++day * 2.5;
result *= 15 – day + 5;
result += b = c;
26
Example: precedence
a = 9 + 8 / 4 * 2 – 1 Division first as it's on the left
9 + 2 * 2 - 1
13 - 1
a = 12
27
Quiz
Which expressions are not implemented correctly?
ab
a * b / ( a + b )
a+b
b
a+ 2 a + b / c * c X
c
a
+c
b a/b + c/( a – b/c ) X
b
a−
c
c = p(1 + r ) y c = p * pow( (1+r), y )
28
Bitwise operators
29
enum data type
• Some programs require variables which can take only a limited
number of predefined values. Can int type provide a solution?
Example:
int today = 1; // SUNDAY
today = 7; // SATURDAY
today = 10; // ? (out of the expected range)
today = -1; // ? (out of the expected range)
• You can define a new data type that has a few possible values
class Example Day is a new data type
{
public enum Day {MONDAY, TUESDAY, WEDNESDAY, FRIDAY}
public static void main(String[] args) {
Day lectureDay; // a variable of type Day
lectureDay = Day.MONDAY; // OK
lectureDay = Day.SUNDAY; // error
lectureDay = Day.FRIDAY; // OK
System.out.print(lectureDay); // output: FRIDAY
}
30
}
Class as a user defined data type
• A variable of a basic data type can describe only one property
double weight; // describes weight
double price; // describes price
Paint colour; // describes colour of the paint
int numOfDoors; // describes the number of doors
Is any data type that could combine several related properties into a
collection
• Class can be considered as a programmer-defined data type that can
contain a collection of properties (fields) and behaviours (methods)
class Car {
private double weight; // describes weight
private double price; // describes price
private Paint colour; // describes the paint colour
private int numOfDoors; // describes the number of doors
}
• You can declare variables of defined class types
Car bmwI8; // a variable of the type Car
31
Reference variables
• Although declarations of basic type variables and variables of type class
may look similar
int numberOrdered; // a variable of type int
Car bmwI8; // a variable of the type Car
there is a fundamental difference between them
• Classes are complex data types. As a result memory allocation for them
is a two stage process:
1. A variable must be declared Program memory
Car bmwI8; A link to
the object
bmwI8
2. An object must be created explicitly
bmwI8 = new Car(); An object of
type Car
contains all
bmwI8 is not an object of class Car. It fields and
is a reference variable ( linked to the methods
object that must be created using the new )
32
Creating objects
• Software objects – created from a class
– State – stored in fields
– Related behaviour – implemented through methods
33
Using objects
• Once an object has been created,
Circle gasket = new Circle( 2.5 );
it can be used
1. You can access its public fields directly
gasket.radius = 14.0;
Reference variable Field name
(object name)
The member access operator
2. You can access its private fields only through public methods
pm = gasket.getPerimeter();
Reference variable
Public method name
(object name)
The member access operator
34
Reference variables
• There is a substantial difference between basic type and reference type
variables:
int a = 1, b = 5;
Variables a and b always
a = b; // a and b are equal to 5
have different locations in memory
b = 4; // b is 4, a is 5
=
• When you assign a reference variable to
another one, only the link is copied
car2 Object2 of
•Object2 is referenced by both variables
type Car
•Object1 is lost in memory
35
Garbage collection
Can ghost objects resulted from wrong operations with reference variables
fill all memory space?
• JVM uses a technique called Garbage Collection to
automatically detect and delete those objects which are no
longer in use
You need to understand how to use Program memory
reference variables properly to avoid
generation of ghost objects:
car1 Object1 of
-Generation of 'ghost' objects indicates
type Car
that you may have bugs in your code and
=
your application may not work correctly
- Automatic garbage collection consumes
additional JVM resources car2 Object2 of
- It can start at any time and slow down type Car
(even pause) your program
36
Strings
• Many applications need to process textual information
- text editors
- word processors
- messaging tools
- command windows
• Character-by-character text processing that uses char data
type is not practical
• In computer science, a sequence of characters is called a
string
• Java provides the String class to create and manipulate
strings. It is defined in java.lang package.
// 1. Create a reference variable of type String
String str1;
// 2. Create an object of type String linked to the variable
str1 = new String("A string is a sequence of characters");
37
Strings
38
Strings
Quiz
What is actually produced and sent to the monitor when you
use print() method?
System.out.print("The distance is: " + distA + " km");
39
Strings
P a u l
40
Characters
• There are no methods defined in Scanner to read individual
characters from the user input
• To read a character, you can:
1. use next() method to read a word, or nextLine()
Scanner keyboard = new Scanner(System.in);
String inWord = keyboard.next(); // read a word
2. Obtain the first character of the word
char letter = inWord.charAt(0); // get first char
Note: Everything what you type before pressing Enter goes into the
keyboard buffer first. Having read next word, the method next()
removes it from the buffer. If you entered two words separated by
whitespace and call next() method only once, the second word will
remain in the keyboard buffer. It's safer to use nextLine() that will
remove everything until cr from the buffer after reading.
41
Strings
45