Java

Array in Java

Pinterest LinkedIn Tumblr

Arrays are a way to store a list of items. Each element of the array holds an individual item, and you can place items into and remove items from those slots as you need to

Declaring Array Variables

The first step to creating an array is creating a variable that will hold the array, just as you would any other variable. Array variables indicate the type of object the array will hold (just as they do for any variable) and the name of the array, followed by empty brackets ([]). The following are all typical array variable declarations:
String difficultWords[];
Point hits[];
int temps[];

An alternate method of defining an array variable is to put the brackets after the type instead of after the variable
String[] difficultWords;
Point[] hits;
int[] temps;

Creating Array Objects

The first way is to use the new operator to create a new instance of an array

String[] names = new String[10]; //create String array with 10 elements

When you create an array object using new, all its elements are initialized for you (0 for numeric arrays, false for boolean, empty string for character arrays, and null for everything else). You can also create and initialize an array at the same time. Instead of using new to create the new array object, enclose the elements of the array inside braces, separated by commas:

String[] vehicle = { "suzuki", "yamaha”, "honda", "toyota"};

Accessing Array Elements

To get at a value stored within an array, use the array with index expression (index start from 0)

array[index]

String animals[] = new String[10];
animals[10] = "tiger"; //set elements at position 11 with value "tiger"
System.out.println(animals[10]);//print element at position 11

Multidimensional Arrays

you can also declare and create an array of arrays (and those arrays can contain arrays, and so on, for however many dimensions you need), and access them as you would C-style multidimensional arrays:

int coords[][] = new int[12][12];
coords[0][0] = 1;
coords[0][1] = 2;

Fetch All Elements Of Array

int[] arr = {1, 2, 3, 4, 5};
for (int i=0; i < arr.length; i++) {
    System.out.println(arr[i]);
}

I'm a full stack developer. I have experiences with Java, Android, PHP, Python, C#, Web development...I hope website https://learncode24h.com will help everyone can learn code within 24h and apply it in working easily.

Write A Comment