int as Default Data Type for Literal Integers

Every literal integer in Java is implicitly of type int by default. Also, any operation done with literal integer operands results to int by default. So the following code will be fine and will definitely compile:

byte b = 5; //byte is made up of 8 bits and int with 32 bits

because the compiler implicitly puts a casting to it like this:

byte b = (byte) 5;

But this won’t compile:

byte a = 5;
byte b = 2;
byte c = a + b;

because any operation done with literal integer operands always have the result of type int by default and the compiler thinks about loss of precision without explicit casting. So to make the above code compile, we put an explicit cast like this:

byte a = 5;
byte b = 2;
byte c = (byte) a + b;

which is like telling the compiler that “Don’t worry, I know what I am doing and am aware about the possible loss of precision thing.”. 😀

About Jeffrey A. Aborot

> Background: BS Computer Science, University of the Philippines Baguio. > Work: Advanced Science and Technology Institute - Department of Science and Technology of the Philippines. > Academics: MS Computer Science (on-going), Algorithms and Complexity Laboratory, Computer Science Department, UP Diliman > Languages: Filipino, Tagalog, Cuyunon, English, Java, Python, C. > Operating Systems: Linux, OSX. > Weird Stuff: Bunch of Pentax film cams.
This entry was posted in Software Development and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s