Java Program to Convert long to int - The Coding Shala

Home >> Java Programs >> Convert long to int

 Hey there, welcome back to another post. In this post, we are going to learn how to convert long to int in Java.

Java Program to Convert long to int

We can convert long to int using the below ways:

  • Using explicit type casting because here we are converting from higher to lower data type so automatic conversion won't happen.
  • Using intValue() method of Long class.

Java Program: 

/**
 * https://www.thecodingshala.com/
 */

public class Main {

    public static void main(String[] args) {
        long longNum = 155L;

        // Explicit type casting
       // int intNum1 = longNum;  -> this will give error
        int intNum1 = (int) longNum;
        System.out.println("Explicit Converted int number is: " + intNum1);

        // using intValue() method of Long class
        // first convert primitive long to Long object
        Long longObj = longNum;
        int intNum2 = longObj.intValue();
        System.out.println("Using intValue method converted int number is: " + intNum2);
    }
}

Output: 

Explicit Converted int number is: 155
Using intValue method converted int number is: 155


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Single Number 3 LeetCode Solution - The Coding Shala

LeetCode - Number of Good Pairs Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Method Overloading - The Coding Shala