📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!


    Question

    A Java method tries to get the length of an array and a

    string. public class LengthChecker {     public void checkLengths() {         String[] names = {"Alice", "Bob"};         String greeting = "Hello";         System.out.println("Array length: " + names.length()); // Potential bug here         System.out.println("String length: " + greeting.length); // Potential bug here     } } What will happen when checkLengths() is executed?
    A Both lines will print the correct lengths (2 and 5). Correct Answer Incorrect Answer
    B A NullPointerException will occur. Correct Answer Incorrect Answer
    C A compile-time error will occur. Correct Answer Incorrect Answer
    D The array length will be incorrect, but the string length will be correct. Correct Answer Incorrect Answer
    E The string length will be incorrect, but the array length will be correct. Correct Answer Incorrect Answer

    Solution

    Correct Answer: C (In Java, arrays use .length (a field), while String objects use .length() (a method). The code swaps these, leading to compile-time errors.)

    Practice Next
    ask-question