English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java complete list of examples
在本教程中,我们将学习在Java中将原始数据类型转换为对应的包装对象,反之亦然。
class Main { public static void main(String[] args) { //创建原始类型 int var1 = 5; double var2 = 5.65; boolean var3 = true; //转换为包装对象 Integer obj1 = Integer.valueOf(var1); Double obj2 = Double.valueOf(var2); Boolean obj3 = Boolean.valueOf(var3); //检查obj是否为对象 //对应的包装器类 if(obj1 instanceof Integer) { System.out.println("创建一个Integer对象。"); } if(obj2 instanceof Double) { System.out.println("创建一个Double对象。"); } if(obj3 instanceof Boolean) { System.out.println("将创建一个Boolean对象。"); } } }
Output result
创建一个Integer对象。 创建一个Double对象。 将创建一个Boolean对象。
在上面的示例中,我们创建了原始类型(int,double和boolean)的变量。 在这里,我们使用了Wrapper类(Integer,Double和Boolean)的valueOf()方法将原始类型转换为对象。
要了解Java中的包装器类,请访问Java包装类。
class Main { public static void main(String[] args) { //创建包装类的对象 Integer obj1 = Integer.valueOf(23); Double obj2 = Double.valueOf(5.55); Boolean obj3 = Boolean.valueOf(true); //转换为原始类型 int var1 = obj1.intValue(); double var2 = obj2.doubleValue(); boolean var3 = obj3.booleanValue(); //Print original values System.out.println("int variable value: " + var1); System.out.println("Double variable value: " + var2); System.out.println("Boolean variable value: " + var3); } }
Output result
int variable value: 23 Double variable value: 5.55 Boolean variable value: true
In the above example, we have created objects of wrapper classes (Integer, Double, and Boolean).
Then, we use the intValue(), doubleValue() and booleanValue() methods respectively to change the object to the corresponding primitive type (int, double and boolean).
Attention:The Java compiler will automatically convert primitive types to corresponding objects and vice versa. This process is calledAutomatic boxing and unboxing。To learn more, please visitJava automatic boxing and unboxing。