class Faltu
{
	public static void main(String aa[])
	{
		int a=4,b;
		if (a==4)
			b=5;
		System.out.println ("b="+b);
	}
}

Here it says : "variable b might not have been initialized", but in the following :

class Faltu
{
	public static void main(String aa[])
	{
		int a=4,b;
		if (true)
			b=5;
		System.out.println ("b="+b);
	}
}

Here it compiles perfectly. Why ?

Dani AI

Generated

As pointed out, this is the Java "definite assignment" rule at work. The compiler performs a conservative flow analysis: it only treats a branch as always taken when that fact can be determined from the source (a compile-time constant), not from runtime values. That is why if (true) is treated as always taken but if (a == 4) is not when a is a normal local variable.

Two practical points that often help:

  • Making the test a compile-time constant lets the compiler treat the branch as definite. For example, a final local constant can participate in constant-folding so the comparison can be evaluated at compile time.
final int c = 4;
int d;
if (c == 4)
    d = 5;
System.out.println(d); // compiles because c==4 is a compile-time constant expression
  • Safer fixes that do not rely on compiler constant-folding: initialize the variable where it is declared, or make sure every possible control-flow path assigns it (for example, add an else branch).
int c = 4;
int d = 0; // explicit initialization
if (c == 4) d = 5;
System.out.println(d);

For the formal rules and edge cases (try/catch/finally, loops, conditional expressions), consult the Java Language Specification: see the Definite Assignment section (JLS: Definite Assignment) and the definition of constant expressions (JLS: Constant Expressions). This explains precisely when the compiler can consider a condition definitely true at compile time.

Recommended Answers

All 2 Replies

Because in the second case the compiler knows that b will always have a value, but it does not know that in the first version (the compiler does not compute expression values).

Thanks !

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.