Java Integer longValue Method

JavaJavaBeginner
Practice Now

Introduction

In Java, we often need to convert one data type value to another. The longValue() method helps us in converting an Integer object into its long equivalent. This lab demonstrates how to use the longValue() method in step-by-step instructions.

Import required classes

In the LongValueDemo.java file, import the java.lang.Integer class and java.util.Scanner class.

import java.lang.Integer;
import java.util.Scanner;

Create the main method

In the LongValueDemo.java file, create the main method.

public class LongValueDemo {
  public static void main(String[] args) {
    // Code goes here
  }
}

Get an integer input from the user

In the main method, add the following code to get an integer input from the user.

Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int input = scanner.nextInt();

Convert integer to long

In the main method, create an Integer object using the input value and then convert it to long using the longValue() method.

Integer integerObject = Integer.valueOf(input);
long longValue = integerObject.longValue();

Output the long value

In the main method, output the long value to the console using System.out.println().

System.out.println("Long value is " + longValue);

Save and compile the Java file

Save the LongValueDemo.java file and open the terminal in the ~/project directory. Use the following command to compile the Java file:

javac LongValueDemo.java

Run the Java program

After the compilation is successful, use the following command to run the Java program:

java LongValueDemo

Summary

This lab demonstrated how to use the longValue() method to convert an Integer object to its long equivalent. We created a Java program that accepts an integer input from the user, converts it to long using the longValue() method, and outputs the long value to the console.

Other Java Tutorials you may like