Text Processing and Wrapper Classes I
- Contents
- Introduction to Wrapper Classes
- Wrapper Classes
- Character Testing and Conversion With the
CharacterClass - Searching Strings
- Extracting Substrings
- Extracting Characters to Arrays
- Returning Modified Strings
- The
valueOfMethods - The
StringBuilderClass - Appending to a
StringBuilderObject
Introduction to Wrapper Classes
Java provides eight primitive data types.
Type Min Max byte-128 127 short-32768 32767 int-2.14748 × 109 2.14748 × 109 long-9.22337 × 1018 -9.22337 × 1018 float-3.40282 × 1038 3.40282 × 1038 double-1.79769 × 10308 1.79769 × 10308 booleanfalsetruechar065535They are called “primitive” because they are not created from classes.
-
A wrapper class is a class that is “wrapped around” a primitive data type.
final class MyWrapper { private final int value; public MyWrapper(int value) { this.value = value; } public int getValue() { return this.value; } // etc. } -
The Java wrapper classes:
Type Min Max ByteByte.MIN_VALUEByte.MAX_VALUEShortShort.MIN_VALUEShort.MAX_VALUEIntegerInteger.MIN_VALUEInteger.MAX_VALUELongLong.MIN_VALUELong.MAX_VALUEFloat-Float.MAX_VALUEFloat.MAX_VALUEDouble-Double.MAX_VALUEDouble.MAX_VALUEBooleanBoolean.FALSEBoolean.TRUECharacterCharacter.MIN_VALUECharacter.MAX_VALUE The wrapper classes are part of
java.langso to use them there is noimportstatement required.Example code:
import java.util.ArrayList; public class Program { public static void main(String[] args) { // Java 7: ArrayList<Integer> list = new ArrayList<>(); final ArrayList<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) list.add(new Integer(i)); for (int i = 0; i < list.size(); i++) System.out.println(list.get(i)); } }
Wrapper Classes
Wrapper classes allow you to create objects to represent primitives.
-
Generic Java classes, like
ArrayList, do not support primitive types; they require objects.import java.util.ArrayList; public class Program { public static void main(final String[] args) { // This will not compile because Java // generic types do not support primitives. // // ERROR: // ArrayList<int> foo = new ArrayList<int>(); // This will compile because the generic // type argument is an object, in this case // the Integer wrapper class. ArrayList<Integer> list = new ArrayList<Integer>(); list.add(new Integer(1013)); } } Wrapper classes are immutable, which means that once you create an object, you cannot change the object’s value.
To get the value stored in an object you must call a method.
Java wrapper classes provide useful static methods.
Example code:
public class Program { public static void main(final String[] args) { final int i = 123456; System.out.print(i + "'s binary value is: "); System.out.println(Integer.toBinaryString(i)); System.out.print(i + "'s octal value is: "); System.out.println(Integer.toOctalString(i)); System.out.print(i + "'s hex value is: "); System.out.println( Integer.toHexString(i)); } }
Character Testing and Conversion With the Character Class
The
Characterclass allows achardata type to be wrapped in an object.The
Characterclass provides methods that allow easy testing, processing, and conversion of character data.Book example:
Example code:
public class Program { public static void main(final String[] args) { final char a[] = { 'a', 'b', '5', '?', 'A', ' ' }; for (int i = 0; i < a.length; i++) { if (Character.isDigit(a[i])) System.out.println("'" + a[i] + "' is a digit. "); if (Character.isLetter(a[i])) System.out.println("'" + a[i] + "' is a letter. "); if (Character.isWhitespace(a[i])) System.out.println("'" + a[i] + "' is white-space. "); if (Character.isLowerCase(a[i])) System.out.println("'" + a[i] + "' is lower-case. "); if (Character.isUpperCase(a[i])) System.out.println("'" + a[i] + "' is upper-case. "); } } }The
Characterclass provides two methods that change the case of the character.char toLowerCase(char ch) char toUpperCase(char ch)
Book example:
Example code:
public class Program { public static void main(final String[] args) { final char[] array = { 'a', 'b', 'C', 'D', 'e', 'f', 'G', 'H', }; for(int i = 0; i < array.length; i++) System.out.print(Character.toLowerCase(array[i]) + " "); System.out.println(); for(int i = 0; i < array.length; i++) System.out.print(Character.toUpperCase(array[i]) + " "); } }
Searching Strings
The
startsWithmethod determines whether a string begins with a specified substring.The
endsWithmethod determines whether a string ends with a specified substring.startsWithandendsWithare case sensitive comparisons.Book example:
Example code:
public class Program { public static void main(final String[] args) { final String str = "Long long ago, long long ago"; if (str.startsWith("Long")) System.out.println("The string starts with 'Long'."); else System.out.println("The string does not start with 'Long'."); if (str.endsWith("Ago")) System.out.println("The string ends with 'Ago'."); else System.out.println("The string does not end with 'Ago'."); } }The
Stringclass also provides methods that will locate the position of a substring.indexOfreturns the first location of a substring or character, or -1 if the text is not found.lastIndexOfreturns the last location of a substring or character, or -1 if the text is not found.-
int indexOf(char ch) int indexOf(char ch, int start) int indexOf(String str) int indexOf(String str, int start) int lastIndexOf(char ch) int lastIndexOf(char ch, int start) int lastIndexOf(String str) int lastIndexOf(String str, int start)
Example code:
public class Program { public static void main(final String[] args) { // ................ 0123456789012345678901234567890 final String str = "and a one and a two and a three"; System.out.println("Locations of 'and', left to right:"); int position = str.indexOf("and"); while (position != -1) { System.out.println(position); position = str.indexOf("and", position + 1); } System.out.println(); System.out.println("Locations of 'and', right to left:"); position = str.lastIndexOf("and"); while (position != -1) { System.out.println(position); position = str.lastIndexOf("and", position - 1); } } }
Extracting Substrings
The
Stringclass provides methods to extract substrings in aStringobject.subStringreturns a substring beginning at a location and, optionally, ending at a location.A new
Stringinstance is returned with the contents of the substring.
Example code:
public class Program { public static void main(final String[] args) { // ......................|<--->| // ................. 012345678901234 final String text = "The Golden Rule"; final String golden = text.substring(4, 10); final String rule = text.substring(11); System.out.println("Golden: " + golden); System.out.println("Rule: " + rule); } }
Extracting Characters to Arrays
The
Stringclass provides methods to extract substrings in aStringobject and store them inchararrays.getCharsstores a substring in achararray.toCharArrayreturns theStringobject’s contents in an array ofcharvalues.
Example:
Example code:
public class Program { public static void main(final String[] args) { // ..................... |<--->| // ................. 012345678901234 final String text = "The Golden Rule"; final char[] golden = new char[6]; text.getChars(4, 10, golden, 0); System.out.println("Golden Chars:"); for (final char ch : golden) System.out.println("'" + ch + "'"); } }
Returning Modified Strings
The
Stringclass provides methods to return modifiedStringobjects.concatreturns aStringobject that is the concatenation of two strings.replacereturns aStringobject with all occurrences of a character being replaced by another character.replaceAllreturns aStringobject with all occurrences of a substring being replaced by another substring.trimreturns aStringobject with all leading and trailing whitespace characters removed.
Example code:
public class Program { public static void main(final String[] args) { final String first = " Jade "; final String last = " Cheng "; final String name = first.trim().concat(" ").concat(last.trim()); System.out.println(name); } }
The valueOf Methods
The
Stringclass provides several overloadedvalueOfmethods.They return a
Stringobject representation of a primitive value or a character array.Example code:
public class Program { public static void main(final String[] args) { System.out.println("Value of a boolean: " + String.valueOf(true)); System.out.println("Value of an integer: " + String.valueOf(34)); System.out.println("Value of a double: " + String.valueOf(3.4)); System.out.println("Value of a char: " + String.valueOf('J')); final char[] chars = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'}; System.out.println("Value of a char array: " + String.valueOf(chars)); System.out.println("Value of a char array: " + String.valueOf(chars, 2, 5)); } }
The StringBuilder Class
The Java
Stringclass is immutable.The Java
StringBuilderclass helps create newStringinstances.- We can change specific characters.
- We can insert characters.
- We can delete characters.
- We can perform other operations.
A
StringBuilderobject will grow or shrink in size, as needed, to accommodate the changes.StringBuilderConstructorsGives the object an initial storage space to hold a small number of characters:
StringBuilder()
Gives the object an initial storage space to hold
lengthcharacters:StringBuilder(int length)
Gives the object an initial storage space to hold
str:StringBuilder(String str)
Other
StringBuilderMethodschar chartAt(int position) void getChars(int start, int end, char[] array, int arrayStart) int indexOf(String str) int indexOf(String str, start) int lastIndexOf(String str) int lastIndexOf(String str, int start) int length() String substring(int start) String substring(int start, int end)
Appending to a StringBuilder Object
The
StringBuilderclass has sever overloaded versions of a method namedappend.They append a string representation of their argument to the calling object’s current contents.
The general form of the
appendmethod is:object.append(item);
The
itemparameter is a:- a primitive literal or variable
- a char array
- a string literal or object
Example code:
public class Program { public static void main(final String[] args) { final StringBuilder builder = new StringBuilder(); builder.append("We sold "); builder.append(12); builder.append(" doughnuts for $"); builder.append(15.95); builder.append(new char[] { ' ', 'd', 'o', 'l', 'l', 'o', 'r', 's' }); final String text = builder.toString(); System.out.println(text); } }The
StringBuilderclass also has several overloaded versions of a method namedinsert.These methods accept two arguments:
- an
intthat specifies the position to begin insertion - the value to be inserted
- an
The general form of the
insertmethod is:object.insert(start, item);
The
itemto be inserted may be:- a primitive literal or variable
- a char array
- a string literal or object
Book example:
Example code:
public class Program { public static void main(final String[] args) { final StringBuilder builder = new StringBuilder("We sold doughnuts"); // 012345678 // We sold doughnuts builder.insert(8, 12); // 01234567890 // We sold 12doughnuts builder.insert(10, " "); // 012345678901234567890 // We sold 12 doughnuts builder.insert(builder.length(), " for $15.95 dollors"); System.out.println(builder); } }