3.1 Wrappers & Strings
In our first lesson within this section we start by looking at code that uses the primitive wrapper classes and/or autoboxing and unboxing. We then look at the differences between the
Lets take a look at the points outlined at the Oracle Website for this part of the certification.
- Section 3: API Contents
- Develop code that uses the primitive wrapper classes (such as Boolean, Character, Double, Integer, etc.), and/or autoboxing & unboxing. Discuss the differences between the String, StringBuilder, and StringBuffer classes.
The Wrapper Classes
The wrapper classes provided in Java allow us to wrap any of the primitive types in an object. The benefits of this are two-fold:
- Wrapped primitives can be used in object-centric activities such as collections or where we need to use an object.
- Wrapped primitives give us access to utility functions that we can use with primitives.
The following table lists the primitive types, their wrapper classes and the constructors available:
|Primitive Type||Description||Wrapper||Constructor Arguments||Examples|
|boolean and char|
|signed numeric integers|
|signed floating point|
Strings In Java
Most computer languages use the standard 8-bit ASCII character set which has a range of
127 to represent characters of a string. Java uses the Unicode character set which has a range of
65,536 that can represent any character found in any human language. The ASCII character set is a subset of Unicode and as such ASCII character are still valid in Java. In Java strings are
objects and like any other object it means we can create (instantiate) them. Another thing to note about strings in Java is that they are immutable, which means once you have assigned a value to a
object it can never be changed.
See String Immutability for more on this.
See String Creation & Efficiency for more information on how Java uses the string constant pool.
String, StringsBuilder, StringBuffer Differences
String immutability can improve efficiency, the downside is we can also have a lot of strings that get lost in the string constant pool, when we reassign or discard our reference variables.
Luckily for us Java comes with the predefined
StringBuilder classes which we can use to modify strings without the pros and cons of immutability. So when you are doing a lot of
string manipulation these are the classes to use. The
StringBuilder class was introduced in Java6 as an alternative to the older
StringBuffer class. Both these classes have the same API apart
StringBuffer class being thread safe and having
synchronized methods. For most situations when manipulating strings, thread safety isn't an issue and so the
StringBuilder class is the better option for efficiency.
StringBuilder class lesson for more information about the