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.

integer types

There are 4 integer data types in Java. byte and short are the 2 uncommon ones, which you may never need:

toggle byte and short

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. int is 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 byte or short instead of an int for small integer values. When you write an integer literal like 3 or 1234 in Java, it is assumed to be of type int.
  • long - The int can go from about -2 Billion to +2 Billion, but sometimes you need to deal with longer numbers. This is where long is 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 long you put a L after it. For example:
    long num1 = 123456789000L;
    long num2 = 12L

floating-point types

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.

End of Free Content Preview. Please Sign in or Sign up to buy premium content.


Contact Us