In line 5 you declare a local variable token, but you do not initialize it.
Suppose that in line 7 an exception occurs.
Execution jumps to line 12, where the stack trace of the exception is printed.
Then line 14 is executed. Note that the variable token has not yet been initialized!
In Java, it is required to initialize local variables before using them. Whenever the compiler finds a code path where it is possible to use a local variable without initializing it first (such as described above), you get an error from the compiler.
Note that the member variable, declared in line 3, is not used at all in your program. The local variable declared in line 5 hides it.
Shamsudeen Akanbi wrote:Compiling this program generates an output that, the variable token has not been initialised. So, I was thinking of a way of updating token from the try block. Because printing token in the try block ain't a problem. I hope you understand...
Well, that compile error is something completely different -- and not related to scope as your topic suggest.
Take a look at your code again -- and you will see that there is a possible path of execution in your code that will try to use the variable before it is initialized (exactly what the compiler says).
[EDIT: wow, that was quick. Not only beaten to the answer, but with a detailed one.]
A simple fix to the immediate problem would be to change line 5 to
or some other default value...but I still think you probably have a mistake by declaring a new String token inside your main method that masks the String token member variable. I could be wrong, but your going to have a hard time convincing me of that fact.
Shamsudeen Akanbi wrote:it was because I wasn't getting any closer I had to declare it there
No offense intended, but that is really not a good way to code. you should strive to understand what the compiler is telling you. Making semi-random changes, hoping it fixes your problem is not going to lead to a good final program.