Java Lesson 4: Variables



The history of computers is deeply rooted in mathematics; in fact, one of the motivations for inventing the first computers was to calculate ballistic trajectories and logarithm tables. If you have a cannon that fires a projectile at 400m/s, at an angle of 45 degrees above the horizon, then how far will the projectile travel? Variables are used in mathematical equations like this one

Formula d = v squared times sine of 2 times a, divided by g

and in programming languages for the same reason.

Variable Declarations

You may remember that identifiers are names given to program elements, including variables. Thus, the rules for naming variables follow the same rules as for naming identifiers.

Every identifier that represents a number or a character must be declared to be a certain type before the identifier appears in an executable statement. This is accomplished by a type declaration. A declaration associates one or more variables with a specific data type.

A declaration consists of a data type, followed by one or more variable names (each separated by a comma), and ending with a semi-colon.

A variable can also be declared and initialized with a value at the same time.


Occasionally, some “variables” are not intended to “vary” at all; rather they are intended to remain constant during program execution. We call these constants, and in Java, they are spelled with all upper case letters. If the constant name consists of more than one word, then separate each word with the underscore (_) character.

Variable Scope and Lifetime

All variables have two attributes known as scope and lifetime. The scope of a variable is the portion of the program code where use of the variable is valid. Variables also have a lifetime, which means that they are instantiated (defined and allocated memory), used, and then they are destroyed (deallocated) and the memory that was allocated to them is returned to the computer for any other use.

In many programming languages, a variable’s scope is either global or local. Global variables are usually defined in the main() method, and exist for the entire lifetime of the program, and these variables are accessible in all parts of the program. Local variables exist for a limited duration and within a block of code.

Java is a little different in that its two major scopes are those defined by a class and those defined by a method, rather than as global or local. Our discussion of scope will be somewhat simplistic until we learn about classes and methods in Tutorial Lessons 9 and 10. Suffice it to say that the scope of a variable is from the point it was declared to the end of the block it is in.

In Java, variables are declared within a block. A block starts with an opening curly brace ({) and ends with a closing curly brace (}). A new scope is created every time you start a new block. In the code fragment below, the scope of variable g is the entire main() method. The variable g can be accessed many lines of code later.

In contrast, the variable i in the following code fragment is limited to the while-loop, and it cannot be used or accessed outside of the while-loop (ie. it cannot be used outside of the curly braces which enclose the while-loop).

If you try to compile the above code the Java compiler will report the error, “cannot find symbol” on the System.out.println line because the variable i is not in scope at that point in the program.

The variable i could be made accessible at that point by defining it before the while-loop; as in the following code fragment:

In general, variables declared inside a block are not accessible to code outside that block. Within a block variables can be declared at any time you wish, but they are valid only after they are declared.

So how do you know where to declare a variable? Usually you should declare them closest to where they are used, and only for the smallest scope needed to accomplish the task at hand. In this way variables are less likely to be incorrectly accessed or inadvertently modified by parts of the program far away from where they are intended.

Program Example 4

Program 4 uses the mathematical equation discussed in the Introduction of this tutorial to calculate ballistic projectile trajectories.

Figure 4.2 Projectile trajectory.


Let’s start by diagramming the situation. A cannon fires a projectile at 400.0 m/s at an angle of 45 degrees above the horizon. The projectile travels in a parabola-shaped arc because gravity is acting upon it. The projectile lands some distance away. The purpose of our program is to determine how far away the projectile landed.

Our equation requires a constant for the standard acceleration due to gravity on the surface of the Earth. This is denoted by the symbol g, and happens to be approximately 9.807 m/s2 (meters per second squared). As you may recall, in Java constants are all uppercase letters, so we will use G for this constant.

  • G = the gravitational constant 9.807 m/s2.

Next, we will define some variables:

  • v = the velocity 400 m/s.
  • a = the angle 45 degrees.
  • d = the distance the projectile travels, measured in meters.

The equation makes use of the Java built-in Math.sin() method; however, it (like all Java trigonometric functions) uses parameters in radians. We need to convert degrees to radians. Fortunately, Java provides another method, Math.toRadians() to do this, and we can make use of it instead of doing the conversion ourselves. We will use a temporary variable (a variable used only for a short time for intermediate calculations), aInRadians, to store the angle in radians.

Next, we write the equation in a form that Java will understand:

Notice that parenthesis and spaces are used where necessary to make the meaning clear, v is multiplied by itself to square it, and the entire numerator is divided by the denominator G.

We will declare our variables to be of type double for three reasons:

  1. We want a higher precision than can be obtained with the integer type.
  2. The Java trigonometric methods require double arguments.
  3. The gravitational constant is a real number (i.e., it has numbers after the decimal point).

Finally, we display the results in a format that is helpful to the user using the System.out.println method.

Now, enter the above code into your computer, compile and run it. Your results should look like the following:


The projectile traveled more than 16314 meters, which is 16.314 km, or 10.137 miles!

As an exercise, modify the program to use different values for the velocity v and run the program again. What happens if the velocity is less, such as 200 m/s? Will the distance be more or less?

As another exercise, suppose the cannon is on the moon, where gravity is only about 16.6% that on the Earth’s surface, or 1.6249 m/s2. Change G to

compile and run the program again, and see what the new distance is. It’s a lot farther, isn’t it?


In this tutorial we learned how variables are defined and used in Java programs similar to how they are used to solve mathematical equations. Each variable in Java has a specific type, which serve different purposes and determines the size and layout of the variable’s memory. For more practice see Java Snippet 1: Convert F to C for another scientific calculation.

Next Lesson

Next we will move on to Operators and Expressions.



  1. […] we learned in Lesson 4, variables store a value, such as the number 4, in a named location. Arrays in Java are a very […]

  2. […] we learned in the lesson on Variables, in order to use a variable you must first declare it. The following declares a variable of type […]

Leave a Reply