You can only initialize a variable in a declaration!
YOU CAN ONLY INITIALIZE A VARIABLE IN A DECLARATION!
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.
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.
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.