Chapter 3.
Primitives and References
2020-2021
COMP2396 Object-Oriented Programming and Java
Dr. T.W. Chim (E-mail: twchim@cs.hku.hk)
Department of Computer Science, The University of Hong Kong
1
Variable Declaration
— Javacaresabouttype(e.g.,itisillegaltoputafloating point number into an integer variable)
— Allvariablesmustbedeclaredbeforeuse
— Avariableisdeclaredbyspecifyingitstypeandname
type
name
int x;
— Thetypeofavariablespecifiesthekindofdatathatcan be stored in the variable
— Thenameofavariableisusedforreferringtothe variable
2
Naming a Variable
— Simple rules in naming variables
— Muststartwithaletter,anunderscore(_),oradollar
sign ($), but not with a number
— Therestofthecharactersmaybeletters,underscores,
dollar signs and numbers
— CannotbeareservedwordinJava
— Reserved words in Java
boolean protected
else class catch
byte abstract
do extends finally
char final
while implements try
double native
switch import throw
float static
case instanceof throws
int strictfp
default interface return
long short synchronized transient
for break new package void const
public private volatile if
continue assert super this goto enum
3
Standard Naming Conventions
— Longmeaningfulnamesmakethesourcecode more readable
— Follow standard naming conventions
— Aclassnamebeginswithacapitalletter(e.g.,Dog)
— Avariableormethodnamebeginswithalowercase letter (e.g., size, makeNoise())
— Thenameofasymbolicconstantconsistsofonly capital letters (e.g., PI, GRAVITY)
— Namesconsistingofmultiplewordsarejoined together with each subsequent word begins with a capital letter (e.g., ShoppingCart, addItemToCart())
4
Data Types
— Thedatatypeofavariabledetermines
— Thememoryspaceallocatedtothevariable
— Howthecomputerinterpretthedatastoredinthe variable
— InJava,datatypescanbeclassifiedinto
— Primitives –fundamental values including integers,
booleans and floating point numbers
— Objectreferences–referencestoobjects
5
Primitive Types
— Java supports 8 primitive types
Type
Bit Depth
Value Range
boolean
JVM-specific
true or false
char
16 bits
0 to 65535
byte
8 bits
−128 to 127
short
16 bits
−32768 to 32767
int
32 bits
−2147483648 to 2147483647
long
64 bits
−huge to huge
float
32 bits
varies
double
64 bits
varies
integer
floating point
6
Declarations and Assignments
— Examples
boolean isFun = true; char c = ‘ f ‘ ;
byte b = 89;
int x=234;
long big = 3456789; float f = 32.5f; double d = 3456.98; int y=x;
int z =3* y;
Java treats all numbers with a floating point as double. The ‘f’ here is used to specify that this number is a float
— Valuesthatcanbeassignedtoaprimitivevariable
— Literalvalueofacompatibletype
— Valueofanothervariableofacompatibletype
— Value(ofacompatibletype)returnedbyanexpression
7
Type Conversion
— Thecompilerdoesnotallowassigningavalueofadatatype with a wider range to a variable declared with a data type with a narrower range (as this might result in information loss)
— Hencethefollowingassignmentstatementsareillegal
int x = 24;
byte b = x; / / type mismatch float f = 32.5; / / type mismatch
— Typecastingtellsthecompileritisanintendedtype conversion and prevents the compiler from reporting an error
int x = 24;
byte b = (byte) x; float f = (float) 32.5;
type casting
8
Type Conversion
— Caremustbetakenwhencarryingouttypecasting as information may be lost
— Example
public class TypeCastingExample {
public static void main(String[] args) {
int x = 40000;
byte b = (byte) x; // type casting System.out.println(“b = ” + b);
} }
— Sampleoutput b = 64
x = 40000 = (1001110001000000) . 2
When x is cast into a byte, only the right most 8 bits are kept, i.e., (01000000)2 = 64. Hence, b is assigned a value of 64.
9
Object References
— Thereareonlyobjectreferencevariables(orsimply reference variables), but not object variables
— Aprimitivevariableholdsbitsthatrepresenttheactual value of the variable
— Areferencevariable
— Holdsbitsthatrepresentawaytoaccessaspecificobject
(i.e., an object reference)
— Doesnotholdtheobjectitself(objectsliveontheheap!)
— Anobjectreferenceissomethingsimilartoapointeror an address, and is used by JVM to get to the object (unlike pointers or addresses in C++, no arithmetic is allowed on object references)
10
Object References
— Areferencevariableislikea remote control
— Usingthedotoperatorona reference variable is like pressing a button on the remote control to access a method or instance variable of an object
— A reference variable has a value of null whenitisnotreferencingany object
Dog myDog = new Dog(); myDog.makeNoise();
11
Declaration, Creation and Assignment
132
— The 3 steps in object declaration, creation and assignment
1. Declare a reference variable
2. Create an object on the heap
3. Assign this object’s reference to the variable
Dog myDog = new Dog();
Dog
object
2
Create a Dog object on the heap
Declare a 1 reference
variable
3 Assign this object’s reference to the variable
Dog
12
— Example
Life and Death on the Heap
Book b = new Book(); Book c = new Book();
Book
object
Book
Book
Book
object
active references: 2 reachable objects: 2
13
— Example
Life and Death on the Heap
Book b = new Book(); Book c = new Book(); Book d = c;
Book
object
Book
Book
Book
object
active references: 3 reachable objects: 2
Book
14
— Example
Life and Death on the Heap
Book b = new Book(); Book c = new Book(); Book d = c;
c = null;
Book
object
Book
Book
Book
object
active references: 2 null references: 1 reachable objects: 2
Book
15
Life and Death on the Heap
— Example
Book b = new Book(); Book c = new Book();
Book d = c; c = null;
b = d;
This object becomes eligible for garbage collection
Book
object
Book
Book
object
active references: 2 null references: 1 reachable objects: 1 abandoned objects:1
Book
Book
16
Arrays
— Anarrayisacollectionofdataofthesametype — Like in C++
— Thesizeofanarraymustbedeterminedatthetime of creation, and cannot be changed afterwards
— Thearrayindexiszero-based
— Eacharrayelementcanbeaccessedusingitsindex
with the subscript operator [ ]
— InJava,arraysareobjectswhichhaveinstance variables and methods (e.g., each array object has an instance variable named length that stores its size)
17
Arrays
— Everyelementinanarrayisjustavariable,i.e.,avariable of 1 of the 8 primitive types or a reference variable
— Anythingthatcanbeputintoavariableofthattypecan be assigned to an array element of that type
— Examples
— Inanintarray(int[]),everyelementisanintvariablethat canholdanint value(anarrayobjectcanhaveelements which are primitives, but the array itself is never a primitive!)
— InaDogarray(Dog[]),everyelementisareferencevariable that can hold a reference to a Dog object (a reference variable holds a reference to an object, but not the object itself!)
18
— Example
An Array of Primitives
int[] nums;
nums = new int[4]; nums[0] = 6; nums[1] = 19; nums[2] = 44; nums[3] = 42;
int[]
0123
int int int int
19
— Example
int[] nums = {6, 19, 44, 42};
An Array of Primitives
A shortcut syntax for creating and initializing an array. The size of the array is determined by the number of initialization values
0123
int int int int
int[]
20
— Example
An Array of Objects
Dog[] pets;
pets = new Dog[4]; pets[0] = new Dog(); pets[1] = new Dog(); pets[2] = pets[0]; pets[3] = pets[1];
Dog
object
0123 Dog Dog Dog Dog
Dog
object
Dog[]
21
Example: An Array of Dogs
— Example
class Dog {
String name;
public void makeNoise() {
System.out.println(name + ” says Woof!”); }
}
public static void main(String[] args) {
Dog dog1 = new Dog(); dog1.makeNoise(); dog1.name = “Bart”;
Dog[] myDogs = new Dog[3]; myDogs[0] = new Dog(); myDogs[1] = new Dog(); myDogs[2] = dog1;
Dog
object
B
a
r
g object
D
o
t
Dog
object
Dog[]
22
012 Dog Dog Dog
Dog
Example: An Array of Dogs
— Example
myDogs[0].name = “Fred”;
myDogs[1].name = “Maggie”; System.out.print(“last dog’s name is “);
System.out.println(myDogs[2].name); for (int i = 0; i < myDogs.length; i++) {
myDogs[i].makeNoise(); }
} }
MaDgogie
object FDreogd
object
B
a
r
g object
D
o
t
Dog[]
23
012 Dog Dog Dog
Dog
Example: An Array of Dogs
— Sampleoutput
null says Woof!
last dog's name is Bart Fred says Woof! Maggie says Woof! Bart says Woof!
MaDgogie
object FDreogd
object
B
a
r
g object
D
o
t
Dog[]
24
012 Dog Dog Dog
Dog
Multidimensional Arrays
— Itispossibletocreateanarrayofarray(akamulti-dimensional array)
— Example
public class MultiDimArray {
public static void main(String[] args) {
String[][] names = {
{"Mr. ", "Mrs. ", "Ms. "}, {"Smith", "Jones"}
};
System.out.println(names[0][0] + names[1][0]); System.out.println(names[0][2] + names[1][1]);
} }
— Sampleoutput
Mr. Smith Ms. Jones
25
— Example
Multidimensional Arrays
public class MultiDimArray2 {
public static void main(String[] args) {
String[][] names = new String[2][3]; names[0][0] = "Mr. ";
names[0][1] = "Mrs. ";
names[0][2] = "Ms. ";
names[1][0] = "Smith"; names[1][1] = "Jones";
System.out.println(names[0][0] + names[1][0]);
System.out.println(names[0][2] + names[1][1]); }
}
Is names in MultiDimArray2 identical to names in MultiDimArray?
26
Multidimensional Arrays
— Example
public class MultiDimArray2 {
public static void main(String[] args) {
String[][] names = new String[2][3]; names[0][0] = "Mr. ";
names[0][1] = "Mrs. ";
names[0][2] = "Ms. ";
names[1][0] = "Smith"; names[1][1] = "Jones";
System.out.println(names[0][0] + names[1][0]);
System.out.println(names[0][2] + names[1][1]); }
}
Is names in MultiDimArray2 identical to names in MultiDimArray?
No! In MultiDimArray, names[0].length is 3 and names[1].length is 2. In MultiDimArray2, both
names[0].length and names[1].length are 3!
27
Multidimensional Arrays
— Example
public class MultiDimArray3 {
public static void main(String[] args) {
String[][] names = new String[2][];
String[] titles = {"Mr. ", "Mrs. ", "Ms. "};
String[] surnames = {"Smith", "Jones"}; names[0] = titles;
names[1] = surnames; System.out.println(names[0][0] + names[1][0]); System.out.println(names[0][2] + names[1][1]);
} }
Now in MultiDimArray3, names[0].length is 3 and names[1].length is 2
28
Chapter 3.
End
2020-2021
COMP2396 Object-Oriented Programming and Java
Dr. T.W. Chim (E-mail: twchim@cs.hku.hk)
Department of Computer Science, The University of Hong Kong
29