Home > Enterprise >  Variable has not have been initialized in Java
Variable has not have been initialized in Java

Time:11-26

The following code fails to compile as the variable 'rt' has not been initialized.

I'm wanting the code to either initialize 'rt' in the switch-Statement, or not use 'rt' anymore when the default case is ran.

Here is the code I've written:

enum RequestType {leader, candidate};

private void processRequest(String input) {


        boolean inputOK = true;
        RequestType rt;

        String[] split = input.split(":");

        if (!input.contains(":")) {
             inputOK = false;
        }
        else {


            if (split.length != 3) {
                inputOK = false;
            }

            else {
                int port = Integer.parseInt(split[2]);

                if (!(port > 0 && port < 65537)) {
                    inputOK = false;

                }

                else {

                    switch (split[0]) {
                        case "Leader":
                            rt = RequestType.leader;
                            break;
                        case "Candidate":
                            rt = RequestType.candidate;
                            break;
                        default:
                            inputOK = false;
                    }

                }
            }
        }

        if (!inputOK) {
            return;
        }

        String address = split[1].concat(split[2]);

        if (rt == RequestType.leader) {

            keepingLeader(address);
        }

CodePudding user response:

You don't initialize rt in the default block, or many of the ifs.

The compiler doesn't look at whether the read of rt is reachable with respect to the value of inputOK, it just looks at whether it is reachable at all.

The easiest thing to do is just to return immediately where you currently have inputOK = false;.

Alternatively, you can assign a default value to rt, for example null, when you declare it. The problem with that is it breaks the checking that the compiler is doing now - that you actually have assigned it in all circumstances, so you don't accidentally use the default value.

Instead, you can use the nullity of rt instead of having a separate boolean value:

  • Where you currently assign inputOK = false, assign rt = null instead;
  • Where you then check !inputOK and return if true, check rt == null instead.
  • Related