English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, we will learn how to convert an integer (int) variable to a long type variable.
To understand this example, you should understand the followingJava programmingTopic:
class Main { public static void main(String[] args) { //Create int variable int a = 25; int b = 34; //Convert int to long //Using type casting long c = a; long d = b; System.out.println(c); // 25 System.out.println(d); // 34 } }
In the above example, we have int type variables a and b. Note the line,
long c = a;
Here, an int type variable will be automatically converted to long. This is because long is a higher data type than int.
Therefore, data truncation will not occur, and the conversion from int to long. This is calledWidening Type Conversion. For more information, please visitJava Type Conversion.
We can convert an int type variable to an object of the class Long. For example,
class Main { public static void main(String[] args) { //Create int variable int a = 251; //Convert to Long Object //Using valueOf() Long obj = Long.valueOf(a); System.out.println(obj); // 251 } }
In the above example, we used Long.valueOf() to convert the variable a to an object of type Long.
In this case, Long is a wrapper class in Java. For more information, please visitJava Wrapper Class.