How do I declare a variable?

I guess the first question is "what does it mean to 'declare a variable'?".  The Java language has a standard vocabulary of words, including words like "class", "int", "extends", and punctuation like curly braces, commas, semicolons, parentheses, etc.  When you create a variable, you're (temporarily) adding a new word to Java's vocabulary.  If you were teaching Spanish to a friend, you might at one point say "Here's a new word: ventana.  It's a feminine noun, and it means 'window'."  Similarly, when you teach Java a new word, you have to be very clear that you are giving it a new word, and you have to tell Java what kind of a word it is.  This is all done by typing the name of the type (or class) of the variable, then a space, then the (new) name of the variable. Here are two examples:
        int x
        Person prof
Once this is done correctly, you should be able to refer to that name later on in the same file and Java will know what you're talking about.

There are three kinds of variables in Java: parameters, local variables, and instance variables.  All three of them are declared with exactly the same syntax as above: a type (or class) name, a space, and the new name of the variable.  They differ in where you put all this.

class Dummy {
	void doSomething (String thisIsAParameter, int thisIsAnotherParameter) {
		String heresALocalVariable;
		int andHereIsAnotherLocalVariable;
		}
	String thisOneIsAnInstanceVariable;
	int andSoAreBothThisOne, andThisOneToo;
	}
The three kinds of variables differ in several interesting ways: where they are visible, how long they live, and how they get values.
Visibility Lifetime How do they get a value?
Parameter the body of the method in which they are declared disappear as soon as the method in which they are declared returns matched up automatically with arguments when method is called
Local variable assignment statement in the method, typically immediately after declaring the variable
Instance variable the whole class in which they are declared as long as the class instance exists assignment statement in any method in the class, most often a constructor method.

Last modified: Tue Feb 8 15:24:11 EST 2000
Stephen Bloch / sbloch@adelphi.edu