Ignora collegamentiHome / Blog

Blog


Create and sort arrays in Java

In Java, you can create an array of any size, limited only by the capacity of computer memory. An array is a particular Java object that contains a fixed number of variables all of the same type. Each variable is assigned a number, or index, between zero and the size of the array minus one.
Arrays can be ordered in a simple way using Arrays.sort (array)

The example shows how to use the array in Java:

import java.util.Arrays;

public class ArrayTest
{
  public static void main(String[] args)
  {
	// Create an array of integers, 10 elements	  
	int[] intArray2 = { 7, 1, 9, 4, 5, 8, 3, 10, 2, 6};

	// Create an array of string, 7 elements
	String[] stringArray = new String[7];
	stringArray[0] = "Rome";
	stringArray[1] = "London";
	stringArray[2] = "Paris";
	stringArray[3] = "Zurich";
	stringArray[4] = "Alexandria";
	stringArray[5] = "Berlin";
	stringArray[6] = "Madrid";

	System.out.println("Array of integers");
	for (int i=0; i<intArray2.length; i++)
	System.out.print("["+intArray2[i]+"]");
	System.out.println("\n");
	
	Arrays.sort(intArray2);
	System.out.println("Array of integers (ordered)");
	for (int i=0; i<intArray2.length; i++)
	System.out.print("["+intArray2[i]+"]");
	System.out.println("\n");
	
	System.out.println("Array of string");
	for (int i=0; i<stringArray.length; i++)
	System.out.print("[" + stringArray[i] + "]");
	System.out.println("\n");
	
	Arrays.sort(stringArray);
	System.out.println("Array of string (ordered)");
	for (int i=0; i<stringArray.length; i++)
	System.out.print("[" + stringArray[i] + "]");
	System.out.println();
  }
}

The program generates the following result:

Array of integers
[7][1][9][4][5][8][3][10][2][6]

Array of integers (ordered)
[1][2][3][4][5][6][7][8][9][10]

Array of string
[Rome][London][Paris][Zurich][Alexandria][Berlin][Madrid]

Array of string (ordered)
[Alexandria][Berlin][London][Madrid][Paris][Rome][Zurich]

 



Category: Java