More on Data Types
Premium Content - Free Preview
The 4 common primitive data types were covered previously; this node will look at all the different data types in more depth.
In Java everything is an Object except the primitive types which represent actual data in memory. Java uses primitive types to keep things optimized for the computer, though it makes it a bit more confusing for the programmer.
No Object is created when assigning primitive types, so you can just assign a variable a literal value without any
new keyword. For example:
int num = 5; char ch = 'c';
Each type in Java takes up a certain amount of memory and can therefore hold a certain range of values. The size in measured in bits, i.e. a single 1 or 0. The range of an integer data type is simply 2bits. For example, an 8-bit number will be able to hold 256 values.
There are 4 integer data types in Java.
short are the 2 uncommon ones, which you may never need:
byte- This can store integers from -127 to 127. You may have guessed that they take up one byte of memory, or 8 bits. It is sometimes used when dealing with raw data or in special low-memory circumstances.
short- This is a 16-bit type that can store integers from –32,768 to 32,767. It is almost never used.
The next two integer types are more common:
int- This is a 32-bit type which can store numbers from –2,147,483,648 to 2,147,483,647.
intis used for almost all integers in Java, even small ones. For example, its used as a counter in loops and to track locations in arrays.
It is not necessary (or even helpful) to use a
shortinstead of an
intfor small integer values. When you write an integer literal like
1234in Java, it is assumed to be of type
intcan go from about -2 Billion to +2 Billion, but sometimes you need to deal with longer numbers. This is where
longis useful. It is a 64-bit type which can store numbers from - 263 to 263 (which is a 9 followed by 18 digits.)
To mark a number as a
longyou put a
Lafter it. For example:
long num1 = 123456789000L; long num2 = 12L
The above types can only deal with integers, so any decimal numbers that come up will be rounded down to integers. For example
System.out.println(5/2); will print 2 instead of 2.5.
I ended up resolving the problem using a type cast, as otherwise I received errors when adding to the char.
@no_name, that's one way though you don't need a cast. The following code works, and
ccan be incremented too.