java array demo
Array in java is defined by specifing the type and the size of the array. Once the array is defined, there is no methods to increase or decrease the size of the array. The array demo below shows how to declare an array of type int as well as some common operations such as reading and updating the values from the array. There is also a handy function from Arrays for sorting the array elements.
import java.util.Arrays; public class ArraysDemo { public static void main(String[] args) { //declaring an integer array of size 5 int[] myScores = new int[5]; // equivalent to int[] myScores = {0,0,0,0,0}; display("Original array: ", myScores); //fill every element of the array with 9 Arrays.fill(myScores, 9); display("After filling with 9s: ", myScores); //change element value at position 2 and 4 myScores[2] = 6; myScores[4] = 3; display("After changing two values: ", myScores); //sort the array Arrays.sort(myScores); display("After sorting: ", myScores); } //display all elements of an integer array public static void display(String message, int array[]) { int sz = array.length; System.out.print(message); for(int x = 0; x < sz; ++x) { System.out.print(array[x] + " "); } System.out.println(); } }
Output:
Original array: 0 0 0 0 0 After filling with 9s: 9 9 9 9 9 After changing two values: 9 9 6 9 3 After sorting: 3 6 9 9 9
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts