2 Data TypesAn important concept in most programming languages is that of data typesEach variable or attribute that is declared needs an associated typeA type identifies a certain set or collection of values that a variable can store
3 Type ExamplesFor instance if we want to store counting numbers we could declare a variable of type intWe do this because the int (or integer) data type can store any whole number from -2,147,483,648 to 2,147,483,647Another example is if we wanted to represent whether someone is married or not we could declare a variable of type booleanWe choose boolean because we can store two values with a boolean (true or false) which is all we need in this particular case
4 Java numeric data types Java has the following data types:byte to 127short to 32767int -2,147,483,648 to 2,147,483,647long -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807float 1.4 x to 3.4 x 1038double 4.9 x to 1.7 x 10308char any unicode character
5 StringsThe type String in Java is not really one of the basic data typesThe type String is actually a class in JavaThis class has the necessary attributes and methods to manipulate a String object e.g. substring(), length(), charAt()The designers of Java made an exception in the case of Strings – you don’t have to declare a new string object as you would with other objects.String myStr = “Hello World”; // this is fineString myStr = new String(); // this is also fine
6 Dynamic Variable Declaration Programming languages that support dynamic variable declaration can have variable declarations anywhere in the programJava supports this type of variable declarationYou can have the line int num1; anywhere in your program so long as it is in scope when it is neededIn other words the only restriction for declaration is that the variable is visible when it is needed
7 Static Variable Declaration Believe it or not some languages don’t use dynamic declaration like Java doesInstead all variables need to be declared in a predefined section of the code.This section is usually above all other code and all variables need to be declared in that section
8 The need for multi-valued variables Sometimes we need to store a collection of data of the same typeOften having a separate variable for each value is cumbersomeFor instance if we wanted to store the temperature for everyday in June we don’t want to declare 30 separate variables (temp1, temp2… temp30)The ideal situation would be to have one variable that could store 30 values such that we can choose which value we want to retrieve or store/changeLuckily most programming languages provide us with this feature.
9 Arrays 1 An array is one variable The array can store as many data items as the programmer choosesEach data item must be of the same type (homogenous)Every data item is stored separately in the arrayWe can specify the location of the data item we want to change or look at
10 Arrays 2We can represent an array called fiveInt of 5 integers as follows:The data in position 2 is the number 6 and the data in position number 4 is 72Notice how the numbering of the positions starts at 0 and ends at 4So even though the array has 5 data items there is no position 5 in the array2334656721234position
11 Arrays 3We can represent an array called myStrings of 4 Strings as follows:The data in position 0 is the word “dog” and the data in position number 3 is “frog”Position 2 has a null value. Note that this is not the word “null” but a way of indicating that the 2nd position in the array is empty“dog”“cat”null“frog”123position
12 Arrays in Java 1Arrays are declared in a similar way to normal integers: int myArray = new int;An array of int’sallocates memoryholds 4 itemscalled myArray
13 The int’s to place in each position Arrays in Java 2The array from the following slide can be filled with values as follows: myArray = 34; myArray = 23;myArray = 87; myArray = 33;The int’s to place in each positionPosition in the arrayto place the data
14 Arrays in Java 3 We can use the values in the arrays as follows: myArray = myArray + 34 * 69; adds the data in position 2 to 34 * 69 and stores the result in position 0 System.out.println(myArray);prints out the value of the integer in position 0 of the array (that is 2433)
15 Arrays in Java 4Why would the following lines of code not work with the previously declared array? myArray = 78; myArray = “bob”; myArray = 45; Can you correct the lines?
16 Static StructuresArrays are static data structures because their size is determined when the code is being writtenThe size of the array cannot be changed during the execution of the programIf we declare an array of 12 integers then once the program starts running we cannot store any more than 12 integers in the arrayOnce memory has been allocated for the array it is fixed during execution of the programStatic data structures are like hose-pipes. If you get a bigger garden then too bad. Buy a new hose-pipe!Static means motionless or inactive
17 Dynamic Data Structures These data structures can change size during execution of a programDynamic data structures grow and shrink as required by the programThe size of the structure is determined during run-timeDynamic data structures are like Kreepy-Krauly pipes. Getting a bigger pool? Just add more pipes :)Dynamic means active or changing
18 ExampleIf we wanted to write a school database and we wanted to declare a structure to store Student objects what size would we make it?Option 1 – 1300? This is fine but what if we get more students next year?Option 2 – 5000? This is way too big. We might never get that many studentsOption 3 – Dynamic Data Structure. Perfect this would grow and shrink depending on the amount of data items needed
19 The story so far… We’ve looked at the basic data types in Java int, float, double, byte, longcharStringArrays of all of the aboveWe’ve looked at the sizes of data structuresStatic and DynamicIn the next episode of Data StructuresAdvanced Data Types (ADT’s)
20 Advanced Data Types (ADT’s) ADT’s provide us with extra functionality in programming languages.Some ADT’s come standard with Java and others need to be implemented by the programmer. Either way they are fairly complex to code.The ADT’s that we will examine are the most widely used ADT’s in programming.
21 Lists Lists are everyday occurences. Telephone directoriesShopping listsTo Do listsClass listsDefinition: A list is a sequence of items of the same typeOrdered lists have their items in a predefined order. i.e. Alphabetically or numericallyThe size of a list is how many items it contains at any given time
22 Linked Lists Linked Lists are a dynamic data structure Each item in a linked list is referred to as a node.Each node consists of two parts:Data (Item) Field – This is the actually data stored in that position of the list (e.g. “dog”, 23)Next Field – Contains a pointer to the next node in the list
24 Design of a Linked ListEach node is connected to the next node via the next field of each node.The first node is indicated by a head node which contains no data field but only a next field.The last node’s next field always points to null.head45678999null
25 Operations on a Linked List Create an empty listCheck if list is emptyGet number of items in the listCopy one list to another listTraverse the listRetrieve an item, given it’s positionSearch for an itemInsert an itemDelete an item
26 AddingWe need to be careful when adding items to a linked list because if we lose a next field of any of the nodes we lose all nodes after that node.5 Steps:Create the new node with a pointer to it.Find the position where the node is to be inserted (call it position x).Create a temporary pointer to the node after the position (i.e. the node in position x + 1).Make the next field of node (x-1) point to the new item.Make the new items next field point to temporary pointer.
35 StacksStacks are data structures that allow data items to be added and removed at the top only.For this reason stacks are called LIFO (Last In First Out) structures because the last item to be added to the stack is the first item to be removed.Just like a stack of plates at a restaurant.Inserting an item at the top of a stack is referred to as pushing.Removing an item off the top is referred to as popping.
36 ExampleConsider the following operations: push “R”; push “T”; push “Y”; pop; push “J”; pop; pop;RTRYTRTRJTRTRROutput: Y J T
37 Stack Operations Empty the stack Check if the stack is empty Determine size of the stackLook at the top itemPushPop
39 QueuesQueues are structures that allow data items to inserted at the rear and removed from the front only.Known as FIFO (First In First Out) structures because the first item to be inserted into the queue will be the first item to be removed.These queues are no different from the queues in everyday life (e.g. shopping centers)
40 ExampleConsider the following operations insert “A” insert “B” insert “C” remove an element remove an elementAA BOutput: A BA B CB CC
41 Uses Print Queues Real-life Simulation Statistics: Average number of element in queueAverage time spent in queueProbability that queue will be longer than xProbability that waiting time will be greater than xMinimum and maximum length of a queue of a period of timeMinimum and maximum waiting time over a period of time
42 Implementation: Stacks and Queues Option 1: Using arraysProgrammer has to keep track of where the front (top) and rear of the structure is.Only homogenous items can be storedFIXED SIZE! Queues and stacks grow and shrink during executionOption 2: Using a dynamic structureLinked list!
43 Trees In a tree each node may have one or more next field. This results in a tree-like structure.NFQEGT
44 Naming Conventions Root Node – The first node Child Node – Node beneath another node (each node has only one parent)Parent Node – A node with nodes beneath itLeaf Node – Nodes with no childrenSiblings – Adjacent nodes
45 Naming Conventions N Root node and parent of F and Q F Q Sibling of Q Child node of N and Parent of TEGTLeaf node
46 Binary TreesBinary trees are trees in which each node may have at most two sub trees. These are called left and right sub trees.Each node has three elements:Data (Item Field)Left PointerRight PointerThe left children of a parent always have smaller values than their parents.The right children of a parent always have larger values that their parents.
47 Example Insert the following into a binary tree: 50, 34, 12, 78, 36, 30, 67, 44, 52N, A, Y, T, F, D, S, R, R
48 Binary Tree Traversal Pre-Order In-Order Post-Order Visit the root Traverse the left sub-tree in pre-orderTraverse the right sub-tree in pre-orderIn-OrderTraverse the left sub-tree in in-orderTraverse the right sub-tree in in-orderPost-OrderTraverse the left sub-tree in post-orderTraverse the right sub-tree in post-order
49 ExamplesTraverse both previous trees in in-order, pre-order and post-order.What do you notice about in-order traversals?