Java Long longValue Method

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to use the longValue() method in Java to get the long equivalent of a Long object. You will also understand the concepts of Boxing and Unboxing in Java.

Declare Long objects

In this step, declare two Long objects with the values of your choice.

Long n1 = 25L;
Long n2 = 46L;

Convert Long objects into long

In this step, use the longValue() method to convert the Long objects into their long equivalent.

// returns the value of the Long object n1 as a long
long i = n1.longValue();
// returns the value of the Long object n2 as a long
long j = n2.longValue();

Display the output

In this step, display the output on the console using System.out.println().

System.out.println("long value is " + i);
System.out.println("long value is " + j);

Get input from the user

In this step, get input from the user using the Scanner class.

System.out.print("Enter the value: ");
Scanner sc = new Scanner(System.in);
long i = sc.nextLong();

Convert long to Long

In this step, convert the long value into a Long object.

Long n = i;

Display the long value

In this step, use the longValue() method to get the long equivalent of the Long object and display it on the console.

System.out.println("Long Value is: " + n.longValue());

Compile and run the code

In this step, compile and run the code in the terminal using the following commands:

javac LongValueMethod.java
java LongValueMethod

Summary

In this lab, you learned how to use the longValue() method in Java to get the long equivalent of a Long object. You also learned the concepts of Boxing and Unboxing in Java.

Other Java Tutorials you may like