编写一个 Java 程序,使用内置函数 int、intValue 和 toIntExact 将 long 转换为整数。在此语言中,我们必须通过将 int 放在值之前来显式地将 long 转换为整数,因为 long 的数据类型比整数大。
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);
}
}

在此编程语言中,我们还可以使用 intValue 方法将 long 数据类型转换为整数或 int 值。
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
此 示例 使用 Math.toIntExact 方法将 long 转换为 int 或整数。
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