Non-primitive data types in Java are also known as reference types. Unlike primitive data types, which hold their values directly, non-primitive data types hold references to the actual data. Here are the main categories of non-primitive data types in Java:
-
Classes:
- A class is a blueprint for creating objects. It can contain fields (attributes) and methods (functions).
- Example:
String,Scanner,ArrayList.
-
Interfaces:
- An interface is a reference type in Java that is similar to a class but can only contain abstract methods (methods without a body) and constants.
- Example:
Runnable,Comparable.
-
Arrays:
- An array is a collection of elements of the same type, stored in a contiguous memory location. Arrays can hold primitive types or objects.
- Example:
int[] numbers = {1, 2, 3};,String[] names = {"Alice", "Bob"};.
-
Strings:
- Although technically a class,
Stringis often treated as a separate category because it is widely used for handling text. - Example:
String greeting = "Hello, World!";.
- Although technically a class,
Key Characteristics of Non-Primitive Data Types:
- Reference Type: They store references to the actual data rather than the data itself.
- Can Be Null: Non-primitive types can be assigned a value of
null, indicating that they do not reference any object. - More Complex: They can encapsulate multiple values and behaviors (methods).
Example:
Here’s a simple example demonstrating non-primitive data types:
public class NonPrimitiveExample {
public static void main(String[] args) {
// Using a String (non-primitive)
String message = "Hello, Java!";
System.out.println(message);
// Using an array (non-primitive)
int[] numbers = {1, 2, 3, 4, 5};
System.out.println("First number: " + numbers[0]);
// Using a class (ArrayList)
java.util.ArrayList<String> list = new java.util.ArrayList<>();
list.add("Apple");
list.add("Banana");
System.out.println("First fruit: " + list.get(0));
}
}
If you have any further questions or need more examples, feel free to ask!
