5. Variable Declarations

Let's take a closer look at the declaration and initialization of primitive and reference types.

5.1. Declaring and Initializing Variables

Variable: A variable stores a value of a particular type. A variable has:

In Java, variables can only store values of primitive data types and reference values of objects.

			package javatutorial;

			/**
			 * Example class to identify various pieces in variable declaration in primitive types
			 * A variable has:
			 *     name – name of the variable.
			 *     type – type of the value it holds.
			 *     
			 * @author f5java.com
			 */
			public class VariableDeclaration {

				// 1. int is type, i.e. variable age can hold value of type int
				// 2. age is the name of the variable
				int age;

				float salary; // type is float, name is salary

				double intRate; // type is double, name of the variable is intRate;
				
				// Note in the above examples that we have only declared variables to hold
				// various types, it has not been initialized yet.

			}
		

Declaration + Initialization: It is always a good idea to initialize the variable as soon as you declare it. Often in Java programs, declaration of the variable is combined with initialization (assigning initial value to the variable while declaration) as follows

			package javatutorial;

			/**
			 * Example class showing the common practice of variable declaration + initialization
			 * in Java real world coding 
			 *     
			 * @author f5java.com
			 */
			public class VariableDeclarationInitialization {

				// 1. Declaration and initialization can be done in one statement as follows
				
				int age = 18; // usually done to set default values, setting the default values as 18 in our case

				float salary = 0; // default value of salary is 0

				double intRate = 6.0; // setting the initial value as 6.0 for intRate	

			}