Names for Variables

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Is the following declaration correct?

int answer;
double rate = 0.05;

Answer:

Yes— as long as the names  answer  and  rate  have not already been used.

Names for Variables

The programmer picks a name for each variable in a program. Various things in a program are given names. A name chosen by a programmer is called an identifier. Here are the rules for choosing an identifier:

  • Use only the characters 'a' through 'z', 'A' through 'Z', '0' through '9', character '_', and character '$'.
    • An identifier can not contain the space character.
  • Do not start with a digit.
  • An identifier can be any length.
  • Upper and lower case count as different characters.
    • SUM  and  Sum  are different identifiers.
  • An identifier can not be a reserved word.
  • An identifier must not already be in use in this part of the program.

A reserved word is a word which has a predefined meaning in Java. For example int, double, true, and import are reserved words. Rather than worry about the complete list of reserved words, just remember to avoid using names that you know already mean something, and be prepared to make a change if you accidentally use a reserved word you didn't know.

As a matter of programming style, a name for a variable usually starts with a lower case letter. If a name for a variable is made of several words, capitalize each word except the first. For example, payAmount and grandTotal. These conventions are not required by syntax, but are useful to follow since they make programs more readable.

QUESTION 6:

Which of the following variable declarations are correct?

int myPay, yourPay;

long good-by ;

short shrift = 0;

double bubble = 0, toil= 9, trouble = 8

byte the bullet ;

int  double;

char thisMustBeTooLong ;

int 8ball;

float a=12.3; b=67.5; c= -45.44;