CoreJavaTutorials
Contribute Us | Ask Question |
z

Array in Java

Array refers to the homogeneous collection of elements.It also termed as similar collection of related elements.
for example: 1,2,3,4.. are all of int type can be contained into a array of int type

Arrays are more handful in terms of processing time and as well as in memory footprint. Specially if we are operating on primitive types, such as int or double, since List requires all elements to be wrapped in an Object (such as Integer or double).
While the autoboxing features introduced by JDK 5 reduces the amount of code you need for such wrapping and unwrapping, it does not remove the performance issues, as wrapper objects are still being created.

However, most applications probably do not have any performance bottlenecks related to these issues, so in most cases, List and other collections should do fine. In these cases, the ease of programming outweighs the increase in memory or CPU usage, and List is the right choice.

Syntax of array

1) dataType[] varname;   // more preferred way.

2) dataType varname[];  //  less preferred way.

Example of array

 int[] varname;   // int array.
  or

 int varname[];   // int array.

 char[] varname;  //  char array.

Advantages of Array

1) It is used to represent multiple data items of same type by using only single name like int [] a={1,2,3}.
2) It can be used to implement other data structures like linked lists, stacks, queues, trees, graphs etc.
3) Helpful in mathematical operations like matrics with the help of 2D and 3D array.

Disadvantages of Array

1) Must be decide in advance the requirement of an program to define size of an array.
2) Array are static in structure. It means that array is of fixed size. The memory which is allocated to array can not be increased or reduced.
3) Memory space will be wasted if we allocated more memory space to array . And if we allocate less memory than requirement, then it will through errors.
4) Elements of array are stored in consecutive memory locations. So insertions and deletions are very difficult and time consuming.

Example of an array

class Firstarray
{
public static void main(String args[])
{
int a[]={10,20,30,40,50};// initialization ,declaration and instantiation
for( int i=0;i < a.length; i++ )

{
System.out.println(a[i]);
}
}

Output


Output:
       10
       20
       70
       40
       50

		

Another Way to use an array

class Firstarray
{
public static void main(String args[])
{
int a[]=new int[5];// initialization the size of an array
a[0]=10; //assign value to a particular index of an array
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;

for( int i=0;i < a.length; i++ )

{ System.out.println(a[i]);
}
}

Output


Output:
       10
       20
       70
       40
       50