Arrays
Arrays are consecutive memory locations allocated to store same type of objects. all arrays in Java are objects.the start index of an array is always 0 and end index is declared size - 1.length is the data member of array object that stores the size of the array;You can decalre arrays of Objects or primitive types
Creating an Array
int[] nos=new int[10]
populating an array
nos[0]=1; or a simple loop
for (int i=0;i<nos.length;i++)nos[i]=i*10;
accessing an item from an array.
nos[5];
Creating a multi dimensioal array
int[][][] arr=new int[10][10][10];
the follwoing example ilutrates an Array
ackage com.vivarem.examples;
import java.lang.Math;
public class JavaArray{
int[] my;
JavaArray(int size){
my =new int[size];
for (int i=0;i<my.length;i++)my[i]=(int)(100*java.lang.Math.random());
}
public void show(){
System.out.println("The current array is");
for (int i=0;i<my.length;i++)System.out.println(my[i]);
}
public void sort(boolean sorttype){
// 1 for desc 0 for asc
System.out.println("Sorting...."+((sorttype)?"Desc":"Ascend"));
nt x;
for(int i=0;i<my.length-1;i++)
for(int j=i+1;j<my.length;j++)
if (sorttype){
if (my[i]<my[j]){
x=my[i];
my[i]=my[j];
my[j]=x;
}}
else
if (my[i]>my[j]){
x=my[i];
my[i]=my[j];
my[j]=x;
}
}
public static void main(String[] a){
JavaArray ja=new JavaArray(10);
ja.show();
ja.sort(true);//sort descending
ja.show();
ja.sort(false);//sort ascending
ja.show();
}
}
< Function overloading Access Sepcifiers and modifiers |
Content |
Inheritance In Java >
|