java tutorial - Java Arrays - tutorial java - java programming - learn java - java basics- java for beginners



Arrays in Java are a data structure that stores ordered collections of fixed-sized elements of the desired type.

  • In Java, an array is used to store a collection of data, but it is often useful to think of an array as a collection of variables of the same type.
  • Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable, for example, numbers and use numbers [0], numbers [1], ..., and numbers [99] for mapping of individual variables.
  • This article will introduce you to how to declare an array of variables in Java, create and manipulate an array using indexed variables.
 scheme2

Learn java - java tutorial - java array - java examples - java programs

Declaring an array

To use an array in a program, you need to declare a variable to reference the array, and you must specify the type of the array that can reference the variable. The syntax for declaring an array variable is:

dataType[] arrayRefVar;   // preferred way.
or
dataType arrayRefVar[];  // works but not preferred way.
click below button to copy the code. By - java tutorial - team

Note: The style dataType[] arrayRefVar is preferred.

Sample Code

The following code snippets are examples of using this syntax:


double [] myList; // Preferred way.

or

double myList []; // Works, but is not the preferred way.
click below button to copy the code. By - java tutorial - team

Creating an array

In Java, you can create an array using the new operator using the following syntax:

arrayRefVar = new dataType[arraySize];
click below button to copy the code. By - java tutorial - team

The above declaration does two things:

  • Creates an array using the new dataType [arraySize];
  • A reference to the new created array is assigned to the variable arrayRefVar.

Declaring a variable, creating and assigning an array reference variable can be shown below:

dataType[] arrayRefVar = new dataType[arraySize];
click below button to copy the code. By - java tutorial - team

Alternatively, arrays in Java can be created as follows:


dataType [] arrayRefVar = {value0, value1, ..., valuek};
click below button to copy the code. By - java tutorial - team
  • Array elements are available to the index. Indices are counted from 0; that is, they start from 0 to arrayRefVar.length-1.

Sample Code

  • The following statement declares an array of variables myList, creates an array of 10 elements of type double and assigns the link myList:
double[] myList = new double[10];
click below button to copy the code. By - java tutorial - team
  • The image displays the array myList. Here myList has ten double values and indices from 0 to 9.
 java-array

Learn java - java tutorial - java array - java examples - java programs

Working with arrays

When working with array elements, the for loop or foreach loop is often used because all elements have the same type and known size.

Sample Code

A complete example showing how to create, initialize, and process an array:

public class TestArray {
 public static void main (String [] args) {
      double [] myList = {1.9, 2.9, 3.4, 3.5};

      // Display all elements of the array
      for (int i = 0; i <myList.length; i ++) {
         System.out.println (myList [i] + "");
      }
      // Sum of array elements
      double total = 0;
      for (int i = 0; i <myList.length; i ++) {
         total += myList [i];
      }
      System.out.println ("Sum of array numbers:" + total);
      // Find the largest element in the array
      double max = myList [0];
      for (int i = 1; i <myList.length; i ++) {
         if (myList [i]> max) max = myList [i];
      }
      System.out.println ("The largest element:" + max);
   }
}
click below button to copy the code. By - java tutorial - team

Output

1.9
2.9
3.4
3.5
Sum of array numbers:11.7
The largest element:3.5

Foreach cycle

JDK 1.5 introduced a new for loop , known as a foreach loop or an extended for loop , which allows you to sequentially traverse an entire array without using a variable index.

Sample Code

The following code displays all the elements in the myList array:

public class TestArray {

   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};

      // Print all the array elements
      for (double element: myList) {
         System.out.println(element);
      }
   }
}
click below button to copy the code. By - java tutorial - team

Output

1.9
2.9
3.4
3.5

Passing an array to a method

  • Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array −
public static void printArray(int[] array) {
  for (int i = 0; i < array.length; i++) {
    System.out.print(array[i] + " ");
  }
}
click below button to copy the code. By - java tutorial - team
  • You can invoke it by passing an array. For example, printArray method to display 3, 1, 2, 6, 4, and 2 :
printArray(new int[]{3, 1, 2, 6, 4, 2});
click below button to copy the code. By - java tutorial - team

Returning an Array from a Method

  • A method may also return an array. For example, the following method returns an array that is the reversal of another array :
public static int[] reverse(int[] list) {
  int[] result = new int[list.length];

  for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
    result[j] = list[i];
  }
  return result;
}
click below button to copy the code. By - java tutorial - team

Methods for an array

The java.util.Array class takes several static methods for sorting and searching arrays, comparing arrays, and filling array elements.

Sr.No. Method & Description
1

public static int binarySearch(Object[] a, Object key)


Using the binary search algorithm it can searches the specified array Object ( Byte, Int , double, etc.).if it is contained in the list it returns index of the search key,otherwise, it returns ( – (insertion point + 1)).

2

public static boolean equals(long[] a, long[] a2)


Two arrays are considered equivalent if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are same this returns true.

3

public static void fill(int[] a, int val)


It Assigns the specified array of value to Int.

4

public static void sort(Object[] a)


Sorts the specified array of objects into an ascending order,the same method could be used by all other primitive data types ( Byte, short, Int, etc.)

Example 1: length of the array

public class Test {

   public static void main (String [] args) {
      // Array of myArray1 from 5 elements of type double.
      double [] myArray1 = {2.4, 3.8, 11.2, 9.8, 1.18};
      // Output the length of the array myArray1 to the screen.
      System.out.println ("The number of elements in the array myArray1:" + myArray1.length);
      
      // The array myArray2 from 4 elements of type String.
      String [] myArray2 = {"Java", "array", "Example", "wikitechy.com"};
      // Display the size of myArray2 array on the screen.
      System.out.println ("The number of elements in the array myArray2:" + myArray2.length);
   }
}
click below button to copy the code. By - java tutorial - team

Output


The number of elements in the array myArray1: 5
The number of elements in the array myArray2: 4

Example 2: the maximum element of an array

  • Simple ways to find the maximum number in an array in Java. First, use the Math.max () method .
public class Test {

   public static void main (String [] args) {
      // Find the maximum element in the array myArray from 4 elements of type double.
      double [] myArray = {11, 5.8, 11.1, 10.9};
        
      // Set the max variable to the minimum double-value.
      double max = Double.MIN_VALUE;

      // Find all the elements of the array.
      for (int i = 0; i <myArray.length; i ++) {
          // Variable max with the method Math.max () assign the maximum value
          // by selecting the largest of the two values (the "old" value of max and the value of the element).
          max = Math.max (max, myArray [i]);
      }

      // Display the largest number of myArray arrays on the screen.
      System.out.println ("The maximum element in the array myArray:" + max);
   }
}
click below button to copy the code. By - java tutorial - team

Output

The maximum element in the array myArray: 11.1

Related Searches to Java Arrays