Link to home
Start Free TrialLog in
Avatar of Software Software
Software SoftwareFlag for Austria

asked on

Declaring an Long

Hello,
when defining a long variable. Why is number an int and not a long?

long number = 1000;

Open in new window


Why do I need a L

long number = 1000L;

Open in new window

Avatar of girionis
girionis
Flag of Greece image

You do not need it. It will compile just fine.
Avatar of dpearson
dpearson

In Java the literal "1000" is an integer so this line of code:

long number = 1000;

Open in new window


is really the same as:

int constant = 1000 ;
long number = constant;

Open in new window


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;

Open in new window

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:

short a = 1000;
int b = 1000;
long c = 1000;

Open in new window


But you cannot do

byte d = 1000;

Open in new window


since byte only allows positive values up to 127.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members 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.