OCAJP 7 Tutorial: Declare and initialize variables
A variable is a container that holds values that are used in a Java program. Before use a variable in our program it needs to be declared.
How to Declare a Variable
In Java every variable must have a data type associated with it. A variable could be declared to use any one of the following eight primitive data types: byte, short, int, long, float, double, char or Boolean. To declare a variable in Java, all that is needed is the data type followed by the variable name.
In the above example, a variable called "add" has been declared with a data type of int and the line ends with a semi-colon.
Before a variable can be used it must be given an initial value. This is called initializing the variable.
varName = Value;
You may initialize the variable at the same time of declaration.
dataTypevarName = Value;
The name given to a variable is known as an identifier. There are certain rules for identifiers,
- Reserved words cannot be used.
- Identifiers cannot start with a digit but digits can be used after the first character.
- Identifiers can start with a letter, an underscore or a dollar sign.
- You cannot use other symbols or spaces.
Primitive types are predefined by Java and their names are reserved keywords. Primitive variables store primitive values. There are eight primitive types in Java programming language:
byte, short, int, long, float, double, boolean, char
Reference types are any instantiable class as well as arrays, reference variables store addresses.
String, Scanner, Random, int, String, etc.
Reference Variables V/S Primitive Variables
There is a difference between reference variables to an object and primitive variables,
The value of a variable of type reference to object is a reference to an object, and not the object itself.
The value of a variable of a primitive type is a value of the primitive type itself (and not the reference to a value or an object).
OCAJP 7 Resources
EPractize Labs OCAJP 7 Training Lab
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)