Hm ...
You can declare it outside. For instance,
JSONArray results = null; try { results = json.getJSONArray("results"); }...
This way you can access it outside, but be sure to use if to find out if it is null.
If you do not set JSONArray results = null
, the compiler will probably whine about not initializing the variable.
Further explanation:
This is due to the area . When you declare inside try, the scope of the variable ends when the attempt completes. When you declare inside an if, when it if ends, the variable can no longer be accessed. This is very useful for temporary variables, where you only use them to compare or improve code reading, memory reuse, etc. (Idk, if thatβs even a word). Anyway, if your variable should be accessible everywhere inside the class, it might be better to declare it as a field.
I have not read this explanation , but it seems good. Take a look.
source share