java.lang.Integerクラス

Integerクラスは、プリミティブ型intの値をオブジェクト内に包んだ(wrap)ラッパークラスであり、int値の処理に役立つ定数やメソッドを提供する。

プリミティブ型ラッパークラス
プリミティブ型 ラッパークラス
boolean java.lang.Boolean
char java.lang.Character
byle java.lang.Byte
int java.lang.Integer
long java.lang.Long
double java.lang.Double

Integerのコンストラクタ

Integer(int value)
Integer(String s)

Integerクラスのインスタンスをコンストラクタで生成するのは非効率である。代わりにvalueOfメソッドを使用するのが望ましい。

Integerのstaticメソッド

Integerのstaticメソッドを次に示す。staticメソッドはIntegerをインスタンス化せずに使うことができる。

メソッド説明
parseInt 整数値の文字列表現をintプリミティブ型に変換して返す。
valueOf Integerインスタンスを返す。

Integerのメソッド

Integerのメソッドを次に示す。

メソッド説明
equals 引数で指定したオブジェクトと比較する。

parseInt()

引数で指定した文字列を10進数の整数型として構文解析する。

public static int parseInt(String s) throws NumberFormatException
public static int parseInt(String s, int radix) throws NumberFormatException
s
整数値の文字列表現
radix
基数

引数がnullの場合、空文字("")の場合又は構文解析可能なint値を含まない場合は、java.lang.NumberFormatException例外が発生する。

try {
  int i = Integer.parseInt("1");
  int binary = Integer.parseInt("10", 2);
  int octal = Integer.parseInt("10", 8);
  int decimal = Integer.parseInt("10", 10);
  int hexadecimal = Integer.parseInt("10", 16);
} catch (NumberFormatException e) {
  e.printStackTrace();
}

valueOf()

valueOfメソッドは、引数で指定した値を元にIntegerインスタンスを生成して戻り値として返す。

public static Integer valueOf(int i)
public static Integer valueOf(String s) throws NumberFormatException
public static Integer valueOf(String s, int radix) throws NumberFormatException
i
s
整数値の文字列表現
radix
基数
Integer x = Integer.valueOf(1);
try {
  Integer y = Integer.valueOf("1");
  Integer binary = Integer.valueOf("10", 2);
  Integer octal = Integer.valueOf("10", 8);
  Integer decimal = Integer.valueOf("10", 10);
  Integer hexadecimal = Integer.valueOf("10", 16);
} catch (NumberFormatException e) {
  e.printStackTrace();
}

equalsメソッド

引数で指定したオブジェクトが、このIntegerインスタンスと同じint値であるIntegerオブジェクトの場合、戻り値としてtrueを返す。

引数で指定したオブジェクトがIntegerオブジェクトでない場合又はint値が異なる場合、equalsメソッドは戻り値としてfalseを返す。

boolean equals(Object obj)