Saturday, July 6, 2019

Java Interview Questions and Answers

1. What are the various access specifiers for Java classes?

The access modifiers in java specify accessibility (scope) of a data member, method, constructor or class. There are 4 types of java access modifiers:

Public: Class, Method, Field are accessible from anywhere.

Protected: The protected access modifier is accessible within package and outside the package but through inheritance only.

Default: If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package.

Private: Methods and Fields are accessible only within class

2. What is the purpose of static methods and static variables?

We use static keyword to make a method or variable shared for all objects. When we want to have a single copy of a variable or method to be shared among all the instances of the class, we create static methods and static variables.

3. What do you mean by Checked Exceptions?

A checked exception is a subclass of Exception. A Compiler checks to see if these exceptions have been properly caught or not else the code doesn't compile. 

Thus, a programmer is forced to deal with the situations where an exception can be thrown. Checked exceptions must be either declared or caught at compile time.

4. Explain the difference between an Inner Class and a Sub-Class.

An Inner class is a class which is nested within another class. An Inner class has access rights for the class which is nesting it and it can access all variables and methods defined in the outer class.

A sub-class is a class which inherits from another class called super class. Sub-class can access all public and protected methods and fields of its super class.

5. What is a singleton class?

A singleton class in java can have only one instance and hence all its methods and variables belong to just one instance. The purpose of singleton is to control the object creation, limiting the number of the objects to one only.

6. What is Final Keyword in Java?

In java, Final Keyword is used to define an entity that can only be assigned once.

Following is what happens when it is applied on classes, variables or methods: 

final classes - A final class cannot have subclasses. 

final variables - Once initialized, a final variable cannot be changed. 

final Methods - A final method cannot be overridden by subclasses.

7. What are Java Packages?

A package is a collection of classes and interfaces which are kept together as they are related to each other. 

It helps modularizing the code and group the code for proper re-use. 

Packages can be imported in other classes.

8. Explain the difference between an Abstract Class and Interface in Java.

Abstract classes can have methods with implementation whereas an interface provides absolute abstraction and can’t have any method implementations.

A class which implements an interface must implement all the methods of the interface while a class which inherits from an abstract class doesn't require implementation of all the methods of its super class.

Subclasses use extends keyword to extend an abstract class whereas subclasses use implements keyword to implement interfaces

A class can implement multiple interfaces but it can extend only one abstract class.

9. Can we declare a class as Abstract without having any abstract method?

Yes, we can have an abstract class without abstract methods as both are independent concepts. Declaring a class abstract means it can’t be instantiated on its own and can only be sub classed. Declaring a method abstract means method will be defined in the subclass.

However, if a class has even one abstract method, it must be declared as abstract otherwise it will give an error.

10. What is an immutable class?

Immutable class is a class which once created; its contents can’t be changed.

Immutable objects are the objects whose state can’t be changed once constructed.

Since the state of the immutable objects can’t be changed once they are created, they are automatically synchronized/thread-safe.

11. How an object is serialized in java?

Serialization is a mechanism of converting an object into a byte stream so that the object can be easily saved to persistent storage or streamed across a communication link. An object of a class is serialized by implementing serializable interface.

12. When we should use serialization?

Serialization is used when data needs to be transmitted over the network. 

You can also save object's state and convert into byte stream using Serialization

13. When the constructor of a class is invoked?

The constructor of a class is invoked when an instance of the object is created and memory is allocated for the object.

For example, in the following class, two objects are created using new keyword and hence, constructor is invoked twice.

Example

public class const_new {
  const_new() {
    system.out.println("constructor");
  }
  public static void main(String args[]) {
     const_new c1 = new const_new();
     const_new c2 = new const_new();
  }
}

14. Why Strings in Java are called as Immutable?

The String class is considered as immutable because once it is created, a String object cannot be changed. If we require to make a lot of modifications to Strings of characters then StringBuffer should be used.

15. Why Runnable Interface is used in Java?

Runnable interface is used for implementing multi threaded applications. 

If you want to execute a code in separate thread, you need to implement Runnable interface in a class whose instance you want to run in separate thread instead of Main thread.

16. What are the two ways of implementing multi-threading in Java?

Java offers implementation of multi-threading by two ways:

By extending Thread class and overriding its run() method.

By Implementing Runnable interface

17. When a lot of changes are required in data, which one should be preferred - String or StringBuffer?

Since StringBuffers are dynamic in nature and we can change the values of StringBuffer objects unlike String which is immutable, it's always a good choice to use StringBuffer when data is being changed too many times. If we use String in such a case, for every data change a new String object will be created which will be an extra overhead.

18. How garbage collection is done in Java?

In java, when an object is not referenced any more, garbage collection takes place and the object is destroyed automatically. Java calls either System.gc() method or Runtime.gc() method for automatic garbage collection

19. How objects of a class are created if no constructor is defined in the class?

When no explicit constructor is defined in a java class, objects can still get created successfully. In this case, Java use default constructor implicitly for object creation. This constructor has no parameters.

20. How can we ensure that a resource isn't used by multiple threads simultaneously?

Using synchronized keyword, we can ensure that only one thread can use shared resource at a time and others can get control of the resource only once it is free from the other one using it.

21. How can we make copy of a java object?

Object cloning refers to creation of exact copy of an object. It creates a new instance of the class of current object and initializes all its fields with exactly the contents of the corresponding fields of this object.

Clone() is a method of Cloneable interface and hence, Cloneable interface needs to be implemented for making object copies.

22. What is the benefit of using inheritance?

Reusability - Inheritance offers facility to use public methods of base class without rewriting the same.

Extensibility - It extends the base class logic as per business logic of the derived class.

Data hiding - In inheritance, base class can decide to keep some data private so that it cannot be altered by the derived class

Overriding - With inheritance, we will be able to override the methods of the base class so that meaningful implementation of the base class method can be designed in the derived class.

23. What are two methods to resist a class from inherited in java?

1. By declaring the class as 'final'

2. By declaring all member's of the class private.

24. What is the difference between Stack and Queue?

A stack is based on Last in First out (LIFO) principle while a queue is based on FIFO (First In First Out) principle.

25. How can we restrict certain variables of a class from getting serialized?

We can do so by using the keyword transient while declaring variables of the class.  

For example, the variable trans_count below is a transient variable and can't be serialized:

Example

public class transientSample { 
    private transient trans_count; 
}

26. Is it possible to use a default constructor even if an explicit constructor is defined?

When an explicit constructor is defined, default constructor can't be invoked. Java invokes default constructor when no explicit constructor is defined

27. Can we override a method by using same method name and arguments but different return types?

For a method to be overriden method name, arguments and return type must be exactly same. so, using a different return type doesn't override a method.

No comments:

Post a Comment

Get max value for identity column without a table scan

  You can use   IDENT_CURRENT   to look up the last identity value to be inserted, e.g. IDENT_CURRENT( 'MyTable' ) However, be caut...