StudySmarter - The all-in-one study app.
4.8 • +11k Ratings
More than 3 Million Downloads
Free
Americas
Europe
Discover the extensive power and functionality inherent within Java Arrays through this comprehensive guide. You'll explore the fundamentals of Java Arrays, delve into their syntax, and examine specific array types. This guide also offers key insights into array manipulation in Java, paving the way for you to implement your newfound knowledge through a variety of practical examples. With a keen focus on facilitating greater understanding, this resource will help you to further enhance your skills in the field of Computer Science. It is the tool that you need to master the art of using Java Arrays effectively.
Explore our app and discover over 50 million learning materials for free.
Lerne mit deinen Freunden und bleibe auf dem richtigen Kurs mit deinen persönlichen Lernstatistiken
Jetzt kostenlos anmeldenDiscover the extensive power and functionality inherent within Java Arrays through this comprehensive guide. You'll explore the fundamentals of Java Arrays, delve into their syntax, and examine specific array types. This guide also offers key insights into array manipulation in Java, paving the way for you to implement your newfound knowledge through a variety of practical examples. With a keen focus on facilitating greater understanding, this resource will help you to further enhance your skills in the field of Computer Science. It is the tool that you need to master the art of using Java Arrays effectively.
An Array is essentially a collection of elements (values or variables) that are accessed through computed indices. The size of an Array is established when the Array is created and remains constant thereafter.
// Declare an array int[] anArray; // allocate memory for 10 integers anArray = new int[10];Here's a list of some key points you need to remember:
Method | Description |
public static int binarySearch(Object[] a, Object key) | Searches the specified array of the specified value using the Binary Search algorithm. |
public static boolean equals(long[] a, long[] a2) | Returns true if the two specified arrays of longs are equal to one another. |
Did you know that the size of an array in Java can be determined using the length field? For example, if you have an array named Sample, 'Sample.length' would return its size.
int[] myArray;To actually create or instantiate the Array, the new keyword comes into play. It lets us allocate memory for the known number of elements of a particular type:
myArray = new int[5];And to declare and instantiate in one line, Java allows you to combine the two steps:
int[] myArray = new int[5];In these examples, 'myArray' is a variable that holds an array of integers. The number in the square brackets is the size of the Array, indicating how many integers 'myArray' can hold. You can also instantiate an array with values:
int[] myArray = { 5, 10, 15, 20, 25 };In this instance, 'myArray' is an Array that holds five integers, which are given at the time of creation. The array size is implicitly set to the number of elements provided in the curly braces.
int[] myArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };Here, you have an integer array named 'myArray' initialized with 10 elements. For an array with complex elements like objects, you can initialise it as follows:
Car[] carArray = new Car[]{ new Car("Red"), new Car("Green"), new Car("Blue")};This statement initialises the `carArray` with three Car objects, each with a different colour. Also, you can initialise a multi-dimensional Array in Java, which amounts to an "array of arrays".
int[][] multiArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};Here, rather than numeric indices, each inner array is contained within the outer array and possesses its own indices.
int[] numArray = {10, 20, 30, 40, 50};If you need to find the length or size of `numArray`, use the 'length' property like so:
int size = numArray.length;The variable `size` will hold the value 5, since `numArray` contains five elements. The length property proves particularly useful when you need to iterate over an array using a loop. For instance,
for (int i = 0; i < numArray.length; i++) { System.out.println(numArray[i]); }This loop prints every element in `numArray` using the 'length' property to establish the loop's termination condition. Importantly remember, the 'length' property in Java gives the total number of slots available in the Array, not the number of slots currently filled. This feature matters particularly when dealing with arrays where all slots aren't filled, or default values are acceptable.
int[][] twoDArray = { {1, 2}, {3, 4}, {5, 6} };In this example, '1' is located at position 0, 0 (first row, first column), while '6' resides at position 2, 1 (third row, second column). To better illustrate, let's define commonly used terms in the context of 2D arrays:
Element: Each individual value is known as an element of the array. For instance, 1, 2, 3, 4, 5, 6 are elements.
Row: Each horizontal line of values in the matrix is referred to as a row.
Column: Each vertical line of values is usually spoken of as a column.
int[][] my2DArray;Creating or instantiating the 2D array is another step. For example, the line below creates a 2D array of integers with 3 rows and 2 columns.
my2DArray = new int[3][2];Note: Java allows ragged arrays or arrays where each row can be of different lengths. In such cases, you only declare the number of rows, and every row can be initialised with a different number of columns. Accessing and setting values in 2D arrays involves two indices - one for the row and one for the column.
my2DArray[0][0] = 1; // sets the first element int x = my2DArray[0][0]; // retrieves the first element
`java.util.Arrays.deepToString()`: It's a handy method present in Java that converts 2D Arrays into a readable String format which is very helpful during Debugging sessions.
ArrayListIn this case, "Hello" is at index 0, and "World" is at index 1.myArrayList = new ArrayList (); myArrayList.add("Hello"); myArrayList.add("World");
Element: Each value inside the ArrayList is known as an element.
String element = myArrayList.get(0); // retrieves "Hello"Removing an element is just as straightforward with the `remove` method:
myArrayList.remove(0); // removes "Hello"ArrayLists become especially useful when working with large amounts of data because of methods that offer excellent functionality, such as `sort`, `contains`, and `isEmpty`. They also support iteration using loops and Iterators. Note: It's advisable to always specify the data type in the ArrayList during declaration to prevent inserting unwanted data types (This practice is known as creating a **Generic ArrayList**).
int[] numArray = {10, 20, 30, 40, 50};For converting the above array to a String, you use the `Arrays.toString()` method.
String arrayAsString = Arrays.toString(numArray);Here, `arrayAsString` now holds the String `"[10, 20, 30, 40, 50]"`. The same can be achieved for multi-dimensional arrays using the `Arrays.deepToString()` method as the `toString()` method in such cases would produce results that aren't very readable.
int[][] multiArray = { {1, 2}, {3, 4}, {5, 6} }; String multiArrayString = Arrays.deepToString(multiArray);Here, the `multiArrayString` holds `"[ [1, 2], [3, 4], [5, 6] ]"`.
toString(): This method returns a string representation of the contents of the specified array. If the array contains other arrays as elements, they are converted to strings themselves by the `Object.toString()` method inherent in the root class `Object`.
deepToString(): This method is designed for converting multidimensional arrays to strings. If an element is a nested array, this method handles it as a deeply nested array.
int[] unsortedArray = {5, 3, 9, 1, 6, 8, 2}; Arrays.sort(unsortedArray);Now, `unsortedArray` is `{1, 2, 3, 5, 6, 8, 9}`. For arrays of objects, you must ensure that the class of the objects implements the `Comparable` interface or provide a `Comparator` object to the `sort()` method.
Student[] studentsArray = { new Student("John", 15), new Student("Alice", 16), new Student("Bob", 14) }; Arrays.sort(studentsArray, Comparator.comparing(Student::getAge));In this example, the `studentsArray` is sorted in the ascending order of ages. The `Arrays.sort()` method uses a variation of the QuickSort algorithm called Dual-Pivot QuickSort. This algorithm is chosen for its efficient \(O(n \log(n))\) average-case time complexity. Remember, apart from ascension, Java arrays can also be sorted in descending order using the `Arrays.sort()` method in combination with the `Collections.reverseOrder()` method for object arrays. Finally, Java arrays can be sorted partially from an index to another as well, thanks to the overloaded `sort()` method.
int[] numArray = {5, 1, 6, 2, 9, 3, 8}; // Only sort elements from index 1 (inclusive) to index 5 (exclusive). Arrays.sort(numArray, 1, 5);Here, the array `numArray` becomes `{5, 1, 2, 3, 9, 6, 8}`. However, take note that only the elements from second to fourth position in the zero-indexed array are sorted while the rest of the array remains unsorted. This method is especially useful when you need to maintain portions of your array while sorting others.
sort(): This method sorts the array in ascending order. For primitive types, it sorts in numerical order, while for objects, it sorts in lexicographical order unless a `Comparator` is provided.
int[] numArray = {2, 4, 6, 8, 10}; for(int i = 0; i < numArray.length; i++){ System.out.println(numArray[i]); }This example declares, initialises, and prints the array values using a for loop. Example 2: Finding the Sum and Average of an Array
double[] numArray = {5.5, 8.5, 10.5, 15.5, 20.5}; double sum = 0.0; for(int i = 0; i < numArray.length; i++){ sum += numArray[i]; } double average = sum / numArray.length; System.out.println("Sum = " + sum); System.out.println("Average = " + average);In this example, you calculate the sum of the array elements using a loop and then the average. Here, also observe the use of a double array to accommodate integer and fractional numbers. These basic examples help familiarise you with the declaration, initialisation, and simple manipulation of arrays in Java. Moving on to the complex examples would solidify your foundation in Java arrays.
double[] numArray = {21.2, 19.6, 37.8, 40.2, 45.6, 50.8, 60.2}; double smallest = numArray[0]; double largest = numArray[0]; for(int i = 1; i < numArray.length; i++){ if(numArray[i] > largest){ largest = numArray[i]; } else if (numArray[i] < smallest){ smallest = numArray[i]; } } System.out.println("Largest number = " + largest); System.out.println("Smallest number = " + smallest);In this example, you learn about finding the largest and smallest numbers in an array. It's an algorithmic approach where you initially assume the first element as the smallest and largest number and then compare with other elements to update accordingly. Example 2: Reversing a Java Array
int[] numArray = {1, 2, 3, 4, 5}; int[] reverseArray = new int[numArray.length]; int j = numArray.length; for (int i = 0; i < numArray.length; i++) { reverseArray[j - 1] = numArray[i]; j = j - 1; } System.out.println("Reversed array is: \n"); for(int k = 0; k < numArray.length; k++) { System.out.println(reverseArray[k]); }Here, you see how to reverse an array in Java. It's a quite interesting task, where you start by creating a new array of the same length as the original one. Then you iterate through the original array, copying its elements to the new one starting from the end.
Flashcards in Java Arrays51
Start learningWhat is a Single Dimensional Array in Java?
A single dimensional array in Java is a container object that holds a sequence of elements, all of the same type, accessed through an index. This index usually starts from zero and continues to the length of the array minus one.
What are the primary functions of a Single Dimensional Array in Java?
A Single Dimensional Array in Java stores elements of the same type, allows accessing these elements using indices which begin at 0, and improves code readability by organising data linearly.
How can you construct a Single Dimensional Array in Java?
Constructing a Single Dimensional Array in Java involves declaring the array variable and allocating memory for the array values. For example, you can declare '& int[] arr; ' and allocate memory as '& arr = new int[5]; '.
What are the steps to create a single dimensional array in Java?
The steps are Declaration, Instantiation, and Initialization where you first declare the type of the array, allocate memory to hold the elements and then assign values to each element using their indexes.
How do you allocate memory for an array in Java?
You allocate memory for a Java array using the 'new' keyword followed by the data type and the number of elements enclosed in square brackets.
How do you initialise elements of a Java array?
You initialise elements of a Java array by assigning values to each element using their index. For example: array[0] = 10;
Already have an account? Log in
The first learning app that truly has everything you need to ace your exams in one place
Sign up to highlight and take notes. It’s 100% free.
Save explanations to your personalised space and access them anytime, anywhere!
Sign up with Email Sign up with AppleBy signing up, you agree to the Terms and Conditions and the Privacy Policy of StudySmarter.
Already have an account? Log in