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


Identify the error in the following code snippet and explain


Download 1.52 Mb.
Pdf ko'rish
bet94/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   90   91   92   93   94   95   96   97   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

Identify the error in the following code snippet and explain
how it can be fixed.
public interface MyInterface {
public static void doSomething() {
System.out.println(“Doing something....”);
}
}
public class MyClass implements MyInterface{
public static void main(String args[]) {
MyClass obj = new MyClass();
obj.doSomething(); //Line 1
}
}
Answer:


The code above defines an interface called MyInterface with a
static method called doSomething(). It then creates a class
called MyClass which implements MyInterface. The main
method of MyClass creates an object of MyClass called obj
and invokes the doSomething() method at Line 1. This causes
a compilation error at Line 1. This is because the code tries to
access a static interface method via an object of the class. Static
interface methods can only be accessed via the interface name.
In order to fix the error, Line 1 needs to be replaced as follows:
MyInterface.doSomething();



247.
248.
CHAPTER
07
Optionals
What is an Optional and why was it added by Java 8?
Answer:
An Optional is used to represent a value that can either be
present or absent. It has methods that can be used to retrieve the
underlying value if present. The following code demonstrates an
Optional:
Optional number;
So here, number is an Optional of type Integer. It may or may
not contain a value.
Optionals were added by Java 8 to avoid the boilerplate code
associated with null checks. Sometimes, a method may return a
null. This can result in a NullPointerException. In order to
avoid the exception, the code that invokes the method needs to
have explicit null checks. This can make the code difficult to read.
Java 8 Optionals help to avoid this boilerplate code. So instead of
having an explicit null check, an optional can be used. If the value
is present it can be retrieved.

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   90   91   92   93   94   95   96   97   ...   171




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