0
0

More than 1 year has passed since last update.

Integerクラスについて。

Last updated at Posted at 2022-12-22

Stringからintへの変換

    public static void main(String[] args) {
        Integer i1 = Integer.valueOf("2");
        int i2 = i1.intValue() * 3;
        System.out.println(i2);
    }
6

Integerからintはunboxingのため、intValue()は省略できる

    public static void main(String[] args) {
        Integer i1 = Integer.valueOf("2");
        int i2 = i1 * 3;
        System.out.println(i2);
    }
6

IntegerのConstructorでもString→intできる

    public static void main(String[] args) {
        Integer i1 = new Integer("2");
        int i2 = i1 * 3;
        System.out.println(i2);
    }
6

"a"をintに変換しようとするとExceptionが発生

    public static void main(String[] args) {
        Integer i1 = new Integer("a");
        int i2 = i1 * 3;
        System.out.println(i2);
    }
Exception in thread "main" java.lang.NumberFormatException: For input string: "a"

なお、valueOfに似たものでparseIntがある。return typeがint。

    public static void main(String[] args) {
        int i1 = Integer.parseInt("2");
        int i2 = i1 * 3;
        System.out.println(i2);
    }
6
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0