CSC110 2.0 Object Oriented Programming Ms. Gnanakanthi Makalanda Dept. of Computer Science University of Sri Jayewardenepura More non-primitive types Lesson 06 1 2 Outline 1. Two-dimensional arrays 2. The String class 3. Enumeration 4. Summary Two-dimensional arrays Arrays with two dimensions are often used to represent tables of values consisting of information arranged in rows and columns. Two-dimensional arrays We must use two indexes to refer to a value in a two-dimensional array, one specifying the row and another the column. In Java, you can create n-dimensional arrays for any integer n. 3 4 Declaring A multidimensional array with the same number of columns in every row can be created with an arraycreation expression or type [][] arrayname; type arrayname [][]; // This style is Example: int [][] grades; // correct, but not preferred Creating Create a 2D array with numrows and numcols arrayname = new type[numrows][numcols]; Example: grades = new int[3][2]; Shortcut to declare and create a 2D array: int [][]grades = new int[3][2]; 5 6 1
Initialization Elements (1/2) Can be initialized with array initializers in declarations. int b[][] = {{1, 2}, {3, 4}, {5, 6}}; Each element in the 2D array must be the same type, either a primitive type or object type. Subscripted variables can be used just like a variable: grade[0][3] = 70; 7 8 Elements (2/2) Array indices must be of type int and can be a literal, variable, or expression. grade[3][j] = 56; If an array element does not exists, the Java runtime system will give you an ArrayIndexOutOfBoundsException Arrays of One-Dimensional Arrays Java does not actually have two-dimensional arrays. In a true 2D array, all the elements of the array occupy a continuous block of memory, but that's not true in Java. Two-dimensional arrays are maintained as arrays of separate one-dimensional arrays. Array in preceding declaration is composed of three separate one-dimensional arrays {1, 2 }, {3, 4} and {5, 6} 9 10 Ragged arrays (1/2) The lengths of the rows are not required to be the same. Creating: // create 2 rows int b[][] = new int[2][]; // create 5 columns for row 0 int b[0] = new int[5]; // create 3 columns for row 1 int b[1] = new int[3]; Ragged arrays (2/2) Initializing: int b[][]= {{1, 2}, {3, 4, 5}}; The int array for row 0 is a one-dimensional array with two elements. The int array for row 1 is a one-dimensional array with three elements. 11 12 2
Lengths Int [][] grades = new int[3][5]; grades.length is 3 grades[0].length is 5 grades[1].length is 5 grades[2].length is 5 grades[3].length is 5 2D Arrays and methods Can have 2D arrays as parameters int calculatesum(int[][] parray) To pass a 2D array argument to a method, specify the name without any brackets. sum = calculatesum(sample); 13 14 The String class A string is an object of class String Constructing a String: String message = "Welcome to Java"; String message = new String( "Welcome to Java"); String s = new String(); Always initialize using the assignment operator = and text in quotation marks. Strings Are Immutable Immutable Contents cannot be changed after they are created. Class String does not provide any methods that allow the contents of a String objects to be modified. Does the following code change the contents of the string? String s = "Hello"; s = "Java"; 16 17 Strings Are Immutable String s = "Hello"; s = "Java"; Interned Strings String literals are stored as String objects and interned. For strings with matching characters, they all point to the same String object. After executing String s = "Hello"; s String object for "Hello" s After executing s = "Java"; String object for "Hello" This string object is now unreferenced String s1 = "Welcome to Java"; String s2 = new String("Welcome to Java"); String s3 = "Welcome to Java"; s1 s3 Interned string object for "Welcome to Java" Contents cannot be changed String object for "Java" System.out.println("s1 == s2 is " + (s1 == s2)); s2 System.out.println("s1 == s3 is " + (s1 == s3)); A string object for "Welcome to Java" 18 19 3
String Concatenation Use + String concatenation Every primitive value and object in Java has a String representation When one of the + operator s operands is a string, the other is converted to a String, and then the two are concatenated. "Maximum is: " + result If any trailing zeros in a double value, these will be discarded when the number is converted to a string. String Indexes It is occasionally helpful to refer to a particular character within a string This can be done by specifying the character's numeric index The indexes begin at zero in each string In the string "Hello", the character 'H' is at index 0 and the 'o' is at index 4 20 21 Simple String methods (1/3) Several methods of the String class return new String objects that are modified versions of the original Simple String methods (2/3) int length() Returns the number of characters in this string char charat(int index) Returns character at the specified index String concat(string str) Returns a new string consisting of this string concatenated with str. 22 23 Simple String methods (3/3) String replace (char oldchar, char newchar) Returns a new string that is identical with this string except that every occurrence of oldchar is replaced by newchar. String substring (int offset, int endindex) Returns a new string that is a subset of this string starting at index offset and extending through endindex-1. Changing the case of characters String tolowercase() returns a String object that contains lowercase equivalent this string. String touppercase() returns a String object that contains uppercase equivalent of this string. Nonalphabetic characters, such as digits, are unaffected. 24 25 4
String comparison (1/2) boolean equals(string str) Returns true if this string contains the same characters as str (including case) and false otherwise. boolean equalsignorecase( String str) Returns true if this string contains the same characters as str (without regard to case) and false otherwise. String comparison (2/2) int compareto (String str) Returns an integer indicating if this string is lexically before (a negative return value), equal to (a zero return value), or lexically after (a positive return value), the string str. 26 27 Strings in switch Statements (1/2) Strings in switch Statements (2/2) switch (day) { case "Mon": case "Fri": case "Sun": day = day + "day"; case "Tue": day = day + "sday"; case "Wed": day = day + "nesday"; case "Thu": day =day +"rsday"; case "Sat": day = day +"urday": default: day = "Sunday"; } 28 29 Enumeration (1/3) A special kind of class that is introduced by the keyword enum and a type name. keyword to indicate this is enumerated type public enum Status { CONTINUE, WON, LOST}; typically public, so can access outside this class name of the enum Similar to class, this is a new data type! Inside the braces is a comma separated list of constants, each representing a unique value- in ALL_CAPS. Enumeration (2/3) To declare a variable of this type: Status gamestatus; Variables of an enum type can be assigned only constants declared in the enumeration Otherwise a compilation error will occur. To specify a value, must include the name of the enumerated type gamestatus = Status.WON; 31 32 5
Enumeration (2/3) Can use in another class, if specify class name in which enum is declared: if (status == Game.Status.WON) An enumerated type variable can be null Ordinal Values Internally, each value of an enumerated type is stored as an integer, called its ordinal value The first value in an enumerated type has an ordinal value of 0, the second 1, and so on However, you cannot assign a numeric value to an enumerated type, even if it corresponds to a valid ordinal value 33 34 enum methods The declaration of an enumerated type is a special type of class, and each variable of that type is an object int ordinal() Returns the ordinal value of the object String name() Equivalent to tostring() Returns the name of the identifier corresponding to the object's value Summary (1/2) A two-dimensional array is really nothing more than an array of arrays Using an array with more than two dimensions is rare in an object-oriented system. The Java platform provides the String class to create and manipulate strings. The String class has over 60 methods and 13 constructors. 35 37 Summary (2/2) enum in Java is a keyword, a feature which is used to represent fixed number of well known values in Java enum can be used to create a set of valid values for a field or a method. Enumerated types are type-safe, ensuring that invalid values will not be used. We can add attributes and methods to the definition of an enumerated type. 38 6