Home
Calculator
Algebra
Fun Games
Geometry
Interactive
Trigonometry
Good Links
Home
Calculator
Algebra
Fun Games
Geometry
Interactive
Trigonometry
Good Links

Arrays in Java

Length, Random elements, Coying Arrays and more

Java array at javaclass.info
    Array Types
  • c
Arrays
  • How to randomly chose an element from a given array
    • use the length property of an array as the example below shows to
       public static void main(String args[]){
      	String[] daysInAweek={"monday","tuesday", "wednesday", "thursday","friday", "saturday", "sunday"};
      	int whichIndex = (int)(Math.random() *daysInAweek.length);
      	String dayOfWeek = daysInAweek[whichIndex];
      	System.out.println("dayOfWeek  "+ dayOfWeek );
      }
      

Initializing an array
The code below causes an error. Can you determine how to fix this error and what the error is?
	public static void main(String args[]){
		int[] myArrayOfIntegers;
		myArrayOfIntegers = new int[1];
		myArrayOfIntegers[0]  = 0;
		myArrayOfIntegers[1] = 3;
		}

Adding 1 element to An Array

Note: If you are doing a lot of adding and subtracting of array elements, you should use Vector or ArrayList. (Vector is preffered. Works better with threads)
CopyArray class
Adding an Element to an array using System.arraycopy.
	double[] originalArry ={1,2,3,4}; //stores original array 

	void addToArray(double[] array, double s)
	{
	   double[] tempArray = new double[array.length+1];
	   System.arraycopy(array, 0, tempArray, 0, array.length);
	   tempArray[tempArray.length - 1] = s;
	   originalArry =tempArray;
	//print out new array
	   for(double d :originalArry  )  System.out.println(d);
	   }


The old fashioned way : Add an element to an array via a loop. (Definitely not a recommended method for adding an element. Use arraylist or vector)
void addToArrayViaLoop(double[] array, double s)
		{
		   double[] tempArray = new double[array.length+1];
		   	for(int i =0;i<(tempArray .length-1);i++) tempArray[i] =array[i];
		   	tempArray[tempArray.length-1] = s;
		   	originalArry = tempArray;
		   	for(double d : originalArry ) System.out.println("new array elements"+d);
		}