- Java Arrays
- Access the Elements of an Array
- Example
- Change an Array Element
- Example
- Example
- Array Length
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Java: getting a value from an array from a defined location
- 3 Answers 3
- How do I find the element at an index position in Java?
- 3 Answers 3
- Arrays
- Declaring a Variable to Refer to an Array
- Creating, Initializing, and Accessing an Array
- Copying Arrays
- Array Manipulations
Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.
To declare an array, define the variable type with square brackets:
We have now declared a variable that holds an array of strings. To insert values to it, you can place the values in a comma-separated list, inside curly braces:
To create an array of integers, you could write:
Access the Elements of an Array
You can access an array element by referring to the index number.
This statement accesses the value of the first element in cars:
Example
String[] cars = ; System.out.println(cars[0]); // Outputs Volvo
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Change an Array Element
To change the value of a specific element, refer to the index number:
Example
Example
String[] cars = ; cars[0] = "Opel"; System.out.println(cars[0]); // Now outputs Opel instead of Volvo
Array Length
To find out how many elements an array has, use the length property:
Example
String[] cars = ; System.out.println(cars.length); // Outputs 4
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Java: getting a value from an array from a defined location
I have an array of numbers and would like to retrieve one of the values from location «index». I’ve looked at the Java documentation http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Array.html but my code still isn’t compiling. here is my method:
public class ConvexPolygon implements Shape < java.awt.Point[] vertices; public ConvexPolygon(java.awt.Point[] vertices) < this.vertices = vertices; this.color = color; this.filled = filled; >java.awt.Point getVertex(int index)
I have numbers in an array representing Points. The value index is going to be the location of the array verities. What can I do to make this work? Thanks !
3 Answers 3
In Java, array indexes are denoted by the square brackets. You can replace your get(vertices, index) call like so:
In looking at your code, it appears you are coming from a language that defines a global get() function for such operations. Be aware that, in Java, there are no global functions. Each class you create defines its own functions, and any function call without an object or class preceding it is assumed to be defined in the local class.
So, your call to get(Point[], int) could work only if you define that function on this class:
public Point get(Point[] vertices, int index)
Or define it statically on another class and precede the call with the class name:
public class PointArrayHelper < public static Point get(Point[] vertices, int index) < return vertices[index]; >> PointArrayHelper.get(vertices, index);
Now, be warned that I don’t think you should do either of these! I just thought it might help you understand Java a little better.
How do I find the element at an index position in Java?
You say you have an «array list» — do you mean ArrayList or just an array? Also, did you really mean to use the «processing» tag which refers to another programming language called «processing» that’s nothing to do with Java?
get() wouldn’t cause your program to freeze (99% sure); something else must be wrong. Show us the entire code you tried.
3 Answers 3
Just do: array[0] Don’t forget arrays position start from 0, so in this case position 1 would be 0.
In the case of array you can get the element at position ‘index’ as follows:
int index = 0; String value = array[index];
If it is an ArrayList, you can get the element at position ‘index’ as follows:
int index = 0; String value = arryList.get(index);
With the .get method I get IndexOutOfBoundsException: Index: 48, Size: 6 and my software freezes saying «Not Responding»
@dsec35 the error message is telling you that you are calling .get(48) . This is probably because you did .get(‘0’) instead of .get(0) . The character ‘0’ has a Unicode value of 48, hence calling .get(‘0’) is like calling .get(48) . You need to call .get(0) instead.
As @KlitosKyriacou mentioned, you are trying to access with character ‘0’ which is being cast to integer 48(Unicode value). As your ArrayList size is less than 48, it is throwing IndexOutOfBoundsException. The get method os ArrayList accepts an integer as a parameter. Hence you should use .get(0) .
Arrays
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You have seen an example of arrays already, in the main method of the «Hello World!» application. This section discusses arrays in greater detail.
Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the preceding illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.
The following program, ArrayDemo , creates an array of integers, puts some values in the array, and prints each value to standard output.
The output from this program is:
Element at index 0: 100 Element at index 1: 200 Element at index 2: 300 Element at index 3: 400 Element at index 4: 500 Element at index 5: 600 Element at index 6: 700 Element at index 7: 800 Element at index 8: 900 Element at index 9: 1000
In a real-world programming situation, you would probably use one of the supported looping constructs to iterate through each element of the array, rather than write each line individually as in the preceding example. However, the example clearly illustrates the array syntax. You will learn about the various looping constructs ( for , while , and do-while ) in the Control Flow section.
Declaring a Variable to Refer to an Array
The preceding program declares an array (named anArray ) with the following line of code:
// declares an array of integers int[] anArray;
Like declarations for variables of other types, an array declaration has two components: the array’s type and the array’s name. An array’s type is written as type[] , where type is the data type of the contained elements; the brackets are special symbols indicating that this variable holds an array. The size of the array is not part of its type (which is why the brackets are empty). An array’s name can be anything you want, provided that it follows the rules and conventions as previously discussed in the naming section. As with variables of other types, the declaration does not actually create an array; it simply tells the compiler that this variable will hold an array of the specified type.
Similarly, you can declare arrays of other types:
byte[] anArrayOfBytes; short[] anArrayOfShorts; long[] anArrayOfLongs; float[] anArrayOfFloats; double[] anArrayOfDoubles; boolean[] anArrayOfBooleans; char[] anArrayOfChars; String[] anArrayOfStrings;
You can also place the brackets after the array’s name:
// this form is discouraged float anArrayOfFloats[];
However, convention discourages this form; the brackets identify the array type and should appear with the type designation.
Creating, Initializing, and Accessing an Array
One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for 10 integer elements and assigns the array to the anArray variable.
// create an array of integers anArray = new int[10];
If this statement is missing, then the compiler prints an error like the following, and compilation fails:
ArrayDemo.java:4: Variable anArray may not have been initialized.
The next few lines assign values to each element of the array:
anArray[0] = 100; // initialize first element anArray[1] = 200; // initialize second element anArray[2] = 300; // and so forth
Each array element is accessed by its numerical index:
System.out.println("Element 1 at index 0: " + anArray[0]); System.out.println("Element 2 at index 1: " + anArray[1]); System.out.println("Element 3 at index 2: " + anArray[2]);
Alternatively, you can use the shortcut syntax to create and initialize an array:
Here the length of the array is determined by the number of values provided between braces and separated by commas.
You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets of brackets, such as String[][] names . Each element, therefore, must be accessed by a corresponding number of index values.
In the Java programming language, a multidimensional array is an array whose components are themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the rows are allowed to vary in length, as shown in the following MultiDimArrayDemo program:
class MultiDimArrayDemo < public static void main(String[] args) < String[][] names = < , >; // Mr. Smith System.out.println(names[0][0] + names[1][0]); // Ms. Jones System.out.println(names[0][2] + names[1][1]); > >
The output from this program is:
Finally, you can use the built-in length property to determine the size of any array. The following code prints the array’s size to standard output:
System.out.println(anArray.length);
Copying Arrays
The System class has an arraycopy method that you can use to efficiently copy data from one array into another:
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
The two Object arguments specify the array to copy from and the array to copy to. The three int arguments specify the starting position in the source array, the starting position in the destination array, and the number of array elements to copy.
The following program, ArrayCopyDemo , declares an array of String elements. It uses the System.arraycopy method to copy a subsequence of array components into a second array:
class ArrayCopyDemo < public static void main(String[] args) < String[] copyFrom = < "Affogato", "Americano", "Cappuccino", "Corretto", "Cortado", "Doppio", "Espresso", "Frappucino", "Freddo", "Lungo", "Macchiato", "Marocchino", "Ristretto" >; String[] copyTo = new String[7]; System.arraycopy(copyFrom, 2, copyTo, 0, 7); for (String coffee : copyTo) < System.out.print(coffee + " "); >> >
The output from this program is:
Cappuccino Corretto Cortado Doppio Espresso Frappucino Freddo
Array Manipulations
Arrays are a powerful and useful concept used in programming. Java SE provides methods to perform some of the most common manipulations related to arrays. For instance, the ArrayCopyDemo example uses the arraycopy method of the System class instead of manually iterating through the elements of the source array and placing each one into the destination array. This is performed behind the scenes, enabling the developer to use just one line of code to call the method.
For your convenience, Java SE provides several methods for performing array manipulations (common tasks, such as copying, sorting and searching arrays) in the java.util.Arrays class. For instance, the previous example can be modified to use the copyOfRange method of the java.util.Arrays class, as you can see in the ArrayCopyOfDemo example. The difference is that using the copyOfRange method does not require you to create the destination array before calling the method, because the destination array is returned by the method:
class ArrayCopyOfDemo < public static void main(String[] args) < String[] copyFrom = < "Affogato", "Americano", "Cappuccino", "Corretto", "Cortado", "Doppio", "Espresso", "Frappucino", "Freddo", "Lungo", "Macchiato", "Marocchino", "Ristretto" >; String[] copyTo = java.util.Arrays.copyOfRange(copyFrom, 2, 9); for (String coffee : copyTo) < System.out.print(coffee + " "); >> >
As you can see, the output from this program is the same, although it requires fewer lines of code. Note that the second parameter of the copyOfRange method is the initial index of the range to be copied, inclusively, while the third parameter is the final index of the range to be copied, exclusively. In this example, the range to be copied does not include the array element at index 9 (which contains the string Lungo ).
Some other useful operations provided by methods in the java.util.Arrays class are:
- Searching an array for a specific value to get the index at which it is placed (the binarySearch method).
- Comparing two arrays to determine if they are equal or not (the equals method).
- Filling an array to place a specific value at each index (the fill method).
- Sorting an array into ascending order. This can be done either sequentially, using the sort method, or concurrently, using the parallelSort method introduced in Java SE 8. Parallel sorting of large arrays on multiprocessor systems is faster than sequential array sorting.
- Creating a stream that uses an array as its source (the stream method). For example, the following statement prints the contents of the copyTo array in the same way as in the previous example:
java.util.Arrays.stream(copyTo).map(coffee -> coffee + " ").forEach(System.out::print);
System.out.println(java.util.Arrays.toString(copyTo));
[Cappuccino, Corretto, Cortado, Doppio, Espresso, Frappucino, Freddo]