Classes and Objects
Classes and Objects
This section of our 1000+ Java MCQs focuses on class fundamentals & object declaration in Java
Programming Language.
1. What is the stored in the object obj in following lines of code?
box obj;
a) Memory address of allocated memory of object.
b) NULL
c) Any arbitrary pointer
d) Garbage
View Answer
a) 9
b) 8
c) Compilation error
d) Runtime error
View Answer
a) 12
b) 200
c) 400
d) 100
View Answer
a) 1
b) 2
c) Runtime error
d) Garbage value
View Answer
a) 0
b) 1
c) Runtime error
d) Garbage value
View Answer
ANSWERS
a) 9
b) 8
c) Compilation error
d) Runtime error
View Answer
Answer: c
Explanation: Two variables with the same name can’t be created in a class.
output:
$ javac main_class.java
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Duplicate local variable x
7. Which of the following statements is correct?
a) Public method is accessible to all other classes in the hierarchy
b) Public method is accessible only to subclasses of its parent class
c) Public method can only be called by object of its class.
d) Public method can be accessed by calling object of the public class.
View Answer
Answer: a
Explanation: None.
8. What is the output of this program?
1. class box {
2. int width;
3. int height;
4. int length;
5. }
6. class mainclass {
7. public static void main(String args[])
8. {
9. box obj = new box();
10. obj.width = 10;
11. obj.height = 2;
12. obj.length = 10;
13. int y = obj.width * obj.height * obj.length;
14. System.out.print(y);
15. }
16. }
a) 12
b) 200
c) 400
d) 100
View Answer
Answer: b
Explanation: None.
output:
$ javac mainclass.java
$ java mainclass
200
9. What is the output of this program?
1. class box {
2. int width;
3. int height;
4. int length;
5. }
6. class mainclass {
7. public static void main(String args[])
8. {
9. box obj1 = new box();
10. box obj2 = new box();
11. obj1.height = 1;
12. obj1.length = 2;
13. obj1.width = 1;
14. obj2 = obj1;
15. System.out.println(obj2.height);
16. }
17. }
a) 1
b) 2
c) Runtime error
d) Garbage value
View Answer
Answer: a
Explanation: When we assign an object to another object of same type, all the elements of right side
object gets copied to object on left side of equal to, =, operator.
output:
$ javac mainclass.java
$ java mainclass
1
10. What is the output of this program?
1. class box {
2. int width;
3. int height;
4. int length;
5. }
6. class mainclass {
7. public static void main(String args[])
8. {
9. box obj = new box();
10. System.out.println(obj);
11. }
12. }
a) 0
b) 1
c) Runtime error
d) Garbage value
View Answer
Answer: d
Explanation: Object obj of box class contains reference to the memory which was given to its class
instances. Printing obj will print the address of the memory.
output:
$ javac mainclass.java
$ java mainclass
box@130671e