Java Arrays

j
Java Arrays:

double[] myList; //preferred way
or
double myList[]; //works but not preferred way

Creating Arrays:

arrayRefVar=new dataType[arraySize];
dataType[] arrayRefVar=new dataType[arraySize];

Alternatively you can create arrays as follows:
dataType[] arraRefVar={value0,value1,......,valueK};

The array elements are accessed throughthe index.Array indices are 0 based; that is, they start from 0 to arrayRefVar.length-1
double[] myList=new double[10];

public class TestArary {
public static void main(String[] args){
	double[] myList={1.9,2.9,3.4,3.5};
	
	//Print all the array elements
	for(int i=0;i<myList.length;i++)
	{
		System.out.print(myList[i]+" ");
	}
	
	//Summing all elements
	double total=0;
	for(int i=0;i<myList.length;i++)
	{
		total=total+myList[i];
	}
	System.out.println("Total is "+total);
	
	//Finding the largest element
	double max=myList[0];
	for(int i=1;i<myList.length;i++)
	{
		if(myList[i]>max)
		{
			max=myList[i];
		}
		System.out.println("Max is: "+ max);
	}
}

}

Output:

1.9 2.9 3.4 3.5 Total is 11.7
Max is: 2.9
Max is: 3.4
Max is: 3.5

foreach loops

public class TestArray{
public static void main(String[] args)
{
double[] myList={1.9,2.9,3.4,3.5};
//print all the array elements

for(double element:MyList)
{
System.out.println(element);

}
}
}

Output:

1.9
2.9
3.4
3.5

Passing Arrays to Methods:

public static void printArray(int[] array)
{
	for(int i=0;i<array.length;i++)
	{
		System.out.println(array[i]+" ");
	}
}

Returning an Array from a method:

public static int[] reverse(int[] list)
{
int[] result=new int[list.length];
for(int i=0;j=result.length-1;i<list.length;i++,j--)
{
	result[j]=list[i];
}
return result;	
}

The array class:

java.util.arrays for soritng and searching arrays,comparing and filling arrays.
public static int binarySearch(Object[] a,Object key)

public static boolean equals(long[] a1,long[] a2)

public static void fill(int[] a,int val)

public static void sort(Object[] a)

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published. Required fields are marked *