1. Arrays in Java
Definition
- An array is a collection of elements of the same type stored in a contiguous memory location.
- Arrays are objects in Java and can store both primitive data types and objects.
Declaration and Initialization
// Declaration
int[] arr; // Preferred style
int arr[]; // Valid, but less preferred
// Allocation
arr = new int[5]; // Creates an array of size 5 with default values (0 for int).
// Declaration + Allocation + Initialization
int[] numbers = {10, 20, 30, 40, 50}; // Initializes the array with values.
Key Features
- Indexing: Array indices start at
0
and go up to n-1
, where n
is the array’s length.
- Length: The size of the array is fixed and accessible using the
.length
property.
- Default Values:
- Numeric types (
int
, float
, etc.): 0
- Boolean:
false
- Objects:
null
Types of Arrays
- Single-dimensional Array:
int[] arr = new int[3]; // Example: [0, 0, 0]
- Multi-dimensional Array:
int[][] matrix = { {1, 2}, {3, 4}, {5, 6} }; // 2D array (matrix)
Accessing Array Elements
int[] numbers = {10, 20, 30};
System.out.println(numbers[1]); // Output: 20
Iterating Through an Array
int[] numbers = {10, 20, 30};
for (int num : numbers) {
System.out.println(num); // Outputs 10, 20, 30
}
Key Limitations
- Arrays have a fixed size once created.
- Do not support dynamic resizing. For dynamic collections, use
ArrayList
or other collections.
2. Strings in Java
Definition
- A
String
is a sequence of characters. In Java, String
is an immutable class in the java.lang
package.
Declaration and Initialization
// Declaration
String str;
// Initialization
str = "Hello, World!";
// Declaration + Initialization
String message = "Welcome to Java!";
Key Features
- Strings are immutable, meaning once created, their content cannot be changed.
- Stored in the String pool for memory optimization.
String Methods
Method | Description | Example |
---|
length() | Returns the length of the string. | "Java".length() → 4 |
charAt(index) | Returns the character at the specified index. | "Java".charAt(2) → 'v' |
substring(start, end) | Returns a substring from start to end-1 . | "Java".substring(1, 3) → "av" |
toUpperCase() | Converts all characters to uppercase. | "java".toUpperCase() → "JAVA" |
toLowerCase() | Converts all characters to lowercase. | "JAVA".toLowerCase() → "java" |
equals(otherString) | Compares two strings for equality (case-sensitive). | "java".equals("Java") → false |
equalsIgnoreCase(otherString) | Compares two strings for equality (case-insensitive). | "java".equalsIgnoreCase("Java") → true |
contains(sequence) | Checks if the string contains the specified character sequence. | "Java".contains("av") → true |
replace(oldChar, newChar) | Replaces all occurrences of oldChar with newChar . | "Java".replace('a', 'o') → "Jovo" |
split(regex) | Splits the string based on the provided regex and returns an array. | "a,b,c".split(",") → ["a", "b", "c"] |
trim() | Removes leading and trailing whitespace. | " Hello ".trim() → "Hello" |
String Concatenation
- Using the
+
operator: String greeting = "Hello" + " " + "World!"; System.out.println(greeting); // Output: Hello World!
- Using
concat()
method: String str1 = "Java"; String str2 = "Programming"; String result = str1.concat(" ").concat(str2); System.out.println(result); // Output: Java Programming
Immutability
- Any operation on a
String
creates a new string object instead of modifying the original.
StringBuilder and StringBuffer
- For mutable strings (modifiable):
StringBuilder
: Faster and not thread-safe.
StringBuffer
: Thread-safe (synchronized) but slower.
Comparison: Arrays vs Strings
Feature | Arrays | Strings |
---|
Type | Fixed-size collection of same-type elements. | Sequence of characters (immutable). |
Flexibility | Size is fixed. Cannot resize dynamically. | Content is immutable. |
Usage | Suitable for numeric or grouped data. | Suitable for text and character sequences. |
Efficiency | Faster for bulk data operations. | Optimized for text operations. |