Core java interview Questions You'll Most Likely Be Asked (Second Edition)


Download 1.52 Mb.
Pdf ko'rish
bet27/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   23   24   25   26   27   28   29   30   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

065.
066.
067.
CHAPTER
06
Classes and Methods
Consider the following code snippet:
static void main(String argument[]) {
System.out.println(“This gets printed”);
}
What will be the output when this code is compiled and
executed?
Answer:
The above code compiles fine. But on executing, an error occurs
as follows:
Error: Main method not found in class
This is because the main method does not have the public
access specifier, so it is not accessible outside the class. So, the
JVM is not able to access the main method and the error occurs.
Can an instance variable be declared as static? Explain.
Answer:
An instance variable cannot be declared as static. If an instance
variable is declared as static, then that variable becomes a class
variable.
Explain what happens when the following code is
compiled and executed.


068.
class Laptop {
Laptop(String laptopName) {
System.out.println(“Laptop Name is ....”);
}
public static void main(String argument[]) {
Laptop l = new Laptop();
}
}
Answer:
The code will not compile and it will cause the following
compilation error:
“The constructor Laptop() is undefined.”
This is because there is no default constructor defined in this
code. Since there is a constructor with an argument, Java cannot
automatically create a default no argument constructor. In order
for this code to work, an explicit constructor needs to be added
as follows:
Laptop() {
}
What happens behind the scenes if a constructor is not
explicitly specified?
Answer:
If a constructor is not explicitly specified, the compiler
automatically generate a default no arguments constructor.
Whenever a new object is created, this default constructor is
used.



Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   23   24   25   26   27   28   29   30   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling