Java - Beginning 152-130 Built-In Classes Notes Quick Links Vector Class Pages Wrapper Classes Pages 91 95 String Class Pages 222 225 342 346 Calendar Class Pages 230 235 DecimalFormat Class Pages 269 Activity Vector Class The main drawback of arrays is they must be fixed size Vectors overcome this drawback vectors are resizable at runtime. Requires import of java.util.vector Vectors are pointers to instances of other classes Defining a vector: Vector vecstring = new Vector( ); Note Vector class name is capitalized ( ) used to define the capacity not [ ] Capacity of vector is a parameter If no capacity is specified (like the example above) the initial capacity is 10 Vectors have both a capacity and a size Capacity is number of elements the vector could hold before automatically expanding Size is the actual number of elements in the vector Can designate the capacity of the vector when instantiating it. Vector vecstring = new Vector(5); Capacity is 5, size is 0 Page 1 of 16
Notes Adding elements to a vector. vecstring.add( Volker ); or vecstring.add(new String( Java )); //Preferred or String coursename = Java ; vecstring.add(coursename); You can also add primitive types to a vector (see Wrapper Classes below) Note that vectors are NOT typed so you can add objects of different types to the same vector. This can be confusing unless you can determine the type (class) of each element. Normally, the elements are all of the same class If adding an element would exceed the current capacity of the vector, the size of the vector is doubled automatically. Retrieving an element of a vector vecstring.get(idx); The get method returns the element at index idx The return value can be assigned to an appropriate variable or used in an equation (or output statement) Determining the location of an element idx = vecstring.indexof(findme); Returns the index of the element that matches findme findme can be of any type though usually it is the same type as the elements in the vector If the item is not found, the method returns -1 contains method works in a similar way, returning either true or false if the vector contains the requested element Activity Page 2 of 16
Notes Activity Removing elements from a vector vecstring.remove(idx); vecstring.remove(findme); Can provide either the index of the item to be deleted or the item itself Capacity of the vector never changes. Wrapper Classes Some object methods (like vectors) require that objects be sent as parameters. This precludes sending the primitive types (int, double, etc.) to these methods Wrapper classes wrap themselves around the primitive types, allowing them to be used where objects are required. Each primitive type has a corresponding wrapper class Wrapper classes have the same names as the primitive except the first letter is capitalized Exception: int wrapper class is Integer Example: myvector.add(new Integer(15)); Integer objage = new Integer(15); It is possible to add a primitive type to a vector. myvector.add(15); I believe this statement actually wraps the integer in an Integer (wrapper) class (behind the scenes) before adding the value to the vector. Page 3 of 16
Notes Extracting a numeric vector element to a primitive data type. The Vector requires its elements be classes, but classes are harder to do math with. Use these techniques to convert a Wrapper to a primitive. Double salary = new Double(25.25); double sal; //Primitive version sal = salary; //Works fine sal = salary.doublevalue(); //Also works //Vector element sal = (Double) myvector.get(1); In the last example, the vector element cannot be converted to a double (primitive); however, it can be converted to a Double (wrapper) which then can be assigned to a double primitive. Personally, until I learn otherwise, I won t be using the Wrapper classes except to do the conversions required to extract a numeric value from a Vector as in the last example above. Primitive literals cannot be assigned to wrapper types Activity Double average; average = total / cnt; //Wrapper class //Error Because of this, I recommend you convert all Wrapper class data back to its primitive type before using it in calculations. Page 4 of 16
String Class 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. String methods (s defined as String) s.tostring(someobject); 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 s.comparetoignorecase(anotherstring) Same as CompareTo, but case insensitive Page 5 of 16
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 s.contentequals(anotherstring) Same as equals method (see below) and = = 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 Same as s == anotherstring 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( ) Returns true if the string contains no characters (length is 0) Same as s == Page 6 of 16
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 s.length( ) Returns number of characters in a string s.startswith(anotherstring, startindex) Returns true is 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 Page 7 of 16
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. s.split(regex) Creates a array of strings that contain all the pieces of the original string split at a designated character string (regex). Example: 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. Example: 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 Example: char characters[]; //array of characters characters = s.tochararray(); Page 8 of 16
s.touppercase( ) s.tolowercase Converts a string to upper or lower case and returns another string Example: 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 Example: String.methodName String.CopyValueOf(charArray) Converts an array of characters back into a String Reverse of tochararray Example: 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 9 of 16
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) Example: s = String.format(formatString, value1, value2, value3); Creating formatting specifiers Starts with % 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 10 of 16
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 %1$ designates this as a format specifier for the first parameter (only parameter, Volker ) 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 $%1$8.2f Hours: $%2$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 %1$ designates this as a format specifier for the 1 st parameter (1537.237) 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 %2$ designates this as a format specifier for the 2 nd parameter (55.25) 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. Example: int age = 25; strage = String.valueOf(age); Page 11 of 16
Convert String to Primitive mydouble = Double.parseDouble(theString); Replace double with any primitive type Convert Wrapper to String astring = wrapvariable.tostring( ); Convert String to Wrapper wrapvariable = Double.valueOf(aString); Calendar Class Many of today s program manipulate date. Java comes with three Date classes that makes processing dates easier. Date class mostly replaced by Calendar class Calendar class has the ability to store dates and times DateFormat allows you to format dates for output Date and Calendar require java.util import Instantiating the Calendar class Calendar cal = Calendar.getInstance( ); new not available Assigning a value to a Calendar object cal.gettime( ); If instance has not been assigned a value, gettime sets its value to the current date and time. cal.set(year, Calendar.AUGUST, 16); Sets the date to 8/16/year (depending on the value in the variable year) Can also set individual calendar components cal.set(calendar.month, 4); Page 12 of 16
Retrieving Calendar components value = cal.get(calendar.component); Returns part of the date based on which component is requested. Components are Calendar class enumerations predefined values Common components: MONTH DATE YEAR DAY_OF_WEEK (1=Sunday) HOUR (12 hour day) HOUR_OF_DAY (24 hour day) MINUTE SECOND MILLISECOND AM_PM strvalue = cal.getdisplayname (component, style, Locale.US); Component must be one of the items listed above that has a named version (MONTH, DAY_OF_WEEK, AM_PM) Style is another Calendar enumeration that includes LONG and SHORT Doing calendar calculations cal.add(calendar.month, 1); First parameter designates the units to be added Second parameter designates how many Use a negative number to subtract values Comparing calendar values if (cal.before(anotherdate) ) if (cal.after(anotherdate) ) Calendar values are not equal unless all components are the same including hours, minutes, seconds and milliseconds Use set to set all time components to zero if need to compare just dates. Page 13 of 16
Displaying Calendar values DateFormat class (java.text) allows you format dates for output Unformatted date System.out.println(cal.getTime()); Sun Sep 16 17:52:04 CDT 2007 First need to create an instance of the DateFormat class that defines what format you want. DateFormat longdate = DateFormat.getDateInstance(DateFormat.LONG); longdate is an instance of DateFormat LONG, MEDIUM, SHORT are available Need a separate instance variable for every format used. Then, use the instance to format an output System.out.println( Date is + longdate.format(cal.gettime() ); longdate is the instance created above format method used to format a date sent to it as a parameter Page 14 of 16
Custom Date Formats Use SimpleDateFormat class SimpleDateFormat fmt = new SimpleDateFormat(formatstring); formatstring can contain any combination of the following characters: yy, yyyy (07, 2007) M, MM, MMM, MMMM (9, 09, Sep, September) d, dd (7, 07) EEE, EEEE (Mon, Monday) Time formatting characters are also available To insert non-format string characters in the formatting string, surround them with apostrophes. Reference Usage is just like DateFormat System.out.println( Date is + fmt.format(cal.gettime()) ); DecimalFormat Class Similar to DateFormat and SimpleDateFormat but used to format numbers Other formatting classes are available, but this one covers most needs Create an instance and designate the format DecimalFormat fmtcurrency = new DecimalFormat(formatstring); Formatstring can contain combinations of the following characters: # optional digit 0 required digit $ dollar sign, commas where appropriate % (automatically multiplies value by 100) Page 15 of 16
Examples DecimalFormat fmtcurrency = new DecimalFormat( $#,##0.00 ); DecimalFormat fmtpercent = new DecimalFormat( #0.00% ); double cost = 5127.5; double discount = 0.0525; System.out.println( Cost is + fmtcurrency.format(cost) ); System.out.println( Discount is + fmtpercent.format(discount) ); Output Cost is $5,127.50 Discount is 5.25% Page 16 of 16