Packing
Concept : A class that encapsulates basic data types into object types is called a wrapper class (the advantage is that it can provide more functions for manipulating basic values).
Java provides 8 basic types of corresponding packaging classes, as shown in the figure:
Convert string to basic type:
Note: parseXXX (String s); where XXX represents the basic type, the parameter is a string that can be converted to the basic type, if the string cannot be converted to the basic type, the problem of number conversion will occur NumberFormatException .
There are 3 ways to convert basic values into strings:
- The basic type can be directly connected with "", 34 + ""
- Call the valueOf method of String; String.valueOf (34) ;
3. Call the toString method in the wrapper class; Integer.toString (34);
JDK5 features: automatic packing and unpacking
- Automatic unboxing: objects are converted to basic values
- Automatic packing: basic values are converted into objects
Integer i = 4; // Automatic packing. Equivalent to Integer i = Integer.valueOf (4);
i = i + 5; // The right side of the equal sign: convert the i object into a basic value (automatic unboxing) i.intValue () + 5; After the addition operation is completed, box again and convert the basic value into an object
- Demonstration of automatic boxing (byte constant pool) details
When the value is within the byte range, automatic boxing is performed, and the existing space is used instead of creating a new object space.
Integer a = new Integer(3);
Integer b = new Integer(3);
System.out.println(a==b);//false
System.out.println(a.equals(b));//true
Integer x = 127;
Integer y = 127;
// When jdk1.5 is automatically boxed, if the value is within the byte range, the object space will not be newly created but the existing space will be used.
System.out.println(x==y); //true
System.out.println(x.equals(y)); //true
char provides the packaging class Character class
Common methods:
1 |
isLetter () : whether it is a letter |
2 |
isDigit () : whether it is a numeric character |
3 |
isWhitespace () : whether it is a blank character |
4 |
isUpperCase () : whether it is an uppercase letter |
5 |
isLowerCase () : whether it is lowercase |
6 |
toUpperCase () : Specify the capitalization of letters |
7 |
toLowerCase (): Specify the lowercase letter |
8 |
toString (): Returns the character string form, the length of the string is only1 |
Case: Counting the number of various character strings
int bigCount = 0;
int smallCount = 0;
int numberCount = 0;
String s1= "wwwTTTcccyyy193yyy";
// 把字符串转换为字符数组
char[] chs = s1.toCharArray();
// 遍历字符数组,获取每一个字符
for (int x = 0; x < chs.length; x++) {
// 判断该字符是
if (Character.isUpperCase(chs[x])) {
bigCount++;
} else if (Character.isLowerCase(chs[x])) {
smallCount++;
} else if (Character.isDigit(chs[x])) {
numberCount++;
}
}
// 输出结果即可
System.out.println("大写字符:" + bigCount + "个");
System.out.println("小写字符:" + smallCount + "个");
System.out.println("数字字符:" + numberCount + "个");