Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/articles/java-tutorials/)
-   -   Arrays in Java (http://www.go4expert.com/articles/arrays-in-java-t1127/)

pradeep 5Aug2006 14:47

Arrays in Java
 
When many items of data of the same class or type have to be stored, it is more efficient to use an array than separate variables or objects.

For example, if the temperature on each day of the (non-leap) year had to be stored, rather than set up tempjan1, tempjan2... tempdec31 (365 variables) we would use the declaration:

Code: Java

double[] tempArray = new double[ 365 ];


The array variable tempArray stores 365 doubles, indexed from 0 to 364. Accessing the values in the array is done by using the index as follows:

Code: Java

tempArray[ 0 ] = 0.0;
 lastDay = tempArray[ 364 ];

Normally, arrays are processed using a for loop.

Example code

This is the code needed to find the average temperature for the year:

Code: Java

double total=0.0, average;
 int size = tempArray.length;
 for ( int index=0; index < size; index++) {
    total += tempArray [ index ];
 } // end for
 average = total / size;


The above code uses the attribute ‘length’ of the array variable.

Initialising an array

The following line initialises the values and sets the size of an array to represent student grade values:
Code: Java

char[] grades = { 'A', 'B', 'C', 'D', 'E' };


The array ‘grades’ has 5 elements, each a char(acter).

Arrays of objects

Consider

String[] words = new String[ 25 ];

The variable words holds 25 String references, but not the Strings themselves, which must be instantiated using ‘new’, eg:

words[0] = new String ("example text");

An array can be a formal parameter, as in:

... main ( String[] args) {

which is the method Java uses to pass command line parameter values into a program: args[0], args[1] etc.

abcdou 11Aug2006 14:18

Re: Arrays in Java
 
hi pradeep!

how about in two dimensional array?

The output is:(Table Students)

Lastname Firstname Address
abcdou dou philippines

how to make a code that has a method/function:(two classes)
1. Assign name
2.Display name
3.Search name(What index?)
4.sort in descending

pls..............

macknonalds 9Jan2007 17:20

Re: Arrays in Java
 
two-dimensional array?

Its just the same as a simple array, but the difference is that you need to control/manipulate 2 indexes of a certain array; commonly the "i" and "j" indexes... Two-dimensional array do have rows and columns which a certain data can be stored....

Just follow how pradeep teaches us how to make use of an array, then apply it to a two-dimensional array.....

<filipino><taga san ka nga pla sa pinas?></filipino>


All times are GMT +5.5. The time now is 08:32.