Data Types in Java
Data Types in Java
In Java, data types are classified into two categories: primitive data types and reference (or
non-primitive) data types.
Primitive data types are the most basic data types available in Java. There are eight primitive
data types:
1. byte
o Size: 8-bit
o Default value: 0
o Range: -128 to 127
2. short
o Size: 16-bit
o Default value: 0
o Range: -32,768 to 32,767
3. int
o Size: 32-bit
o Default value: 0
o Range: -2^31 to 2^31-1
4. long
o Size: 64-bit
o Default value: 0L
o Range: -2^63 to 2^63-1
5. float
o Size: 32-bit
o Default value: 0.0f
o Range: Approximately ±3.40282347E+38F (7 digits of precision)
6. double
o Size: 64-bit
o Default value: 0.0d
o Range: Approximately ±1.79769313486231570E+308 (15 digits of precision)
7. char
o
Size: 16-bit (Unicode)
o
Default value: '\u0000'
o
Range: '\u0000' (or 0) to '\uffff' (or 65,535)
8. boolean
o Size: not precisely defined
o Default value: false
o Values: true or false
Reference data types are used to refer to objects. They can be any class, array, or interface.
1. Class
o Examples: String, Scanner, Random
o Usage: String str = "Hello";
2. Array
o Usage: int[] arr = new int[10];
3. Interface
o Examples: Runnable, Comparable
o Usage: Runnable r = new MyRunnable();
• Though String is a class, it's often treated specially in Java because of its frequent use
and special behavior.
• Usage: String str = "Hello";
Java automatically converts primitive types to their corresponding wrapper classes when
needed (autoboxing) and vice versa (unboxing).
• Examples:
o Autoboxing: Integer intObj = 5; (converts int to Integer)
o Unboxing: int num = intObj; (converts Integer to int)
Each primitive data type has a corresponding wrapper class in the java.lang package:
Understanding these data types is crucial for effective Java programming, as they form the
foundation of how data is stored, manipulated, and used in Java applications.