I am wondering how to represent 5400000000,5400000001,5400000002,.... in java
(how to represent 5 billion in java)
java ints only hold 2^32-1,
java longs hold 2^64-1,..but i am having a problem representing 5400000000,5400000001,5400000002,....and doubles aren't helping either.
can someone plz provide insight how to represent large values like this (IN JAVA) without having to do multiplication on strings
because Long max = Long(5462205000); just isnt doing it for me.
thx in advance
Your 64-bit integer type can easily hold numbers like 5 billion. Even the signed version can hold values up to 9223372036854775807. Slow bigint libraries not necessary.
To specify these in code you need to use what's called a 'long int literal', which means adding an L to the end of the number. Example:
long x = 5000000000L;
Put an L at the end, e.g.
5400000001L
^
so the compiler knows it's a long
You're having a syntax issue. This will fix your issue nicely:
Long max = new Long(5462205000L);
You need to add the L suffix to indicate this as a Long, otherwise the Java compiler is assuming you're entering an Integer, and this # (anything beyond 2,147,483,647) falls beyond the range of an Integer.
Related
public class ConstantsAndCasting{
public static void main (String args[]){
long hugeNum = 23456013477456L;
int smallNum = (int)hugeNum;
System.out.println(hugeNum);
System.out.println(smallNum);
}
}
The output to the code listed above is:
23456013477456
1197074000
It appears as though when casting a long to an integer value, java retains 32 bits starting from the right working left. What results is a value that is closer to 0 than to the original long value. This totally makes sense from a machine perspective but what is the practical use for this? It seems like you'd be better off using the random number generator to produce 10 random characters.
Thanks in advance!
It's a little unclear how to answer that... As with any type conversion, it iis used when you have a value of one type (in this case, long) but you need a value of a different type (in this case, int).
Yes, sometimes it will give you unwanted results, because of the limitations of the casting operation (Which, in turn, are based on the limitations of the data types). But picking one of those out, and saying "so what's the point in ever doing this operation", would be like saying "if I have two ints, a and b, each valued at 2,000,000,000 - adding them doesn't get the desired result... so what's the point adding ints?"
The primary useful purpose of casting a long to an int is to take a long value which is in the range -2147483648..2147483647 and use that number with code that expects an int value in that range. The behavior with values was outside that range was chosen because:
The designers of Java wanted to fully specify its behavior whenever practical.
Taking the bottom 32 bits and ignoring the top 32 bits was faster than any other consistent course of action which would work sensibly with values in the range -2147483648..2147483647.
There are a number of situations where other courses of action might sometimes allow more efficient code generation if consistency wasn't required, or more useful semantics if speed wasn't required. The approach that was taken, however, offers the best compromise between speed, usefulness, and consistency.
I'm developing a chemistry app, and I need to include the Avogadro's number:
(602200000000000000000000)
I don't really know if I can use scientific notation to represent it as 6.022 x 10x23 (can't put the exponent).
I first used double, then long and now, I used java.math.BigInteger.
But it still says it's too big, what can I do or should this is just to much for a system?
Pass it to the BigInteger constructor as a String, and it works just fine.
BigInteger a = new BigInteger("602200000000000000000000");
a = a.multiply(new BigInteger("2"));
System.out.println(a);
Output: 1204400000000000000000000
First of all, you need to check your physics / chemistry text book.
Avogadro's number is not 602,200,000,000,000,000,000,000. It is approximately 6.022 x 1023. The key word is "approximately". As of 2019, the precise value is 6.02214076×1023 mol−1
(In 2015 when I originally wrote this reply, the current best approximation for Avogadro's number was 6.022140857(74)×1023 mol−1, and the relative error was +/- 1.2×10–8. In 2019, the SI redefined the mole / Avogadro's number to be the precise value above. Source: Wikipedia)
My original (2015) answer was that since the number only needed 8 decimal digits precision, the Java double type was an appropriate type to represent it. Hence, I recommended:
final double AVOGADROS_CONSTANT = 6.02214076E23;
Clearly, neither int or long can represent this number. A float could, but not with enough precision (assuming we use the best available measured value).
Now (post 2019) the BigInteger is the simplest correct representation.
Now to your apparent problems with declaring the constant as (variously) an double, a long and a BigInteger.
I expect you did something like this:
double a = 602200000000000000000000;
and so on. That isn't going to work, but the reason it won't work needs to be explained. The problem is that the number is being supplied as an int literal. An int cannot be that big. The largest possible int value is 231 - 1 ... which is a little bit bigger than 2 x 109.
That is what the Java compiler was complaining about. The literal is too big to be an int.
It is too big for long literal as well. (Do the math.)
But it is not too big for a double literal ... provided that you write it correctly.
The solution using BigInteger(String) works because it side-steps the problem of representing the number as a numeric literal by using a string instead, and parsing it at runtime. That's OK from the perspective of the language, but (IMO) wrong because the extra precision is an illusion.
You can use E notation to write the scientific notation:
double a = 6.022e23;
The problem is with how you're trying to create it (most likely), not because it can't fit.
If you have just a number literal in your code (even if you try to assign it to a double or long), this is first treated as an integer (before being converted to the type it needs to be), and the number you have can't fit into an integer.
// Even though this number can fit into a long, it won't compile, because it's first treated
// as an integer.
long l = 123456788901234;
To create a long, you can add L to your number, so 602200000000000000000000L, although it won't fit into a long either - the max value is 263-1.
To create a double, you can add .0 to your number, so 602200000000000000000000.0 (or 6.022e23 as Guffa suggested), although you should not use this if you want precise values, as you may lose some accuracy because of the way it stores the value.
To create a BigInteger, you can use the constructor taking a string parameter:
new BigInteger("602200000000000000000000");
Most probably you are using long to initialize BigInteger. Since long can represent 64-bit numbers, your number would be too big to fit in to long. Using String would help.
I am a little confused on when to use what primitives. If I am defining a number, how do I know what to use byte, short, int, or long? I know they are different bytes, but does that mean that I can only use one of them for a certain number?
So simply, my question is, when do I use each of the four primitives listed above?
If I am lets say defining a number, how do I know what to use byte, short, int, or long?
Depending on your use-case. There's no huge penalty to using an int as opposed to a short, unless you have billions of numbers. Simply consider the range a variable might use. In most cases it is reasonable to use int, whose range is -2,147,483,648 to 2,147,483,647, while long handles numbers in the range of +/- 9.22337204*1018. If you aren't sure, long won't specifically hurt.
The only reasons you might want to use byte specifically is if you are storing byte data such as parts of a file, or are doing something like network communication or serialization where the number of bytes is important. Remember that Java's bytes are also signed (-128 to 127). Same for short--might be useful to save 2GB of memory for a billion-element array, but not specifically useful for much other than, again, serialization with a specific byte alignment.
does that mean that I can only use one of them for a certain number?
No, you can use any that is large enough to handle that number. Of course, decimal values need a double or a float--double is usually ideal due to its higher precision and few drawbacks. Some libraries (e.g. 3D drawing) might use floats however. Remember that you can cast numeric types (e.g. (byte) someInt or (float) functionReturningADouble();
A byte can be a number from -128 to 127
A short can be a number from -32,768 to 32,767
An int can be from -2^32 to 2^32 - 1
A long is -2^63 to 2^63 - 1
Usually unless space is an issue an int is fine.
In order to use a primitive you need to know the data range of the number stored in it. This depends heavily on the thing that you are modeling:
Use byte when your number is in the range [-128..127]
Use short when your number is in the range [-32768..32767]
Use int when your number is in the range [-231..231-1]
Use long when your number is in the range [-263..263-1]
In addition, byte data type is used for representing "raw" binary data, in which case it is not used like a number.
When you want an unlimited range, use BigInteger. This flexibility comes at a cost: operations on BigInteger can be orders of magnitude more expensive than identical operations on primitives.
Do you know what values your variable will potentially hold?
If it will be between -128 and 127, use a byte.
If it will be between -32,768 and 32,767, use a short.
If it will be between -2^32 and 2^32 - 1, use an int.
If it will be between -2^63 and 2^63 - 1, use a long.
Generally an int will be fine for most cases, but you might use a byte or a short if memory is a concern, or a long if you need larger values.
Try writing a little test program. What happens when you put a value that's too large in one of these types of variables?
Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
See also: the year 2038 problem
The general guidance should definitely be: If you don't have any good reason to pick a specific primitive, pick int.
This has at least three advantages:
Every kind of arithmetic or logical operation will return an int. Hence if you use anything smaller you will have to cast a lot to actually assign values back.
It's the accepted standard for "some number". If you pick anything else, other developers will wonder about the reasons.
It will be the most efficient, although it's likely that the performance difference from using anything else will be minuscule.
That said if you have an array of millions of elements yes you definitely should figure out what primitive fits the input range - I refer you to the other answers for a summary of how large each one is.
#dasblinkenlight
When you are working for large project, you need to optimize the code for each requirement. Apparently you would reduce the memory occupied by the project.
Hence using int, short, long, byte plays a vital role in terms of optimising the memory. When the interger holds a 1 digit value then you declare the integer with int or short, but you can still choose long,float and double technically but to become a good programmer you can try to follow standards.
Byte - Its 8 bit. So it can hold a value from -128 to 127.
short: Its 32 bit. so -32,768 and a maximum value of 32,767
Long- Its 64 bit. -2 (power of) 63 and a maximum value of 2(power of)63-1
float and double- for large decimal values.
Boolean for Yes or No decesions- can hold a value of 1 or 0
Char for characters.
Hope this answer helps you.
I'm a little confused as to how longs work in C.
If I ask for the maximum value of a long in Java I get a number in the quintillions. If I ask for it in C, signed or unsigned, it's in the billions.
Java is built on C... so where is the difference coming from?
I've also tried representing literals with long long values, unsigned/signed long values and long int values. None of them seem to handle numbers past the mid-billions. Why? Am I making a mistake?
The C standard defines long to be at least as large as int. The actual size is implementation dependent. This is not the case for Java, in which long is required to be 64 bits long.
The C99 standard defines fixed size integer types like int64_t defined in stdint.h that you can use if you need fixed size integers on all platforms.
C also has the long long type. That one is guaranteed to be at least 64 bit.
If you want to work with bigger numbers you can use the GNU MP Bignum Library here:
http://gmplib.org/
The numbers and the precision is only limited by available memory of the machine that it runs on.
Hey , i hope i get help with this.
im a coder of a rsps (runescape private server)
and in this game you could like have items and weapons
and the max anmount of a item you can have is 2147000000
and i can change the amount of the max by changing this int
public int maxItemAmount = 2147000000;
and it works
but i want to make it like 3000000000
and i do this
public int maxItemAmount = 3000000000;
and when i compile i get this error
integrer number too large: 3000000000
please guys help me out if you can :)
Integer has an upper bound of 2^31 (2147483648). If you want numbers longer than that, you can use a long or double.
Integers are signed 32-bit values and thus can have a maximum value of 231 = (note that one bit is used for the sign).
You need to change the type of maxItemAmount to long.
you should go for 64 bit types ... i.e: long ...
do ...
public long maxItemAmount = 3000000000L;
A 32-bit signed integer has a range of -232 to 232-1, or − 2,147,483,648 to 2,147,483,647. If you want an integral value outside this range you need to use a 64-bit (long) variable. On the other hand, how likely is it that anyone will have over 2 billion distinct items or weapons? Perhaps, you want to rethink it and keep track of items and their quantities separately. You might also want to consider that changing to use a long may have unexpected consequences if parts of the code assume that it's a 32-bit value.
You can check out the max value of numbers with Integer.MAX_VALUE and Long.MAX_VALUE.
If a long is still not enough for your needs, you can check out the BigInteger class.
Instead of int you should use long. Here you can find more information about the precision of Java primitive data types.
Quoting from the link:
long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.
As other people has sayed, you have to use another data type that support big numbers.
I recommend you using long. For example:
public long maxItemAmount = 3000000000L;
Notice the L at the end of the value. It tells the runtime that 3000000000 is a long value. Or use:
public long maxItemAmount = new Long("3000000000");
See more info on this page.
Also, someone commented using a BigInteger. It's like a String; don't have limit.
However, I recommend you to use it rarely. A long will probably suit your needs.
EDIT: Strictly speaking, BigIntegers and Strings have limit (see comments).