Why does the compiler get an error that the variable is not initialized on orderAssert after exiting the loop?

 int i=1; boolean orderAssert; String orderNumAfter; while(i<=10) {... if(orderNum != orderNumAfter) {orderAssert = true;i=11;} else orderAssert = false; i++; } Assert.assertEquals(orderAssert, true); // <<-- ошибка на этой строке 
  • one
    Because this variable may not be initialized at the time of the call. - Vartlok
  • 6
    well, probably because he is not 100% sure that the block in the cycle will be executed at least once - ermak0ff
  • what is in place ... ? - Grundy
  • 3
    1) Sure that there should be no `else {orderAssert = false; i ++; }? - andy.37
  • one
    @DmitryFeniks, in the process of getting the value for orderNumAfter , an exception (exception) can occur? - Grundy

2 answers 2

In general, it is very similar to the compiler feature:

 public static void testvar() { int a; boolean c = false; // if (c) a = 0; else a = 1; for (int i=0; i<10; i++) { if (c) a = 0; else a = 1; // a = 1; } System.out.println("a is " + a); } 

It does not compile ( Error:(23, 38) java: variable a might not have been initialized ), even if you leave a = 1; instead of if in the loop a = 1; . And if you uncomment the line before the loop, it is compiled.

S-shny compiler, for example (for me) does not give vorning on

 int a, f=0; if (f) a = 1; a++; 

but if you remove if (or change to if(0) ), it already gives)

P.S. The proposed answer naturally solves the problem (and much better in terms of style)

    Since orderAssert may not be initialized in a loop (for example, if it is break), it is necessary to initialize the variable before the loop.

    Try this:

     int i = 1; boolean orderAssert = false; String orderNumAfter; while (i <= 10) {... if (orderNum != orderNumAfter) { orderAssert = true; i = 11; } i++; } 
    • I need to get the orderAssert value from the loop - Dmitry Feniks