Java 中的 intValue() 方法和原始数据类型转换

Sarwan Soomro 2023年10月12日
  1. Java 中的 intValue() 方法
  2. Java 中 IntInteger 之间的区别
  3. 使用 Java 中的 intValue() 方法进行字符串转换
Java 中的 intValue() 方法和原始数据类型转换

intValue() 是 Java 中的方法,int 是 Java 中的原始类型。它将整数的二进制值存储在变量类型 int 中,而 Integer 是类似于任何其他编程语言的类。

与任何其他引用对象类型一样,Integer 变量包含对 Integer 对象的引用。

Java 中的 intValue() 方法

语法:

public int intvalue();
说明
值得一提的是,该方法不带任何参数。

当将此 Integer 转换为 int 时,此方法是正确的。准确地说,此方法在将此对象转换为 int 类型后返回该对象表示的数值。

下面的代码块做同样的事情。

public class IntValueMethod {
  public static void main(String[] args) {
    @SuppressWarnings("removal") Integer test = new Integer(5000);
    // This object
    int converts = test.intValue();
    // Returns this Iteger value in int type
    System.out.println("The intValue returns the integer value in int " + converts);
  }
}

它也可以处理其他原始数据类型。检查以下代码示例。

// The intValue can also convert Long data type to int
Long abc = 563L;
int xyz = abc.intValue();
System.out.println(xyz);
// IntValue converts Double into int
@SuppressWarnings("removal") Double iAmdoubleType = new Double(19.93);
int dc = iAmdoubleType.intValue();
System.out.println(dc);

输出:

The intValue returns the integer value in int 5000
563
19

Java 中 IntInteger 之间的区别

准确地说,Integer 是一个只有一个 int 类型字段的类。

当你需要一个 int 来像任何其他对象一样工作时,可以使用此类,例如泛型类型或目标。

差异示例:

public class IntVsInteger {
  public static void main(String[] args) {
    // This works
    int b = 100;
    // This will now work
    // Integer b = 100;
    // Similarly, you can parse integer like:
    Integer.parseInt("1");
    // But you can not do it like:
    // int.parseInt("1");
    System.out.println("int b returns: " + b);
  }
}

输出:

int b returns: 100
注意
Java 为每个原始数据类型维护一个包装类。

例如,byte=>Bytefloat=>Floatdouble=>Doubleint=>Integer 等等。

使用 Java 中的 intValue() 方法进行字符串转换

intValue() 的范围取决于一个人的要求。你可以使用此方法实时解决复杂问题。

但首先,你需要锐化你的概念。运行以下程序,然后创建一些你自己的程序。

public class ConvertStringswithIntValue {
  @SuppressWarnings({"removal"})
  public static void main(String[] args) {
    String iAmstring = "4000";
    // this integer takes the string and passes it over to the intValue for
    // conversion
    int iAmint = new Integer(iAmstring).intValue(); // intValue will convert string into int
    System.out.println("The string value has successfully been converted to int value: " + iAmint);
  }
}

输出:

The string value has successfully been converted to int value: 4000

除了这篇文章,如果你想了解更多关于字符串的知识,请参考:Char vs String in Java,如果你有兴趣了解更多关于 Integers 的知识,请参考:Java Integer

作者: Sarwan Soomro
Sarwan Soomro avatar Sarwan Soomro avatar

Sarwan Soomro is a freelance software engineer and an expert technical writer who loves writing and coding. He has 5 years of web development and 3 years of professional writing experience, and an MSs in computer science. In addition, he has numerous professional qualifications in the cloud, database, desktop, and online technologies. And has developed multi-technology programming guides for beginners and published many tech articles.

LinkedIn