Constructors And Methods(Computer Science > Java Program ) Questions and Answers
Question 1. What is the expected output? public class Profile { private Profile(int w) { // line 1 System.out.print(w); } public static Profile() { // line 5 System.out.print (10); } public static void main(String args[]) { Profile obj = new Profile(50); } }
Won't compile because of line (1), constructor can't be private
10 50
50
Won't compile because of line (5), constructor can't be static
Explanation:-
Answer: Option D. -> Won't compile because of line (5), constructor can't be static
Question 2. The following code contains one compilation error, find it? public class Test { Test() { } // line 1 static void Test() { this(); } // line 2 public static void main(String[] args) { // line 3 Test(); // line 4 } }
At line 1, constructor Tester must be marked public like its class
At line 2, constructor call
At line 3, compilation error, ambiguity problem, compiler can't determine whether a constructor
At line 4
Explanation:-
Answer: Option B. -> At line 2, constructor call
Question 3. What will be the return type of a method that not returns any value?
void
int
double
None of the above
Explanation:-
Answer: Option A. -> void
Question 4. Which of the following options is the best for generating random integer 0 or 1?
(int)Math.random()
(int)Math.random() + 1
(int)(Math.random() + 0.5)
(int)(Math.random() + 0.2)
Explanation:-
Answer: Option C. -> (int)(Math.random() + 0.5)
Question 5. What is Math.floor(3.6)?
3.0
3
4
4.0
Explanation:-
Answer: Option B. -> 3
Question 6. In which area of memory, the system stores parameters and local variables whenever a method is invoked?
Heap
Storage Area
Stack
Array
Explanation:-
Answer: Option C. -> Stack
Question 7. What is the expected output? public class Profile { private Profile(int w) { // line 1 System.out.print(w); } public final Profile() { // line 5 System.out.print(10); } public static void main(String args[]) { Profile obj = new Profile(50); } }
Won't compile because of line (1); constructor can't be private
Won't compile because of line (5); constructor can't be final
50
10 50
Explanation:-
Answer: Option B. -> Won't compile because of line (5); constructor can't be final
Question 8. What is the expected output? class Animal { Animal() { System.out.println("Animal"); } } class Wild extends Animal{ Wild() { System.out.println("Wild"); super(); } } public class Test { public static void main(String args[]) { Wild wild = new Wild(); } }
Animal Wild
Wild Animal
Runtime Exception
Compilation Error
Explanation:-
Answer: Option D. -> Compilation Error
Question 9. Which of the modifier can't be used for constructors?
public
private
static
protected
Explanation:-
Answer: Option C. -> static
Question 10. The variables declared in a class for the use of all methods of the class are called