1

I'm trying 2 create a project in java, but this is the epitome of my problem. I m initialising a variable inside a while loop , now as soon as the while loop ends the variable is unset or simply a=7 doesn't get printed. I have no other choice other than using while loop. i have 2 get the value of a that has been initialized.

package Hotel_room_reservation_system;
import java.awt.*;
import java.lang.*;
import java.io.*;
public class NewClass {

    public  NewClass()
    {
        int a;
        int z=0;
        while(z<10)
        {
            a=7;
            z++;
        }
        System.out.println(a);
    }
}

Then i create a new object of this class.

Current Output

variable a might not have been initialized

REQUIRED OUTPUT

7

HELP.

Info_wars
  • 85
  • 1
  • 2
  • 14
ErrorrrDetector
  • 139
  • 1
  • 13
  • 3
    You will get the error *"variable a might not have been initialized"* because the compiler doesn't realise that you will **always** enter the while-loop. It considers the possibility that it won't, even though it always will in your example. You need to initialize it outside the loop. Not sure why it is an error rather than warning, though. – RaminS Aug 19 '16 at 20:40
  • @JonnyHenly The issue is not that he's not initializing it before using it. It is that he's initializing inside the loop and nowhere else. That duplicate doesn't address this issue. – RaminS Aug 19 '16 at 20:46
  • @Gendarme yea you're right – Jonny Henly Aug 19 '16 at 20:47
  • @ErrorrrDetector You should include the code inside your `main()` and the error message too. – RaminS Aug 19 '16 at 20:47

2 Answers2

4

Just initialize your variable a:

public NewClass() {
    int a = 0;
    int z = 0;
    while (z < 10) {
        a = 7;
        z++;
    }
    System.out.println(a);
}

public static void main(String[] args) {
    new NewClass();
}

In Java, class and instance variables assume a default value (null, 0, false) if they are not initialized manually.

However, local variables don't have a default value. Unless a local variable has been assigned a value, the compiler will refuse to compile the code that reads it.

DimaSan
  • 12,264
  • 11
  • 65
  • 75
4

The java compiler is complaining that the variable a might not have been initialized.

This is because the compiler does not actually check loop conditions to ascertain whether execution of the loop will occur or not. In other words, it does not know whether the loop will set the variable or not.

In general it is usually a goo idea to initialize your variables with a reasonable default (such as int a=0;).

RudolphEst
  • 1,240
  • 13
  • 21
  • This is the proper answer and should be accepted. The other two fail to explain how the problem is related to the loop: *The compiler doesn't check loop conditions to know whether the variable has been initialized or not*. – RaminS Aug 19 '16 at 21:04