Arrays in Java
Arrays in Java
Arrays in Java
Advantages
•Code Optimization: It makes the code optimized, we can retrieve or sort the
data efficiently.
•Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't
grow its size at runtime.
Types of Array in java
dataType []arr;
Example : int []arr;
OR
dataType arr[];
Example : int arr[];
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
10
20
70
40
50
We can declare, instantiate and initialize the java
array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
33
3
4
5
What happens if we try to access element
outside the array size?
Output
10
20
How to read values into an array using for loop
import java.util.*;
public class arr1
{
public static void main()
{ System.out.println("elements
of array a[]");
int a[]= new int[10];
for(i=0;i<10;i++)
int i;
{
Scanner sc=new
Scanner(System.in);
System.out.print(a[i]+"\t");
System.out.println("enter }
numbers"); }
for(i=0;i<10;i++) }
{
a[i]=sc.nextInt();
}