Given: class Tree {} class Pine extends Tree {} class Oak extends Tree {} public
ID: 3827866 • Letter: G
Question
Given: class Tree {} class Pine extends Tree {} class Oak extends Tree {} public class Forest {public static void main(String [] args) {Tree tree = new Pine (); if(tree instance of Pine) System.out.println ("Pine"); if(tree instance of Tree) System.out.println("Tree"); if(tree instance of Oak) System.out.println("Oak"); else System.out.println("Oops");}} Select all choices that will be printed: a) Pine b) Tree c) Forest d) Oops e) Nothing is printed What will be the output of the program? public class Foo {public static void main(String [] args) {try {return;} finally {System.out.println("Finally");}}} a) Finally b) Compilation Fails c) The code runs with no output d) An exception is thrown at runtimeExplanation / Answer
47. Given
class Tree{}
class Pine extends Tree{}
class Oak extends Tree{}
public class Forest {
public static void main(String[] args) {
Tree tree = new Pine();
if(tree instanceof Pine)
System.out.println("Pine");
if(tree instanceof Tree)
System.out.println("Tree");
if(tree instanceof Oak)
System.out.println("Oak");
else
System.out.println("Oops");
}
}
Select all choices that will be printed:
a) Pine
b) Tree
c) Forest
d) Oops
e) Nothing is printed
Answer: a,b,d
Explanation: In the above code Tree is the parent class and Pine and Oak are child classes of Tree.
In the given code an object tree is created as Pine.
As Pine is the subclass of Tree tree will be the instance of both the class with which its being created and the parent class.
Hence the condition if(tree instanceof Pine) returns true and prints Pine
The next condition if(tree instanceof Tree) returns true, as an object of subclass type is also a type of parent class and hence prints Tree
The next condition if(tree instanceof Oak) returns false as tree is not an object of Oak and hence the else part is executed and print Oops
Finally the output is
Pine
Tree
Oops
48) What will be the output of the program?
public class Foo {
public static void main(String[] args) {
try
{
return;
}
finally{
System.out.println("Finally");
}
}
}
a) Finally
b) Compilation Fails
c) The code runs with no output
d) An exception is thrown at runtime
Answer: a) Finally
Explanation: When the above code is executed the control first goes into the try block and as the try block has the return statement the control come out of the block, next we have a print statement in the finally block, the finally block always executes whether an exception is handled or not hence the finally block of the above code executes and prints Finally
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.