All the posts and topics that contain only an error report will be moved here after the error is corrected. This is to ensure that when users view a question in ETS Viewer, the "Discuss" button will not indicate the presence of a discussion that adds no value to the question.
won't work. I tested the code out in Eclipse and using a text editor and compiling on the command line and it compiles and runs, when including a main method just as the else statement
The explanation says:
Choice "Insert after line 2 : if(n <= 0) local = "bad";" doesn't work because the second 'if' will actually be another statement and is not considered as a part of first 'if'. So, compiler doesn't realize that 'local' will be initialized even though it does get initialized.
C:\works>javac TestClass.java
TestClass.java:8: variable local might not have been initialized
System.out.println( s1+" = " + local);//3
^
1 error
So the given explanation is correct.
Also, the code given in the question is different from the one that you are running. In the question's code, local is a method variable, while in your code it is an instance variable, which is always initialized so there is no compilation error.
Interesting... I am using the JRE and SDK for Java 7 on my machine and in Eclipse
This questions asks the test taker to make two changes the first is moving one of the variables outside the method to become an instance member. I think this question asks the test taker to make two changes and not just one change in two different situations.
Whatever though, this is a cool Java practice program.
Ok, I see your point now. The question has now been update to include the statement, "Which of the changes given in options can be done (independent of each other) to let the following code compile and run without errors?" That should make it clearer.
This code is not required to be run from command line directly. There could be some other class that can invoke the given method. Notice that there is an int argument to this method, which could be anything. So the code should work for any value of n without any exception.
Problem statement has now been updated to make it clear.