Declaration of Arrays
C++
data_type variable_name[size];
Example
int arr[5];
Java
data_type variable_name[] = new data_type[size];
Example
int arr[] = new int[5];
Let us see the declaration in the code for Java using a problem to find the sum of array elements.
import java.util.*;
class Main {
public static void main (String[] args) {
int a[] = new int[5];
a[0] = 0;
a[1] = 1;
a[2] = 2;
a[3] = 3;
a[4] = 4;
int sum = 0;
for(int i=0;i<5;i++){
sum = sum + a[i];
}
System.out.println(sum);
}
}
We can also create arrays of Objects. Refer to the below code:-
import java.util.*;
class Main {
public static void main (String[] args) {
Student students[] = new Student[3];
students[0] = new Student(0, "Ram");
students[1] = new Student(0, "Laxman");
students[2] = new Student(0, "Shiv");
System.out.println(students[0].name);
}
}
class Student{
int id;
String name;
Student(int id, String name){
this.id = id;
this.name = name;
}
}
In the above code, we have a Student class with id and name as its attributes. Inside the main function, we have made an array Student of size 3.
Also see, Hashcode Method in Java
Cloning of Arrays
We can make the exact copy of the arrays using the clone() method in Java.
import java.util.*;
class Main {
public static void main (String[] args) {
int a[] = new int[5];
a[0] = 0;
a[1] = 1;
a[2] = 2;
a[3] = 3;
a[4] = 4;
int b[] = a.clone();
for(int i=0;i<5;i++){
System.out.println(b[i]);
}
}
}
In the above code, we made an array ‘a’ and then assigned the copy of array ‘a’ to array ‘b’ using the clone() method. clone() method creates a new array and copies the exact values of the previous array in the new array. Try it on online java compiler.
Must Read Array of Objects in Java
FAQs
-
What is an array?
The array is a Data Structure that is used to store data of similar types. All the data is stored in a contiguous manner. We can access any data using the indices. Also, arrays are cache-friendly.
-
How arrays are Cache-Friendly?
In particular, arrays are contiguous memory blocks, so large chunks of them will be loaded into the cache upon first access. This makes it comparatively quick to access future elements of the array.
Key Takeaways
In this blog, we have covered the following things:
- We first discussed what are Arrays.
- Then we discussed how to initialize arrays and their example code.
If you want to learn more about Programming Language and want to practice some questions which require you to take your basic knowledge on Programming Languages a notch higher, then you can visit our here.
Also, see Array in Java
Check out this problem - Search In Rotated Sorted Array
Until then, all the best for your future endeavors, and Keep Coding.
