Java 程序将 Int 转换为 Long

本文介绍了如何编写一个Java程序将整数或int转换为long数据类型。我们可以使用赋值运算符(=)将较低(整数)类型转换为较高(long)数据类型。等于运算符会隐式地将整数转换为long。

在下面的Java示例中,我们声明了一个整数变量并赋值为10。接下来,我们将int值赋给long变量。

public class IntToLong {

	public static void main(String[] args) {
		int i = 10;
		
		long l1 = i;
		
		System.out.println(l1);
	}
}

整数转换为Long输出

10

Java 程序使用 valueOf 将 Int 转换为 Long

将 int 转换为 Long 的另一种方法是初始化整数为 long 或使用 Long.valueOf() 函数。请参阅 Java 中的 程序

import java.util.Scanner;

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

		System.out.println("\n Please Enter any Integer Value :  ");
		i = sc.nextInt();
		
		long l1 = i;
		
		long l2 = new Long(i);
		
		long l3 = Long.valueOf(i);
		
		System.out.println("The first way to convert int to Long = " + l1);
		System.out.println("The second way to convert int to Long = " + l2);
		System.out.println("The third way to convert int to Long = " + l3);
	}
}
Java Program to Convert Int to Long