News & UpdatesProgrammingWeb programming StoreMy Projects
Links
Affiliates

Java Tutorial – 04 – Variables

Variables are used for storing data during program execution.

Data types

Depending on what data you need to store there are several kinds of data types. Java has eight types that are built into the language. These are called primitives. The integer (whole number) types are byte, short, int and long. The float and double types represent floating-point numbers (real numbers). The char type holds a Unicode character and the boolean type contains either a true or false value. Except for these primitive types, every other type in Java is represented by either a class, an interface or an array.

Data TypeSize (bits)Description
byte
short
int
long
8
16
32
64
Signed integer
float
double
32
64
Floating-point number
char16Unicode character
boolean1Boolean value

Declaring variables

To declare (create) a variable you start with the data type you want it to hold followed by a variable name. The name can be anything you want, but it is a good idea to give your variables names that are closely related to the values they will hold. The standard naming convention for variables is that the first word should be lowercase and any subsequent words initially capitalized.

int myInt;

Assigning variables

To give the variable a value you use the assignment operator (=) followed by the value. When a variable is initialized (assigned a value) it then becomes defined (declared and assigned).

myInt = 10;

The declaration and assignment can be combined into a single statement.

int myInt = 10;

If you need multiple variables of the same type, there is a shorthand way of declaring or defining them by using the comma operator (,).

int myInt = 10, myInt2 = 20, myInt3;

Using variables

Once a variable has been defined it can be used by simply referencing the variable’s name, for example to print it.

System.out.print(myInt); // "10"

Integer types

As shown earlier, there are four signed integer types that can be used depending on how large a number you need the variable to hold.

byte  myInt8  = 2;  // -128   to +127
short myInt16 = 1;  // -32768 to +32767
int   myInt32 = 0;  // -2^31  to +2^31-1
long  myInt64 = -1; // -2^63  to +2^63-1

In addition to standard decimal notation, integers can also be assigned by using octal or hexadecimal notation.

int myHex = 0xF; // hexadecimal (base 16)
int myOct = 07;  // octal (base 8)

Floating-point types

The floating-point types can store integers as well as floats. They can be assigned with either decimal or exponential notation.

double myDouble = 3.14;
double myDouble2 = 3e2; // 3*10^2 = 300

Note that constant floating-point numbers in Java are always kept internally as doubles. Therefore, if you try to assign a double to a float you will get an error, because a double has a higher precision than a float. To assign it correctly you can append an “F” character to the constant, which says that the number is in fact a float.

float myFloat = 3.14;  // error: possible loss 
                       // of precision
float myFloat = 3.14F; // ok

A more common and useful way to do this is by using an explicit cast. An explicit cast is performed by placing the desired data type in parentheses before the variable or constant that is to be converted. This will convert the value to the specified type, in this case float, before the assignment occurs.

float myFloat = (float)3.14;

Char type

The char data type can contain a single Unicode character, delimited by single quotes.

char myChar = 'A';

Chars can also be assigned by using a special hexadecimal notation that gives access to all Unicode characters.

char myChar = '\u0000'; // \u0000 to \uFFFF

Boolean type

The boolean type can store a Boolean value, which is a value that can only be either true or false. These values are specified with the true and false keywords.

boolean myBool = false;

Variable scope

The scope of a variable refers to the code block within which it is possible to use that variable without qualification. For example, a local variable is a variable declared within a method. Such a variable will only be available within the method’s code block, after it has been declared. Once the scope (code block) of the method ends, the local variable will be destroyed.

public static void main(String[] args)
{ 
  int localVar; // local variable
}

In addition to local variables, Java has field and parameter type variables, which will be looked at in later chapters. Java does not, however, have global variables, as for example does C++.

Anonymous block

The scope of local variables can be restricted by using an anonymous (unnamed) code block. This construct is seldom used, because if a method is large enough to warrant the use of an anonymous block, a better choice is often to break up the code into separate methods.

public static void main(String[] args)
{
  // Anonymous code block
  { 
    int localVar = 10; 
  }
  // localVar is unavailable from here
}
Recommended additional reading:
Sams - Teach Yourself Java in 24 Hours