Java 数字数据类型
Java数据类型教程 - Java数字数据类型
字节,短整数,整数,长整数,浮点数和双精度类是数字包装类。
它们都继承自抽象的Number类。我们不能创建Number类的对象。然而,er可以声明Number类的引用变量。
我们可以将六个数值包装类中的任何一个的对象引用分配给Number类的引用。
Number类包含六个方法。它们被命名为xxxValue(),其中xxx是六种基本数据类型之一(byte,short,int,long,float和double)。
方法的返回类型与xxx相同。
例子
以下代码显示如何从数值包装器对象检索不同的primate类型值:
public class Main {
public static void main(String[] args) {
Integer intObj = Integer.valueOf(100);
// Gets byte from Integer
byte b = intObj.byteValue();
// Gets double from Integer
double dd = intObj.doubleValue();
System.out.println("intObj = " + intObj);
System.out.println("byte from intObj = " + b);
System.out.println("double from intObj = " + dd);
// Creates a Double object
Double doubleObj = Double.valueOf("123.45");
// Gets different types of primitive values from Double
double d = doubleObj.doubleValue();
float f = doubleObj.floatValue();
int i = doubleObj.intValue();
long l = doubleObj.longValue();
System.out.println("doubleObj = " + doubleObj);
System.out.println("double from doubleObj = " + d);
System.out.println("float from doubleObj = " + f);
System.out.println("int from doubleObj = " + i);
System.out.println("long from doubleObj = " + l);
}
}
上面的代码生成以下结果。

方法
Java 8在一些数值包装类(如Integer,Long,Float和Double)中添加了一些方法,如sum(),max()和min()。
例如,Integer.sum(10,20)简单地返回10 + 20的结果。
它们的引用用于使用集合的lambda表达式。
包装器类帮助处理包含原始值的字符串。
- 使用valueOf()方法将字符串转换为包装器对象。
- 使用parseXxx()方法将字符串转换为原始值。
字节,短整型,整型,长整型,浮点型和双精度型分别包含parseByte(),parseShort(),parseInt(),parseLong(),parseFloat()和parseDouble
以下代码将包含二进制格式的整数的字符串转换为Integer对象和int值:
public class Main {
public static void main(String[] args) {
String str = "01111111";
int radix = 2;
// Creates an Integer object from the string
Integer intObject = Integer.valueOf(str, radix);
// Extracts the int value from the string
int intValue = Integer.parseInt(str, 2);
System.out.println("str = " + str);
System.out.println("intObject = " + intObject);
System.out.println("intValue = " + intValue);
}
}
上面的代码生成以下结果。

值
所有数值包装类都包含几个有用的常量。它们的MIN_VALUE和MAX_VALUE个常数表示最小值和最大值。它们还具有SIZE常数,其表示对应原始类型的变量占据的位的大小。
以下代码尝试将两个字符串解析为双精度值。
第一个字符串包含有效的double,第二个字符串包含无效的double。当调用parseDouble()方法来解析第二个字符串时,抛出NumberFormatException。
public class Main {
public static void main(String[] args) {
String str1 = "123.45";
try {
double value1 = Double.parseDouble(str1);
System.out.println("value1 = " + value1);
} catch (NumberFormatException e) {
System.out.println("Error in parsing " + str1);
}
String str2 = "8H.9"; // An invalid double
try {
double value2 = Double.parseDouble(str2);
System.out.println("value2 = " + value2);
} catch (NumberFormatException e) {
System.out.println("Error in parsing " + str2);
}
}
}
上面的代码生成以下结果。


免费 AI IDE


更多建议: