Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable might already have been assigned when it cannot be assigned

research this code:

public class TestFinalAndCatch {
    private final int i;

    TestFinalAndCatch(String[] args) {
        try {
            i = method1();
        } catch (IOException ex) {
            i = 0;  // error: variable i might already have been assigned
        }
    }

    static int method1() throws IOException {
        return 1;
    }
}

compiler says that java: variable i might already have been assigned

But for me it is looks like impossible situation.

like image 696
gstackoverflow Avatar asked Sep 07 '14 12:09

gstackoverflow


People also ask

What does it mean when a variable might not have been initialized?

Should we declare a local variable without an initial value, we get an error. This error occurs only for local variables since Java automatically initializes the instance variables at compile time (it sets 0 for integers, false for boolean, etc.).

What happens when the local variable is not initialized& used inside a program?

If the programmer, by mistake, did not initialize a local variable and it takes a default value, then the output could be some unexpected value. So in case of local variables, the compiler will ask the programmer to initialize it with some value before they access the variable to avoid the usage of undefined values.


2 Answers

The problem is that in this case compiler works syntax-based not semantic-based. There are 2 workarounds: First base on moving exception handle on method:

package com.java.se.stackoverflow;

public class TestFinalAndCatch {
    private final int i;

    TestFinalAndCatch(String[] args) {
        i = method1();
    }

    static int method1() {
        try {
            return 1;
        } catch (Exception ex) {
            return 0;
        }
    }
}

Second base on using temporar variable:

package com.java.se.stackoverflow;

import java.io.IOException;

public class TestFinalAndCatch {
    private final int i;

    TestFinalAndCatch(String[] args) {
        int tempI;
        try {
            tempI = method1();
        } catch (IOException ex) {
            tempI = 0;
        }
        i = tempI;
    }

    static int method1() throws IOException {
        return 1;
    }
}
like image 57
Maciej Szumielewicz Avatar answered Sep 27 '22 18:09

Maciej Szumielewicz


To overcome this problem, use a local variable in the try catch block and then assign that result to the instance variable.

public class TestFinalAndCatch {
    private final int i;

    TestFinalAndCatch(String[] args) {
        int tmp;
        try {
            tmp = method1();
        } catch (IOException ex) {
            tmp = 0;
        }
        i = tmp;
    }

    static int method1() throws IOException {
        return 1;
    }
}
like image 45
Brent Worden Avatar answered Sep 27 '22 18:09

Brent Worden