Software Software
asked on
Declaring an Long
Hello,
when defining a long variable. Why is number an int and not a long?
Why do I need a L
when defining a long variable. Why is number an int and not a long?
long number = 1000;
Why do I need a L
long number = 1000L;
You do not need it. It will compile just fine.
In Java the literal "1000" is an integer so this line of code:
is really the same as:
which still compiles (as girionis pointed out) because you can convert an integer to a long.
But if you want to create a constant which is itself a long, you need to let Java know by adding the L at the end:
long number = 1000;
is really the same as:
int constant = 1000 ;
long number = constant;
which still compiles (as girionis pointed out) because you can convert an integer to a long.
But if you want to create a constant which is itself a long, you need to let Java know by adding the L at the end:
long constant = 1000L ; // The right hand side is now a long
long number = constant;
Strictly speaking the number 1000 is a short, an integer and a long, since it falls within the range of all these three data types. You can represent 1000 with 16, 32 and 64 bits. Therefore all of them are valid:
But you cannot do
since byte only allows positive values up to 127.
short a = 1000;
int b = 1000;
long c = 1000;
But you cannot do
byte d = 1000;
since byte only allows positive values up to 127.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIALMembers can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.