Arrays, String, StringBuffer & Wrapper Classes in Java
1. Arrays in Java
An Array is a fixed-size, indexed collection of homogeneous elements (elements of the same data type) stored in contiguous memory locations.
- Unlike C/C++, Arrays in Java are dynamically allocated Objects stored in Heap memory!
- Every array in Java has a built-in
lengthproperty (arr.length) that stores the number of elements in the array, and Java automatically performs Array Bounds Checking (throwingArrayIndexOutOfBoundsExceptionif you access an invalid index).
A. One-Dimensional (1D) Array
// 1. Declaration + Memory Allocation
int[] marks = new int[5];
// 2. Declaration + Initialization in one line
int[] scores = {85, 92, 78, 88, 95};
// Traversing using .length property
for (int i = 0; i < scores.length; i++) {
System.out.print(scores[i] + " ");
}
B. Two-Dimensional (2D) Array (Matrix)
A 2D array in Java is an “array of arrays” organized into rows and columns:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
// Accessing element at Row 1, Column 2 (0-indexed)
System.out.println(matrix[1][2]); // Output: 6
2. String and StringBuffer Classes in Java
In C/C++, a string is simply a char[] array terminated by \0. In Java, strings are first-class Objects provided by the java.lang package through two core classes: String and StringBuffer.
A. The String Class (Immutable Strings)
- Objects of the
Stringclass are Immutable (Unchangeable). - What does Immutable mean? Once a
Stringobject is created in memory, its text content cannot be modified. If you concatenate or alter a string (s = s + " World"), Java does not change the original string—instead, it creates a brand-newStringobject in the String Constant Pool!
String s1 = "Campus";
s1.concat("Notes"); // Creates a new string "CampusNotes", but s1 still points to "Campus"!
System.out.println(s1); // Output: Campus
s1 = s1.concat("Notes"); // Re-assigning s1 to the newly created object
System.out.println(s1); // Output: CampusNotes
Important Methods of the String Class:
| Method | Example (String s = "Java BCA";) |
Output / Description |
|---|---|---|
length() |
s.length() |
8 (Returns total number of characters) |
charAt(int i) |
s.charAt(2) |
'v' (Returns character at index 2) |
substring(start, end) |
s.substring(0, 4) |
"Java" (Extracts substring from index 0 to 3) |
equals(String s2) |
s.equals("java bca") |
false (Case-sensitive content comparison) |
equalsIgnoreCase(s2) |
s.equalsIgnoreCase("java bca") |
true (Case-insensitive comparison) |
toUpperCase() / toLowerCase() |
s.toUpperCase() |
"JAVA BCA" |
indexOf(String str) |
s.indexOf("BCA") |
5 (Returns starting index of "BCA") |
trim() |
" hello ".trim() |
"hello" (Removes leading & trailing spaces) |
B. The StringBuffer Class (Mutable & Thread-Safe Strings)
- Because
Stringcreates a new object on every modification, modifying strings inside a loop usingStringwastes huge amounts of memory. - To solve this, Java provides
StringBuffer—a Mutable (Modifiable) sequence of characters that grows dynamically and modifies the text in the exact same memory location without creating new objects! - All methods in
StringBufferare synchronized (thread-safe).
Important Methods of the StringBuffer Class:
public class StringBufferDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java");
sb.append(" Programming"); // 1. append(): Adds text at the end -> "Java Programming"
sb.insert(5, "BCA "); // 2. insert(): Inserts at index 5 -> "Java BCA Programming"
sb.replace(5, 8, "DAVV"); // 3. replace(): Replaces index 5-7 -> "Java DAVV Programming"
sb.delete(4, 9); // 4. delete(): Deletes index 4-8 -> "Java Programming"
sb.reverse(); // 5. reverse(): Reverses string in-place!
System.out.println("Reversed: " + sb);
System.out.println("Capacity: " + sb.capacity()); // Default initial capacity is 16 + length
}
}
C. Detailed Comparison: String vs StringBuffer
This is a 100% guaranteed question in DAVV BCA exams!
| Basis | String Class |
StringBuffer Class |
|---|---|---|
| 1. Mutability | Immutable (content cannot be changed once created). | Mutable (content can be modified in-place using append(), insert(), reverse()). |
| 2. Memory Efficiency | Slow and consumes more memory when performing frequent concatenations (creates a new object every time). | Fast and memory-efficient for frequent modifications (modifies the same buffer). |
| 3. Storage Area | String literals are stored in the String Constant Pool inside Heap. | Objects are always allocated on the standard Heap using new. |
4. Built-in reverse()? |
Does not have a built-in reverse() method. |
Has a built-in sb.reverse() method. |
| 5. When to Use? | When string content remains mostly constant (e.g., usernames, file paths, config keys). | When string content changes frequently (e.g., building dynamic SQL queries or reports). |
3. Wrapper Classes in Java
Java is an Object-Oriented language, yet its 8 primitive data types (int, double, char, boolean, etc.) are NOT objects—they exist for raw speed.
However, many advanced Java features (such as Collection Framework ArrayList<Integer>, Serialization, and Multithreading synchronization) only work with Objects, not primitives!
To bridge this gap, Java provides Wrapper Classes in the java.lang package. A Wrapper Class is a class whose object wraps (encapsulates) a single primitive data value inside an Object.
int a = 25;Integer obj = a;int b = obj;The 8 Primitive Types and Their Corresponding Wrapper Classes
| Primitive Type | Wrapper Class (java.lang) |
Utility Parsing Method (String → Primitive) |
|---|---|---|
byte |
Byte |
Byte.parseByte("10") |
short |
Short |
Short.parseShort("100") |
int |
Integer (Full word!) |
Integer.parseInt("500") |
long |
Long |
Long.parseLong("99999") |
float |
Float |
Float.parseFloat("3.14") |
double |
Double |
Double.parseDouble("99.95") |
char |
Character (Full word!) |
(Uses "A".charAt(0)) |
boolean |
Boolean |
Boolean.parseBoolean("true") |
Key Uses of Wrapper Classes + Autoboxing & Unboxing
- Autoboxing: The automatic conversion of a primitive data type into its corresponding Wrapper Object by the Java compiler.
- Unboxing: The automatic conversion of a Wrapper Object back into its primitive data type.
- Utility Conversion Methods (
parseInt,parseDouble): Converting user input strings (from command-line arguments or GUI text fields) into numeric values for calculation.
public class WrapperDemo {
public static void main(String[] args) {
// 1. Autoboxing: Primitive int -> Integer Object automatically
int num = 50;
Integer intObj = num; // Internally: Integer.valueOf(num)
// 2. Unboxing: Integer Object -> Primitive int automatically
int unboxedNum = intObj + 10; // Internally: intObj.intValue() + 10
// 3. String to int conversion using Integer.parseInt()
String strPrice = "450";
int price = Integer.parseInt(strPrice);
System.out.println("Autoboxed Object : " + intObj);
System.out.println("Unboxed + 10 : " + unboxedNum);
System.out.println("Parsed Price + 50: " + (price + 50)); // Output: 500
}
}
💡 Exam Preparation Tips for DAVV BCA
- Notice the spelling of the two Wrapper classes that use full words:
int→Integerandchar→Character. All other 6 simply capitalize the first letter (Byte,Short,Long,Float,Double,Boolean). - In the
StringvsStringBufferquestion, always demonstrate howStringBufferhas.append(),.insert(), and.reverse(), whereasStringis immutable.