Array are used typically to group objects of same type. Arraya enable you to refer to the group of objects by a common name.
you can declare arrays in two types
1> char[] s;
2>int i [];
Creating ARRAYS::
you can create arrays like all objects, using new keyword
s= new char[26];
it creates an array of 26 char values. afer creation arrays are intialised to default value('\u000' for characters). you must fill in the array for it to be useful; for example:
public char[] createArray() {
char[] s;
s= new char[26];
for (int i=0; i<26;>
s[i] = (char) ('A' +i);
}
return s;
}
**this code generates an array in the heap memory with upper case letters of english alphabet.
Creating Reference Arrays::
p= new Point[10]; // where Point is a class
this line creates an array of 10 references of type Point. However, it does not create 10 point objects. create these seperately as follows::
public Point[] createArray()
{
Point[] p;
p= new Point[10];
for(int i=0; i<10;i++)
{
p[i]=new Point(i,i+1);
}
return p;
}
Initialising Arrays::
When you create array, every element is initialised.
incase of char it is initialise to ('\u0000'), in case of Point it is intialised to 'null'.
Shorthand in Java programming language::
String[] names={ "Geeta","Jen","Simon"};
This code is equivalent to::
String[] names;
names= new String[3];
names[0]="Geeta";
names[1]="Jen";
names[2]="Simon";
Multi dimension Array::
for example ::
to create an array of four arraysof five integers::
int[][] twoDim= new int[4][5];
No comments:
Post a Comment