Incremental Java
Initializing Primitive Variables

Initializing Variables

You can only initialize a variable in a declaration.

You can only initialize a variable in a declaration!

YOU CAN ONLY INITIALIZE A VARIABLE IN A DECLARATION!

Initializing Variables, Again

Java designers believe every variable should be properly initialized. To initialize a variable is to give it a correct initial value. It's so important to do this that Java either initializes a variable for you, or it indicates an error has occurred, telling you to initialize a variable.

Most of the times, Java wants you to initialize the variable. If Java does initialize for you, it sets the value to 0, or the closest thing to 0 for the appropriate type. However, it usually asks you to initialize.

Here's a problem you need to be aware of. There's initializing, which is giving a variable an initial value, and then there's an initializer, which can only be used during declaration.

We're going to look at an initializer.

  int x = 10 ;
This creates a box called x with type int and writes a value of 10 in the box.

The syntax for an initializer is the type, followed by the variable name, followed by an equal sign, followed by an expression. That expression can be anything, provided it has the same type as the variable.

In this case, the expression is 10, which is an int literal.

We can use more complicated expressions.

  int x = 10 + 2 * 3 ;
We'll talk about expressions in more detail soon. Hopefully, it's obvious what we're trying to do.

Can Initialize Some Variables

We can initialize some variables, such as:
  int x = 10, y, z = 3 ;
In this case, x and z have been initialized, but y has not.

Java won't complain about y not being initialized until it gets used in the program. If it does get used, it complains.

Initializing With Compatible Types

When you initialize a variable, use a literal of a compatible type. (Later on, you can use an expression of a compatible type). In other words, if you declare an int variable and want to initialize it, use an int literal (later on, you can use an int expression).

Don't initialize an int variable with a boolean literal (usually this is an error, but not always), unless you know why you're doing it.