wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Array vs Variable?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array vs Variable??" Watch "Array vs Variable??" New topic
Author

Array vs Variable??

Jeremy Parsons
Ranch Hand

Joined: Apr 21, 2006
Posts: 74
I am just learning arrays and have a snippet of code from my book shown here..

My question is why use an array instead of a variable? They look almost exactly alike to me..
Jeroen T Wenting
Ranch Hand

Joined: Apr 21, 2006
Posts: 1847
In that example there's no clear reason, but then it's only meant to show the syntax of arrays and not their justification.

Arrays are nice for grouping sets of similar data together and passing them as one.
Say you have a method that prints a set of data but you don't know when writing the method how large that set is going to be.
You could use an array to pass the data into that method and loop over it.

And that's just one use, but a common one.


42
John Bartlett
Ranch Hand

Joined: Jan 25, 2006
Posts: 116
Hi,

A simple change to your code will hopefully give you an idea of how usefull arrays are.




So much easier than writing a series of system.out.println's. Also imagin if there were hundreds of salaries in the array!!

Arrays are extrememly useful, altho they do have there limitations which is why i tend to use the dynamic Lists i.e ArrayList.

John Bartlett
[ September 06, 2006: Message edited by: John Bartlett ]
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I wish I could properly attribute this but I've forgotten where it came from: The only good numbers in a program are zero, one and infinity.

If you coded

double salary1 ...
double salary2 ...
double salary3 ...
double salary4 ...
print salary1
print salary2
etc

the effort to expand from 4 fields to 5 would be pretty big, potentially affecting many methods in your system. I worked with a mainframe system with a count of "7" coded so many places it could never be changed to "8". The effort to expand the array and loop is much smaller ... just resize the array. The effort to expan a collection is even less, but beyond today's example

So back to "zero, one, infinity" ... if you're going to have more than one of something, think about supporting "any number" of something.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Array vs Variable??
 
Similar Threads
A Quadrilateral extend program
Needs help in editing
Casting problem
java code problem
Polymorphism example