What Will Be The Output Of The Following Java Codep Pre #829
What will be the output of the following Java code?</p> <pre><code class="language-java"> class Base { String s = "NVAEducation"; } class Derived extends Base { void index() { System.out.println(s.indexOf('N')); } } public class Index { public static void main(String[] args) { Derived a = new Derived(); a.index(); } }</code></pre>
This multiple choice question (MCQ) is related to the book/course gs gs111 OOP Object Oriented Programming Java. It can also be found in gs gs111 Inheritance (Using Java) - Single Level Inheritance - Quiz No.1.
What will be the output of the following Java code?
class Base { String s = "NVAEducation"; } class Derived extends Base { void index() { System.out.println(s.indexOf('N')); } } public class Index { public static void main(String[] args) { Derived a = new Derived(); a.index(); } }
3
7
2
-1 View Answer
Answer: The object ‘a’ is an object of the class Derived, which inherits the properties of the class Base through single inheritance. The indexOf function returns the index of the character specified in the parameters in the string calling it. It is case sensitive. Hence ‘n’ and ‘N’ are different. Output:
$ javac Index.java $ java Index -1