The Java Developer's Resource, Chapter 4: Variables

In this chapter

Variables In this chapter, ????.


A variable is a box that holds a value. Each variable has three pieces:

All variables used in Java programs must be declared. This means you give their name and type (not in that order). For example, this line declares a variable of type String named title:

String title;

This line declares a variable of type int named numberOfColumns:

int numberOfColumns;

In Java you can change the value of a variable but you cannot change its name or type. You can create a new variable with a different name and sometimes even a different type and store the same value in that new variable. This may look like you're changing the name or type of a variable, but you're not really.

Before you do anything with a variable, you should assign a value to it. The value can be given as a literal, as another variable whose value is copied, or as the return value of a method call. For the moment let's concentrate on literals. The equals sign is the assignment operator. The variable being assigned to goes on the left hand side. The value being assigned from goes on the right hand side. This line of code assigns the value "American Journal of Biochemistry" to the variable title:

title = "American Journal of Biochemistry";

This line of code assigns the value 23 to the variable numberOfColumns:

numberOfColumns = 23;

note about use of equals sign to not mean equality????

Primitive Data Types


Variable names are just one member of a broader class of names in Java. These names are called identifiers. They are used to name variables, classes, methods, fields, packages, and a few other things. The names of all these things follow the same rules for what are legal and illegal names.

rules from course notes????

Naming Conventions

As far as the compiler is concerned a name that works for a method works equally well for a variable and a class. Human beings aren't nearly so forgiving however. Java defines a number of conventions for how different quantities should be named. You don't have to follow these conventions, but if you do your code will be much easier for other programmers to read.

The first convention you should be aware of is that variable names begin with lower case letters. If they are made up of more than one word, then the words in the name are identified by use of internal capitalization. For example, ????

Previous | Next | Top | Cafe au Lait

Copyright 2000 Elliotte Rusty Harold
Last Modified December 28, 2000