rmp2150
rmp2150

Reputation: 797

How can I store the number one trillion in Java?

I am attempting to store the number one trillion in a variable. However eclipse continues to worn that it is out of its range even when the variable type is a long.

Here is my code:

long temp = 1;

if(...){
    temp = 1000000000000;
}

If anyone has any insight into why this is occurring, I would really appreciate it.

Upvotes: 2

Views: 9668

Answers (3)

jbranchaud
jbranchaud

Reputation: 6087

An int in Java is a signed 32bit, so the largest int value is 2,147,483,647. Using a long to represent a larger number like 1 trillion is a good option.

long temp = 1000000000000L;

To learn more about Java's primitive data types and their limitations, I would highly recommend referring to this Oracle article on Primitive Data Types.

Upvotes: 0

Chris911
Chris911

Reputation: 4199

Java has a BigInteger type in the math library.

http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigInteger.html

Example:

import java.math.BigInteger;
public class BigIntegerExample 
{
  public static void main(String[] args) 
  {
  BigInteger bigInteger1 = new BigInteger ("123456789");
  BigInteger bigInteger2 = new BigInteger ("112334");
  BigInteger bigIntResult =
    bigInteger1.multiply(bigInteger2); 
  System.out.println("Result is  ==> " + bigIntResult);
  }
}

Upvotes: 0

Charlie Wu
Charlie Wu

Reputation: 7757

try

temp = 1000000000000L;

java in 1000000000000 is recognized as int, add L to the end to make it long

Upvotes: 17

Related Questions