Question

    1.    Predict the output of the code public

    class Animal {     public static void main(String args[])              {                        public int localVar = 5;              }          }
    A Error : Illegal Start of Expression Correct Answer Incorrect Answer
    B Compile successfully Correct Answer Incorrect Answer
    C Run Time Exception Correct Answer Incorrect Answer
    D Access specifier not mentioned Correct Answer Incorrect Answer
    E None` Correct Answer Incorrect Answer

    Solution

    1. Illegal Access Modifier in Method Scope :
      • The keyword public is not allowed within the body of a method to declare a variable. Variables declared inside methods are considered local variables, and local variables cannot have access modifiers (public, private, protected).
      • This results in a compilation error.
    Corrected Code If the intent is to declare and initialize a local variable within the main method, the corrected code would be:                                                                                                                                   public class Animal {     public static void main(String args[]) {                int localVar = 5; // Correct declaration of a local variable         System.out.println(localVar); // Printing the value of localVar to demonstrate usage     } }

    Practice Next