Convert Long to numeric primitive data types in Java



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
Updated on: 2019-07-30T22:30:24+05:30

723 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements