array in java :: futureX |
1D Array:
Declaration:
datatype []var = new datatype[size];
OR
datatype[] var = new datatype[size];
OR
datatype var[] = new datatype[size];
Example:
class A{
public static void main(String[] args){
int a[]=new int[5];
a[0]=11;
a[2]=33;
a[4]=1;
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}
}
Output:(default value is zero)
11
0
33
0
1
Q: Write a program to find minimum from the Array?
class A{
static void printmin(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
{
if(min>arr[i])
min=arr[i];
}
System.out.println("min is ::" +min);
}
public static void main(String[] args){
int a[]=new int[5];
a[0]=12;
a[1]=1;
a[2]=22;
a[3]=5;
a[4]=32;
printmin(a);
}}
2D Array:
datatype[][] var = new datatype[size][size];
OR
datatype [][]var = new datatype[size][size];
OR
datatype var[][] = new datatype[size][size];
OR
datatype []var[] = new datatype[size][size];
Example:
class A{
public static void main(String args[]){
int a[][]=new int[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++){
a[i][j]=i+j;
System.out.println(a[i][j]+" ");
}
System.out.println();
}}}
Anonymous Array:
JAVA feature of array.
In normal array, as int a[]={} same array can't declared twice.
static void printarray(int arr[]){
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
public static void main(String args[]){
printarray(new int[]{14,5,5,8});
printarray(new int[]{14,3,8,8});
}}
JAVA TUTORIALS HOMEPAGE
No comments:
Post a Comment