int cost ;Write down the name of the type, then an identifier, then a semicolon. When the program is run, and it sees this declaration, a box is created with name cost and type int.
In any scope (we'll explain scope later), you can only declare a given name once. For example, I can't declare cost and then declare it again.
int cost ; int cost ; // ERROR! Declaring cost a second timeThe double slash you see in red is called a comment. Comments are ignored by Java. They are used by programmers like you and me. They help you and others to understand the program you've written.
The rule is:
int cost, tax, surcharge ;We've declared three variables, each of type int. This creates three different boxes.
We've put the variables on the same line, but we could do:
int cost, tax, surcharge ;Java doesn't care about spaces. A space can be replaced by 5 spaces or 10 spaces. You can hit return once or not at all or a hundred times. However, most Java programmers wouldn't spread out the spacing as above.
My preference is to start a new declaration on each line.
int cost ; int tax ; int surcharge ;
int cost, tax, surcharge ;as the type name, "int", followed by whitespace, followed by a variable name, "cost", followed by whitespace, followed by repeat pattern, ", tax", followed by repeat pattern ", surcharge", followed by a semicolon.
Do these rules sound complicated? I give you the rules in this way because Java defines them in this manner.
However, don't worry. It's simple. Put a type name, and a list of variables separated by commas, ending in a semicolon.
int earningsInJanuary, earningsInFebruary, earningsInMarch, earningsInApril, earningsInMay, earningsInJune, earningsInJuly, earningsInAugust, earningsInSeptember, earningsInOctober, earningsInNovember, earningsInDecember ;This is perfectly valid Java. It is a single declaration (of many variables). However, it uses up four lines.
I prefer to break it up into four declarations, putting each declaration on one line. I find it easier to look up the type---once you find the variable, you just look all the way to the left to find its type.
You don't have to do this, but I like it better this way.
Here's how I would rewrite it:
int earningsInJanuary, earningsInFebruary, earningsInMarch ; int earningsInApril, earningsInMay, earningsInJune, earningsInJuly ; int earningsInAugust, earningsInSeptember, earningsInOctober ; int earningsInNovember, earningsInDecember ;This is four declarations instead of one. Java doesn't particularly care which way you do it, so think of this as a style rule.