Text Processing and Wrapper Classes I
- Contents
- Introduction to Wrapper Classes
- Wrapper Classes
- Character Testing and Conversion With the
Character
Class - Searching Strings
- Extracting Substrings
- Extracting Characters to Arrays
- Returning Modified Strings
- The
valueOf
Methods - The
StringBuilder
Class - Appending to a
StringBuilder
Object
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 boolean
false
true
char
0
65535
They 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 Byte
Byte.MIN_VALUE
Byte.MAX_VALUE
Short
Short.MIN_VALUE
Short.MAX_VALUE
Integer
Integer.MIN_VALUE
Integer.MAX_VALUE
Long
Long.MIN_VALUE
Long.MAX_VALUE
Float
-Float.MAX_VALUE
Float.MAX_VALUE
Double
-Double.MAX_VALUE
Double.MAX_VALUE
Boolean
Boolean.FALSE
Boolean.TRUE
Character
Character.MIN_VALUE
Character.MAX_VALUE
The wrapper classes are part of
java.lang
so to use them there is noimport
statement 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
Character
class allows achar
data type to be wrapped in an object.The
Character
class 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
Character
class 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
startsWith
method determines whether a string begins with a specified substring.The
endsWith
method determines whether a string ends with a specified substring.startsWith
andendsWith
are 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
String
class also provides methods that will locate the position of a substring.indexOf
returns the first location of a substring or character, or -1 if the text is not found.lastIndexOf
returns 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
String
class provides methods to extract substrings in aString
object.subString
returns a substring beginning at a location and, optionally, ending at a location.A new
String
instance 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
String
class provides methods to extract substrings in aString
object and store them inchar
arrays.getChars
stores a substring in achar
array.toCharArray
returns theString
object’s contents in an array ofchar
values.
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
String
class provides methods to return modifiedString
objects.concat
returns aString
object that is the concatenation of two strings.replace
returns aString
object with all occurrences of a character being replaced by another character.replaceAll
returns aString
object with all occurrences of a substring being replaced by another substring.trim
returns aString
object 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
String
class provides several overloadedvalueOf
methods.They return a
String
object 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
String
class is immutable.The Java
StringBuilder
class helps create newString
instances.- We can change specific characters.
- We can insert characters.
- We can delete characters.
- We can perform other operations.
A
StringBuilder
object will grow or shrink in size, as needed, to accommodate the changes.StringBuilder
ConstructorsGives the object an initial storage space to hold a small number of characters:
StringBuilder()
Gives the object an initial storage space to hold
length
characters:StringBuilder(int length)
Gives the object an initial storage space to hold
str
:StringBuilder(String str)
Other
StringBuilder
Methodschar 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
StringBuilder
class 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
append
method is:object.append(item);
The
item
parameter 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
StringBuilder
class also has several overloaded versions of a method namedinsert
.These methods accept two arguments:
- an
int
that specifies the position to begin insertion - the value to be inserted
- an
The general form of the
insert
method is:object.insert(start, item);
The
item
to 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); } }