English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)

Java Reader/Writer

Other Java topics

Java program converts int type variable to long

Java Examples

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:

Example1: Java program to convert int to long using type casting

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.

Example2: Java program uses valueOf() to convert int to Long object

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.

Java Examples