Lesson 7: Non-Primitive Data Types: Strings and Arrays Introduction
Non-primitive (or reference) types are fundamentally different from primitives. They do not store the value directly but hold a reference (an address) to the object in memory.
1. Reference Types Overview
- They are created by the programmer or defined by Java (like
String). - They always start with a capital letter (e.g.,
String,Scanner,Car). - Their default value is
null(meaning 'no object reference').
2. The String Class
The String is the most common non-primitive type, representing sequences of characters.
java // String initialization String greeting = "Welcome to the course!"; // Double quotes for String String name = new String("Alice"); // Can also use the 'new' keyword
// Strings are objects, meaning they have methods: int length = greeting.length(); // length will be 22 String upperCase = greeting.toUpperCase(); // WELCOME TO THE COURSE!
3. Introduction to Arrays
An Array is a collection of fixed-size elements of the same data type (either primitive or reference).
Declaration and Initialization
-
Declare: Specify the type and use square brackets
[]. -
Initialize (Method 1: Fixed Size): Create the array using
newand specify the size.java int[] scores = new int[5]; // An array of 5 integers scores[0] = 90; // Arrays are zero-indexed scores[4] = 95; // scores[5] would cause an error (IndexOutOfBoundsException)
-
Initialize (Method 2: Initializer List): Define the elements directly.
java String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri"}; System.out.println(days[1]); // Output: Tue