Java Non-Primitive Data Types
Non-primitive data types in Java are also known as reference types because they refer to objects. Unlike primitive types, non-primitive types are created by the programmer and are not defined by Java (except for String
).
Key Topics
1. Strings
The String
class is used to store a sequence of characters. Strings are widely used in Java programming.
String greeting = "Hello, World!";
System.out.println(greeting);
2. Arrays
An array is a container that holds a fixed number of values of a single type.
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[0]); // Prints: 1
3. Classes and Objects
Classes are blueprints for creating objects. Objects are instances of classes.
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person("Alice", 30);
person.displayInfo();
}
}
Output:
Name: Alice, Age: 30
Key Takeaways
- Non-primitive types are created by the programmer and can be used to create complex data structures.
- They store references to the memory location where the data is stored.
- Understanding non-primitive types is essential for object-oriented programming in Java.