QUESTIONS & ANSWERS
JAVA
Explain different types of Arrays in Java.
In Java, there are two types of arrays: primitive arrays and object arrays.
-
Primitive Arrays: Primitive arrays store values of primitive data types such as int, boolean, char, float, double, byte, and short. They are used to hold basic data types and have the same memory allocation as their respective data types. Here are some examples of how to declare and initialize primitive arrays in Java:
int[] intArray = new int[5]; // Declare and initialize an int array with 5 elements boolean[] boolArray = {true, false, true}; // Declare and initialize a boolean array with 3 elements char[] charArray = {'a', 'b', 'c'}; // Declare and initialize a char array with 3 elements
- Object Arrays: Object arrays store objects of any class. They are used to hold complex data types such as Strings, custom objects, and arrays themselves. Here are some examples of how to declare and initialize object arrays in Java:
String[] stringArray = new String[3]; // Declare and initialize a String array with 3 elements Object[] objectArray = {new Integer(1), "two", new Double(3.0)}; // Declare and initialize an object array with 3 elements of different types MyClass[] classArray = new MyClass[2]; // Declare and initialize a custom object array with 2 elements
In addition to these basic types, Java also supports multi-dimensional arrays, which are arrays of arrays. Multi-dimensional arrays can be declared and initialized using the same syntax as single-dimensional arrays, with additional square brackets to indicate the number of dimensions. For example:
int[][] twoDimArray = new int[3][4]; // Declare and initialize a 2D array with 3 rows and 4 columns
Overall, arrays are an important and versatile data structure in Java, used extensively in programming to store and manipulate collections of related data.