What data types exist in Java?
sobes.tech AI
Answer from AI
In Java, there are primitive and reference data types.
Primitive Data Types: They directly store values. Their size and value range are defined by the Java specification.
- Integer types:
byte: 8 bits, from -128 to 127.short: 16 bits, from -32768 to 32767.int: 32 bits, from -2^31 to 2^31-1. The most commonly used integer type.long: 64 bits, from -2^63 to 2^63-1. For very large integers.
- Floating-point types:
float: 32 bits, single precision according to IEEE 754 standard.double: 64 bits, double precision according to IEEE 754 standard. The most frequently used type for fractional numbers.
- Character type:
char: 16-bit Unicode character.
- Boolean type:
boolean: storestrueorfalse.
Reference Data Types: They do not store data directly but store a reference (memory address) to an object containing data. They include classes, interfaces, arrays, and enumerations (enums).
- Classes:
- For example,
String,Integer,ArrayList, and any user-defined class.
- For example,
- Interfaces:
- For example,
List,Map.
- For example,
- Arrays:
- For example,
int[],String[].
- For example,
- Enums:
- They are a special type of class.
Example of declaring and using primitive and reference types:
class DataTypeExample {
public static void main(String[] args) {
// Primitive types
int age = 30; // Integer
double balance = 1500.75; // Floating-point
char initial = 'J'; // Character
boolean isActive = true; // Boolean
// Reference types
String name = "John Doe"; // String class
int[] numbers = {1, 2, 3}; // Array of integers
java.util.ArrayList<String> cities = new java.util.ArrayList<>(); // ArrayList class
cities.add("New York");
System.out.println("Age: " + age);
System.out.println("Balance: " + balance);
System.out.println("Initial: " + initial);
System.out.println("Is Active: " + isActive);
System.out.println("Name: " + name);
System.out.println("First number in array: " + numbers[0]);
System.out.println("First city: " + cities.get(0));
}
}
The key difference: primitive types store values directly, while reference types store references to objects. Primitive types have a fixed size, reference types do not (size depends on the object's content). When assigning primitive types, the value is copied; when assigning reference types, the reference is copied.