Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays, Casting & User Defined Variables

Similar presentations


Presentation on theme: "Arrays, Casting & User Defined Variables"— Presentation transcript:

1 Arrays, Casting & User Defined Variables
G6DICP - Lecture 10 Arrays, Casting & User Defined Variables

2 Data Structures Data is stored in variables
Closely related data items may conveniently be stored in a “data structure” Data structures are complex variables that contain more than one item of data “Metavariables” - variables containing variables Arrays are a common form of data structure

3 Arrays Arrays are a data structure that contains a group of data items (elements) All elements must be of a single type Elements are indexed by an integer Arrays are of a pre-determined size For example: An array of 3 integers called data data[0]=3; data[1]=24; data[2]=12; An array of 3 Strings called day: day[0]=“Monday”; day[1]=“Tuesday”; day[2]=“Wednesday”

4 Java Arrays Arrays are a variables type, and so must be declared
int[] data; or int data[]; Before they can be used, arrays must be initialized This determines their size The new reserved word allocates memory to a data structure, fixing the size and type of an array data = new int[3]; Once initialized elements of the array may be addressed by index (counting from 0) data[0] data[1] data[2]

5 Casting A simple form of data type conversion
For example if you need to use the double 5.0 as an int then it must be converted to an int Syntax: double d=5; int I = (int) d; Many types can be cast into many other types Only if this makes sense! Information may be lost in the casting process

6 User defined data types
Composite data structures A data type containing several different data types Analagous to a record of a flat field database Record in Pascal Struct in C Class in Java

7 A simple Class declaration
class Person { String name; String ; String room; int phone; }

8 Using a user defined class
Person tim; tim = new Person(); tim.name = “Tim Brailsford”; tim. = tim.room = “C5”; tim.phone = 14231;


Download ppt "Arrays, Casting & User Defined Variables"

Similar presentations


Ads by Google