Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange variable initialization error

Tags:

java

eclipse

I have a strange problem with variable initialization.

There is following code:

public void test()
    {
        StringBuilder buf;

        org.junit.Assert.assertFalse((buf = new StringBuilder("qwe3")).toString().isEmpty());
        org.junit.Assert.assertEquals("", buf.toString()); // The local variable buf may not have been initialized
    }

What??? Variable is initialized, what is wrong?

also when I change org.junit.Assert.assertFalse to my own local method error disappears.

private static void assertFalse(final boolean o) throws Exception
    {

    }

I am using jdk 1.7.0_51 if that matters. Class code is here

like image 201
michael nesterenko Avatar asked Jan 22 '14 13:01

michael nesterenko


1 Answers

Note: this is now reported as Eclipse JDT Bug 426443.

I have trimmed your issue down to an MCVE:

package org.junit;
public class Assert {
  public static void assertTrue(boolean b) {}
}

package test;
import static org.junit.Assert.assertTrue;
public class Test {
  void test() {
    int i;
    assertTrue((i = 1) == 1);
    assertTrue(i == 1);
  }
}

Only when compiling with Eclipse Kepler SR1 do I get your exact error; compiling with javac does not reproduce it.

In addition, changing org.junit.Assert.assertTrue(boolean b) to a slightly different:

  • package name;
  • class name;
  • method name;
  • method signature

the error disappears. assertFalse has the same problem and probably other methods in the real Assert class.

Conclusion: the bug is in the Eclipse compiler.

like image 118
Marko Topolnik Avatar answered Sep 23 '22 22:09

Marko Topolnik