Search⌘ K

A Bit More About Arrays

Explore the declaration and use of char and String arrays in Java. Understand how to initialize arrays, handle index out of bounds exceptions, and pass arrays to methods where modifications affect the original array, enhancing your array handling skills.

Let’s discuss how to declare and use arrays of char & String data types.

Character Arrays

We can declare an Array of char in which we can store characters. Let’s write a code to declare and initialize a character array.

Java
class CharArr {
public static void main(String args[]) {
char[] chArray1 = {
'a',
'b',
'c'
}; //initialization of first char array
char[] chArray2 = new char[5]; //instantiation of second char array
int index = 0;
for (char i = 'v'; i <= 'z'; i++) { //Assiging char values to second array using loop
chArray2[index] = i;
index++;
}
//printing out the stored values in the arrays
System.out.print("The Values stored in ChArray1 are: ");
for (int i = 0; i < chArray1.length; i++) {
System.out.print(chArray1[i] + " ");
}
System.out.println();
System.out.print("The Values stored in ChArray2 are: ");
for (int i = 0; i < chArray2.length; i++) {
System.out.print(chArray2[i] + " ");
}
}
}

Note: Our AI Mentor can explain the above code as well.

The above example has a loop that uses char variable. Each char value is represented by a number, so i++ ...