|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
Creating Arrays in Java
Consider these statements: |
int[] numbers = new int[5]; Object[] objects = new Object[10]; String[] strings1 = new String[] {"javadb.com", "www.javadb.com"}; String[] strings2 = {"javadb.com", "www.javadb.com"}; |
An array may be created in a couple of different way. Since an array is an object it can be created with the 'new' keyword, and since an array doesn’t have a constructor (like ordinary objects have) it is instead recognized through its square brackets which follow the data type. In the first example above an int array is created with the length of 5. After the creation, every element in the array has the value 0 since this array contains value types and value types cannot be null. The second example creates an object array with the length of 10. Since this array contains reference types, all elements are null. Each and every elements need to be populated with an object instance, like: |
for (int i = 0; i < objects.length; i++) { objects[i] = new Object(); } |
The third and fourth example shows how to create and initialize an array with values at the same time. It is possible to do so without using the 'new' keyword; it is implicit in the last example. |
| Previous | Next | |
Tutorial Home | ||
| Do you know your Java? | |
| Take a Ten-Question-Java-Quiz! | |
Search for code examples on this site
