A)
->when multiple data items of same type, if we want to group under name is known as Arrays.
->Array is a subscripted variable, it is a collection of homogeneous Elements referred under same name.
->purpose of the array, lower bound, upper bound, and item over the array to retrieve its elements, dynamically homogeneous, contiguous memory allocation. In these areas java arrays are similar to that of c language.
->Java arrays are different from that of c language in the fallowing areas
1. Syntax
2. Object oriented representation
3. In specifying the size.
4. spl property “length” that specifies the array size dynamically.
->in java arrays are objects. But in c++ arrays are not objects.
->in java array size must be mentioned, can specify dynamically.
->in c, c++ array size must be mentioned at compile time But can’t be specified dynamically.
In c, c++ languages:
for( i=0 ; i<10 ; i++) here array size is arr[10].
In java :
for (i=0 ; i<arr.length ; i++)
In c language:
int main(arg,argv[])
int main(arg,argv[])
{
int a[4];
int l;
for(i=0;i<10;i++)
Scanf(“%d”, &a[i]);
for(i=0;i<5;i++)
pringf(“%d”,a[i]);
}
->In c,c++ there is no boundary checking.
-> in java if we cross the limits of array size exception is raised ArrayIndexOutOfBounds and the process is terminated.
->// primitivearrayexample.java
import java.util.Scanner;
class primitivearrayexample {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int arr[];
// arris an array variable
//that can be reference an integer array of any size
arr= new int[4];
// arrinteger array of size 4 created.
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
System.out.print("Enter the array size: ");
int size=s.nextInt();
int ar[]=new int [size];//mostly used Syntax for array created.
for(inti=0;i<size;i++)
//or you can use for(int i=0;i<ar.length;i++)
System.out.println(ar[i]);
}
}
Output:
0
0
0
0
0
Enter the array size: 2
0
0
--------------------------------------------------------------------------------------------------------------
// arrayinitialization.java
class arrayinnitialization {
public static void main(String[] args) {
int a[]={10,20,30,40};
System.out.println("the first output with normal for loop :");
for(int i=0;i<a.length;i++) // normal for loop
System.out.println(a[i]);
System.out.println("the second output with enhanced for loop:");
for(int c:a) // enhanced for loop
System.out.println(c);
}
}
Output:
the first output with normal for loop :
10
20
30
40
the second output with enhanced for loop:
10
20
30
40
Note : from jdk 1.5 on words the for(int c:a) is used for iterating.
Comments
Post a Comment