Array in java

An array in java is a data a structure used to process a collection of data that is all of the same type

Other definition about Array in java

An array is a flexible structure for storing a sequence of values all of the same type.

A structure that holds multiple values of the same type.

  • An array behaves behaves like a numbered numbered list of variables variables with a uniform naming mechanism
  • It has a part that does not change: the name of the array
  • It has a part that can change: an integer in square brackets

Example

score[0] , score[1] , score[2] , score[3] , score[4] , score[0], score[1], score[2], score[3], score[4]

Creating and Accessing Arrays

  • An array that beheaves like this collection of variables, all of type double, can be created using one statement as follows

double[] [ ]; score = new double[5];

  • Or using two statements:

double[] score;
score = new double[5];

  • The individual variables that together make up the array are called indexed variables
    • They can also be called subscripted variables or elements of the array
    • The number in square brackets is called an index or subscript
    • In Java, indices must be numbered starting with 0, and nothing else

score[0] , score[1], score[2] , score[3] , score[4] , score[0], score[1], score[2], score[3], score[4]

  • The number of indexed variables in an array is called the length or size of the array
  • When an array is created, the length of the array is given in square brackets after the array type
  • The indexed variables are then numbered starting with 0, and ending with the integer that is one less than the length of the array

score[0], score[1], score[2], score[3], score[4];

  • A variable may be used in place of the integer

Example

double[] score = new double[5];

Declaring and Creating an Array

  • An array is declared and created in almost the same way that objects are declared and created

BaseType[] ArrayName = new BaseType[size];

  • The size may be given as an expression that evaluates to a nonnegative integer, for example, an int variable

char[] line = new char[80];
double[] reading = new double[count];
Person[] specimen = new Person[100];

Array Traversal in java

Processing each array element sequentially from the first to the last

for (int i = 0; i < <array>.length; i++) {
<do something with array [i]>;
}

A Complete Array Program in java

 import java.util.*;
public class Temperature1 {
 public static void main(String[] args) {
Scanner console = new Scanner(System.in);
 System.out.print("How many days' temperatures? ");
 int numDays = console.nextInt();
 int sum = 0;
 for (int i = 1; i <= numDays; i++) {
System.out.print("Day " + i + "'s high temp: ");
int next = console.nextInt();
sum += next;
 }
 double average = (double) sum / numDays;
 System.out.println();
 System.out.println("Average = " + average);
 }
 }


Buffer Overruns

One of the earliest and still most common sources of computer security problems is a buffer overrun (also known as a buffer overflow). A buffer overrun is similar to an array index out of bounds exception. It occurs when a program writes data beyond the bounds of the buffer set aside for that data.

Buffer overruns are often written as array code. You might wonder how such a malicious program could be written if the computer checks the bounds when you access an array. The answer is that older programming languages like C and C++ do not check bounds when you access an array. By the time Java was designed in the early 1990s, the danger of buffer overruns was clear and the designers of the language decided to include array-bounds checking so that Java would be more secure. Microsoft included similar bounds checking when it designed the language C# in the late 1990s

The For-Each Loop in java Array

Java 5 introduced a new loop construct that simplifies certain array loops. It is known as the enhanced for loop, or the for-each loop. It can be used whenever you find yourself wanting to examine each value in an array.

The foreach loop, or enhanced for statement, as Java calls it, is used to enumerate the values in a collection of values

int sum= 0;
for (int v : b) { 
sum= sum + v;
}

Example

public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {2, 4, 6, 8, 10};
for (int n: numbers) {
System.out.println(n);
}
}
}

output

2
4
6
8
10

Iterate over Java String Array using For-Each

public class ArrayExample {
public static void main(String[] args) {
String names[] = {"apple", "banana", "cherry", "mango"};
for(String name: names) {
System.out.println("Hello " + name + "!");
}
}
}

Output

Hello apple!
Hello banana!
Hello cherry!
Hello mango!

Limitations of Arrays

some general limitations of arrays:

  • You can’t change the size of an array in the middle of program execution
  • You can’t compare arrays for equality using a simple == test. Remember that arrays are objects, so if you ask whether one array is == to another array, you are asking whether they are the same object, not whether they store the same values
  • You can’t print an array using a simple print or println statement. You will get odd output when you do so

The first limitation is more difficult to overcome. Because an array is allocated as a contiguous block of memory, it is not easy to make it larger. To make an array bigger, you’d have to construct a new array that is larger than the old one and copy values from the old to the new array. Java provides a class called ArrayList that does this growing operation automatically. It also provides methods for inserting values in and deleting values from the middle of a list

Multidimensional Arrays

Arrays of more than one dimension are called multidimensional arrays

Rectangular Two-Dimensional Arrays

The most common use of a multidimensional array is a two-dimensional array of a certain width and height. For example, suppose that on three separate days you took a series of five temperature readings. You can define a two-dimensional array that has three rows and five columns as follows

double[][] temps = new double[3][5];

Example

public class Main {
   public static void main(String[] args) {
     int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
     for (int i = 0; i < myNumbers.length; ++i) {
        for(int j = 0; j < myNumbers[i].length; ++j) {
           System.out.println(myNumbers[i][j]);
        }
     }
   }
}

Output

1
2
3
4
5
6
7

Leave a Comment