Main Content

Setting up individual variables, and arrays, in Java - some commented examples

Archive - Originally posted on "The Horse's Mouth" - 2010-11-09 14:32:39 - Graham Ellis

In Java, variables must be defined before they have an initial value assigned to them, and they must have an initial value assigned to them before the value thay contain is used; there's no automatic assumption that a new name is a variable, nor is there an assumption made of what type of data a variable can contain.

[Here]'s an example of a "first day program" that I wrote on yesterday's Starting Java Course showing this setup of variables, calculations using them, and output. Keyboard input in Java isn't straightforward, so I used a class of my own to provide a method which hides the complicated bits of that stage within in - and that's [here].

Following of from that example for newcomers to coding, I provided an example with a loop - [here] - showing the same principle in use, but now with a repeating block of code too. Note - in both of theses examples - how vital it is to have to code well commented to make it followable!

Arrays similarly need to be defined (telling Java what type of data they'll contain) and their length needs to be set up / memory allocated too via the new keyword. Arrays in Java start at position number 0, so an array with 7 members has elements numbered 0 through to 6 inclusive (it's very easy for this to confuse you!)

You'll want to set up an array, you'll want to fill it with values. You'll want to echo those values out, find the lowest and highest values, and do a lot more. I've just written an (over)commented example [here] so you can see how many of those things are done ... no longer on the first day of the course and just for newcomers to Java ... we're now into the Java Bootcamp Course!.