Non Initialized Local Variables

In a previous post I presented you with a table with the primitive data types available in Java.

The table had a default value for each one of the different types. This means you should be able to use a variable as soon as you declare it, even you don’t explicitly give it a value.

The following example tries to print a local variable before it’s initialized. According to the table, it should print a zero.

public class Example {

	public static void main(String[] args) {
		//create an instance of the class
		Example instance = new Example();
		//invoke method
		instance.print();
	}

	// method
	public void print() {
		//declare local variable
		int result;
		//causes error, can't compile
		System.out.println(result);
	}
}

The code above cannot be compiled. It will throw the error: The local variable result may not have been initialized. The Java compiles expects that we initialize the local variable before we try to use it.

Now take a look at this code. We declare the variable as a member of the class instead of a local variable in the method. This code will run fine without initializing the variable.

public class Example {

	//private member
	private int result;

	public static void main(String[] args) {
		//create an instance of the class
		Example instance = new Example();
		//invoke method
		instance.print();
	}

	// method
	public void print() {
		//will print 0
		System.out.println(result);
	}
}

Of course I’m not saying you should make every variable a member of the class. Just give the variable a value when you declared. The above examples are just to compare the behavior of the compiler in each situation.

Get Free Updates
Related Posts
Comments