• Register
1 vote
555 views

Problem:

Hello everyone,

I am a newly registered member here. I found you guys so amazing and helpful. Out of curiosity I just started learning the Java programming language and made my very first program that will add two different numbers.

public class Main{
  public static void main(String[] args) {
    int a = 2;
    int b;
    int sum = a + b;
    system.out.println("Sum is: " + sum)
  }
}

This is the code. But the problem is, I can’t run my code. It is returning an error java variable might not have been initialized.

Please figure out the error in my code. I know I did something very silly but I am unable to figure out that.

Thanks a lot.

12 7 7
15,250 points

Please log in or register to answer this question.

2 Answers

1 vote

Solution:

That particular error occurred when we don’t declare a variable but not initialize it. Initialize means put a certain value into it. In your case, you’ve declared three variables a, b, and sum but initialized the variable a only.

You had to initialize all the variables you declared before using them. The compiler never assigns a value to your variable. So you wanted to do something like this:

public class Main{
  public static void main(String[] args) {
    int a = 2;
    int b = 5; // Initializing the variable
    int sum = 0; // This a better practise to do.
    int sum = a + b;
    system.out.println("Sum is: " + sum)
  }
}

 

13 9 6
94,260 points
0 votes

Solution:

Reason:

This error happenss when you are trying to use a local variable without initializing it. You won't get this error if you use a uninitialized class or instance variable since they are initialized with their default value e.g. Reference types are initialized with null and integer types are initialized with zero, however if you try to use an uninitialized local variable in Java, you will get this error. This is happen because Java has the rule to initialize the local variable before accessing or using them and this is checked at compile time. In case compiler believes that a local variable might not have been initialized before the next statement which is using it, you get this error. You will not get this error if you just declare the local variable however will not use it.

To Solve this

Now, there are some tricky scenarios where you think that you have initialized the variable however compiler thinks otherwise and throws "variable might not have been initialized" error. One of them is creating more than one local variable in the same line as shown in following Java program:

public class Main { 
   public static void main(String[] args) { 
      int a, b = 0;
      System.out.println("a:" + a);
      System.out.println("b:" + b);
      
       }
   }


Here you might think that both variable "a" and "b" are initialized to zero however that's not correct. Only variable b is initialized and variable "a" is not initialized, therefore when you run this program, you will get the "variable might not have been initialized" error as shown below:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: The local variable a may not have been initialized 

at Main.main(Main.java:13)

Moreover, the error message is very precise, it says that variable "a" is not initialized on line 13 where you have used it for reading its value. In addition you can see Core Java Volume 1 - Fundamentals to learn more about how variables are initialized in Java.

One more continuity, where compiler complains about "variable might not have been initialized" is when you initialize the variable inside if() block, since if is a condition block, compiler know that variable may not get initialized when if block is not executed, hence it complains as shown in the following program:

public class Main { 
  public static void main(String[] args) {
    int count;
 
    if (args.length > 0) {
    count = args.length;
   } 
   System.out.println(count);
 } 
}




In this instance, the variable count will not be initialized before you use it on System.out.println() statement if args.length is zero, hence compiler will throw "variable may not have been initialized" at the time you run this program :

Exception in thread "main" java.lang.Error: Unresolved compilation problem: The local variable count may not have been initialized at Main.main(Main.java:17)



Now, sometimes, you will think that compiler is wrong since you know that variable is always going to be initialized but in reality, compilers are not as smart as you and you see this error as shown in the following program:

public class Main{

  public static void main(String[] args) {
    int count;

    if (args.length > 0) {
      count = args.length;
    }

    if (args.length == 0) {
      count = 0;
    }

    System.out.println(count);

  }

}






Now, you know that count will always initialize since length of argument array would either be zero or greater than zero, however compiler is not convinced and it will throw the "variable might not have been initialized" error as :

Exception in thread "main" java.lang.Error: Unresolved compilation problem: The local variable count may not have been initialized at Main.main(Main.java:21)



For convincing the compiler you can use the else block, this will satisfy the compiler and the error will go away as shown below:

public class Main{ 
   public static void main(String[] args) {
    int count;

  if (args.length > 0) {
   count = args.length;
  } else {
    count = 0;
 } 
 System.out.println(count); 
 } 
}




In case you run this program, there won't be any compile error since now compiler knows for sure that count will be initialized before accessed. In case you remove all the if else and System.out.println() block then also code will compile fine since we have only declared count variable and never used it. 

Thre are more continuity where you get the "variable might not have been initialized" error, especially when you initialize a variable inside a block e.g. try or catch block. So beware of this rule, it's not a big problem however sometimes becomes a headache for Java beginners, especially when they get tons of "variable might not have been initialized" error at the time they compile their Java source file.

You declared them, but you didn't initialize them. Initializing them is setting them equal to a value:

int a;        // This is a declaration
a = 0;        // This is an initialization
int b = 1;    // This is a declaration and initialization

You get the error since you haven't initialized the variables, however you increment them (e.g., a++) in the for loop.
Java primitives have default values but as one user commented below

Their default value is zero at the time declared as class members. Local variables don't have default values

You require an initialisation of the variable change double double celsiusOutput; into double celsiusOutput = 0;. Also there are braces in if statements needed for the algorithm to work. The correct one would be:

import java.util.Scanner;
public class Temperature
{
    public static void main(String[] args)
    {
        // Declaration of output terms;
        double celsiusOutput = 0;
        double fahrenheitOutput = 0;
        double kelvinOutput = 0;

        // Printing request for input terms from the user + reception of said terms
        Scanner scan = new Scanner(System.in);
        System.out.println("Welcome to the temperature scale converter.");
        System.out.println("Please enter your input temperature scale and degree value in the following format:");
        System.out.println("\"A n∈ℝ\", where A is the first letter of your scale (C, F or K) and n∈ℝ is the degrees.");
        String input = scan.next().toUpperCase();
        char inputScale = input.charAt(0);
        double inputDegrees = scan.nextDouble();

        // Declaration of final terms, i.e. the conversion formulae:
        final double C_DEGREES_IN_F = (inputDegrees - 32.00) / 1.80;
        final double C_DEGREES_IN_K = inputDegrees + 273.15;
        final double F_DEGREES_IN_C = (inputDegrees - 32.00) / 1.80;
        final double F_DEGREES_IN_K = (inputDegrees + 459.67) / 1.80;
        final double K_DEGREES_IN_C = inputDegrees - 273.15;
        final double K_DEGREES_IN_F = (inputDegrees - 273.15) * 1.80 + 32.00;

        // Conditional assignment of output terms, as conditioned by the user's input terms
        if(inputScale == 'C') {
            celsiusOutput = inputDegrees;
            fahrenheitOutput = F_DEGREES_IN_C;
            kelvinOutput = K_DEGREES_IN_C;
        }
        if(inputScale == 'F') {
            celsiusOutput = C_DEGREES_IN_F;
            fahrenheitOutput = inputDegrees;
            kelvinOutput = K_DEGREES_IN_F;
        }
        if(inputScale == 'K') {
            celsiusOutput = C_DEGREES_IN_K;
            fahrenheitOutput = F_DEGREES_IN_K;
            kelvinOutput = inputDegrees;
        }

        // Printing of output terms + legality check
        switch(inputScale)
        {
            case 'C':
            case 'F':
            case 'K':
                System.out.println(celsiusOutput + " C");
                System.out.println(fahrenheitOutput + " F");
                System.out.println(kelvinOutput + " K");
                break;
            default:
                System.out.println("Illegal input.");
                break;
        }
    }
}

 

10 6 4
31,120 points

Related questions

1 vote
1 answer 5 views
5 views
Problem: Any ideas on what I need to do to fix this? java variable might not have been initialized
asked Mar 26 MUHAMMAD MUNEEB 83k points
0 votes
1 answer 12 views
12 views
What's going wrong?
asked Feb 8 TeamScript 13.5k points
0 votes
1 answer 16 views
16 views
Problem: java variable might not have been initialized if statement
asked Feb 24 Hira 2.2k points
0 votes
1 answer 26 views
26 views
Problem: variable might not have been initialized java
asked Feb 23 Hira 2.2k points
1 vote
1 answer 18 views
18 views
Problem: I need a help , How I can fix this : variable sized object may not be initialized
asked Mar 13 MUHAMMAD MUNEEB 83k points
1 vote
1 answer 9 views
9 views
Problem: Can someone please help fix this : variable-sized object may not be initialized
asked Mar 13 MUHAMMAD MUNEEB 83k points
0 votes
1 answer 32 views
32 views
Problem: variable may not have been initialized java
asked Feb 23 Hira 2.2k points
0 votes
1 answer 5 views
5 views
Problem: Any ideas on what I need to fix this:what is a counter variable in java?
asked Apr 12 ashik 14.6k points
0 votes
1 answer 19 views
19 views
Problem: Hello! I just started learning programming in Java with no prior knowledge of any other programming language. Today I attempted a quiz in which there was a question that asked me to declare a string variable and name it as ‘title’. I attempted the ... follows: string title; I have not worked with strings alot. So want to know whether my answer is correct or not? Thanks!
asked Feb 25 Code Learner 9.8k points
1 vote
1 answer 87 views
87 views
Problem: I am a little curious about java variables. I was trying to figure out how does it work if I don’t initialize a variable after defined. I assumed if the variable is an integer it could be equivalent to 0 and for String, it could be a null ... use a local variable before it has been given a value: Can anybody explain the thing clearly to me? Your answers are appreciated. Thanks.
asked Mar 19, 2020 Gavin 15.3k points