Multiple choice technology programming languages

What is the output for the below code ? public class B { public String getCountryName(){ return "USA"; } public StringBuffer getCountryName(){ StringBuffer sb = new StringBuffer(); sb.append("UK"); return sb; } public static void main(String[] args){ B b = new B(); System.out.println(b.getCountryName().toString()); } }

  1. Compile with error

  2. USA

  3. UK

  4. Runtime Exception

Reveal answer Fill a bubble to check yourself
A Correct answer
Explanation

Java doesn't allow method overloading based solely on return type. Both methods have the same name and no parameters, so this is a compile-time error regardless of the different return types (String vs StringBuffer).

AI explanation

To answer this question, let's go through each option to understand why it is correct or incorrect:

Option A) Compile with error - This option is correct because there is a compilation error in the code. The class B has two methods with the same name getCountryName(), but with different return types (String and StringBuffer). In Java, you cannot have two methods with the same name and different return types.

Option B) USA - This option is incorrect. Although the method getCountryName() returns a String with the value "USA", the compilation error prevents the code from executing successfully.

Option C) UK - This option is incorrect. Although the getCountryName() method with the StringBuffer return type appends "UK" to the StringBuffer object and returns it, the compilation error prevents the code from executing successfully.

Option D) Runtime Exception - This option is incorrect. There is no runtime exception in the code. The compilation error prevents the code from executing successfully.

The correct answer is A) Compile with error. This option is correct because the code has a compilation error due to having two methods with the same name but different return types.