1
0

Data Types in Java

Before we indulge in more serious programming let us have a look at various types of data types available in Java. Java language is rich in data types. Every variable declared has a data type associated with it. The data type specifies the type of value, range of value, and memory space used by the variable. Since Java is a strictly typed language, it is a must to, specify the data type of each variable. A variety of data types are available for the programmer to satisfy his need. Various data types available in Java are:

  1. Built-in data types:
    boolean      
    char      
    byte short int long
    float double    
    void      

     

  2. Derived Data Types:
    class
    array
    interface

     

A built-in data type (Primitive Data Type) is predefined by the language and is named by a reserved keyword. Primitive values do not share a state with other primitive values. The nine primitive data types supported by the Java programming language are:

  • boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its “size” is not precisely defined.
  • char: The char data type is a single 16-bit Unicode character. It has a minimum value of ‘\u0000’ (or 0) and a maximum value of ‘\uffff’ (or 65,535 inclusive).
  • byte: The byte data type is an 8-bit signed two’s complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where memory savings matter. They can also be used in place of int where their limits help to clarify your code; the fact that a variable’s range is limited can serve as a form of documentation.
  • short: The short data type is a 16-bit signed two’s complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings matter.
  • int: The int data type is a 32-bit signed two’s complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else. This data type will most likely be large enough for the numbers your program will use, but if you need a wider range of values, use long instead.
  • long: The long data type is a 64-bit signed two’s complement integer. It has minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.
  • float: The float data type represents a single-precision 32-bit floating point number. Its range of values is -3.4e038 to +3.4e+038 as specified in Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use java.math.BigDecimal class instead. Numbers and Strings cover BigDecimal and other useful classes provided by the Java platform.
  • double: The double data type represents a double-precision 64-bit floating point number. Its range of values is -1.7e308 to +1.7e+308 as specified in Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
  • void: It has no values. It is usually used to specify the type of functions. If a function does not return any value to the calling function, void type is used. It can also represent the generic type i.e. it can represent any other standard type.

A quick look at the size and range of primitive data types

Data Type Size in Bytes Minimum Value Maximum Value
boolean Not-defined False True
char 2 Byte ‘\u0000’ ‘\uffff’
byte 1 Byte -128 +127
short 2 Byte -32768 +32767
int 4 Byte -2147483648 +2147483647
long 8 Byte -9223372036854775808 +9223372036854775807
float 4 Byte -3.4e038 +3.4e038
double 8 Byte -1.7e308 +1.7e+308
void Not-defined Not-defined Not-defined

In addition to the nine primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.String class. Enclosing your character string within double quotes will automatically create a new String object; for example, String s = “this is a string”;. String objects are immutable, which means that once created, their values cannot be changed. The String class is not technically a primitive data type, but considering the special support given to it by the language; you’ll probably tend to think of it as such. You’ll learn more about the String class in subsequent topics. Derived data types will be explained in the due course.

Default Values

It’s not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default value by the compiler. Generally speaking, this default value will be zero or null, depending on the data type. Relying on such default values, however, is generally considered a bad programming style.

The following chart summarizes the default values for the above data types.

Data Type Default Value(for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char ‘\u0000’
String (or any object) null
boolean false

Note: Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

Sample program illustrating some data type

class DataTypeDemo
{
    public static void main(String s[])
    {
        int sum;
        float money;
        char letter;
        double pi;
        sum = 10;  // assign integer value
        money = 2.21f;  // assign float value
        letter = 'A';
        pi = 2.01E6;  // assign a double value
        System.out.println("value of sum = " + sum);
        System.out.println("value of money = " + money);
        System.out.println("value of letter = " + letter);
        System.out.println("value of pi = " + pi);
    }
}

Sample program output

value of sum = 10
value of money = 2.210000
value of letter = A
value of pi = 2010000e+06

Indentation

Perhaps we should say programming style or readability. The most common complaints we would have about beginning JAVA programmers can be summarized as,

  • They have a poor layout
  • Their programs are hard to read

Your programs will be quicker to write and easier to debug if you get into the habit of actually formatting the layout correctly as you write it. The best practice is to properly indent your program.

For instance, look at the program below:

Sample program to demonstrate the bad programming form.

class ProgramLayout{
public static void main(String arg[]){
int sum,loop,kettle,job;
char WhoKnows;
sum=9;
loop=7;
whoKnows='A';
System.out.println("WhoKnows="+WhoKnows+",Kettle="+kettle);}}

It is our contention that this program is hard to read, and because of this, will be difficult to debug for errors by an inexperienced programmer. It also contains a few deliberate mistakes!

Okay then, let’s rewrite the program using proper indentation.

class ProgramLayout{
    public static void main(String arg[])
    {
        int sum,loop,kettle=0,job;
        char WhoKnows;
        sum=9;
        loop=7;
        WhoKnows='A';
        System.out.println("WhoKnows="+WhoKnows+",Kettle="+kettle);
    }
}

We have also corrected the mistakes. The major differences are the { and } braces directly line up underneath each other. This allows us to check indent levels and ensure that statements belong to the correct block of code. This becomes viral as programs become more complex.

We as humans write sentences using spaces between words. This helps our comprehension of what we read (if you do not believe us, try reading the following sentence).

wishihadadollarforeverytimeimadeamistake. The insertion of spaces will also help us identify mistakes more quickly.

good indentation

Indent levels (tab stops) are clearly used for a block of statements, here we clearly see and identify functions and the statements which belong to each {block} or program body.

initialization of variables

The first example prints out the value of the kettle, a variable that has no initial value. This is corrected in the second example.

Leave a Reply