Array
] Collection Of Similar Data Type Stored In Continous Memory Location
] Arrays Are A Way To Store A
List Of Items.
] Array will store Multiple values in single variable.
Single
Dimensional Array
A One -Dimensional Array Is,Essentially,A List Of Like -Typad
Variables. To Create An Array In Java,You Use Three Steps:
·
Declare A
Variable To Hold The Array
·
Create A New
Array Object And Assign It To The Array Variable
·
Assigning Value
Declaring Array Variables
String dificultwords[];
Point hits[];
Int temps[];
Creating Array Objects
The Second step is to create an array object and assign
it to that variable.There are two ways to do this
Ø Using new
Ø Directly initializing the contents of that array
String[] names=new String[10];
int[] temps=new int[99];
String[]
fruits={"Apple","Orange","Banana","Pineapple',"Mango"};
accessing array elements
Once you have an array with initial values, you can test
and change the values in each slot of that array.
To get a value stored within an array, use the array
subscript expression:
myArray[subscript];
String []arr=new String[10];
arr[10]="eggplant";
Changing array Elements
Example
myarray[1]=15;
sentence[0]="The";
sentence[10]=sentence[0];
Example 1
class ArrayDemo
{
int i;
int arr[]={1,2,3,4,5,6,7,8,9,10};
void result()
{
System.out.println("Array details \n");
for(i=0;i<10;i++)
{
System.out.print(arr[i]+"\t");
}
}
public static void main(String args[])
{
ArrayDemo d=new ArrayDemo ();
d.result();
}
}
//Average an Array of Values
class Average{
public static void main (String args[]){
double
nums[]={10.1,11.2,12.3,13.4,14.5};
double result=0;
int i;
for(i=0;i<5;i++)
result=result+nums[i];
System.out.println("average
is"+result/5);
}
}
Multidimensional
Array
int coords[][]=new int[12][12];
coords[0][0]=1;
coords[0][1]=2;
class TwoD{
public static void main (String args[]) {
int twoD[][]=new
int[4][4];
int i,j,k=0;
for(i=0;i<4;i++)
for(j=0;j<4;j++){
twoD[i][j]=k;
k++;
}
for(i=0;i<4;i++) {
for(j=0;j<4;j++)
System.out.print(twoD[i][j]+" ");
System.out.println();
}
}
}
Ragged
Array
Multidimensional array are faked as "array of
array".it is also called ragged array.The Ragged Array has different rows
and different lengths.
class TwoDAgain{
public static void main (String args[]) {
int twoD[][]=new
int[4][];
twoD[0]=new int[1];
twoD[1]=new int[4];
twoD[2]=new int[3];
twoD[3]=new int[2];
int i,j,k=0;
for(i=0;i<4;i++)
for(j=0;j<twoD[i].length;j++){
twoD[i][j]=k;
k++;
}
for(i=0;i<4;i++) {
for(j=0;j<twoD[i].length;j++)
System.out.print(twoD[i][j]+" ");
System.out.println();
}
}
}
0 comments:
Post a Comment