6.2. Initializing Local Variables of Primitive Data Types

Local variables: Local variables are variables that are declared in methods, constructors, and blocks.

Local Variables Initialization: Local variables will not get initialized to default values. You have to explicitly initialize the local variable before usage or else compiler reports an error.

			package javatutorial;

			 * Example class explaining the local variable initialization of primitive types
			public class LocalPrimitiveVariableInit {
				// Variable inside methods, constructor and blocks are called local variable.
				int age; // Not in any method/constructor/block , hence NOT a local variable
				float salary; 
				String name;
				public void sayHello(){
					String message = "This is local variable"; // local variable
					String reason = " beacause the variable is in a method"; // local variable
					// Printing the message
					System.out.println("Hello " + message + reason);

				public static void main(String[] args) {
					// local variable
					String anotherMessage = "This is another local variable in main method";
					int hoursWorked; // local variable will not be initialized to default value of 0		
			//		System.out.println("Hours worked : " + hoursWorked); // compiler wont allow this
					// Instantiate
					LocalPrimitiveVariableInit variableInit = new LocalPrimitiveVariableInit();
					// Instance variable are initialized to default values
					System.out.println("Default Salary is " + variableInit.salary);
					variableInit.sayHello(); // call the method and print message