Fachbereich Informatik und Elektrotechnik Java Programming in Java Introduction to Arrays Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Java Objects Class-Definition: Template (blueprint, prototype) of an object. Methods Variable Declarations Object-Definition: Software unit of variables (data) and related methods. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Java – The Array Concept Array: Array object (object oriented) Collection of items, group of memory locations Properties of Arrays: Definite sequence (linear or multidimensional) Fixed length, established when the array is created The individual items are called elements The elements are selected by a number called an index, in Java, the index is of type "int" starting from zero Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Java – The Array Concept position number index (int) 0 1 2 3 4 5 6 7 8 9 ArrayName 47 11 05 14 14 36 04 03 02 01 Name of Array Array Element Programming in Java, Helmut Dispert ArrayName[0] ArrayName[1] ArrayName[2] ArrayName[3] ... = = = = 47 11 05 14 Fachbereich Informatik und Elektrotechnik Java – The Array Concept Specifying an element: a[4] a 0 1 2 3 4 5 6 Array length: n elements from ... n-1 0 to n-1 In Java arrays are semidynamic: the size (length) will be defined at run-time, but it cannot be changed anymore. Programming in Java, Helmut Dispert index Fachbereich Informatik und Elektrotechnik Java – How to create an array 1. Declaration 2. Creation, Initialisation Similar to normal variables Declaration: double [ ] salary; Student [ ] friends; preferred form Square brackets indicate array. Optional form of declaration (for compatibility with C/C++): double salary[ ]; Student friends[ ]; Programming in Java, Helmut Dispert less preferred form Fachbereich Informatik und Elektrotechnik Java – How to create an array Creation, Initialisation: Creation must specify the length salary = new double[3]; friends = new Student[7]; array constructor Declaration and Initialisation can be combined in one statement: double [ ] salary = new double[3]; Student [ ] friends = new Student[7]; Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Java – How to create an array new operator: used to create an instance of an array object in memory (reserving the required number of memory locations – allocation of memory). The attempt to assign values to array elements or to access them before memory has been allocated the compiler will issue an error message like: Variable salary may not have been initialized. Arrays are objects. Immediately after creation the array contains zeroes or nulls. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Java – Primitive Arrays Primitive Java arrays contain zeroes after creation: 0.0 0.0 0.0 salary 0 1 2 Abbreviated diagram: salary 0.0 0.0 0.0 0 Programming in Java, Helmut Dispert 1 2 Fachbereich Informatik und Elektrotechnik Java – Primitive Arrays Array elements can be used in all contexts appropriate for the type: - e.g.: salary[1] = 56000.0; System.out.println(salary[1] + salary[2]); The array index can be a variable: - e.g.: int i = 0; x = (salary[i] + salary[i+1])/2; Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Java – Arrays of Objects Immediately after creation the array contains null references – no element objects exist: friends null null null null null null null 0 1 2 3 4 5 6 4 5 6 Element objects must be created: - e.g.: friends[4] = new Student(); friends 0 Programming in Java, Helmut Dispert 1 2 3 Fachbereich Informatik und Elektrotechnik Java – Arrays of Objects Some element can remain null (code may have to check this) friends null null 0 1 2 3 null null 4 5 6 Elements can be used like single objects - e.g.: friends[4].readMarks(); System.out.println(friends[i].getName() + "lives beside" + friends[i+1].getName()); Remember: friends[0] is the "first" element, friends[1] the "second" Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Java – Arrays Bounds Arrays "know" their length, and can be queried - Use the public attribute length - e.g.: n = friends.length; Arrays protect against illegal accesses "off the ends" or "out of bounds" - i.e. attempts to use an index value outside the range 0 to (length – 1) - e.g. friends[7].readMarks(); is illegal - unless code is written to handle this, the program crashes with an ArrayIndexOutOfBoundsException Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Java – Arrays and for-Loops For-loops are ideal for use with arrays. Examples: int count; double[ ] stairs; count = Keyboard.readInt("how many stairs do you want?"); stairs = new double[count]; // initialise: for (int i=0; i<count; i++) { stairs[i] = (i + 1)*0.19; // metres above ground } count 4 stairs 0.19 0.38 0.57 0.76 0 Programming in Java, Helmut Dispert 1 2 3 Fachbereich Informatik und Elektrotechnik Java – Arrays and for-Loops Examples (continued): n must be ≥ 0 // creation friends = new Student[n] for (int i=0; i<n; i++) { friends[i] = new Student(); } // sending the same message to each student: for (int j=0; j<n; j++) { friends[j].readMarks(); } Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Arrays – Common Programming Errors Animal[ ] a; for (int i=0; i<5; i++) { a[i].makeNoise(); } // raises NullPointerException Animal[ ] a = new Animal[5]; // legal for (int i=0; i<=5; i++) { a[i] = new Animal(); // raises // ArrayIndexOutOfBoundsException } Animal[ ] a = new Animal[5]; // legal a.makeNoise(); // compile time error Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Arrays – Common Programming Errors Look carefully! Animal[ ] a = new Animal[5]; //legal for (int i=0; i<5; i++); { a[i].makeNoise(); } Programming in Java, Helmut Dispert // compile or run-time error // depending on visibility and // value of another i Fachbereich Informatik und Elektrotechnik Arrays – Common Programming Errors Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Arrays – Common Programming Errors public class Frequencies { public static void main(String[] args) { final int n=6000, faces=6; // constants int[] count = new int[faces]; int toss; double randomValue; // simulate n tosses of the die for (int j=0; j < n; j++) { randomValue = Math.random(); // 0.0 <= r < 1.0 toss = (int)(randomValue * faces); // 0 to 5 count[toss]++; } e.g. 0.51 (int) (3.06) Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Arrays – Common Programming Errors System.out.println("face\tcount"); for (int j=0; j<faces; j++) { System.out.println((j+1) + "\t" + count[j]); } } } C:\JavaLecCode>javac Frequencies.java Java Programming in Java, Helmut Dispert C:\JavaLecCode>java Frequencies face count 1 990 2 1002 3 1041 4 960 5 1005 6 1002 Fachbereich Informatik und Elektrotechnik Java – Multidimensional Arrays The arrays introduced so far were limited to one dimension only. Multidimensional arrays can be implemented as arrays of arrays. Example: Array of two dimensions public class MultArray { public static void main(String[] args) { int[][] a = new int[2][3]; a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] = = = = = = 1; 2; 3; 4; 5; 6; c:\JavaLecCode>javac MultArray.java c:\JavaLecCode>java MultArray 123 456 System.out.println(""+a[0][0]+a[0][1]+a[0][2]); System.out.println(""+a[1][0]+a[1][1]+a[1][2]); } } Programming in Java, Helmut Dispert Java Fachbereich Informatik und Elektrotechnik Java – Initialising Arrays int steps[] = {91,92,93,94}; int matrix[][] = { {0,1,0,1}, {1,0,1,0}, {0,1,0,1}, {1,0,1,0}, }; Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Java – Dynamic Arrays The Java language has a dynamic memory allocation model, therefore arrays can be dimensioned at run time (in contrast to languages such as C). But, once an array is dimensioned it cannot be modified (e.g. extended). Help: Java supports several collection types that allow the definition of structures that can hold a series of objects, even if the exact number of objects is not known yet. e.g. Vectors (linear list) ArrayLists (in Java 2) Disadvantage: The information is not stored sequentially in memory, so their use is less efficient as with an array. See: JDK 1.2 Collections-Framework java.util Programming in Java, Helmut Dispert Javadoc Fachbereich Informatik und Elektrotechnik Arrays – Key Terms • • • • • • • array array bounds base type double element index length attribute Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Strings • Every string we create is actually an object of type String. Even string constants are actually String objects. • Objects of type String are immutable; once a String object is created, ist contents cannot be altered: • If we need to change a string, we can always create a new one that contains the modification • Java defines a class called StringBuffer, which allows strings to be altered. • String class contains several methods. Some of them are: We can test two strings for equality by using equals(): (String object) We can obtain the length of a string by calling the length() method: int length() We can obtain the character at a specified index within a string by calling charAt(): char charAt(int index) Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Strings The String Class A string is an object of type String (this also includes string constants). Once created, Strings cannot be altered anymore. String 0 1 2 3 4 5 6 ... n-1 Elements of type char (UNICODE) Strings that can be altered: use StringBuffer Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Strings Methods of class String: Method Function boolean equals (String object) Test strings for equality int length() Return length of string char charAt (int index) Return character at specified index position substring(int begin, int end) Return specified substrings result substring begin Programming in Java, Helmut Dispert end Fachbereich Informatik und Elektrotechnik Method String.equals() class EquTest { public static void main(String args[]) { String str1, str2; str1 = "FH Kiel, FB Elektrotechnik"; str2 = str1; Java System.out.println("String: " + str1); System.out.println("String: " + str2); System.out.println("Same Object? " + (str1 == str2)); str2 = new String(str1); System.out.println("String: " + str1); System.out.println("String: " + str2); System.out.println("Same Object? " + (str1 == str2)); System.out.println("Same value? " + str1.equals(str2)); } } Programming in Java, Helmut Dispert continued Fachbereich Informatik und Elektrotechnik Method String.equals() Output: String: FH Kiel, FB Elektrotechnik String: FH Kiel, FB Elektrotechnik Same Object? true String: FH Kiel, FB Elektrotechnik String: FH Kiel, FB Elektrotechnik Same Object? false Same value? true Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Input / Output Command Line Input: main (String args[]) {...} Array of Strings Command args[0] args[1] … args[n-2] args[n-1] Argument 1 Argument 2 Argument n-1 Argument n String Arguments Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Input / Output Array of Strings (has to be converted): Integer.parseInt (args[...]); Standard Output: System.out.print(...); System.out.println(...); // no <CR>,<LF> // with <CR>,<LF> Obs.: Output with “print” will be buffered; at least one “println” is necessary to terminate a sequence of output operations. Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Command Line Input class helloCLI /** HelloWorld with Command Line Input */ { public static void main(String args[]) { int i; System.out.print("Hello "); for (i=0; i < args.length; i = i+1) { System.out.print(args[i]); System.out.print(" "); } System.out.println(); // new line } } Programming in Java, Helmut Dispert Fachbereich Informatik und Elektrotechnik Numerical Command Line Input class helloCLIn /** HelloWorld with numerical Command Line Input { public static void main(String args[]) { int i, sum=0; System.out.print("Hello "); for (i=0; i < args.length; i = i+1) { sum += Integer.parseInt(args[i]); } System.out.println("Result: " +sum); } } Programming in Java, Helmut Dispert */