| data types | scope | Exercises |
In your Basic Programming class, you used variables in your programs. Sometimes it's just for convenience and sometimes it's absolutely necessary. Think about some of the different ways you might have used variables. In a FOR-NEXT loop, you used a variable to count the steps through the loop:
DIM n AS INTEGER
FOR n = 1 TO 20
When you wrote a program that asked the user a question, you had to use a variable in order to store the answer to the question.
DIM playerName AS STRING
INPUT "What is your name"; playerName
Without the variable called "playerName," there would be no way to remember the player's name and use it later on in the game. Variables are directly connected to the use of the computer's memory. When you establish a variable in your program, you are requesting that a certain area of memory be identified and reserved to hold some information. In BASIC, you did this with the DIM keyword. Here are some examples of declaring variables in Java:
int n;
String playerName;
Both examples follow the general syntax of:
typeOfVariable     nameOfVariable;
Java is known as a "strongly-typed" language. You are not allowed to introduce a variable without specifying its type. You do have a choice about when you actually assign a value to the variable. If you wish, you may initialize the variable at the same time as you declare it:
String myName = "Tyler";
int numNeighbors = 5;
boolean gameOver = false;
You also can declare a variable without initializing it:
String myName;
And then some place later in the code, you would initialize it like this:
myName = "Tyler";
You use the assignment operator (=) in order to assign the variable a value. Notice that you only state the data type at the first declaration. After that, you just refer to the variable name and the compiler knows what type it is. Assignment follows this syntax:
nameOfVariable = expression;
The expression must be of the same type as the variable.
You may use any name you want for your variable, with just a few restrictions. You can't use one of the reserved Java keywords. There really aren't too many of those; you can see a list here. Also, you have to be sure that the first letter of your variable name is in fact a letter (not a number). After that you may use numbers within the variable name. The convention for typing variable names is the same one that you learned in Basic Programming. You keep the first letter lower case and then capitalize any subsequent words in the variable name, as seen here:
addressList
numBlackSquares
In Java, the most basic data types are known as "primitives." When you establish a primitive variable, the computer knows exactly how much memory to allocate for the variable. The most efficient primitive is a boolean. It's only got two possible values: true or false:
![]() boolean |
|
To store that information takes only one bit of memory. The other primitives require more memory. You will most commonly be using the integer primitive, abbreviated as "int," which takes up 32 bits of memory. See a complete list of primitives here.
When you declare a primitive variable, you always use lower case letters for the data type. Java is a case-sensitive language. The names of the primitives are all Java keywords, and keywords are always lower case in Java. If you were to try declare an integer variable this way:
Int score = 0;      won't work!
the compiler would not recognize it and you would get an error message. Try that out to see what the error message is.
When you assign the value of a primitive variable, you may use what is called a "literal" or you may assign it with an expression that includes the name other variable of the same type. Here is an example of an integer literal:
![]() int |
|
And here is an example of using an existing variable to assign the value of a new variable:
int boxHeight = 2 * boxWidth;
If you cannot store your numerical information with a whole number, you can use a primitive type known as float:
![]() float |
|
The "f" at the end of .25 is used for a float literal. Without the "f," .25 would be a double literal. Doubles are another type of primitive, and they offer more precision than floats do:
![]() double |
|
Primitives also include a data type for characters. A char is only a single character--a letter, a digit, or a symbol such as $. It is stored in memory as an integer, according to the Unicode convention that assigns a particular number for each character. You do not need to know any of those numbers in order to use char variables. Initialize a variable of type char like this:
![]() char |
|
In Java, there are two kinds of variables: primitive and reference. With reference variables, it's not definite how much memory will be required to store the variable. They are actually stored in a different location in the computer (the "heap" instead of the "stack", if you are interested in that type of thing). A string is an example of a reference type. When you declare a string variable,like this:
String letterToEditor;
it could be very short or very long. It does not have a definite size. (Of course there is a boundary on just how many characters it will allow the string to contain, but that maximum is quite high. In fact, when you type code in the Java editor, your entire document is stored in just one string variable.) In contrast, when declaring a primitive variable:
int numPlayers;
32 bits of memory are automatically allocated to hold the value of numPlayers.
When you mention numPlayers in code, the variable directly holds the value of that number. When you mention letterToEditor in code, the variable doesn't hold the actual text of your string. Instead it holds the address where that text can be found. For more complicated types of reference variables, such as a button, there is a lot of information to know about that button--its size, text, color, position, enabled status, etc.. Again, the variable holds the address where all of that information is stored.
All reference variables are objects in Java, whereas primitives are not objects. As in the case of the button, there are a lot of different things to know about an object. These features are known as the "fields" of the object. Furthermore, objects can do things. For your first few coding challenges, you will be working with strings, which are objects. Strings can do things, like tell you what their 5th letter is. An ability to do something is known as a "method" of the object. Objects have fields and methods, but primitives do not. If an integer variable equals 28, that's it. That's the only thing to know about that int, and you can't ask the int to do anything for you.
By convention, reference data types are capitalized. Examples of some of the existing data types include:
Label    
Date    
Color    
Polygon
These are only examples. There are actually hundreds of available types and people are always making more of them. You do not need to know about all of the types in order to use Java effectively. There are probably very few people in the world who are familiar with all of Java. The types that come from Sun Microsystems, Inc. are all listed in the API Specification, which you have as an icon on your Novell-delivered Applications. You will be consulting that document frequently to find out what the various objects can do. You can look up Label, Date, Color, etc. and see the fields and methods of that class. You cannot look up "int" or "boolean," however, because those are primitives.
In Java, you can declare a variable of type Label in exactly the same way that you declare an integer variable:
Label instructionLabel;
Notice that it still uses the syntax of:
typeOfVariable nameOfVariable
but now the type of variable is "Label" rather than "int." In order to use Label as a variable type in your program, you will need to put this statement at the very top of the file:
![]() import |
|
Without this import statement, you will get a "cannot resolve symbol" error. The compiler won't recognize Label as an established Java class. There are so many different Java classes that they are grouped into packages and stored in library files separate from the compiler. One package, called java.lang, contains the most frequently used classes such as String, Object, and Math. That package is imported automatically for you.
Once you declare your variable of type Label, you will not be able to use a literal to assign its value, as you could with primitive variables. (Strings are an exception; they are the one reference data type that allows you to use a literal for assigning value.) To assign a variable of type Label, you will typically do something like this:
![]() new |
|
The scope of a variable tells you how long that variable will be available to you in a program. It all depends on when you declare the variable. If you declare the variable inside a loop:
start of loop{
int numPlayers = 5;
stuff to repeat inside of loop
}end of loop
the variable named numPlayers is alive only inside that loop. Once the loop finishes its last iteration, there is no longer an integer variable called numPlayers. The memory that numPlayers was tying up is released, and you won't be able to get access to the value of numPlayers. Compare that to this situation:
int numPlayers = 5;
start of loop{
stuff to repeat inside of loop
}end of loop
System.out.println("there are " + numPlayers + " players.")
Here the variable numPlayers will continue to exist after the loop is done. I can still refer to it if I want to, as I did when I printed the sentence about how many players there are. The scope of a variable really means the region of code where it stays alive. That region is marked off by curly braces {}. In the first example of variable scope above, the scope of numPlayers ends when the }brace of that loop closes. In the next example, though, the variable is declared before the start of the loop. That's why it's still alive after the }brace closes the loop. Instead, it is contained inside of some larger pair of braces, perhaps inside of a method. It will be alive until the }brace closes the method. This will make more sense once you start learning how to make your own loops and other structures.
The scope of a variable might be inside of a loop, or an "if" block or a method or a whole program. You should keep the scope as local as possible. Don't keep a variable alive for the whole program, if it's only needed in one small section of the code. This is not simply to save on memory (which you really don't need to worry about). It's important because it helps you to avoid errors. If a variable is floating around, you might end up using it again without realizing that its value got set in some other section of code. You might be surprised by what that value is, and it could cause an error that is difficult to track down.
| Read more about variables: | Sun Java tutorial. |
| David Eck's textbook. |
Open up the file MyFirstApp.java. Change the code in MyFirstApp so that you forget the semi-colon at the end of line 3. What kind of error message do you get?
Experiment with other mistakes in the code for MyFirstApp, so that you can familiarize yourself with various types of error messages. You may need to scroll the error window so that you can see the full message (or resize the window if you wish).
What do you suppose it means when you get the message "cannot resolve symbol"? See how many different things you can do to get that message. What do they all have in common?
Here is a short program that will allow you to experiment with char primitives:
public class Test{
public static void main(String[] args){
char testChar = 121;
System.out.println(testChar);
}
}
As mentioned above, char primitives are stored as integers, even though they are displayed as actual characters on the screen. Try changing the value of the integer assigned to the variable testChar and see what you characters you can get to appear on the screen.
Try using a keyword as a variable name and see what kind of error message you get.
Write a program that will demonstrate the difference between floats and doubles. Check to see how many decimal places are displayed for each type of number.
What's wrong with this variable assignment?
boolean switchOn = 0;
Try declaring the same variable twice within the same method. See what error message you get.
| Previous Topic | Java Home Page | Syntax Sheet | Next Topic |