Java Tutorial/Variables

Note: Some examples in this section do not have the class declaration and main method declaration parts. You can copy this from the previous lesson and place any code within the main method.

You can assign, edit, and retrieve data from variables. Before doing any of this, however, you must declare them, as follows:

Basic Data Types
The basic "types" you can use are as follows:

Therefore, you can declare integer myInteger like:

To assign a value to a variable (that has been declared) you can use the assignment operator :

You can also use a shorter method by providing a variable initializer:

You can retrieve the value of a variable simply by typing its name, like:

Math with Numbers
There are several variables you can use with numbers, and here are two:

For example (including class and main method declarations):

Note: Java uses order of operations in its math.

Arrays
An array is a set of values.

Each [x] section is one of the "thing". As you can see, they begin not at 1 but at 0. An example of declaring an integer array:

Once the array is created, you can access individual elements in the array as if they were variables (e.g. myIntArray[0], myIntArray[1] and so on.)

The details of arrays will be discussed in a later lesson.

Data Structures
(To be added)

Exercises

 * Add, subtract, multiply, and divide numbers and see what weird things you get (like dividing integers, and storing into another integer when it isn't exact)
 * Check out the remainder operator, for example: