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


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

073.
074.
public class Electronics {
int price;
Electronics(int price) {
this.price = price;
} //constructor
public static void main(String argument[]) {
Electronics e = new Electronics(); //Line 1
}
}
In the above code, as soon as Line 1 is executed, the JVM
invokes the constructor. This initializes the price field with the
value passed in.
Explain the void keyword with a code sample.
Answer:
The void keyword is useful when a method does not return a
value. It is specified as the return type for such methods. The
following code demonstrates this:
public void doSomething(){
}
Here, the void keyword is specified with the doSomething()
method which indicates that this method does not return any
value.
Explain the differences between a constructor and an
ordinary method.
Answer:






075.
There are several differences between a constructor and an
ordinary method. These are as follows:
A constructor has the same name as the class name, an
ordinary method can have any name.
A constructor does not have a return type, not even void. A
method has a return type. If a method does not return any
value, then the keyword void needs to be specified.
A constructor is automatically invoked when an object of the
class is created. A method needs to be invoked explicitly.
If a class does not have a constructor, Java automatically
creates a default constructor. If a class does not have a
method, Java does not automatically add a method.
Explain this keyword with a code sample.
Answer:
The this keyword is used to refer to the current object. It can be
used to reference a field or a method corresponding to the
current object. The following code demonstrates this:
public class Book {
private String name;
private String author;
public Book(String name, String author) {
this.name = name;
this.author = author;
}
public void doSomething(Book book) {
}
public void doSomethingElse(Book book) {
this.doSomething(book);
}



Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   25   26   27   28   29   30   31   32   ...   171




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