Java Data Types - Data types in Java, Java basic data types, Java primitive data types, Data types in Java, Basic Java data types, Primitive and non primitive data types in Java, Primitive data types in Java, Data types in Java language, Data types in Java programming language, Basic data types in Java, Java primitive data types examples, float size in Java, Size of boolean data type in Java, Java boolean size memory, Java boolean byte, Java boolean size in memory, Boolean size, Boolean in Java example, Default value of boolean in Java, How to use boolean in Java, Size of boolean in Java, Intermediate Type Promotion in Expressions, Type Conversion and Type Casting, Java local variable initialization, Dynamic initialization of variable in Java, Default values of data types in Java, Default value of primitive data types in Java, Primitive data type definition, Initialize long variable in Java.
Java Data Types
As name suggests a data type tells us the type of a data item.
A data type is a classification mechanism whereby it can be identified that
what kind of data is stored inside the variable, and what operations it supports.
Every modern programming language provides a set of basic data types that is built-in
to the language. Likewise, Java provides a richer set of primitive or basic or built-in data
types than other languages like C and C++. There are
eight built-in types supported
by Java to support integer, floating-point, character, and boolean values.
All basic data types
hold numeric data that is directly understood by system.
The following table lists all primitive types, their storage requirements in bytes and the
numeric range they support.
Table 1: List of primitive types in Java
| byte |
1 byte |
128 to 127 |
| short |
2 bytes |
32,768 to 32,767 |
| int |
4 bytes |
2,147,483,648 to 2,147,483, 647 |
| long |
8 bytes |
9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
| float |
4 bytes |
approximately ±3.40282347E+38F
(67 significant decimal digits)
Java implements IEEE 754 standard
|
| double |
8 bytes |
approximately ±1.79769313486231570E+308 (15 significant decimal digits) |
| char |
2 byte |
0 to 65,536 (unsigned) |
| boolean |
not precisely defined* |
true or false |
*boolean represents one bit of information, but its "size" isn't something that's precisely defined.
[Source:
Sun's data type tutorial]
It is worthwhile to note that Java does not support unsigned types. All
int
variants are signed. But
char is an exception, it is unsigned and consumes 2
bytes in memory. It stores 16-bit Unicode
UTF-16 character.
Type
char to be unsigned seems logical because there are no negative characters.
Default Values
While programming in Java you declare and use variables at two places. One, inside a
function that are local to that function. And two, as a class member.
When a variable is declared local to a function, it must be initialized or assigned before
its first use, otherwise compiler reports an error "variable <variable name>
might not have been initialized".
But when a variable is declared as a class member or field, it is not always essential
to assign a value to the member. In that case class members are initialized to some default
values by the compiler. Though, leaving class members uninitialized is not reckoned a good practice.
The following table lists the default values for the data types shown in Table 1.
Table 2: Default values of primitive types in Java
| byte |
0 |
| short |
0 |
| int |
0 |
| long |
0 |
| float |
0.0f |
| double |
0.0d |
| char |
'\u0000' |
| boolean |
false |
| String or other object |
null |
Literals
Literals are fixed values in a program's source code. You can use any primitive type value as
a literal e.g, int, char, float, and boolean.
Integer literals can be used in three flavors in a Java program those are
decimal,
octal (base 8), and
hexadecimal (base 16).
Octal literals are specified in Java program by a leading zero e.g., 07 or 06 are valid octal values,
while 09 or 08 are not, because octal range lies between 0-7. If you try 08 as an octal literal
for experiment, it will result into the error "The literal 08 of type int is out of range".
An hexadecimal constant starts with a leading zero-x (0x) or zero-X (0X). For example, 0xff or 0XFF are
valid hexadecimal literals.
Decimal integer literals neither start with a leading zero nor a zero-x or zero-X. Following
piece of code shows all three variants of integer literals.
int octLit = 0400; //octal equivalent of decimal 256
int hexLit = 0x100; //hexadecimal equivalent of decimal 256
int decLit = 256; // decimal 256
Integer literals create an
int value, which in Java is a 32-bit integer value. Since
Java is strongly typed, you might be wondering how it is possible to assign an integer
literal to one of Java's other integer types, such as
byte or
long,
without causing a type mismatch error. Fortunately, such situations are easily handled.
When a literal value is assigned to a
byte or
short variable,
no error is generated if the literal value is within the range of the target type.
Also, an integer literal can always be assigned to a
long variable.
However, to specify a
long literal, you will need to explicitly tell the compiler that the
literal value is of type
long. You do this by appending an upper or lowercase
L to
the literal. For example, 0x7ffffffffffffff
L or 9223372036854775807
L is the largest long.
Floating-point literals in Java default to
double precision. To specify a float literal,
you must append an
F or
f to the constant. You can also explicitly specify a double literal
by appending a
D or
d. For example,
float f = 89.0; // Type mismatch: cannot convert from double to float
float ff = 89.0f; //OK
double dou = 89.0D; //OK
double doub = 89.0d; //OK
double doubl = 89.0; //OK, by default floating point literal is double
Boolean literals have only two possible values those are
true and
false
Character literals are enclosed in single quotes when they are used for example,
'a' or 'A'.
Whereas string literals are enclosed in double quotes for example, "Coffea arabica".
Variables
A variable is a container which hold some value. And, because Java is a strongly typed language
so every variable must be declared and initialized or assigned before it is used. A variable, in the simplest way,
is declared by placing a valid type followed by the variable name. For example,
byte age; //contains -128 to 127
long population;
float temperature;
double salary;
Don't forget to place a semicolon at the end of every statement because it completes the statement.
While naming a variable you have to adhere to some naming conventions or rules. Such as, a variable name
must begin with a letter (any Unicode character that denotes a letter in a language) followed by
an optional sequence of letters or digits. Special characters except underscore (_) are not permitted in a
variable name, for example, '+' or '?' or '@' are invalid characters for a variable name.
Dynamic Initialization
Initialization is the process of providing value to a variable at declaration time.
A variable is initialized once in its life time. Any attempt of setting a variable's
value after its declaration is called assignment. To use a local variable you have to either initialize or
assign it before the variable is first used. But for class members, the compulsion is not so strict. If you don't
initialize them then compiler takes care of the initialization process and set class members to default values.
Java allows its programmers to initialize a variable at run time also. Initializing a variable at run time is called
dynamic initialization. The following code piece demonstrates it for your reference.
double dynSqrt = Math.sqrt (16);
System.out.println("sqrt of 16 is : " + dynSqrt);
Intermediate Type Promotion in Expressions
Can you think of such a situation where intermediate result of an expression is out of range of
the variable to which the final result has to be assigned, while the final result is in variable's range?
Let's consider an example where you have to compute average age of three octogenarian gentlemen. Suppose that
you store individual's and average age in
byte variables. The ages of all three are
82, 87, and 89 years respectively. Now to compute the average of their age you first have to add all three
ages together and then divide it by 3. But, if you see, as soon as you add all three ages you will get 258
that is beyond the range of
byte (127 is the largest positive value a
byte can contain),
while the final averaged age 86 is in the range of
byte.
Java handles this situation very smartly by promoting intermediate results to integer. But it imposes an extra
overhead on programmers to cast results back to the resultant type,
byte in our case. See the following
piece of code.
byte age1 = 82, age2 = 87, age3 = 89;
byte avgAge = (byte) ((age1 + age2 + age3) / 3);
System.out.println("Average age is : " + avgAge);
In addition to the elevation of
byte to
int, Java defines several type promotion
rules that apply to expressions. First, all
byte and
short values are
promoted to
int, as just described. Then, if one operand is a
long, the whole expression
is promoted to
long. If one operand is a
float, the entire expression is promoted to
float. If any of the operands is
double, the result is
double.
Type Conversion and Type Casting
When value of one variable is assigned to another or a literal is assigned to a variable
then either automatic type conversion takes place or you have to type cast explicitly.
Automatic type conversion is done when either both hands (left and right) sides are of same
type or the left hand (destination) side is larger in size. The latter is called
widening.
For example assigning
byte to
short or
int to
long.
If you wish to assign incompatible types then you will have to type cast at your own and according to
your need. For example
int to
short conversion will not be done automatically,
because
short is smaller than
int. In this case you will have to cast it.
This type of conversion is called
narrowing.
Java is Statically Typed
Note that Java is a
statically-typed language that means the type of a variable must
be known at compile time, as type checking is done during compilation of the code.
The main advantage static typing offers is that type checking is done by the compiler
before the program is executed. The compiler can therefore deduce whether or not a
given variable is capable of performing actions requested of it. For example, the
following piece of code will result into compilation error.
byte s = 90;
s = s + 2; // Type mismatch: cannot convert from int to byte
System.out.println(s);
Because, in statement
s = s + 2; the intermediate term
s + 2 is
automatically promoted to
int and therefore, can not be assigned to a
byte
without the use of a cast. The same example also illustrates the
strong type checking that
Java places severe restrictions on the intermixing of operations that is permitted to occur.
Final Word
Along with primitive set of data types Java provides a rich set of ready made classes for general
data structures and problems. If you would like to read more then following references maybe helpful to you.
References