This Java video tutorial demonstrates the syntax for declaring and initializing variables in Java. We also give examples to show that variables can vary their value. As we mentioned, Java variables are typed. That is, variables are created to store exactly one particular type of data.
Java has eight primitive data types: byte, short, int, long, float, double, char, and boolean. Variables can be created to be of any of these types, as well as more complex types that we will explore in later lessons. A variable of a primitive type can be assigned any value in the range specified by its type in the table below.
In order to declare a variable, we write its type followed by its name and a semicolon, as shown:
In a variable a name, we can use any uppercase and lowercase letters, numeric digits, the "$" character, and the "_" character. However, we can not begin the name of a variable name with a numeric digit. When naming variables, we prefix the names with lowercase letters to indicate the type of the variable. This is called Hungarian notation, and you can find a full description of Hungarian notation in our Java reference section.
After we declare a variable, we can assign it a value. In fact, we can assign it a value over and over again, and we must assign it a value before we use it or the compiler will complain. We can even declare and initialize a variable with a value in one line, as shown:
double dMyDouble = 3.14159;
Multiple variables can be declared or assigned in one line. The code below demonstrates how we can declare two boolean variables in one line and then assign them both the value false in the next line. Then we output the values in the last four lines.
boolean bResult, bIsDone; bResult = bIsDone = false; System.out.print("bResult = "); System.out.println(bResult); System.out.print("bIsDone = "); System.out.println(bIsDone);
If this code is added to the default program and we compile and execute it, we see this in the output pane.