Arrays
An array is a fixed-size object that stores multiple values of the same type. Every array has a length determined at creation time that cannot be changed.int[] numbers = new int[5];
Arrays are objects allocated in heap memory, even when they store primitive values.
Array Declaration
Arrays can be declared in multiple ways.int[] numbers;
String[] names;
Employee[] employees;
Although Java allows the brackets after the variable name, placing them with the type is the standard convention.
int numbers[];
Array Initialization
Arrays may be initialized during declaration.int[] numbers = {10, 20, 30, 40};
Or created first and populated later.
int[] numbers = new int[3];
numbers[0] = 100;
numbers[1] = 200;
numbers[2] = 300;
Default Values
Array elements receive default values.| Type | Default Value |
|---|---|
| Numeric | 0 |
| boolean | false |
| char | '\u0000' |
| Reference | null |
int[] values = new int[3];
System.out.println(values[0]);
Output:
0
Array Length
Every array exposes a public final length field.int[] numbers = {1, 2, 3};
System.out.println(numbers.length);
Output:
3
Unlike Strings, arrays use the length field instead of a method.
Accessing Array Elements
Elements are accessed using zero-based indexing.int[] numbers = {10, 20, 30};
System.out.println(numbers[0]);
System.out.println(numbers[2]);
Attempting to access an invalid index throws ArrayIndexOutOfBoundsException.
Iterating Arrays
Arrays can be traversed using a traditional for loop.for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Or using the enhanced for loop.
for (int number : numbers) {
System.out.println(number);
}
The enhanced for loop cannot access the current index.
Multidimensional Arrays
Java supports multidimensional arrays.int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
Accessing elements:
System.out.println(matrix[1][2]);
Output:
6
Jagged Arrays
Java multidimensional arrays are actually arrays of arrays. Rows may have different lengths.int[][] values = {
{1, 2},
{3, 4, 5},
{6}
};
This is known as a jagged array.
Array Copying
Assigning one array variable to another copies only the reference.int[] first = {1, 2, 3};
int[] second = first;
Both variables refer to the same array. To create an actual copy:
int[] copy = Arrays.copyOf(first, first.length);
Or:
int[] copy = first.clone();
Or:
System.arraycopy(first, 0, copy, 0, first.length);
Comparing Arrays
The== operator compares references.
int[] a = {1, 2};
int[] b = {1, 2};
System.out.println(a == b);
Output:
false
To compare contents:
Arrays.equals(a, b);
For multidimensional arrays:
Arrays.deepEquals(array1, array2);
Arrays Utility Class
The Arrays class provides common operations.Arrays.sort(numbers);
Arrays.binarySearch(numbers, 30);
Arrays.fill(numbers, 100);
Arrays.copyOf(numbers, 5);
Arrays.equals(a, b);
Arrays.toString(numbers);
The Arrays utility class should be preferred over manually implementing these operations.
Variable-Length Arrays
Method parameters can accept arrays of variable size using varargs.void print(int... values) {
for (int value : values) {
System.out.println(value);
}
}
Internally, varargs are represented as arrays.
Strings
A String represents an immutable sequence of Unicode characters.String language = "Java";
Once created, a String object cannot be modified. Operations that appear to modify a String actually create a new String object.
String Creation
Strings can be created using literals.String language = "Java";
Or constructors.
String language = new String("Java");
String literals should generally be preferred.
String Pool
Java maintains a special memory area called the String Pool. Identical string literals share the same object.String a = "Java";
String b = "Java";
System.out.println(a == b);
Output:
true
Using the constructor creates a new object.
String a = "Java";
String b = new String("Java");
System.out.println(a == b);
Output:
false
The String Pool reduces memory consumption and improves performance.
String Immutability
Strings are immutable.String text = "Java";
text.concat(" Programming");
System.out.println(text);
Output:
Java
The returned String must be assigned.
text = text.concat(" Programming");
Immutability enables thread safety, caching, security, and efficient String pooling.
String Comparison
Useequals() to compare contents.
String a = "Java";
String b = new String("Java");
System.out.println(a.equals(b));
Output:
true
The == operator compares object references.
System.out.println(a == b);
Output:
false
For case-insensitive comparison:
a.equalsIgnoreCase(b);
Common String Methods
Frequently used String methods include:text.length();
text.isEmpty();
text.isBlank();
text.charAt(0);
text.substring(1, 4);
text.contains("Java");
text.startsWith("Ja");
text.endsWith("va");
text.indexOf("a");
text.lastIndexOf("a");
text.replace("Java", "Python");
text.toUpperCase();
text.toLowerCase();
text.trim();
text.strip();
text.repeat(3);
text.split(",");
text.matches(regex);
Strings provide a rich API for text processing.
String Concatenation
Strings can be concatenated using the + operator.String fullName = firstName + " " + lastName;
Or using concat().
String fullName = firstName.concat(lastName);
The compiler automatically converts simple concatenations into StringBuilder operations.
StringBuilder
StringBuilder provides mutable strings.StringBuilder builder = new StringBuilder();
builder.append("Java");
builder.append(" Programming");
String result = builder.toString();
StringBuilder should be preferred for repeated string modifications within a single thread.
StringBuffer
StringBuffer is similar to StringBuilder but provides synchronized methods.StringBuffer buffer = new StringBuffer();
buffer.append("Java");
StringBuffer is thread-safe but generally slower than StringBuilder.
StringBuilder vs StringBuffer
- Use StringBuilder for single-threaded code.- Use StringBuffer only when synchronized mutable strings are explicitly required.
- Most modern applications use StringBuilder.
String Formatting
Java supports formatted strings.String message = String.format(
"Employee: %s Age: %d",
"John",
30
);
Formatted strings improve readability when generating dynamic text.
Text Blocks
Java supports Text Blocks for multiline strings.String query = """
SELECT *
FROM employees
WHERE active = true
""";
Text Blocks improve readability for SQL, JSON, XML, HTML, and multiline templates.
String Interning
Theintern() method returns the pooled String representation.
String a = new String("Java");
String b = a.intern();
Interning can reduce memory usage when many identical strings exist.
Character Encoding
Internally, Java Strings represent Unicode characters. Conversion between Strings and byte arrays requires a character encoding.byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
String value = new String(bytes, StandardCharsets.UTF_8);
Explicitly specifying the character set avoids platform-dependent behavior.
Performance Considerations
Array element access provides constant-time performance. String concatenation inside loops repeatedly creates new immutable objects and should be avoided.StringBuilder builder = new StringBuilder();
for (String word : words) {
builder.append(word);
}
Using StringBuilder significantly reduces object creation and garbage collection overhead.
Final Notes
Arrays provide fixed-size indexed storage with efficient random access, while Strings provide immutable text handling with extensive built-in functionality.Understanding array copying, multidimensional arrays, the String Pool, String immutability, String comparison, and choosing between String, StringBuilder, and StringBuffer is fundamental for writing efficient, reliable, and maintainable Java applications.