Java program to Convert Long to Int

Write a Java program to convert long to int or integer. In Java, we must explicitly convert the long to an integer by placing int before the value because long is a larger data type than the integer.

package NumPrograms;

import java.util.Scanner;

public class longToInt1 {
	private static Scanner sc;	
	
	public static void main(String[] args) {
		
		sc= new Scanner(System.in);	

		System.out.print("Please Enter Long Value =  ");
		long num1 = sc.nextLong();
		
		int i = (int)num1;

		System.out.println("Long To Int Value = " + i);
	}
}
Java program to Convert Long to Int

In Java, we can also use the intValue method to convert the long data type to integer.

package NumPrograms;

import java.util.Scanner;

public class longToInt2 {
	private static Scanner sc;	
	
	public static void main(String[] args) {
		
		Long num1 = new Long(24890);
		int i = num1.intValue();
		System.out.println("Long To Int Value = " + i);
		
		
		sc= new Scanner(System.in);	
	
		System.out.print("Please Enter Long Value =  ");
		Long num2 = sc.nextLong();
	
		int j = num2.intValue();

		System.out.println("Long To Int Value = " + j);
	}
}
Long To Int Value = 24890
Please Enter Long Value =  2135
Long To Int Value = 2135

This Java example uses the Mathematical toIntExact method to convert long to int or integer.

package NumPrograms;

import java.util.Scanner;

public class longToInt3 {
	private static Scanner sc;	
	
	public static void main(String[] args) {
		
		sc= new Scanner(System.in);	

		System.out.print("Please Enter Long Value =  ");
		long num1 = sc.nextLong();
		
		int i = Math.toIntExact(num1);

		System.out.println("Long To Int Value = " + i);
	}
}
Please Enter Long Value =  1345698
Long To Int Value = 1345698