hello ranchers,i have a doubt in the code
when i compile the code with the else statement the program run and gives the output as 4,but when i remove the else statement it shows an error: Bingo.java:8: variable a might not have been initialized
It is because- the variable a is never initialized. And with condition evaluating to "false" always the block right after the if doesnt get executed. So when you get that exception. When you add an else block- the variable a gets initialized. One option is to initialize the variable a when you are declaring it or add the else block.
Just to add "local variable always needs to be initialized before use" and if initialization occurs on a conditional way e.g. inside an if statement then you have to provide else statement to make sure it initialize on all cases.
here if you want to run your program without else you can initialize int a=0 ;( or any default value) at the time of declaration.
sumedha rao wrote:thanks for your quick reply,how can i do the same thing without an else block
The same thing as what? It's hard to tell what you're trying to do in the original code - it seems unnecessarily complex, checking for things that could not possibly happen. What are you trying to achieve?
In particular, why would you write "if (x)" and then immediately check again if x is true or not? And then in the else clause, check yet again to see if x is true or not? It seems like this whole thing could be written easily with EITHER (a) a single if/else, or (b) a single ternary operation. Not both. And not one if/else with TWO ternary operations. How many times do you need to test if x is true or not?
The sad part is, the original question is about scoping.... and the ternary operators confuse the question.
Here's (a slightly sarcastic way) in response to how to do it without a ternary and without an else....
When you do things right, people won't be sure you've done anything at all.
posted 9 years ago
Well, yes, you can also shorten the entire program to
But this goes back to what I asked: what is the original poster actually trying to do? It's not clear.
Also, I don't see how the original question is about scoping at all. It seems to be about the rules of definite assignment, which is making sure a variable has been assigned to be something before you try to use it. Variable a is in scope for most of the program (from the moment it's declared to the end of the main method). The problem is that it hasn't been definitely assigned - if we comment out the else clause.