Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are Int and Long data types?
3.
What is Type Casting?
3.1.
Widening Type Casting
3.2.
Narrow Type Casting
4.
Methods to Convert Long to Int in Java
4.1.
Explicit Type casting
4.2.
Using toIntExact() Method 
4.3.
Using intValue() Method
5.
Frequently Asked Questions
5.1.
What is a wrapper class in Java?
5.2.
What is signed representation?
5.3.
How do we represent a negative number in two’s complement representation?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Converting Long to Int in Java

Author Nikhil Joshi
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Hey Ninjas, Welcome back!

You must have gotten stuck sometime on the error “incompatible types: possible lossy conversion from long to int". You have found some quick fixes on the internet and later fall into the same pit.

ogi_image

Well, not anymore! After reading this article titled Converting Long to Int in Java, you will thoroughly know why this error occurs. How can you get rid of this error? You'll learn different ways of converting long to int in Java instead of the first solution appearing on the web.

Before we start, let us first understand what Int and Long data types are in Java. 

Also see, Duck Number in Java and Hashcode Method in Java.

What are Int and Long data types?

Int (for integer) and Long data types store numeric values (without decimal). 

They hold larger numbers than the short data type. 

Int: 
Int representation uses 32-bit signed two's complement integers

Int can store values ranging from  -231 to a maximum of 231-1. 

Long: 

The long data type used 64-bit two's complement integer representation

The long data type can store numbers between a minimum value of -263 and a maximum value of 263-1

From ranges, it is clear that the Long datatype is used to store larger numbers than the Int data type.

long-int-range

We may have some need where we have to convert long to int in Java. This is called Narrow Type Casting.

Also see, Swap Function in Java and Java Ioexception

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is Type Casting?

We might want to convert one datatype into another. 

Suppose we have taken input from a user, which is a number, but in string format. Here, we have to convert the string input to a number( int/long) before processing so that arithmetic operations can be done on the input. 

Here, we will have to convert the data type of the entered string into the desired data type.

Type casting means converting one data type into another datatype.

There are two types of Type Casting:

Widening Type Casting

When a smaller data type converts to a large one. Widening type casting does not involve loss of information and is hence safe to be done by the compiler implicitly. Implicit casting is possible only for the compatible data type.

Example 

public class MyClass {
    public static void main(String args[]) {
      int x = 10;
      long y = x;
      System.out.println("Widening Type Casting !");
      System.out.println("Value of y is "+y);
    }
}


Java implicitly converts an integer variable 'x' to a data type variable long before assigning it to y.


Output

output

Narrow Type Casting

When a variable of a higher data type is converted to a smaller data type, then it is known as Narrow Type Casting. 

Conversion of long to int in Java is an example of Narrow Type Casting. It involves loss of information, and hence the compiler will not do it implicitly, even for the compatible data type.

Example

public class MyClass {
    public static void main(String args[]) {
      long x = 10;
      int y = x;
      System.out.println("Narrow Type Casting !");
    }
}


Output

output

Even though 'x' contains a value that lies in the integer range, the compiler will not do it on its own. It is showing "possible lossy conversion”.

We have now discussed long and int data types and type casting. Let's move on to the next step of converting long to int in Java.

Methods to Convert Long to Int in Java

Following are the three methods to convert long to int in Java:

methods-to-convert-long-to-int-in-java

Explicit Type casting

When a programmer explicitly directs the compiler to convert a variable into a variable of a different data type. It is implemented by using '(newDataType)', as shown in the following example.

Example

public class MyClass {
    public static void main(String args[]) {
      long x = 10L;
      int y = (int) x;
      System.out.println("Explicit Type Casting !");
    }
}


Output

output

Using (int) before x while assigning it to y, converts it first to an integer data type.

Using toIntExact() Method 

Conversion of long to int in Java is possible using toIntExact() function of the Math library. 
Note: It will convert only if the value of the long variable lies in the integer range.

Example

public class MyClass {
    public static void main(String args[]) {
      long x = (long) Math.pow(2,33);
      int y = Math.toIntExact(x);
      System.out.println("Using toIntExact !");
    }
}


Output

output


In this example, ‘x’ contains a value that is outside the range of an integer. Hence, It is showing an “integer overflow” error.

Below is the corrected code: 

public class MyClass {
    public static void main(String args[]) {
      long x = 555L;
      int y = Math.toIntExact(x);
      System.out.println("Using toIntExact !");
      System.out.println("Value of y is "+y);
    }
}


Output

output

 

Using intValue() Method

Instead of using primitive data type, we use an object of class Long, and then we can use this method to convert long to int in Java. The following code demonstrates the conversion:

Example

public class MyClass {
    public static void main(String args[]) {
      Long x = 555L; // long wrapper class datatype
      int y = x.intValue();
      System.out.println("Using intValue !");
      System.out.println("Value of y is "+y);
    }
}


Output

output

Frequently Asked Questions

What is a wrapper class in Java?

Java is an object-oriented language. Its many features depend heavily on the concept of the object. That's why sometimes we need int, long, i.e. primitive datatypes in object form. Wrapper classes are just a method to get objects of such primitive data types. 

What is signed representation?

In signed representation, the most significant bit denotes the sign of the number, i.e. positive or negative. The rest bits (except the most significant bit) make the magnitude of the number. For example, In signed representation, 1111 is -7, and 0111 is +7.

How do we represent a negative number in two’s complement representation?

To represent a negative number in two’s complement notation, reverse each bit of the number and then add 1 to it. That will make the negative number in two’s complement.

Conclusion

We use primitive data types such as integers and long to store numbers. Integer can store data ranging from -231 to 231-1, while long stores data between -263 and -263 +1.  Sometimes, we need to assign the value of a long variable to the int one. This is called narrow-type casting. In this article, we have discussed several methods for conversion of long to int in Java. Explicit type casting, toIntExact(), and intValue() in case of long wrapper class are discussed.

Similarly, If you want to know how to convert a long number to a string in Java, you can read it from here. You can also read our article on Converting Java String to Int.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enrol in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Happy Learning!

Previous article
Separators in Java
Next article
Functional Interface in Java
Live masterclass