Tuesday 31 March 2020

Convert Object to int

Approach 1: Using explicit casting.
int i = (int) obj;

Approach 2: Using intValue() method.
i = ((Integer) obj).intValue();

Approach 3: Using parseInt() method.
i = Integer.parseInt(obj.toString());

App.java
package com.sample.app;

public class App {

 public static void main(String args[]) {

  Object obj = 10;

  int i = (int) obj;
  System.out.println("i = " + i);

  i = ((Integer) obj).intValue();
  System.out.println("i = " + i);
  
  i = Integer.parseInt(obj.toString());
  System.out.println("i = " + i);
 }

}

Output

i = 10
i = 10
i = 10



You may like

No comments:

Post a Comment