- 1 1. What You’ll Learn in This Article (Conclusion First)
- 1.1 1.1 Quickly Understand the Role of long (“What is it used for?” becomes clear)
- 1.2 1.2 Be Able to Explain the long Range (Max/Min) Accurately
- 1.3 1.3 Understand Why Numeric Literals Need “L” (So It Finally Makes Sense)
- 1.4 1.4 Learn How Overflow Works (and How to Prevent It)
- 1.5 1.5 Understand the Difference Between long and Long (Primitive vs Wrapper)
- 1.6 1.6 Your Goal After Reading This Article
- 2 2. What Is Java’s long Type? (Basic Definition)
- 3 3. Understanding the Range of long (Max/Min) Correctly
- 4 4. Why the “L” Suffix Is Required for Numeric Literals (The Most Confusing Point)
- 5 5. Basic Operations with long (Assignment, Calculation, Casting)
- 6 6. Overflow Behavior and Countermeasures
- 7 7. The Difference Between long and Long (Primitive Type vs Wrapper Class)
- 8 8. String ↔ long Conversion (Essential for Input, Configs, and External Data)
- 9 9. Practical Use Cases for long (Real-World Examples)
- 10 10. (Advanced) Treating long as Unsigned
- 11 11. Summary (Most Important Points About long)
- 12 12. Frequently Asked Questions (FAQ)
1. What You’ll Learn in This Article (Conclusion First)
In Java, long is a primitive type for safely handling large integers.
However, there are a few common stumbling points for beginners. In this article, we’ll organize what people searching for java long most likely want to know right now, and explain it step by step so you can understand it in a clear, logical order.
1.1 Quickly Understand the Role of long (“What is it used for?” becomes clear)
long is a 64-bit signed integer, so it can handle much larger numbers than int.
That’s why it’s commonly used in scenarios like these:
- IDs (e.g., database sequences that can grow very large)
- Time (milliseconds in UNIX time, log timestamps, etc.)
- Money (when you want to avoid decimals and manage amounts as integers in the smallest unit)
In other words, if you’re dealing with an integer that could grow large, long becomes extremely important.
1.2 Be Able to Explain the long Range (Max/Min) Accurately
“How big can a long get?” is a question that comes up frequently in real-world work as well.
In this article, we’ll use Long.MAX_VALUE and Long.MIN_VALUE to explain how to safely understand and handle the range.
We’ll also clearly explain common confusion like: “Why does it error even though long should be able to hold values larger than int?”
1.3 Understand Why Numeric Literals Need “L” (So It Finally Makes Sense)
This is the most searched-and-confusing part of long:
- What is the
Lin123L? - Why does assigning
3000000000cause an error? - When should you add
L?
Starting from the key premise that Java treats integer literals as int by default, we’ll explain carefully why L becomes necessary.
Once this clicks, your understanding of long becomes much more stable.
1.4 Learn How Overflow Works (and How to Prevent It)
long can handle big numbers, but it’s not infinite.
If you calculate beyond the maximum value, you may see results that look “wrong” (this is overflow).
In this article, we’ll cover:
- Common examples where overflow occurs
- Why it happens (without going into overly difficult details)
- Practical countermeasures (how to calculate safely)
…all explained in a beginner-friendly way.
1.5 Understand the Difference Between long and Long (Primitive vs Wrapper)
Java has both long and Long.
They look similar, which makes them easy to confuse, but they serve different purposes.
long: primitive type (fast, cannot benull)Long: class (has methods, can holdnull)
We’ll organize this difference so you understand it as a real “how to choose” decision, not just something to memorize.
1.6 Your Goal After Reading This Article
By the end of this article, you should be able to:
- Decide when to use
longand whenintis enough - Explain what
Lmeans and fix related errors yourself - Use
Long.MAX_VALUEand similar constants to handle boundaries safely - Avoid overflow and type-conversion traps in intermediate calculations
- Use
longvsLongappropriately depending on the situation
Once you get here, you’ll move past “I’m kind of unsure about java long” and be able to write code with confidence.
2. What Is Java’s long Type? (Basic Definition)
From here, we’ll solidify the fundamentals of the long type.
The goal is to go beyond “it’s a type that holds big numbers” and understand it correctly as a language specification.
2.1 long Is a “64-bit Signed Integer Type”
In Java, long is a 64-bit (8-byte) signed integer type.
“Signed” means it can represent negative values as well.
Internally, it has these characteristics:
- Bit width: 64 bits
- Values supported: positive numbers, zero, and negative numbers
- No decimals (integer-only)
Because it’s 64-bit, long can handle much larger integers than int.
long a = 10;
long b = -500;
long c = 1234567890123L;All of these assignments work without issue.
2.2 Differences from int, short, and byte
Java has several integer types besides long.
Let’s organize the “size feel” here once.
| Type | Bits | Typical Use |
|---|---|---|
| byte | 8-bit | Binary data, low-level processing |
| short | 16-bit | Special cases (rarely used) |
| int | 32-bit | Standard for typical integer calculations |
| long | 64-bit | Large integers, IDs, time, etc. |
In real-world work, the basic rule of thumb is:
- Normal calculations →
int - Integers that might grow large →
long
This is the standard way to choose.
2.3 Why Not Use long for Everything from the Start?
A common beginner question is something like this:
“If
longcan hold bigger numbers, why not just uselongeverywhere?”
Technically you can, but it’s not always the best choice.
Here’s why:
intoften has a lower computation cost (it’s easier for the CPU to handle)- With arrays and large datasets, memory usage can differ
- Many Java APIs are designed with
intas the default assumption
So, in practice:
- If the size is clearly small → use
int - If it may grow in the future or could overflow → use
long
This is usually the most realistic decision.
2.4 Common Real-World Use Cases for long
long is frequently used in cases like these:
2.4.1 IDs and Sequential Numbers
Database primary keys or unique IDs inside a system can, over long-term operation,
eventually exceed the upper limit of int (about 2.1 billion).
long userId = 10000000001L;In cases like this, long is almost required.
2.4.2 Time and Dates (Timestamps)
In Java, time is often handled as an “integer in milliseconds.”
long now = System.currentTimeMillis();UNIX time in milliseconds becomes a very large number, so int is definitely not enough.
2.4.3 Money (Managing Values in the Smallest Unit)
When money is handled with double, rounding errors can become an issue.
So in real-world systems, it’s common to manage amounts as integers in the “smallest unit.”
// Manage in units of 1 yen
long price = 1500;This is another classic use case for long.
2.5 long Is “Large” but Not “Infinite”
Here’s an important caution:
longcan hold large numbers- But it is not infinite
If a calculation goes beyond the upper or lower limit, overflow occurs.
We’ll cover this in detail in a later section.
3. Understanding the Range of long (Max/Min) Correctly
When working with long, one must-know point is the “numeric range.”
If you use it while being vague about this, it can lead to unexpected bugs and calculation mistakes.
3.1 Where Can You Check long’s Maximum and Minimum Values?
Java provides a way to safely obtain the range of long as constants.
long max = Long.MAX_VALUE;
long min = Long.MIN_VALUE;Long.MAX_VALUE: the maximum value representable bylongLong.MIN_VALUE: the minimum value representable bylong
You don’t need to memorize these numbers.
What matters is the idea of “get them in code.”
3.2 The Actual Numeric Range of long
For reference, the range of long in numbers is:
- Max: 9,223,372,036,854,775,807
- Min: -9,223,372,036,854,775,808
It’s a huge number of digits and not very intuitive, but it’s enough to remember:
- It can handle up to about 9 quintillion
- It’s on a completely different scale than
int(about 2.1 billion)
That mental model is usually sufficient.
3.3 Why Are the Maximum and Minimum Values Asymmetric?
If you look closely, long’s range seems a bit odd:
- Max: +9,223,372,036,854,775,807
- Min: -9,223,372,036,854,775,808
You might wonder, “Why is the negative side larger by 1?”
This happens because Java integers are managed using two’s complement representation.
You don’t need to overthink it—just remember:
By design, one extra value is allocated on the negative side.
That understanding is enough.
3.4 Comparing long with int
Now let’s compare it with int more concretely.
int intMax = Integer.MAX_VALUE; // 2,147,483,647
long longMax = Long.MAX_VALUE; // 9,223,372,036,854,775,807int’s maximum is about 2.1 billion.
In contrast, long has a range that is millions of times larger.
Because of this difference, values like:
- counts
- time (milliseconds)
- cumulative totals
- sequential IDs
are much more likely to exceed what int can hold.
3.5 Caution When Handling Boundary Values
You must be especially careful near the maximum and minimum values of long.
long value = Long.MAX_VALUE;
value = value + 1;
System.out.println(value);If you run this code, no error occurs.
However, the printed value will not be what you expect.
This phenomenon is called overflow.
- As soon as the value exceeds the upper limit, it wraps around into the negative range
- Java does not automatically throw an error for overflow
If you don’t know this behavior, it’s easy to end up thinking, “Why did it suddenly become negative?”
3.6 Don’t “Memorize” the Range—“Protect” It
The key mindset is:
- Don’t memorize the raw numbers
- Use
Long.MAX_VALUE/Long.MIN_VALUE - Be careful with calculations that might cross boundaries
Just keeping this mindset will greatly reduce long-related trouble.
4. Why the “L” Suffix Is Required for Numeric Literals (The Most Confusing Point)
For people searching for java long, the most confusing topic is often the “L” appended to numeric literals.
Once you understand this correctly, many long-related errors and doubts disappear at once.
4.1 In Java, Integer Literals Are int by Default
First, there is a crucial premise.
In Java, integer literals are treated as int by default.
int a = 100;This is obviously fine.
But take a look at the following code:
long b = 3000000000;At first glance it looks okay, but this causes a compile-time error.
The reason is simple:
3000000000exceeds the range ofint- Java first tries to interpret it as an
int - At that point, it is judged as “too large”
That’s why the error occurs.
4.2 What Changes When You Add “L”?
This error is resolved by rewriting the code like this:
long b = 3000000000L;By adding L at the end of the number, you clearly tell Java:
- “This value is a long literal.”
- “Treat it as
longfrom the beginning, notint.”
In short, L is a marker that explicitly specifies the type.
4.3 When Is “L” Required?
You need L in the following cases:
4.3.1 When Writing Numbers That Exceed the int Range
long x = 2147483648L; // exceeds int maxIn this case, L is mandatory.
4.3.2 When You Want to Explicitly Indicate a long
Even if the value is within the int range, you may want to clearly indicate that it should be treated as a long.
long count = 100L;This isn’t required, but it can improve readability.
4.4 Is Lowercase “l” Allowed?
From a syntax perspective, this is valid:
long y = 100l;However, lowercase l is not recommended.
The reasons are simple:
- It’s easy to confuse with the digit “1”
- It can be misread during code reviews
That’s why the common rule is: always use uppercase L.
4.5 Hex, Binary, Underscores, and L
long literals can also be written in bases other than decimal.
long hex = 0x7FFF_FFFF_FFFF_FFFFL;
long bin = 0b1010_1010_1010L;Key points:
_(underscore) can be used as a digit separatorLis placed at the very end- This greatly improves readability for large numbers
4.6 “L” Also Matters Inside Expressions
The following code is a classic beginner trap:
long result = 1000 * 1000 * 1000;Although it looks fine, all intermediate calculations are performed as int.
This can cause overflow during the calculation.
The correct version is:
long result = 1000L * 1000 * 1000;By adding L at the start, the entire expression is evaluated as long, making it safe.
4.7 “L” Is Not Just for Avoiding Errors
To summarize, the role of L is:
- Explicitly tell Java “this is a
long” - Safely handle numbers beyond the
intrange - Prevent overflow during intermediate calculations
- Communicate intent clearly to readers of the code
Think of it not as a mere symbol, but as an important tool for writing safe and readable code.
5. Basic Operations with long (Assignment, Calculation, Casting)
Here we’ll organize the key points of assignment, arithmetic, and type conversion (casting) that always come up when using long.
This is where beginners often say, “I thought it would work, but the result is weird,” so let’s go through it carefully.
5.1 Basic Assignment to long
Assignments to long generally look like this:
long a = 10;
long b = 100L;- Values within the
intrange → can be assigned directly - Values beyond the
intrange → requireL
This follows directly from what we covered earlier.
5.2 Watch Out for “Type Promotion” in Calculations
Java has a rule where the type used in intermediate calculations is determined automatically.
If you don’t understand this, it can easily lead to subtle bugs.
5.2.1 int × int Produces an int
Consider this example:
long result = 1000 * 1000 * 1000;The processing order is:
1000 * 1000→intresult* 1000→ stillint- Then assign the result to
long
Because the intermediate steps stay as int, overflow can occur before assignment.
5.2.2 Force the Calculation to Use long from the Start
To avoid this, it’s important to promote to long at the very beginning.
long result = 1000L * 1000 * 1000;This ensures:
- The entire expression is evaluated as
long - Intermediate overflow is avoided
This is the safest approach.
5.3 Implicit Type Conversion (Safe Cases)
In Java, conversions from a smaller type to a larger type are performed automatically.
int x = 100;
long y = x; // OKThis kind of conversion is safe because no information is lost.
5.4 Cases That Require Explicit Casting (Dangerous)
On the other hand, narrowing conversions such as long → int require special caution.
long big = 3000000000L;
int small = (int) big;This code compiles, but the value is not preserved correctly.
- The higher-order bits are truncated
- The result becomes a completely different number
In other words, casting is not “safe”—it is “forced”.
5.5 How to Decide Whether Casting Is Appropriate
A safe way to think about casting is:
- “The value is guaranteed to fit within
int” → casting may be acceptable - “I don’t know how it might change in the future” → don’t cast
- “Boundary values are possible” → keep it as
long
Rather than forcing values back into smaller types, it’s usually best to continue using a type that’s large enough.
6. Overflow Behavior and Countermeasures
long can handle very large numbers, but once its limits are exceeded, problems are unavoidable.
Here we’ll explain why overflow occurs and how to prevent it, in a beginner-friendly way.
6.1 Overflow Can Occur Even with long
First and foremost, long is still a finite type.
As a result, code like the following does not cause a compile-time error, but produces incorrect values at runtime.
long value = Long.MAX_VALUE;
value = value + 1;
System.out.println(value);The result is a very large negative number, even though you just added 1 to the maximum value.
This is not a bug—it’s exactly how Java is specified to behave.
6.2 Why Does the Value “Wrap Around”?
Java integers are internally represented using two’s complement.
Because of this representation:
- The maximum value is exceeded
- The most significant bit flips
- The value wraps around into the negative range
The key point is that Java does not automatically detect overflow.
If you take no precautions, you may continue using invalid values without noticing.

6.3 Typical Situations Where Overflow Becomes a Problem
You need to be especially careful in scenarios like these:
- Cumulative monetary calculations
- Incrementing counters or totals
- Time calculations (adding durations)
- Automatic generation of IDs or sequence numbers
All of these values tend to grow gradually, meaning they can eventually reach the upper limit during long-term operation.
6.4 Calculating Safely (Using Math.addExact, etc.)
Java provides methods that detect overflow explicitly.
long result = Math.addExact(a, b);This method behaves as follows:
- If the result is within the
longrange → returns normally - If it exceeds the range → throws
ArithmeticException
There are similar methods as well:
Math.subtractExactMath.multiplyExact
For calculations where safety is critical, these methods let you detect abnormal conditions immediately.
6.5 Checking in Advance with if Statements
You can also avoid exceptions by checking conditions beforehand.
if (value > Long.MAX_VALUE - add) {
// Overflow may occur
}This approach is useful when:
- The code runs very frequently
- You want to avoid exceptions for performance reasons
6.6 What If long Is Not Enough?
If:
- The value may exceed the
longrange - Precision is extremely important (for example, in financial calculations)
then continuing to use long is not the right choice.
In such cases, consider:
BigInteger(arbitrary-precision integers)BigDecimal(arbitrary-precision decimals)
Choosing not to “force” long is also part of good design.
7. The Difference Between long and Long (Primitive Type vs Wrapper Class)
Java has two very similar-looking types: long and Long.
They serve clearly different purposes, and not understanding how to use them properly can lead to bugs or design mistakes.
7.1 Fundamental Differences Between long and Long
Let’s organize the differences first.
| Item | long | Long |
|---|---|---|
| Type | Primitive | Class (Wrapper) |
| null allowed | No | Yes |
| Methods | None | Available |
| Memory efficiency | High | Slightly lower |
| Main usage | Calculations, high-performance logic | Collections, API integration |
In simple terms:
- Main choice for numeric calculations →
long - When you need an object →
Long
That’s the basic idea.
7.2 What Is the Long Class?
Long is a class that allows you to treat a long value as an object.
Long a = 10L;
Long b = Long.valueOf(20);Using Long enables you to:
- Represent
null - Use methods for conversion and comparison
- Store values in collections (
List,Map, etc.)
7.3 Autoboxing and Unboxing
Java automatically converts between long and Long.
Long a = 10L; // Autoboxing (long → Long)
long b = a; // Unboxing (Long → long)This is convenient, but it comes with important caveats.
7.3.1 Beware of null and Runtime Exceptions
Long a = null;
long b = a; // NullPointerExceptionIf unboxing occurs when a Long is null,
a runtime exception is thrown.
Therefore:
- Value always exists →
long - Value may be missing or unset →
Long
This distinction is extremely important.
7.4 Comparison Pitfalls (== vs equals)
When comparing Long objects, you should not use ==.
Long a = 100L;
Long b = 100L;
System.out.println(a == b); // May be true
System.out.println(a.equals(b)); // Always true== compares references, while equals compares values.
With Long, internal caching can make behavior especially confusing.
Always use equals when comparing values.
This is the safe rule.
7.5 Commonly Used Constants and Methods in Long
The Long class provides features that are frequently used in practice.
Long.MAX_VALUE
Long.MIN_VALUEThese constants are essential for safely handling long boundaries.
Conversion methods are also very common:
long x = Long.parseLong("123");
Long y = Long.valueOf("456");parseLong: returns a primitivelongvalueOf: returns aLongobject
Choose based on your use case.
7.6 How to Decide Which One to Use
If you’re unsure, use these guidelines:
- Calculations and numeric logic →
long - Possible
nullvalues →Long - Storing in collections →
Long - Performance-sensitive code →
long
In practice, the most stable approach is: use long by default, and use Long only when necessary.
8. String ↔ long Conversion (Essential for Input, Configs, and External Data)
In real-world applications, you’ll more often convert values to long from strings than write them directly in code.
- Form inputs
- CSV or JSON data
- Configuration files
- Environment variables
Here, we’ll organize safe and correct ways to convert between strings and long.
8.1 String → long (Parsing Numbers)
The two most common ways to convert a string to long are:
8.1.1 Using Long.parseLong (Most Common)
long value = Long.parseLong("12345");- Return type:
long - On failure: throws
NumberFormatException
This is the default choice when you want to use the value in calculations.
8.1.2 Using Long.valueOf
Long value = Long.valueOf("12345");- Return type:
Long - May use internal caching
This is useful when storing values in collections or when null handling is required.
8.2 Handling Conversion Failures and Exceptions
The following strings will fail to convert:
Long.parseLong("abc");
Long.parseLong("12.3");
Long.parseLong("");All of these throw NumberFormatException at runtime.
When dealing with external input, always use exception handling:
try {
long value = Long.parseLong(input);
} catch (NumberFormatException e) {
// Handle invalid numeric input
}In practice, never assume input is always valid.
8.3 long → String (For Display and Output)
There are several ways to convert long values to strings.
8.3.1 Using Long.toString
long value = 12345;
String text = Long.toString(value);This method is specific to long and clearly expresses intent.
8.3.2 Using String.valueOf
String text = String.valueOf(value);This approach is also common and provides null safety.
8.4 Which Conversion Method Should You Choose?
Use these guidelines:
- You need a numeric value for calculations →
Long.parseLong - You need an object →
Long.valueOf - Display or logging →
String.valueOf/Long.toString
8.5 Key Points to Remember During Conversion
Always keep these in mind:
- Never trust input blindly
- Write code assuming exceptions can occur
- Be mindful of boundary values (MAX / MIN)
- Consider future growth in digit length
Following these principles will greatly reduce conversion-related bugs.
9. Practical Use Cases for long (Real-World Examples)
Now that we’ve covered the fundamentals, let’s look at why long is chosen in real-world systems, case by case.
9.1 UNIX Time and Timestamps
A typical way to get the current time in Java is:
long now = System.currentTimeMillis();UNIX time in milliseconds already far exceeds the int range, so long is effectively the standard.
- Log timestamps
- Measuring execution time
- Expiration and timeout handling
9.2 Database IDs and Sequential Keys
Most systems use sequential IDs to identify records.
long userId;
long orderId;Over long periods of operation:
- Record counts can exceed hundreds of millions or billions
- Future expansions can increase digit length
Using long from the start reduces the risk of painful type changes later.
9.3 Money Management (Avoiding Floating-Point Errors)
Using double or float for money can introduce rounding errors.
A common solution is to store amounts in the smallest unit using long.
// Manage amounts in yen
long price = 1500;- Accurate addition and subtraction
- Simpler comparisons
- Easier overflow detection
9.4 Counters, Totals, and Accumulators
Values that continuously increase—such as access counts—are also good candidates for long.
long totalCount = 0;
totalCount++;Even if the value starts small, choosing long anticipates future growth.
9.5 Hash Values and Internal Calculations
In algorithms or internal processing, you may need:
- Temporary storage of calculation results
- More range than
int, but not arbitrary precision
long often provides the right balance.
9.6 Is “Just Use long” Always Correct?
The key takeaway:
- Using
longblindly is not always correct - But if the value may grow, it’s a strong candidate
At design time, simply thinking about:
- The maximum expected value
- Whether the value grows over time
makes the choice much clearer.
10. (Advanced) Treating long as Unsigned
Java’s long is a signed integer.
If you want to maximize the non-negative range, you need a different approach.
10.1 Java Has No Unsigned long Type
Unlike C or C++, Java does not provide an unsigned long type.long always uses this range:
-9,223,372,036,854,775,808+9,223,372,036,854,775,807
10.2 When You Want Unsigned Semantics
In practice, you may want unsigned behavior in cases like:
- Bitwise operation results
- Hash values
- Network protocol numbers
- IDs or tokens treated as raw numbers
10.3 Using Unsigned Methods in the Long Class
The Long class provides methods for unsigned operations:
Long.compareUnsigned(a, b);
Long.divideUnsigned(a, b);
Long.remainderUnsigned(a, b);This allows:
- Keeping the internal representation as
long - Applying unsigned logic only to comparisons or calculations
10.4 Displaying Values as Unsigned
String text = Long.toUnsignedString(value);This converts a value to a string as if it were unsigned.
10.5 Don’t Force Unsigned Usage
For typical business data—money, counts, time—
signed long is safer and clearer.
Think of unsigned handling as a specialized tool, not the default.
11. Summary (Most Important Points About long)
Let’s recap the most important points:
longis a 64-bit signed integer- Ideal for large integers (IDs, time, money, etc.)
- Use
Long.MAX_VALUE/Long.MIN_VALUEto handle ranges safely - Add
Lto numeric literals when required - Beware of
int-based overflow during intermediate calculations - Overflow can occur even with
long - Use
Math.addExactand related methods for safety - Default to
long, useLongonly when necessary - Don’t underestimate string conversion, boundaries, or exception handling
Keeping these points in mind will help you avoid most long-related issues.
12. Frequently Asked Questions (FAQ)
12.1 Q. What are the maximum and minimum values of long?
A.
You don’t need to memorize the numbers.
Use these constants:
Long.MAX_VALUE;
Long.MIN_VALUE;12.2 Q. Is the “L” suffix always required?
A.
It is required for numeric literals that exceed the int range.
It’s also useful when you want calculations to be evaluated as long.
12.3 Q. Can overflow occur even with long?
A.
Yes. Java does not throw errors automatically.
Use methods like Math.addExact when detection is important.
12.4 Q. Should I use long or Long?
A.
Use long by default.
Use Long only when you need null or collections.
12.5 Q. What is the correct way to convert a string to long?
A.
The most common approach is:
long value = Long.parseLong(str);Always remember to handle exceptions for external input.


