Java Reference
In-Depth Information
PITFALL: A Wrapper Class Does Not Have a
No-Argument Constructor
Normally, it is good programming practice to define a no-argument constructor for
any class you define. However, on rare occasions, a no-argument constructor simply
does not make sense. The wrapper classes discussed in the previous subsection do not
have a no-argument constructor, which is reasonable if you think about it. To use
the static methods in a wrapper class, you need no calling object and hence need no
constructor at all. The other function of a wrapper class is to provide a class object
corresponding to a value of a primitive type. For example,
new
Integer(42)
creates an object of the class
Integer
that corresponds to the
int
value
42
. There is
no no-argument constructor for the class
Integer
, because it makes no sense to have
an object of the class
Integer
unless it corresponds to an
int
value, and if it does cor-
respond to an
int
value, that
int
value is naturally an argument to the constructor.
■
Display 5.9
String Processing with a Method from the
Class
Character
(part 1 of 2)
1
import
java.util.Scanner;
2 /**
3 Illustrate the use of a static method from the class Character.
4 */
5
6
public class
StringProcessor
7 {
8
public static void main
(String[] args)
9 {
10 System.out.println("Enter a one line sentence:");
11 Scanner keyboard =
new
Scanner(System.in);
12 String sentence = keyboard.nextLine();
13
14 sentence = sentence.toLowerCase();
15
char
firstCharacter = sentence.charAt(0);
16 sentence = Character.toUpperCase(firstCharacter)
17 + sentence.substring(1);
18
19 System.out.println("The revised sentence is:");
20 System.out.println(sentence);
21 }
22 }
(continued)