Java 简明教程

Java - Integer class

Introduction

Java Integer 类将基本类型 int 的一个值封装到一个对象中。类型为 Integer 的一个对象包含一个字段,其类型为 int。

The Java Integer class wraps a value of primitive type int in an object. An object of type Integer contains a single field whose type is int.

Class Declaration

以下是 java.lang.Integer 的声明 −

Following is the declaration for java.lang.Integer class −

public final class Integer
   extends Number
      implements Comparable<Integer>

Field

以下是 java.lang.Integer 类字段 −

Following are the fields for java.lang.Integer class −

  1. static int MAX_VALUE − This is a constant holding the maximum value an int can have, 231-1.

  2. static int MIN_VALUE − This is a constant holding the minimum value an int can have, -231.

  3. static int SIZE − This is the number of bits used to represent an int value in two’s complement binary form.

  4. static Class<Integer> TYPE − This is the class instance representing the primitive type int.

Class constructors

Class methods

Methods inherited

此类从以下类中继承方法:

This class inherits methods from the following classes −

  1. java.lang.Object

Getting int from a String Example

以下示例显示如何使用 Integer 类从字符串获取 int。

The following example shows the usage of Integer class to get int from a string.

package com.tutorialspoint;

public class IntegerDemo {

   public static void main(String[] args) {

      // create a String s and assign value to it
      String s = "+120";

      // create a Integer object i
      Integer i;

      // get the value of int from string
      i = Integer.valueOf(s);

      // print the value
      System.out.println( "Integer value of string " + s + " is " + i );
   }
}

Output

让我们编译并运行上述程序,这将生成以下结果 −

Let us compile and run the above program, this will produce the following result −

Integer value of string +120 is 120