Developers work with many different data types: some defined by the programming language and some defined by the developer. Data types actually represent memory locations.  Java specifically defines all aspects of its built-in data types. This means that no matter what low-level, operating system a Java Virtual Machine (JVM) is running on, the attributes of the data types will remain the same. Many languages depend on the specific machine and compiler implementation for data-type attributes, such as word and integer size.

Primitive data types

Primitive data types are built-in data types, defined by a programming language, that represent real numbers, characters, and integers. Larger, more complex data types are defined using combinations of primitive data types. Many times, there are hardware equivalents of primitive data types. For example, an int primitive type is sometimes stored in a 32-bit hardware register. Java provides an assortment of primitive data types to represent numbers and characters.

Primitive data types are usually grouped into four categories: real numbers, integers, characters, and booleans. Some of these categories contain multiple primitive types. For instance, Java defines two primitive types, float and double, within the real numbers category; it defines four primitive types, byte, short, int, and long, within the integer category; it defines one type, char, within the character category; and it defines one type, boolean, within the boolean category. Table A details Java”s primitive data types.

Java’s primitive data types

All numeric variables in Java are signed, and Java prevents arbitrary casting between data types. Only casts between numeric variables are allowed. For example, a boolean cannot be cast to another data type, and no other data type can be cast to a boolean.

Since all primitive data types are precisely defined in Java, and since direct memory access is not possible, the sizeof operator isn”t provided.

Java”s primitive data types are not objects. To treat a Java primitive data type in an object-oriented fashion, you need to wrap it in a class first.

 Wrapper classes

Java provides built-in wrapper classes for Byte, Short, Boolean, Character, Integer, Double, Float, and Long. These wrapper classes provide some very handy utility methods. For example, the Byte, Float, Integer, Long, and, of course, Double classes all provide a doubleValue() method that converts the value stored in an instance of each class to a Double. Also, all of the wrapper classes provide a static, valueOf(String s) method that converts a given String to the corresponding primitive type. The code snippet in Listing A demonstrates some uses of the wrapper classes.

Leave a Reply