0

I wrote this code in an online java test recently. It was inside a method that was set to return an integer. I got an error message something like "variable a has no value assigned to it". I find this odd because the forloop must have access to the methods variable and the assignments inside of the loop must be registered right?

int a;
for(int i=1;i<5;i++){
    a = i;} 
return a;

I did assume that the method would return the integer 5.

This is only a question regarding scope of the variable a. I know that the code makes no sense.

Robin Cox
  • 1,470
  • 2
  • 16
  • 31

1 Answers1

0

You can try below code , that will help you. Initialisation is mandatory for any variable to return or hold any value.

class a{
    public static void main(String[] args) {
        System.out.println(test());
    }
    public static int test(){
        int a = 0;
        for(int i=1;i<5;i++){
            a = i;}
        return a;
    }
}
Ronak R
  • 79
  • 3