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:

type name;

Basic Data Types edit

The basic "types" you can use are as follows:

Name Description
int An integer like 32
float A number with a decimal like 2.7
double A double precision number with a decimal like 3.141
boolean A value that represents true or false
char A character, like 'c' or 'n'
String Text, like "Hello World!"

Therefore, you can declare integer myInteger like:

int myInteger;

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

int myInteger;
myInteger = 3;

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

int myInteger = 3; //combine two steps into one

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

int myInteger = 3;
System.out.println(myInteger); //print the integer

Math with Numbers edit

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

Arithmetic Operators
Symbol Description Example
+ Adds two numbers together myInt + otherInt; would add myInt and otherInt together
- Subtracts one number from another myInt - otherInt would subtract otherInt from myInt
* Multiplies two numbers myInt * otherInt
/ Divides one number by another myInt / otherInt
% Divides one number by another and produces the remainder myInt % otherInt

For example (including class and main method declarations):

public class AddTwoNumbers {
    public static void main(String[] args) {
        float num1 = (float) 1.5;   // The "(float)" "casts" the number as a single precision number
        float num2 = (float) 1.7;   // Without the cast, the Java compiler will interpret a number with a decimal point
                                    // as a double precision constant.
        System.out.println(num1 + num2); // would output 3.2
    }
}

Note: Java uses order of operations in its math.

Arrays edit

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:

int size = 4;
int[] myIntArray = new int[size];

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 edit

(To be added)

Exercises edit

  • 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: 5 % 4
Previous: Hello World! Up: Java Tutorial Next: Control Structures I - Decision structures