Java Introduction
Getting StartedÂ
Java Syntax
Java Output – Printing Text
Java Output: Printing Numbers
Java Comments
Java Variables
Java Print Variables
Java: Declare Multiple Variables
Java Identifiers
Real-Life Examples
Java Type Casting
Java Data Types
Java Numbers
Java Boolean
Java Characters and Strings
Real-Life Example
Advanced Billing Example
Non-Primitive Data Types in Java
Type Casting
….
Non-Primitive Data Types in Java
In Java, non-primitive data types (also known as reference types) are used to store references to objects rather than the actual value itself. They provide more flexibility and functionality compared to primitive types.
Think of primitive types as simple building blocks (like bricks), whereas non-primitive types are like fully built houses with rooms, furniture, and appliances—capable of performing more complex tasks.
Key Differences Between Primitive and Non-Primitive Data Types
Feature | Primitive Data Types | Non-Primitive Data Types |
---|---|---|
Definition | Predefined by Java and store simple values. | Created by programmers (except String ) and store references to objects. |
Examples | int , float , char , boolean | String , Array , Class , Object |
Method Support | Cannot call methods directly. | Can call built-in or user-defined methods. |
Case | Always lowercase (e.g., int , char ). | Usually start with an uppercase letter (e.g., String , ArrayList ). |
Null Value | Cannot be null (always holds a value). | Can be assigned null . |
Examples of Non-Primitive Types
- String – Used to store sequences of characters.
- Arrays – Store multiple values of the same type.
- Classes & Objects – Used in object-oriented programming to model real-world entities.
- Interfaces – Define a contract for classes to implement.
Example: Using Non-Primitive Data Types in Java
public class NonPrimitiveExample {
public static void main(String[] args) {
// String example
String message = "Welcome to GoNimbus!";
System.out.println(message.toUpperCase()); // WELCOME TO GONIMBUS!
// Array example
int[] scores = {90, 85, 88};
System.out.println("First score: " + scores[0]);
// Object example
Student student = new Student("John", 21);
student.displayDetails();
}
}
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
void displayDetails() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
Output:
WELCOME TO GONIMBUS!
First score: 90
Name: John, Age: 21
Why Non-Primitive Types Are Powerful
- They allow complex data storage and manipulation.
- They can store multiple attributes in a single entity.
- They support methods for direct operations on data.
- They are essential for Object-Oriented Programming (OOP) in Java.
💡 Pro Tip:
Use primitive types for simple calculations and memory efficiency, but rely on non-primitive types when you need flexibility, reusability, and advanced functionality.