Convert Long to numeric primitive data types in Java

Java 8Object Oriented ProgrammingProgramming

Let’s say we have Long object here.

Long myObj = new Long("9879");

Now, if we want to convert this Long to short primitive data type. For that, use the in-built shortValue() method −

// converting to short primitive types
short shortObj = myObj.shortValue();
System.out.println(shortObj);

In the same way convert Long to another numeric primitive data type int. For that, use the in-built intValue() method −

// converting to int primitive types
int intObj = myObj.intValue();
System.out.println(intObj);

The following is an example wherein we convert Long to numeric primitive types short, int, float, etc −

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      Long myObj = new Long("9879");
      // converting to numeric primitive types
      short shortObj = myObj.shortValue();
      System.out.println(shortObj);
      int intObj = myObj.intValue();
      System.out.println(intObj);
      float floatObj = myObj.floatValue();
      System.out.println(floatObj);
      double doubleObj = myObj.doubleValue();
      System.out.println(doubleObj);
   }
}

Output

9879
9879
9879.0
9879.0
raja
Published on 26-Dec-2018 10:43:36
Advertisements