Notes Quick Links Introductory Mobile Application Development 152-160 Java Syntax Part 2 - Activity String Class Add section on Parse ArrayList Class methods. Book page 95. Toast Page 129 240 242 String Class tostring charat codepointat codepointbefore codepointcount CompareTo CompareToIgnoreCase concat contains contentequals endswith equals equalsignorecase getbytes indexof isempty lastindexof length startswith matches regionmatches replace replaceall replacefirst split substring tochararray tolower toupper trim Author suggests this is the best way to instantiate a String String mystring = Volker ; //OK String mystring = new String( Volker ); //Better Method types Instance methods (aka nonstatic methods) must be applied to an instance of a class Class methods (aka static methods) are applied by referencing the class name, not an instance name. Page 1 of 10
String instance methods (s defined as String) someobject.tostring( ) Where possible, converts other types to String See example below s.charat(i) vecstring.get(1).tostring().charat(2); s.codepointat(i) Returns the ASCII (Unicode) value of the character in position i s.codepointbefore(i) Returns the ASCII (Unicode) value of the character in position i-1 s.codepointcount(startindex, endindex) Returns the number of ASCII (Unicode) characters between startindex and endindex, not counting endindex. s.compareto(anotherstring) Returns a negative number if string s is alphabetically (Unicode sequence) before anotherstring Returns a positive number if string s is alphabetically after anotherstring Returns zero if the strings are identical Substitute for < and > operators s.comparetoignorecase(anotherstring) Same as CompareTo, but case insensitive s.concat(anotherstring) Never use it Same as s = s + anotherstring; s.contains(anotherstring) Returns true if anotherstring exists anywhere in string s. Returns false otherwise. Note, no case insensitive version Page 2 of 10
s.contentequals(anotherstring) Same as equals method (see below) No Ignore Case alternative available s.endswith(anotherstring) Returns true if the last characters in string s are the same as anotherstring Returns false otherwise s.equals(anotherstring) Returns true if two strings have exactly the same characters Substitute for == comparison s.equalsignorecase(anotherstring) Same as equals, except character by character comparison is case insensitive s.getbytes( ) Returns an array of bytes. Each element of the array contains the ASCII (Unicode) value of the corresponding character in the string. s.indexof(anotherstring, startindex) Returns the index where anotherstring is located in string s, starting at position startindex If startindex is omitted, the search begins at the beginning of string s anotherstring could also be of type char If anotherstring is not found, the function returns -1 s.isempty( ) Same as s.equals(new String("")) Same as s.length == 0 Easier to enter, easier to understand s.lastindexof(anotherstring, startindex) Returns the index of anotherstring within string s, searching backwards from the end of the string If startindex is not specified, the search begins from the end of the string. anothersting can also be of type char If anotherstring is not found, the function returns -1 Page 3 of 10
s.length( ) Returns number of characters in a string s.startswith(anotherstring, startindex) Returns true if string s, (starting in character position startindex) starts with the letters in anotherstring startindex can be omitted. If it is, start index 0 is used s.matches(regularexpressionstring) Returns true if the string s matches the regular expression pattern provided. Still working on this one s.regionmatches(true/false, starts, anotherstring, starta, length) Returns true if the designated parts of two strings match True/false designates whether the comparison should ignore case (true to ignore case). If this parameter is omitted, the default is false. starts designates where in string s to start comparing starta designates where in anotherstring to start comparing length designates how many characters to compare s.replace(ministring, newstring) Replaces all occurrences of ministring with newstring in the string s Returns a new String with the changes ministring and newstring can also be of type char s.replaceall(regex, newstring) Replaces all occurrences of strings that match the regular expression provided with newstring. Not functioning yet s.replacefirst(regex, newstring) Replaces the first occurrence of a string that matches the regular expression provided with newstring. Works OK if just use strings, but regular expressions not working yet. Page 4 of 10
s.split(regex) Creates a array of strings that contain all the pieces of the original string split at a designated character string (regex). String words[]; //Array of word strings words = s.split(" "); //Split at spaces A second, optional integer parameter allows you to limit the number of times the string is split String firstthree[]; //1 st 3 words words = s.split(" ",3); The last split will always contain the remainder of the string. s.substring(start, end) Extract part of the string starting at start, ending at end Second parameter is not required. If it s not included, the substring includes all characters to the end of the string. Note: the end character is not included in the substring (see example) Note: unlike other languages, the second parameter is not the length of the desired substring. myname = "Volker F. Gaul"; mi = myname.substring(7,9); //Returns F. s.tochararray Similar to tobytearray. Might be more valuable because characters are more readily accessible. Coverts a string to an array of characters char characters[]; //array of characters characters = s.tochararray(); Page 5 of 10
s.touppercase( ) s.tolowercase Converts a string to upper or lower case and returns another string state = state.touppercase( ); s.trim( ) Removes all leading and trailing whitespace from a string White space includes spaces, carriage returns, tabs, backspaces Static String Methods Static methods are NOT associated with an instance of a String Instead, they are implemented by referencing the String class directly String.methodName String.CopyValueOf(charArray) Converts an array of characters back into a String Reverse of tochararray newstring = String.CopyValueOf(charArray); Second (overloaded) version allows you designate which character to start with and how many characters you want. newstring = String.CopyValueOf(charArray,10,15); //Starts at char 10, extracts 15 characters Page 6 of 10
String.format Allows you to control the display of just about any type Allows you to control the field width used to display a value Reference: http://java.sun.com/j2se/1.5.0/docs/api/jav a/util/formatter.html#syntax The format method s first parameter is the formatting string. Designates how the values should be formatted Each value gets its own format specifier (see below) After the formatting string you list the values (any types, any combination) s = String.format(formatString, value1, value2, value3); Creating formatting specifiers Starts with % These are optional. Only used a parameter value needs to be displayed more than once (rare) or if the parameters should be displayed in a different order (why not just put them in the right order?) Next is the (parameter) number of the value you want to format (starts at 1, not 0) The parameter number must always be followed by a $ Next (optional) come flags that allow you to designate text alignment, whether signs are included, zero padding, etc (see reference) The flags are followed (optional) by a width specifier. This designates the minimum number of characters the field will take up. If the data contains decimal places, you can specified the number of decimal places to display by following the width with a period and the number of decimal places Finally, the width is followed by the conversion code. This code tells the format method what type of data to expect. See codes on the reference page. Any other text in the format string is displayed as entered Page 7 of 10
String.format Examples s = String.format("My name is %1$10s","Volker"); Volker is the text to be formatted My name is appears exactly as it is typed 10 designates the parameter should always take up a minimum of 10 characters s designates the parameter should be a string Result: My name is Volker (4 extra spaces before Volker) Adding a - (no quotes)(left-justify flag) before the 10 would have aligned Volker to the left in the field and the 4 extra spaces (to fill 10 characters) would have appeared after Volker s = String.format("Salary is $%8.2f Hours: %4.1f, 1537.237, 55.25); 1537.237 is the first parameter, 55.25 is the second parameter Salary is $ appears exactly as it is typed 8 is the total width of the field (includes the decimal point and decimal places) 2 is the number of decimal places to display (will round as necessary) f designates the first parameter be treated as a floating point number Hours: appears exactly as it is typed 4 is the total width of the field 1 is the number of decimal places to display f designates the second parameter be treated as a floating point number There doesn t seem to be a way to include $, % or commas in values using the format method. See DecimalFormat below. String.valueOf(x) Converts a primitive to a string Static (class) method. Note the class name is used, not an instance name. int age = 25; strage = String.valueOf(age); Convert String to Primitive mydouble = Double.parseDouble(theString); Replace double with any primitive type Page 8 of 10
ArrayList Class Arrays can be limiting Fixed size (can t add delete) Limited support library (sorting, searching) ArrayList is available to provide more flexibility To use ArrayLists in a Java project, you must import java.util.*; Declaring ArrayList<elementType> listname = new ArrayList<elementType>(); Replace elementtype with the type of data that each element will store Programmer-defined classes can be used Replace listname with an appropriate name for this list. Adding an element to the ArrayList listname.add(pointertoelement); pointertoelement can be any variable of the appropriate type for this ArrayList Retrieving an element from the ArrayList listname.get(index) index designates which element to retrieve (0-based).size.indexOf.contains lastindexof.remove(index) toarray Navigating for(int i=0; i<listname.size(); i++) for(listtype anitem : listname) For testing purposes it might be convenient to fill an ArrayList with initial values. You can t initialize an ArrayList the same way you initialize an array Luckily, the ArrayList class and arrays have methods that make them fairly compatible ArrayList<String> names = new ArrayList<String>( Arrays.asList("Adam","Betty","Claire")); ArrayList<Integer> values = new ArrayList<Integer>( Arrays.asList(100, 200, 300, 400)); Page 9 of 10
Toast Note ArrayLists are not compatible with the primitive types. To create an ArrayList of integers or doubles use the wrapper classes Integer or Double. Toast is normally used during debugging to popup messages on the screen Can also be used to send messages to the user Example Toast.makeText(this, "Your text here" Toast.LENGTH_LONG).show(); Most common mistake: leave off the.show() Page 10 of 10