Java Data Types
Data types are the kind of data that variables hold in a programming language. A data type is an attribute of data that tells the compiler or interpreter how the programmer plan to use the data. There are two types of data types in Java:
- Primitive data types ( intrinsic or built-in types )
- Non-primitive data types (derived types )
1. Primitive Data Types :
Primitive types are predefined (already defined) in Java. A primitive type starts with a lowercase letter. The primitive data types include char, byte, short, int, long, boolean, float, and double.
The char data type is used to store a single character. The character must be surrounded by single quotes.
The byte data type can store whole numbers from -128 to 127. This can be used instead of int or other integer types to save memory.
The short data type can store whole numbers from -32768 to 32767.
The int data type is the preferred data type when we create variables with a numeric value. The int data type can store whole numbers from -2147483648 to 2147483647.
The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807. This is used when int is not large enough to store the value. Note that you should end the value with an "L".
A boolean data type is declared with the boolean keyword and can only take the values true or false.
The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you should end the value with an "f".
The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that you should end the value with a "d".
2. Non-Primitive Data Types
Non-primitive types are created by the programmer. non-primitive types start with an uppercase letter. The non-primitive data types include Classes, Interface, Strings, and Arrays.
A class is a group of objects which have common properties. It is a user-defined data type with a template that serves to define its properties. To create a class, use the keyword class. Let's learn the class in detail in upcoming chapters.
The interface keyword to create an interface. An interface is slightly different from the class. It contains only ****constants and method declarations.
The String data type is used to store a sequence of characters (text). String values must be surrounded by double quotes.
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To declare an array, define the variable type with square brackets.