Java assigns a default value to a local variable in a method if the variable is not initialized.

Become a member of our community to ask questions, answer people's questions, and connect with others.

Have an account? Sign In

Primitive data types are built-in data types in java and can be used directly without using any new keyword. As we know primitive data types are treated differently by java cause of which the wrapper class concept also comes into play. But here we will be entirely focussing on data types. So, in java, there are 8 primitive data types as shown in the table below with their corresponding sizes.

Data Type Size
Byte 1 byte
Short 2 bytes
Int 4 bytes
Long 8 bytes
Float 4 bytes
Double 8 bytes
Boolean 1 bit
Char 1 byte

Now, here default values are values assigned by the compiler to the variables which are declared but not initialized or given a value. They are different according to the return type of data type which is shown below where default values assigned to variables of different primitive data types are given in the table. However, relying on such default values is not considered a good programming style.

Data Type

Default Values

Byte

0

Short

0

Int

0

Long

0

Float

0.0

Double

0.0

Boolean

false

Char

\u0000′ or null

Now as we know Initializing a variable means to give an initial value to a variable before using it. So, in order to use the default values first, declare the variable with data type and name (eg, int x, here int is the data type and x is the name of the variable), if you don’t declare the variable before using it, it would result in a compile-time error. Now to use the default value of the variable do not initialize it, i.e. do not assign a value to it.

Example 1

    public static void main(String[] args)

Output explanation:

Here ‘a‘ is a class member variable or you can say an instance variable and it will be initialized to its default value by the compiler.

Note: There would have been a problem if variable (‘a’) was not a class member as the compiler never assigns default values to an uninitialized local variable.

In this scenario, there will be an error pointing to variable ‘a‘ that variable ‘a‘ might not have been initialized yet. This is because here ‘a‘ is the main() method local variable and has to be initialized before being used. The compiler never assigns default values to an uninitialized local variable. If you haven’t initialized the variable where you have declared it, assign the variable a value before using it, or else it will result in a compile-time error.

It is as shown in the next example as shown below for a better understanding of the class variable.

Example 2

    public static void main(String[] args)

Output:


Article Tags :

The idea behind local variables is they only exist inside the limited scope for which they are needed. As such, there should be little reason for uncertainty as to the value, or at least, where that value is coming from. I could imagine many errors arising from having a default value for local variables.

For example, consider the following simple code... (N.B. let us assume for demonstration purposes that local variables are assigned a default value, as specified, if not explicitly initialized)

System.out.println("Enter grade"); int grade = new Scanner(System.in).nextInt(); // I won't bother with exception handling here, to cut down on lines. char letterGrade; // Let us assume the default value for a char is '\0' if (grade >= 90) letterGrade = 'A'; else if (grade >= 80) letterGrade = 'B'; else if (grade >= 70) letterGrade = 'C'; else if (grade >= 60) letterGrade = 'D'; else letterGrade = 'F'; System.out.println("Your grade is " + letterGrade);

When all is said and done, assuming the compiler assigned a default value of '\0' to letterGrade, this code as written would work properly. However, what if we forgot the else statement?

A test run of our code might result in the following

Enter grade 43 Your grade is

This outcome, while to be expected, surely was not the coder's intent. Indeed, probably in a vast majority of cases (or at least, a significant number, thereof), the default value wouldn't be the desired value, so in the vast majority of cases the default value would result in error. It makes more sense to force the coder to assign an initial value to a local variable before using it, since the debugging grief caused by forgetting the = 1 in for(int i = 1; i < 10; i++) far outweighs the convenience in not having to include the = 0 in for(int i; i < 10; i++).

It is true that try-catch-finally blocks could get a little messy (but it isn't actually a catch-22 as the quote seems to suggest), when for example an object throws a checked exception in its constructor, yet for one reason or another, something must be done to this object at the end of the block in finally. A perfect example of this is when dealing with resources, which must be closed.

One way to handle this in the past might be like so...

Scanner s = null; // Declared and initialized to null outside the block. This gives us the needed scope, and an initial value. try { s = new Scanner(new FileInputStream(new File("filename.txt"))); int someInt = s.nextInt(); } catch (InputMismatchException e) { System.out.println("Some error message"); } catch (IOException e) { System.out.println("different error message"); } finally { if (s != null) // In case exception during initialization prevents assignment of new non-null value to s. s.close(); }

However, as of Java 7, this finally block is no longer necessary using try-with-resources, like so.

try (Scanner s = new Scanner(new FileInputStream(new File("filename.txt")))) { ... ... } catch(IOException e) { System.out.println("different error message"); }

That said, (as the name suggests) this only works with resources.

And while the former example is a bit yucky, this perhaps speaks more to the way try-catch-finally or these classes are implemented than it speaks about local variables and how they are implemented.

It is true that fields are initialized to a default value, but this is a bit different. When you say, for example, int[] arr = new int[10];, as soon as you've initialized this array, the object exists in memory at a given location. Let's assume for a moment that there is no default values, but instead the initial value is whatever series of 1s and 0s happens to be in that memory location at the moment. This could lead to non-deterministic behavior in a number of cases.

Suppose we have...

int[] arr = new int[10]; if(arr[0] == 0) System.out.println("Same."); else System.out.println("Not same.");

It would be perfectly possible that Same. might be displayed in one run and Not same. might be displayed in another. The problem could become even more grievous once you start talking reference variables.

String[] s = new String[5];

According to definition, each element of s should point to a String (or is null). However, if the initial value is whatever series of 0s and 1s happens to occur at this memory location, not only is there no guarantee you'll get the same results each time, but there's also no guarantee that the object s[0] points to (assuming it points to anything meaningful) even is a String (perhaps it's a Rabbit, :p)! This lack of concern for type would fly in the face of pretty much everything that makes Java Java. So while having default values for local variables could be seen as optional at best, having default values for instance variables is closer to a necessity.