Non Primitive Data Types
Non-primitive data types in Java are more complex than primitive data types. They include classes, interfaces, arrays, and enums. Non-primitive data types are also known as reference types because they refer to objects.
1. String #
A String is an object that represents a sequence of characters. It is part of the java.lang package.
Example:
public class Main {
public static void main(String[] args) {
String greeting = "Hello, World!";
System.out.println(greeting); // Output: Hello, World!
}
}
2. Arrays #
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created.
Example:
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.print(num + " "); // Output: 1 2 3 4 5
}
}
}
3. Classes #
A class is a blueprint for creating objects. It can contain fields (variables) and methods to define its behavior.
Example:
public class Main {
public static void main(String[] args) {
Person person = new Person("Alice", 30);
person.displayInfo(); // Output: Name: Alice, Age: 30
}
}
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
4. Interfaces #
An interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields or constructors.
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.makeSound(); // Output: Bark
}
}
interface Animal {
void makeSound();
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Bark");
}
}
5. Enums #
An enum (short for enumeration) is a special data type that enables a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.
public class Main {
public static void main(String[] args) {
Day day = Day.MONDAY;
System.out.println(day); // Output: MONDAY
}
}
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
Summary
- String: Represents a sequence of characters.
- Arrays: Container objects that hold a fixed number of values of a single type.
- Classes: Blueprints for creating objects, containing fields and methods.
- Interfaces: Define methods that must be implemented by classes.
- Enums: Special data types that enable variables to be a set of predefined constants.
Each of these non-primitive data types provides a way to create complex data structures and objects that can be manipulated within your Java programs.