Java program to Convert Long to Int

Write a Java program to convert long to an integer using the built-in functions int, intValue, and toIntExact. In this language, 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

Java program to Convert Long to Int using intValue

In this language, we can also use the intValue method to convert the long data type to an 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("Result 1 = " + i);
		
		
		sc= new Scanner(System.in);	
	
		System.out.print("Please Enter Value =  ");
		Long num2 = sc.nextLong();
	
		int j = num2.intValue();

		System.out.println("Result 2 = " + j);
	}
}
Result 1 = 24890
Please Enter Value =  2135
Result 2 = 2135

This 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 Value =  ");
		long num1 = sc.nextLong();
		
		int i = Math.toIntExact(num1);

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