General Java
Can == be used on enum?
es: enums have tight instance controls that allows you to use == to compare instances. Here's the guarantee provided by the language specification.
Compare the sleap() and wait()
methods in Java
sleep()
is a blocking operation that keeps a hold on the monitor/ lock of the shared object for the specified number of milliseconds.wait()
on the other hand, simply pauses the thread until either- the specified number of milliseconds have elapsed
- it receives a desired notification from another thread (whichever is first), without keeping a hold on the monitor/lock of the shared object
sleep()
is mostly commonly used for polling, or to check for certain results, at a regular interval. wait()
is generally used in multithreaded applications in conjunction with notify()/notifyAll()
, to archive synchronization and avoid race conditions
How do I read/convert in InputSteam into a String in Java?
A nice way to do this is using Apache commons IOUtils
to copy the InputStream
into a StringWriter
like:
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
or
// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding);
Is Java "pass-by-reference" or "pass-by-value"?
Java is always pass-by-value. Unfortunately, when we pass the value of an object, we are passing the reference to it. There is no such thing as "pass-by-reference" in Java. This is confusing to beginners.
The key to understanding this is that something like
Dog myDog;
is not a Dog; it's actually a pointer
to a Dog.
So when you have
Dog myDog = new Dog("Rover");
foo(myDog);
State the features of an interface.
An interface is a template that contains only the signature of methods. The signature of a method consists of the numbers of parameters, the type of parameter (value, reference, or output), and the order of parameters. An interface has no implementation on its own because it contains only the definition of methods without any method body. An interface is defined using the interface keyword. Moreover, you cannot instantiate an interface. The various features of an interface are as follows:
- An interface is used to implement multiple inheritance in code. This feature of an interface is quite different from that of abstract classes because a class cannot derive the features of more than one class but can easily implement multiple interfaces.
- It defines a specific set of methods and their arguments. Variables in interface must be declared as public, static, and final while methods must be public and abstract.
- A class implementing an interface must implement all of its methods.
- An interface can derive from more than one interface.
What is a JavaBean exactly ?
Basically, a "Bean" follows the standart:
- is a serializable object (that is, it implements java.io.Serializable, and does so correctly), that
- has "properties" whose getters and setters are just methods with certain names (like, say, getFoo() is the getter for the "Foo" property), and
- has a public 0-arg constructor (so it can be created at will and configured by setting its properties). There is no syntactic difference between a JavaBean and another class - a class is a JavaBean if it follows the standards.
What is difference between fail-fast and fail-safe?
The Iterator's fail-safe property works with the clone of the underlying collection and thus, it is not affected by any modification in the collection. All the collection classes in java.util package are fail-fast, while the collection classes in java.util.concurrent are fail-safe. Fail-fast iterators throw a ConcurrentModificationException, while fail-safe iterator never throws such an exception.
What is structure of Java Heap?
The JVM has a heap that is the runtime data area from which memory for all class instances and arrays is allocated. It is created at the JVM start-up. Heap memory for objects is reclaimed by an automatic memory management system which is known as a garbage collector. Heap memory consists of live and dead objects. Live objects are accessible by the application and will not be a subject of garbage collection. Dead objects are those which will never be accessible by the application, but have not been collected by the garbage collector yet. Such objects occupy the heap memory space until they are eventually collected by the garbage collector.
What is the volatile keyword useful for?
volatile
has semantics for memory visibility. Basically, the value of a volatile field becomes visible to all readers (other threads in particular) after a write operation completes on it. Without volatile, readers could see some non-updated value.
What is Double Brace initialization in Java?
Double brace initialisation
creates an anonymous class derived from the specified class (the outer braces), and provides an initialiser block within that class (the inner braces). e.g.
new ArrayList<Integer>() {{
add(1);
add(2);
}};
However, I'm not too fond of that method because what you end up with is a subclass of ArrayList
which has an instance initializer, and that class is created just to create one object -- that just seems like a little bit overkill to me.
Why is char[] preferred over String for passwords?
Problem
Why does String pose a threat to security when it comes to passwords? It feels inconvenient to use char[]?
Answer
Strings are immutable. That means once you've created the String, if another process can dump memory, there's no way (aside from reflection) you can get rid of the data before garbage collection kicks in.
With an array, you can explicitly wipe the data after you're done with it. You can overwrite the array with anything you like, and the password won't be present anywhere in the system, even before garbage collection.
How is event handling done in Spring?
Event handling in the ApplicationContext is provided through the ApplicationEvent class and ApplicationListener interface. So if a bean implements the ApplicationListener, then every time an ApplicationEvent gets published to the ApplicationContext, that bean is notified.
Can we make a constructor final, Explain ?
When you set a method as final it means: "I don't want any class override it." But according to the Java Language Specification:
JLS 8.8 - "Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding."
When you set a method as abstract it means: "This method doesn't have a body and it should be implemented in a child class." But the constructor is called implicitly when the new keyword is used so it can't lack a body.
When you set a method as static it means: "This method belongs to the class, not a particular object." But the constructor is implicitly called to initialize an object, so there is no purpose in having a static constructor.
If a method throws NullPointerException
in super class, can we override it with a method which throws RuntimeException
?
Yes
The NullPointerException
is descendant of RuntimeException
. So we can override it.
What is double check
in Singleton pattern?
public class DclSingleton {
private static volatile DclSingleton instance;
public static DclSingleton getInstance() {
if (instance == null) {
synchronized (DclSingleton .class) {
if (instance == null) {
instance = new DclSingleton();
}
}
}
return instance;
}
// private constructor and other methods...
}
WARNING
One thing to keep in mind with this pattern is that the field needs to be volatile to prevent cache incoherence issues. In fact, the Java memory model allows the publication of partially initialized objects and this may lead in turn to subtle bugs.
Need To Answer
Why String are immutable in Java? What are its benefits?
How does ConcurrentHashMap
works?
How to make an Object Immutable
in Java? Why should you make an Object Immutable?
Explain Open Closed Design
Principle?
Difference between NoClassDefFoundError
and ClassNotFoundException
?
How Hashmap works internally ? Importance of hashcode
and equals
method?
Advantages and Disadvantages of Garbage Collection
?
Explain the difference
types of Garbage Collector
in Java?
Explain Heap Generations
for Garbage Collection in Java ?
When an object becomes eligible
for Garbage Collection ?
Why wait
and notify
is declared in Object class instead ot Thread ?
Explain ThreadLocal
in Java ? When do we need ThreadLocal
?
Why happens if your Serializable class contains a member which is not serializable?
###Can you override static method in Java ?