Java Interview Question & Answers

Question & Answers Series Part -2

00:00 / 00:00

1.What is an interface in Java?

An Interface in Java is an abstract type blueprint of a class. It contains the methods that a class must implement. It is like a protocol. It has method signatures and constant declarations.

2. Is it allowed to mark an interface method as static?

Yes, from Java 8 onwards, we can define static and default methods in an interface. Prior to Java 8, it was not allowed.

3. Why an Interface cannot be marked as final in Java?

A final method cannot be overridden. But an interface method has to be implemented by another class. So the interface method cannot be marked as final.

4. What is a marker interface?

There are interfaces that do not have any data member or methods. These interfaces are called Marker interface. E.g. Serializable, Cloneable, Remote etc.

5. How Annotations are better than Marker Interfaces?

Annotations serve the purpose of conveying metadata about the class to its consumers without creating a separate type for it. Annotations are more powerful than a Marker interface. They allow programmers to pass more sophisticated information to classes that "consume" it.

6. What is the difference between abstract class and interface in Java?

Differences between Abstract class and Interface are as follows:
1. An abstract class can have implemented methods with body (non-abstract methods). Interface has only abstract methods. From Java 8 onwards, interface can have static/default methods in implemented form.
2. An abstract class can have instance member variables. An interface cannot have instance variables. It can only have constants.
3. An abstract class can have a constructor. Interface cannot have constructor. It has to be implemented by another class.
4. A class can extend only one abstract class. A class can implement more than one interface.

7. How can we cast to an object reference to an interface reference?

An Object that implements an Interface can be cast to the same Interface. Since An Object implementing an Interface already provides implementation for the methods of that Interface, it is allowed to do so as per the rules of Inheritance. Final

8. How can you change the value of a final variable in Java?

Java does not allow changing the value of a final variable. Once the value is set, it cannot be changed.

9.Can a class be marked final in Java?

Yes a class can be marked final in Java. Once a class is marked final, it cannot be extended.

10. How can we create a final method in Java?

To mark a method, add modifier final to that method. A final method can not be overridden by a child class.

11. How can we prohibit inheritance in Java?

If you mark a class final, it cannot be extended. This will prohibit the inheritance of that class in Java.

12. Why Integer class in final in Java?

Integer class is a wrapper for int. If it is not marked final, then any other class can extend it and modify the behavior of Integer operations. To avoid this Integer wrapper class is marked as final.

13. What is a blank final variable in Java?

When we declare a final variable without giving any initial value, then it is called blank final variable.

14. Is it allowed to declare main method as final?

Yes, we can mark the main method as final. Package

15. What is the purpose of package in Java?

A package is used to encapsulate a group of classes, interfaces and sub-packages. Often, it is a hierarchical structure of storing information. It is easier to organize the related classes and subpackages in this manner. A Package also provides access protection for classes and interfaces. A package also helps in removing naming collision.

16. What is java.lang package?

In Java, java.lang package contains the classes that are fundamental to the design of Java programming language. The most important class in this package is Object class. It also contains wrapper classes like- Integer, Boolean, Character etc. It provides Math class for mathematical operations.

17. Which is the most important class in Java?

It is an open-ended question with many answers. In my view, Object class is the most important class of Java programming language. It is the root of all the classes in Java. It provides some very important and fundamental methods.

18. Can you import same package or class twice in your class?

If we import same package multiple times in a class, compiler includes it only once. So neither JVM nor Compiler gives any error/warning on including a package multiple times. If you have two classes with same name, then you may get name collision on importing the class erroneously. JVM internally loads the class only one time.

19. What is a static import in Java?

Static import is similar to normal import declaration. Normal import allows us to import classes from packages without using package qualifier. Static import allows us to import static members from a class without using class qualifier.

20. What is the difference between import static com.test.Fooclass and import com.test.Fooclass?

First import is a static import and the second import is normal import of a class. First import allows us to import static members of class. Internationalization

21. What is Locale in Java?

A Locale object represents a specific geographical, political, or cultural region. It is used to locale-sensitive operations in Java. It helps is following the local conventions of a country, native or region. These conventions can be for formatting the dates, money, numbers etc.

22. How will you use a specific Locale in Java?

To use a specific Locale, we need to load that Locale. We can use ResourceBundle.getBundle("Locale.UK") method to load a Locale. Serialization

23. What is the serialization?

Serialization is a process converting an object into a byte array. This byte array represents the class, version and internal state of the object. JVM can use this byte array to transmit/read the object over a network.

24. What is the purpose of serialization?

Some of the uses of serialization are:
1. Communication: It is used for transmitting an object over network between two machines.
2. Persistence: We can store the object’s state in a database and retrieve it from database later on.
3. Caching: Serialization can be used for caching to improve performance. We may need 10 minutes to build an object, but it may take just 10 seconds to de-serialize the object.
4. Cross JVM Synchronization: It can be used in same way across multiple JVM that follow different architecture.

25. What is Serialization and Deserialization conceptually?

Serialization is to convert Object data into a stream of bytes Deserialization is to convert a stream of bytes back into a copy of the original object.

26.Why do we mark a data member transient?

Member variables of an object are marked transient to indicate that they should not be serialized. During serialization process the transient variables are not considered part of the persistent state of an object.

27. How does marking a field as transient makes it possible to serialize an object?

Let say we have a class ABC that implements Serializable interface, but it contains a member variable object of class XYZ that does not implement Serializable interface. Due to this it is not possible to Serialize the class ABC. To solve this issue, we can mark the member variable XYZ as Transient in class ABC. This will allow us to serialize the class ABC.

28. What is Externalizable interface in Java?

Externalizable interface extends Serializable interface in Java. It is used for giving the Class control over saving and restoring the contents of its instances. A class implements methods writeExternal() and readExternal() to store and restore the object.

29. What is the difference between Serializable and Externalizable interface?

Serializable is a marker interface but Externalizable is not a marker interface. When we implement Serializable interface, the class is serialized automatically by default. We can override writeObject() and readObject()methods to control more complex object Serialization process.
In case of Externalizable, we use readExternal() and writeExternal() methods to give control to class for class's serialization process. Serializable interface is based on recursive algorithm.
Serializable gives you two options. One option is to provide custom way of serialization, the other default way. In Externalizable, you have to always implement readExternal() and writeExternal() methods. A public no-arg constructor is needed while using Externalizable interface.
In Serialization, we need to define serialVersionUID. If it is not explicitly defined it will be generated automatically based on all the fields, methods of the class. Reflection

30. What are the uses of Reflection in Java?

Reflection is often used in Testing, Debugging and in Integrated Development Environment (IDE). Reflection allows you to write programs that do not have to "know" everything at compile time. It makes programs more dynamic, since they can be tied together at runtime. Many modern frameworks like Spring etc. use Reflection. Some modern languages like Python etc. also use Reflection. JAVA API for XMLParsing (JAXP) also uses Reflection.

31. How can we access private method of a class from outside the class?

We can use Reflection to access private method of a class from outside the class. IN Java, we use getDeclaredMethod() to get instance of a private method.
In following sample code, we are accessing private method message() of class Foo by Reflection.
FileName: Foo.java
public class Foo{
private void message(){System.out.println("hello java"); }
FileName: FooMethodCall.java
import java.lang.reflect.Method;
public class FooMethodCall{
public static void main(String[] args)throws Exception{
Class c = Class.forName("Foo");
Object o= c.newInstance();
Method m =c.getDeclaredMethod("message", null);
m.setAccessible(true); m.invoke(o, null);

32. How can we create an Object dynamically at Runtime in Java?

We can use Reflection to create an Object dynamically at Runtime in Java. We can use Class.newInstance() or Constructor.newInstance() methods for creating such Objects. Garbage Collection

33.What is Garbage Collection in Java?

Java has an internal mechanism called Garbage collection to reclaim the memory of unused projects at run time. Garbage collection is also known as automatic memory management.

34. Why Java provides Garbage Collector?

In Java, there are no pointers. Memory management and allocation is done by JVM. Since memory allocation is automated, after some time JVM may go low on memory. At that time, JVM has to free memory from unused objects. To help with the process of reclaiming memory, Java provides an automated process called Garbage Collector.

35.What is the purpose of gc() in Java?

Java provides two methods System.gc() and Runtime.gc() to request the JVM to run the garbage collection. By using these methods, programmers can explicitly send request for Garbage Collection. But JVM process can reject this request and wait for some time before running the GC.

36.How does Garbage Collection work in Java?

Java has an automated process called Garbage Collector for Memory Management. It is a daemon in JVM that monitors the memory usage and performs memory cleanup. Once JVM is low on memory, GC process finds the unused objects that are not referenced by other objects. These unused objects are cleaned up by Garbage Collector daemon in JVM.

37. When does an object become eligible for Garbage Collection in Java?

An object can be Garbage Collected by JVM, if it is not reachable. There are two cases for deciding eligibility of objects for Garbage Collection: 1. An Object/instance that cannot be reached by a live thread. 2. A set of circularly referenced instances that cannot be reached by any other instance outside that set.

38.Why do we use finalize() method in Java?

Java provides finalize() method to perform any cleanup before Garbage Collection. This method is in Object class, and it is invoked by JVM internally. Developers are free to implement this method for any custom cleanup in case of Garbage Collection. If an Object is not Garbage Collected, then this method may not be called. This method is never invoked more than once by JVM.

39.What are the different types of References in Java?

In Java, there are four types of references:
1. Strong Reference
2. Soft Reference
3. Weak Reference
4. Phantom Reference

40.How can we reference an unreferenced object again?

We can provide implementation in finalize() method to reference and unreferenced object. For an unreferenced object, finalize() method is called at the time of Garbage Collection. At this time, Object can pass its reference ‘this’ to finalize() method and revive itself.

41.What kind of process is the Garbage collector thread?

Garbage Collection is a Daemon process in JVM. It is an internal process that keep checking Memory usage and cleans up the memory.

42.What is the purpose of the Runtime class?

The purpose of the Runtime class is to provide access to the Java Runtime system. This class provides certain important methods like:
1. Runtime.freeMemory() – This method returns the value of free memory in JVM
2. Runtime.maxMemory() - This method returns the value of maximum memory that JVM can use.
3. Runtime.gc() – This method can invoke garbage collection.

43. What are the uses of Runtime class?

Runtime class in Java provides following benefits: 1. It allows to read data via key board 2. It can use system properties and environment variables 3. It helps in running non-java programs from within a java application. Inner Classes

44. How many types of Nested classes are in Java?

Java provides four types of Nested classes:
  1. Member inner class
  2. Local inner class
  3. Anonymous inner class
  4. Static nested class

45.Why do we use Nested Classes?

There are following reasons for using nested classes:
1. Logical Grouping: We can logically group classes in one place. If one class is useful to only one other class, then we put smaller class within the larger class and keep them in one file. This kind of nesting "helper classes" in a top level class makes the package more streamlined.
2. Encapsulation: Nested classes increase encapsulation. Let say there are two top-level classes, Foo and Bar. Bar needs access to private members of Foo. We can hide class Bar within class Foo. In this way, private members of Foo can be accessed by class Bar. So class Foo remains encapsulated. Also, class Bar remains hidden from the outside world.
3. Code Clarity: Nested classed make the code more readable and well organized. Only Top-level classes are exposed. The helper classes are kept hidden and closer the code where it is used by a Top-level class.

46.What is the difference between a Nested class and an Inner class in Java?

An Inner class in Java is non-static class. It is a type of Nested class that is defined in another class but not qualified with a Static modifier. A Nested class is also a class can be Static Nested class or a non-Static Inner class. An Inner class has access to other members of the enclosing class, even if they are declared private. A Static Nested class can not access the other members of the enclosing class.

47. How can we access the non-final local variable, inside a Local Inner class?

Java allows a Local Inner class to access only Constant local members. So we have to make the non-final local variable as final constant to access it inside a Local Inner class.

48.Why do we use Static Nested interface in Java?

Only the enclosing class can access a Static Nested interface. Consider following code in which interface Xyz is enclosed in class Abc.
public class Abc {
public interface Xyz {
void callback(); }
public static void registerCallback(Xyz xyz) {...} } // Client Code
Abc.registerCallback(new Abc.Xyz() {
public void callback() {...} }
Any code that cannot access Abc can not access interface Xyz also. So the purpose of declaring an Inner interface is to restrict its access from outside world. String

49.What is the meaning of Immutable in the context of String class in Java?

An Immutable object cannot be modified or changed in Java. String is an Immutable class in Java. Once a String object is created, it cannot be changed. When we assign the String to a new value, a new object is created.

50.Why a String object is considered immutable in java?

Java language uses String for a variety of purposes. For this it has marked String Immutable. There is a concept of String literal in Java.
Let say there are 2 String variables A and B that reference to a String object “TestData”. All these variables refer to same String literal. If one reference variable A changes the value of the String literal from “TestData” to “RealData”, then it will affect the other variable as well. Due to which String is considered Immutable. In this case, if one variable A changes the value to “RealData”, then a new String literal with “RealData” is created and A will point to new String literal. While B will keep pointing to “TestData”.

Sign up to EdnSquare, Here is lot more to explore

Get the things deliverd to your inbox that matters to you most

More About EdnSquare

·       ·       ·