Quiz About Java Constructors
Quiz About Java Constructors
Question 1
Java
class Point {
int m_x, m_y;
public Point(int x, int y) { m_x = x; m_y = y; }
public static void main(String args[])
{
Point p = new Point();
}
}
Yes
No
Discuss it
Question 1 ‒ Explanation
The main function calls parameterless constructor, but there is only one constructor defined in class which takes two
parameters. Note that if we write our own constructor, then compiler doesn\'t create default constructor in Java. Thi
s behavior is same as C++.
Question 2
JAVA
class Test
{
static int a;
static
{
a = 4;
System.out.println ("inside static block\\n");
System.out.println ("a = " + a);
}
Test()
{
System.out.println ("\\ninside constructor\\n");
a = 10;
}
}
}
Compiler Error
Discuss it
Question 2 ‒ Explanation
Static blocks are called before constructors. Therefore, on object creation of class Test, static block is called. So, s
tatic variable a = 4. Then constructor Test() is called which assigns a = 10. Finally, function func() increments its v
alue.
Question 3
Java
(10.0 + 15.0i)
(0.0 + 0.0i)
Discuss it
Question 4
Java
class Point {
int m_x, m_y;
10
compiler error
Discuss it
Question 4 ‒ Explanation
it\'s a simple program where constructor is called with parameters and values are initialized.
Question 5
1, 2
1, 2 and 3
1, 2, 3 and 4
Discuss it
Question 6
Java
package main;
class T {
int t = 20;
}
class Main {
public static void main(String args[]) {
T t1 = new T();
System.out.println(t1.t);
}
}
20
Compiler Error
Discuss it
Question 6 ‒ Explanation
In Java, member variables can assigned a value with declaration. In C++, only static const variables can be assign
ed like this.
Question 7
Java
class T {
int t = 20;
T() {
t = 40;
}
}
class Main {
public static void main(String args[]) {
T t1 = new T();
System.out.println(t1.t);
}
}
20
40
Compiler Error
Discuss it
Question 7 ‒ Explanation
The values assigned inside constructor overwrite the values initialized with declaration.