Strings & Arrays CSCI-1302 Lakshmish Ramaswamy
Organizational Matters Tutor hours Tuesday 6:00 – 7:00 PM; 306 GSRC Wednesday 6:00 – 7:40; 306 GSRC Office hours Will be emailed to you today Email list details
The “==“ Operator For reference types “==“ operator returns true only if They refer to the same object They are null Button a = new Button (“yes”); Button b = new Button (“yes”); Button c = a; c==a returns true where as b==a returns false Observe that semantics is consistent with reference concept
Strings Handled through the String reference type Permits operator overloading But not a primitive type Immutable – may not be changed after assignment Safe to use “=“ operator String empty = “”; String message = “Hello”; String repeat = message; Value of repeat can be changed by creating a new String object
String Concatenation Java does not allow operator overloading for reference types “+” is the only exception for strings + performs concatenations of lhs and rhs and returns reference to newly constructed String object Left associative “a” + “b” “b” + 5 5 + “c” “a” + 1 + 2 1 + 2 + “a”
String Comparisons <, >, <=, >= not defined == and != have semantics identical to reference types String lhs = new String(“CSCI 1302”); String rhs = “CSCI String(“CSCI 1302”); lhs == rhs returns false Equals method for testing equality lhs.equals(rhs) returns true compareTo for lexicographic comparison
String Methods String temp = “CSCI1302” int len = temp.length(); char ch = temp.charAt(2); String subtemp = temp.substring(1, 4)
More on Arrays Array of reference types Button [ ] arrayofButtons; arrayofButtons = new Button [5]; for (int i = 0; i < arrayofButtons.length(); i ++){ arrayofButtons[i] = new Button(); } arrayofButton[4].setLabel(“No”);
Dynamic Array Expansion int [] arr = new int [10]; ……. // But you actually need array of 12 integers int[ ] original = arr; arr = new int[12]; for(int i = 0; i < 10; i ++) arr[i] = original[i] original = null;
Illustration
ArrayList Built in functionality for dynamic sized arrays Size and capacity add method increases size by 1 & adds new item at the given position Expands the size if the capacity is reached get method for retrieving object at particular index
Multidimensional Arrays Multidimensional arrays are actually array of arrays int [ ][ ] x = new int [2][3]; \\ x is a an array of two arrays, x[0] and x[1] x.length(); \\ answer is 2 x[0].length(); \\ answer is 3; x[1].length(); \\ answer is 3;
Ragged Arrays