Data Types in Java
Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java:
- Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
- Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data manipulation.
Non-Primitive Data Types
Non-primitive data types are called reference types because they refer to objects.
The main difference between primitive and non-primitive data types are:
- Primitive types are predefined (already defined) in Java. Non-primitive types are created by the programmer and is not defined by Java (except for
String
). - Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot.
- A primitive type has always a value, while non-primitive types can be
null
. - A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase letter.
- The size of a primitive type depends on the data type, while non-primitive types have all the same size.
Data type | |||||
Primitive Data | Non-Primitive Data | ||||
Integer | Decimal | Textual | Logical | String | |
Byte – 8bit | float – 32bit | char – 16bit | boolean – 1bit | Array | |
Short – 16bit | double – 64bit | Enum | |||
int – 32bit | Class | ||||
long – 64bit | Object |
Formula to find the Range of values
-2n-1 to 2n-1-1
Here, n is the number of bits
Example
byte = 8 bits
-28-1 to 28-1-1 = -128 to 127
Integer Category:
Can store whole numbers
Example: 121, 776688998877
Decimal Category
Can store numbers with decimal point.
Example: 22.3, 234.45, 546456.45, 3.14, 9.8
Textual Category
Can store single character.
Example: M, F
Logical Category:
Can Store only two values either true or false
Default Values of Data Type
Data Type | Value |
byte | 0 |
short | 0 |
int | 0 |
long | 0 |
float | 0.0f |
double | 0.0 |
char | 0 or \u0000 |
boolean | false |
Non-primitive | null |
Note : This default values are only applicable to instance and class/static variable.
Program :-
public class DataTypes { public static void main(String args[]) { int id = 111; char gender = 'f'; double age = 65522.35767f; boolean status = true; System.out.println(id); System.out.println(gender); System.out.println(age); System.out.println(status); } }
Join Telegram : Click Here
All Full Stack Java Study Material
Job’s For Fresher