Fundamentals

Arrays & Strings

Arrays & Strings

1. Arrays

An array is a fixed-size collection of elements of the same data type.

1D Array

java
1int[] numbers = {10, 20, 30, 40};
2
3System.out.println(numbers[0]); // 10
OperationExample
Createint[] arr = new int[5];
Initializeint[] arr = {1, 2, 3};
Accessarr[0]
Updatearr[0] = 10;
Lengtharr.length

2D Array

A 2D array is an array of arrays, commonly used to represent a matrix.

java
1int[][] matrix = {
2 {1, 2, 3},
3 {4, 5, 6}
4};
5
6System.out.println(matrix[0][1]); // 2
java
1for (int i = 0; i < matrix.length; i++) {
2 for (int j = 0; j < matrix[i].length; j++) {
3 System.out.print(matrix[i][j] + " ");
4 }
5}

2. Strings

String is used to represent a sequence of characters.

java
1String name = "Akash";

Strings are immutable, meaning their value cannot be changed after creation.

java
1String s = "Hello";
2s = s + " World";

The original "Hello" string is not modified; a new string is created.

3. Common String Methods

MethodExampleResult
length()"Hello".length()5
charAt()"Hello".charAt(1)'e'
substring()"Hello".substring(1, 4)"ell"
toUpperCase()"hello".toUpperCase()"HELLO"
toLowerCase()"HELLO".toLowerCase()"hello"
equals()"abc".equals("abc")true
equalsIgnoreCase()"ABC".equalsIgnoreCase("abc")true
contains()"Hello".contains("ell")true
startsWith()"Hello".startsWith("He")true
endsWith()"Hello".endsWith("lo")true
indexOf()"Hello".indexOf('l')2
replace()"abc".replace('a', 'x')"xbc"
trim()" Hello ".trim()"Hello"
isEmpty()"".isEmpty()true

Interview Tip: Use .equals() to compare String values instead of ==.

java
1String a = "Hello";
2String b = new String("Hello");
3
4System.out.println(a.equals(b)); // true
5System.out.println(a == b); // false

4. StringBuilder

StringBuilder is used when a string needs to be modified frequently.

Unlike String, StringBuilder is mutable.

java
1StringBuilder sb = new StringBuilder("Hello");
2
3sb.append(" World");
4
5System.out.println(sb); // Hello World
MethodExamplePurpose
append()sb.append("Java")Add text
insert()sb.insert(0, "Hi ")Insert text
delete()sb.delete(0, 3)Delete characters
reverse()sb.reverse()Reverse string
charAt()sb.charAt(0)Get character
setCharAt()sb.setCharAt(0, 'A')Change character
length()sb.length()Get length
toString()sb.toString()Convert to String

5. Arrays.sort()

Used to sort an array in ascending order.

java
1import java.util.Arrays;
2
3int[] arr = {5, 2, 8, 1, 3};
4
5Arrays.sort(arr);
6
7System.out.println(Arrays.toString(arr));
8// [1, 2, 3, 5, 8]

6. Arrays.toString()

Used to convert a 1D array into a readable String representation.

java
1import java.util.Arrays;
2
3int[] arr = {10, 20, 30};
4
5System.out.println(Arrays.toString(arr));
6// [10, 20, 30]

For a 2D array, use Arrays.deepToString():

java
1int[][] matrix = {
2 {1, 2},
3 {3, 4}
4};
5
6System.out.println(Arrays.deepToString(matrix));
7// [[1, 2], [3, 4]]
Next TopicClass & Object