Java TUTORIAL -Data Types
In the previous post we saw how we could write a simple program that will take the length and width of a rectangle and calculate and print out its area. We had conveniently assumed that the length and width are represented in integers.
In more general cases, the length width or for that matter the area ( that was calculated) may not be an integer. It can be a decimal number. Java provides a number of data types other than integers. Let us rewrite the same program that takes a decimal input and prints the out put in decimals. In this particular example we will use data type double to store decimal values.
class example3
{
public static void main ( String[] args )
{
double length,width,area ; //declaration of variables length,width and area as float
length = 2.1;
width = 6.1;
area = length * width ; // Calculate the area
System.out.println("The Area of rectangle is : " + area );
}
}
If you compile and run this program, you will get the output as follows
C:\javatutorial>javac example3.java C:\javatutorial>java example3 The Area of rectangle is : 12.81 C:\javatutorial> |
The int and double are two types of data types that are called primitive data types. Java provides a number of other data types that we have listed in the table below. Refer them when you need to.
Table 2-2. Java Primitive Data Types
Type | Contains | Default | Size | Range |
---|---|---|---|---|
boolean | true or false | false | 1 bit | NA |
char | Unicode character | \u0000 | 16 bits | \u0000 to \uFFFF |
byte | Signed integer | 0 | 8 bits | -128 to 127 |
short | Signed integer | 0 | 16 bits | -32768 to 32767 |
int | Signed integer | 0 | 32 bits | -2147483648 to 2147483647 |
long | Signed integer | 0 | 64 bits |
-9223372036854775808 to 9223372036854775807 |
float |
IEEE 754 floating point | 0.0 | 32 bits |
±1.4E-45 to ±3.4028235E+38 |
double |
IEEE 754 floating point | 0.0 | 64 bits |
±4.9E-324 to ±1.7976931348623157E+308 |