What Is An Array (Java)
What Is An Array (Java)
An array is a very common type of data structure where in all elements must be
of the same data type.Once defined , the size of an array is fixed and cannot
increase to accommodate more elements.The first element of an array starts
with zero.
What is an array?
Array Variables
Syntax for Declaring Array Variables
Constructing an Array
Declaration and Construction combined
Initializing an Array
Declaring and Initializing an Array
First Array Program
Java Arrays passed by reference
Multidimensional arrays
Array of Objects
x0=0;
x1=1;
x2=2;
x3=3;
x4=4;
x5=5;
with this …
x[0]=0;
x[1]=1;
x[2]=2;
x[3]=3;
x[4]=4;
x[5]=5;
how this helps is that the index (the number in the bracket[]) can be referenced
by a variable for easy looping.
for(count=0; count<5; count++) {
System.out.println(x[count]);
}
Array Variables
Using and array in your program is a 3 step process -
or
Example:
int intArray[];
// Defines that intArray is an ARRAY variable which will store integer values
int []intArray;
Constructing an Array
= new [];
Example:
intArray = new int[10]; // Defines that intArray will store 10 integer values
Initializing an Array
intArray[0]=1; // Assigns an integer value 1 to the first element 0 of the array
intArray[1]=2; // Assigns an integer value 2 to the second element 1 of the arra
y
Example:
Step 2) Save , Compile & Run the code. Observe the Output
Step 3) If x is a reference to an array, x.length will give you the length of the
array.
Uncomment line #10 . Save , Compile & Run the code.Observe the Output
Uncomment line #11 . Save , Compile & Run the code.Observe the Output
class ArrayDemo {
public static void passByReference(String a[]){
a[0] = "Changed";
}
Step 2) Save , Compile & Run the code. Observe the Output
Multidimensional arrays
Multidimensional arrays, are arrays of arrays.
When you allocate memory for a multidimensional array, you need only specify
the memory for the first (leftmost) dimension.
Ex:
Array of Objects
It is possible to declare array of reference variables.
Syntax:
class ObjectArray{
public static void main(String args[]){
Account obj[] = new Account[2] ;
//obj[0] = new Account();
//obj[1] = new Account();
obj[0].setData(1,2);
obj[1].setData(3,4);
System.out.println("For Array Element 0");
obj[0].showData();
System.out.println("For Array Element 1");
obj[1].showData();
}
}
class Account{
int a;
int b;
public void setData(int c,int d){
a=c;
b=d;
}
public void showData(){
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b);
}
}
Step 4) The line of code , Account obj[] = new Account[2] ; exactly creates an
array of two reference variables as shown below
Step 5) Uncomment Line # 4 & 5. This step creates objects and assigns them to
the reference variable array as shown below. Your code must run now.