-
Notifications
You must be signed in to change notification settings - Fork 1
Arrays
In this section we'll be going over using and processing arrays. The array class is a powerful tool that allows us to store multiple values at once and as a result, allows us to return more than one value outside of a method for use.
- Declaring arrays
- Accessing elements
- Foreach loop
- Cloning/Copying
- Passing as arguments
- Returning arrays
An array is a group of like-typed variables that are referred to by a common name.Array can contains primitives data types , like integers and strings, as well as objects of a class depending on the definition of array.
An array declaration has two components: the type and the name. type declares the element type of the array.
java ```
public class Main{ int[] numbers = ....;//the type is int, and the name is numbers ... string[] names = ...; }
To **instantiate** an array, we also need to specify the size of the array. So as a recap:First, we must declare a variable of the desired array type. Second, we must allocate the memory that will hold the array, using new, and assign it to the array variable.
```java
> public class Main{
> int[] numbers = new int[20];//this int array has a size of 20, meaning it can hold 20 integers
>}
In a situation, where the size of the array and elements of the array are already known, array literals can be used. We essentially list out the array elements without specifying the size
> public class Main{
> int[] numbers = new int[]{1,2,3,4,5,6,7,8,9,10};//this int array has a size of 10, an the elements are 1-10
>}