What will happen if you compile/run this code? 1: public class Q31 2: { 3: int maxElements = 100; 4: 5: public static void show() 6: { 7: System.out.println(maxElements); 8 } 9: 10: public static void main(String[] args) 11: { 12: new Q31().show(); 13: } 14: } A) Prints 100. B) Prints 0. C) Compilation error in line 12. D) Compilation error in line 7.Answer
What will happen if you compile/run this code? 1: public class ThisSuperExample 2: { 3: static int maxElements = 9999; 4: 5: public ThisSuperExample() 6: { 7: System.out.println("Default Constructor"); 8: } 9: 10: public ThisSuperExample(int maxElementsVal) 11: { 12: this(); 13: maxElements = maxElementsVal; 14: System.out.println(maxElements); 15: } 16: 17: public ThisSuperExample(String msg) 18: { 19: super(); 20: System.out.println(msg); 21: } 22: 23: public static void main(String[] args) 24: { 25: a = new ThisSuperExample(); 26: a = new ThisSuperExample(1000); 27: a = new ThisSuperExample("Welcome"); 29: } 30: } A) "Default Constructor" and "Welcome". B) "Default Constructor" and "Default Constructor" and 1000. C) "Default Constructor" and 1000 and "Welcome". D) "Default Constructor" and "Default Constructor" and 1000 and "Welcome". E) None of these.
Answer
1: public class Q33 2: { 3: public static void main(String[] args) 4: { 5: int total = 0; 6: for (int counter = 0; counter <100; ++counter) 7: total += counter; 8: System.out.println(counter); 9: } 10 } A) Prints 100. B) Prints 99. C) Prints 0. D) Compilation error in line 8.
1: public class Q34 2: { 3: private int maxElements = 100; 4: 5: public int getMaxelements() 6: { 7: return maxElements; 8: } 9: public void setNull(Q34 b) 10: { 11: b = null; 12: } 13: public static void main(String[] args) 14: { 15: Q34 a = new Q34(); 16: a.setNull(a); 17: 18: System.out.println(a.getMaxelements()); 19: } 20: } A) NullPointerException. B) Prints 100; C) Prints 0; D) Compilation error. E) None of these.
Answer
D. Here show() is a static method. It is not possible to access non-static variables in static mentods.
Back to Question 31
Question No: 32
D. this() will invoke corresponding methods/constructors of that particular class. super() will invoke corresponding methods/constructors of the super class.
Back to Question 32
Question No: 33
D. Here variable "counter" is defined inside for loop, which is not accesible outside of for loop.
Back to Question 33
Question No: 34
B. Here "b" gets "only a local copy of reference a". If you change any attributes of then "a" will get the changes. But if you set "b" to null, "a" still holds the original reference and will not throw any NullPointerException. .
Back to Question 34