Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ReferenceJava Reference1

Java long Keyword
Usage and Examples



long Keyword in Java

The long keyword in Java is a primitive data type used to store large integer values. If your program needs to handle numbers beyond the range of int, then long is the ideal choice.

It occupies 64 bits (8 bytes) in memory and can store values from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

Syntax

long variableName = value;

When Should You Use long?

Example 1: Declaring and Printing a long Variable

public class LongExample1 {
    public static void main(String[] args) {
        long population = 7800000000L;
        System.out.println("World Population: " + population);
    }
}
World Population: 7800000000

Explanation: Notice the L at the end of the number. By default, Java treats whole numbers as int. Appending L tells Java this number should be interpreted as a long.

Example 2: What Happens Without L?

public class LongExample2 {
    public static void main(String[] args) {
        long bigValue = 2200000000; // Compilation error
        System.out.println(bigValue);
    }
}
error: integer number too large: 2200000000

Explanation: Java assumes numeric literals are int by default. Without the L, the number is too large to be stored in an int, causing a compilation error.

Example 3: Arithmetic with long

public class LongExample3 {
    public static void main(String[] args) {
        long millisecondsPerDay = 24L * 60 * 60 * 1000;
        System.out.println("Milliseconds in a Day: " + millisecondsPerDay);
    }
}
Milliseconds in a Day: 86400000

Explanation: Using L ensures that at least one operand is a long, so the result is also a long. This avoids overflow when dealing with large products.

Default Value of long

If a long variable is declared as a class-level field and not initialized, Java assigns it a default value of 0L.

public class LongExample4 {
    static long count;
    public static void main(String[] args) {
        System.out.println("Default value: " + count);
    }
}
Default value: 0

Comparison with Other Integer Types

TypeSize (bits)Min ValueMax Value
byte8-128127
short16-32,76832,767
int32-231231-1
long64-263263-1

Key Points to Remember



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M