Tuesday, 31 March 2020

Java: Convert int to Long

Approach 1: By explicit casting.
Long result1 = (long) i;

Approach 2: Using 'Long.valueOf' method.
Long result2 = Long.valueOf(i);

Approach 3: Using Integer.longValue().
Integer intObj = i;
Long result3 = intObj.longValue();

Approach 4: Using Long constructor.
Long result4 = new Long(i);

App.java
package com.sample.app;

public class App {

  public static void main(String args[]) {
    int i = 10;

    Long result1 = (long) i;

    Long result2 = Long.valueOf(i);

    Integer intObj = i;
    Long result3 = intObj.longValue();

    Long result4 = new Long(i);

    System.out.println("result1 : " + result1);
    System.out.println("result2 : " + result2);
    System.out.println("result3 : " + result3);
    System.out.println("result4 : " + result4);

  }

}

Output

result1 : 10
result2 : 10
result3 : 10
result4 : 10


You may like

No comments:

Post a Comment