For each of the flowing programs that involve casting predic
For each of the flowing programs that involve casting, predict the result of compiling and running the program. Potential answers include \"there is a syntax error because ..., \" \"there is a run-time error because ..., \" and \"the output of the program would be ...\" public class test l {public static void main(String[] args) {String s1. s2; Object o1; s2 = \"E. E. Cummings\"; o1= s2; s1= o1; System. out. print ln (s1. toLowerCase ());}} public class test2 public static void main(String [] args) {String s1, s2; Object o1; s2= \"E. E. Cummings\"; o1 = s2; s1= (String) o1; System. out. print ln (s1. toLowerCase ());
Solution
a. There is a compile time error in line \"s1=o1;\".
It is because Object is the superclass of every Java class, and we can use the reference variable of superclass to hold the reference to a subclass object. Hence, an Object type reference variable(o1) can hold the reference to any object whatsoever(s1), but the opposite is not true and we\'ll have to explicitly cast o1 as String type before assigning it to a String reference variable.
b. The output of the program would be:-
e. e. cummings
The program compiled successfully, as the Object o1 was explicitly typecasted before being assigned to String s1.
