Java Interview Questions and Answers

by Bharathkumar, on Sep 10, 2022 11:59:30 AM

Interview Questions (43)Q1. What is Java?

Ans: Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere" (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.

OR:

  • Java is an object-oriented computer language.
  • It is a high-level programming language developed by James Gosling in Sun Microsystem in 1995.

Java is a fast, secure and reliable language used for many games, devices and applications.

Q2. What are the Features of Java?

Ans:

simple. Java was designed with a small number of language constructs so that programmers could learn it quickly. It eliminates several language features available in C/C++ that are associated with poor programming practices or rarely used: goto statements, header files, structures, operator overloading, multiple inheritance and pointers.

object-oriented. Java is an OOPL that supports the construction of programs that consist of collections of collaborating objects. These objects have a unique identity, encapsulate attributes and operations, and are instances of classes related by inheritance and polymorphism.

distributed. Java is designed to support various levels of network connectivity. Java applications are network aware: TCP/IP support is built into Java class libraries. They can open and access remote objects on the Internet.

interpreted. Java is compiled to bytecodes, which are interpreted by a Java run-time environment.

robust. Java is designed to eliminate certain types of programming errors. Java is strongly typed, which allows extensive compile-time error checking. It does not support memory pointers, which eliminates the possibility of overwriting memory and corrupting data. In addition, its automatic memory management (garbage collection) eliminates memory leaks and other problems associated with dynamic memory allocation/de-allocation.

secure. Java is designed to be secure in a networked environment. The Java run-time environment uses a bytecode verification process to ensure that code loaded over the network does not violate Java security constraints.

architecture neutral. Java applications that are compiled to bytecodes can be interpreted by any system that implements the Java Virtual Machine. Since the Java Virtual Machine is supported across most operating systems, this means that Java applications are able to run on most platforms.

portable. In addition to supporting architecture neutrality, Java ensures that other implementation-dependent aspects of language specification are eliminated. For example, Java specifies the sizes of primitive data types and their arithmetic behavior.

high performance. Although Java is an interpreted language, it was designed to support “just-in-time” compilers, which dynamically compile bytecodes to machine code.

multithreaded. Java supports multiple threads of execution (a.k.a., lightweight processes), including a set of synchronization primitives. This makes programming with threads much easier.

dynamic language. Java supports dynamic loading of classes (a.k.a. “load on demand”), dynamic compilation, and automatic memory management (garbage collection).

Q3. What is the difference between an Inner Class and a Sub-Class?

Ans: 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.

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

Ans: In Java, access specifiers are the keywords used before a class name which defines the access scope. The types of access specifiers for classes are:

  • Public: Class,Method,Field is accessible from anywhere.
  • Protected: Method,Field can be accessed from the same class to which they belong or from the sub-classes,and from the class of same package,but not from outside.
  • Default: Method,Field,class can be accessed only from the same package and not from outside of it’s native package.
  • Private: Method,Field can be accessed from the same class to which they belong.

Q5. What’s the purpose of Static methods and static variables?

Ans: When there is a requirement to share a method or a variable between multiple objects of a class instead of creating separate copies for each object, we use static keyword to make a method or variable shared for all objects.

Q6. What is data encapsulation and what’s its significance?

Ans: Encapsulation is a concept in Object Oriented Programming for combining properties and methods in a single unit.Encapsulation helps programmers to follow a modular approach for software development as each object has its own set of methods and variables and serves its functions independent of other objects. Encapsulation also serves data hiding purpose.

Q7. What do you mean by Object?

Ans: An object consists of methods and class which depict its state and perform operations. A java program contains a lot of objects instructing each other their jobs. This concept is a part of core java.

Q8. What is class in Java?

Ans: Java encapsulates the codes in various classes which define new data types. These new data types are used to create objects.

Q9. Differentiate between JDK, JRE and JVM.

Ans:

  • JVMstands for Java Virtual Machine which provides runtime environment for Java Byte Codes to be executed.
  • JRE(Java Runtime Environment) that includes sets of files required by JVM during runtime.
  • JDK(Java Development Kit) consists of JRE along with the development tools required to write and execute a program.

Q10. Define Inheritance.

Ans: Java includes the feature of inheritance which an object-oriented programming concept. Inheritance lets a derived class to inherit the methods of a base class.

Q11. Explain method overloading.

Ans: When a Java program contains more than one methods with the same name but different properties, then it is called method overloading.

Q12. Compare Overloading and Overriding.

Ans: Overloading refers to the case of having two methods of same name but different properties, but overriding occurs when there are two methods of same name and properties, but one is in child class and one is in parent class.

Q13. Explain the creation of a thread-safe singleton in Java using double-checks locking.

Ans: Singleton is created with double checked locking as before Java 5 acts as an broker and it’s been possible to have multiple instances of Singleton when multiple threads creates an instance of Singleton at the same time. Java 5 made it easy to create thread-safe Singleton using Enum. Using a volatile variable is essential for the same.

Q14. Differentiate between StringBuffer and StringBuilder in Java programming.

Ans:

String Buffer String Builder
StringBuffer methods are synchronized StringBuilder is non synchronized
Storage area is Heap and modified easily. Storage is Heap and can be modified.
StringBuffer is thread safe. StringBuilder is fast as it is not thread safe
Performance is very slow Performance is very fast.

 

Q15. Difference between Array list And Vector.

Ans: 

Array List Vector
Array List is not synchronized. Vector is synchronized.
Array List is fast as it’s non-synchronized. Vector is slow as it is thread safe.
If an element is inserted into the Array List, it increases its Array size by 50%. Vector defaults to doubling size of its array.
Array List does not define the increment size. Vector defines the increment size.
Array List can only use Iterator for traversing an Array List. Except Hashtable, Vector is the only other class which uses both Enumeration and Iterator.

 

Q16. Differentiate between Iterator and Enumeration.

Ans:

Iterator Enumeration
Iterator is an interface found in the java.util package. Enumeration is an object that generates elements one at a time. Used for passing through a collection for unknown size.
Uses 3 methods to interface such as:

1.       i) hasNext()

2.     ii) next()

3.     iii)  remove()

Methods used are:

1.       i) hasMoreElements()

2.     ii) nextElement()

Iterators allow removing elements from the given collection during the iteration with well-defined semantics. It is used for passing through a collection, usually of unknown size.
Iterator method names have been improved. The traversing of elements can only be done once per creation

 

Q17. How can we restrict inheritance for a class?

Ans: We can restrict inheritance for class by following steps:

  • By using final keyword
  • If we make all method final, then we cannot override that.
  • By using private constructors
  • By using Javadoc comment (//)

Q18. Can we execute any code, even before the main method? Explain?

Ans: Yes, We can execute any code, even before the main method. We are using a static block of code in the class when creating the objects at load time of class. Any statements within this static block of code will get executed one time while loading the class, even before the creation of objects in the main method.

Q19. Java doesn't support multiple inheritance. Why?

Ans: Java doesn’t support multiple inheritance. Because we cannot use different methods in one class it creates an ambiguity.
Example:

class Intellipaat1

{

void test()

{

system.out.println("test() method");

}

}class Intellipaat2

{

void test()

{

system.out.println("test() method");

}

}Multiple inheritance

class C extends Intellipaat1, Intellipaat2

{

………………………………………….

…………………………………………..

}

Intellipaat1 and Intellipaat2 test() methods are inheriting to class C
So which test() method C class will take. As Intellipaat1 & Intellipaat2 class test () methods are different, So here we would face ambiguity.

Q20. What is multi-threading?

Ans: Multi threading is a programming concept to run multiple tasks in a concurrent manner within a single program. Threads share same process stack and running in parallel. It  helps  in performance improvement of any program.

Q21. Why Runnable Interface is used in Java?

Ans: Runnable interface is used in java for implementing multi threaded applications. Java.Lang.Runnable interface is implemented by a class to support multi threading.

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

Ans: Multi threaded applications can be developed in Java by using any of the following two methodologies:

  1. By using Java.Lang.Runnable Interface. Classes implement this interface to enable multi threading. There is a Run() method in this interface which is implemented.
  2. By writing a class that extend Java.Lang.Thread class.

Q23. When a lot of changes are required in data, which one should be a preference to be used? String or StringBuffer?

Ans: 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 much. 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.

Q24. What’s the purpose of using Break in each case of Switch Statement?

Ans: Break is used after each case (except the last one) in a switch so that code breaks after the valid case and doesn’t flow in the proceeding cases too.

If break isn’t used after each case, all cases after the valid case also get executed resulting in wrong results.

Q25. How garbage collection is done in Java?

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

Q26. How we can execute any code even before main method?

Ans: If we want to execute any statements before even creation of objects at load time of class, we can use a static block of code in the class. Any statements inside this static block of code will get executed once at the time of loading the class even before creation of objects in the main method.

Q27. Can a class be a super class and a sub-class at the same time? Give example.

Ans: If there is a hierarchy of inheritance used, a class can be a super class for another class and a sub-class for another one at the same time.

In the example below, continent class is sub-class of world class and it’s super class of country class.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

public class world {

 

..........

 

}

 

public class continenet extends world {

 

............

 

}

 

public class country extends continent {

 

......................

 

}

 

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

Ans: Even if no explicit constructor is defined in a java class, objects get created successfully as a default  constructor is implicitly used for object creation. This constructor has no parameters.

Q29. In multi-threading how can we ensure that a resource isn’t used by multiple threads simultaneously?

Ans: In multi-threading, access to the resources which are shared among multiple threads can be controlled by using the concept of synchronization. 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 has become free from the other one using it.

Q30. Can we call the constructor of a class more than once for an object?

Ans: Constructor is called automatically when we create an object using new keyword. It’s called only once for an object at the time of object creation and hence, we can’t invoke the constructor again for an object after its creation.

Q31. There are two classes named classA and classB. Both classes are in the same package. Can a private member of classA can be accessed by an object of classB?

Ans: Private members of a class aren’t accessible outside the scope of that class and any other class even in the same package can’t access them.

Q32. Can we have two methods in a class with the same name?

Ans: We can define two methods in a class with the same name but with different number/type of parameters. Which method is to get invoked will depend upon the parameters passed.

For example in the class below we have two print methods with same name but different parameters. Depending upon the parameters, appropriate one will be called:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

public class methodExample {

 

public void print() {

 

system.out.println("Print method without parameters.");

 

}

 

public void print(String name) {

 

system.out.println("Print method with parameter");

 

}

 

public static void main(String args[]) {

 

methodExample obj1= new methodExample();

 

obj1.print();

 

obj1.print("xx");

 

}

 

}

 

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

Ans: We can use the concept of cloning to create copy of an object. Using clone, we create copies with the actual state of an object.

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

Q34. What’s the benefit of using inheritance?

Ans: Key benefit of using inheritance is reusability of code as inheritance enables sub-classes to reuse the code of its super class. Polymorphism (Extensibility ) is another great benefit which allow new functionality to be introduced without effecting existing derived classes.

Q35. What’s the default access specifier for variables and methods of a class?

Ans: Default access specifier for variables and method is package protected i.e variables and class is available to any other class but in the same package,not outside the package.

Q36. Give an example of use of Pointers in Java class.

Ans: There are no pointers in Java. So we can’t use concept of pointers in Java.

Q37. How can we restrict inheritance for a class so that no class can be inherited from it?

Ans: If we want a class not to be extended further by any class, we can use the keyword Final with the class name.

In the following example, Stone class is Final and can’t be extend

1

2

3

4

5

public Final Class Stone {

 

// Class methods and Variables

 

}

 

Q38. What’s the access scope of Protected Access specifier?

Ans: When a method or a variable is declared with Protected access specifier, it becomes accessible in the same class,any other class of the same package as well as a sub-class.

MODIFIER CLASS PACKAGE SUBCLASS WORLD
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
Access Levels

 

Q39. What’s difference between Stack and Queue?

Ans: Stack and Queue both are used as placeholder for a collection of data. The primary difference between a stack and a queue is that stack is based on Last in First out (LIFO) principle while a queue is based on FIFO (First In First Out) principle.

Q40. In java, how we can disallow serialization of variables?

Ans: If we want certain variables of a class not to be serialized, we can use the keyword transient while declaring them. For example, the variable trans_var below is a transient variable and can’t be serialized:

1

2

3

4

5

6

7

public class transientExample {

 

private transient trans_var;

 

// rest of the code

 

}

[teaserbox type="5" img="2803" title="Interested in Learning Artificial Intelligence" subtitle="Join myTectra" link_url="http://www.mytectra.com/artificial-intelligence-training-in-bangalore.html" target="blank"]

Q41. How can we use primitive data types as objects?

Ans: Primitive data types like int can be handled as objects by the use of their respective wrapper classes. For example, Integer is a wrapper class for primitive data type int. We can apply different methods to a wrapper class, just like any other object.

Q42. Which types of exceptions are caught at compile time?

Ans: Checked exceptions can be caught at the time of program compilation. Checked exceptions must be handled by using try catch block in the code in order to successfully compile the code.

Q43. Describe different states of a thread.

Ans: A thread in Java can be in either of the following states:

  • Ready: When a thread is created, it’s in Ready state.
  • Running: A thread currently being executed is in running state.
  • Waiting: A thread waiting for another thread to free certain resources is in waiting state.
  • Dead: A thread which has gone dead after execution is in dead state.

Q44. Can we use a default constructor of a class even if an explicit constructor is defined?

Ans: Java provides a default no argument constructor if no explicit constructor is defined in a Java class. But if an explicit constructor has been defined, default constructor can’t be invoked and developer can use only those constructors which are defined in the class.

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

Ans: The basic condition of method overriding is that method name, arguments as well as return type must be exactly same as is that of the method being overridden.  Hence using a different return type doesn’t override a method.

Q46.What will be the output of following piece of code?

1

2

3

4

5

6

7

8

9

10

11

public class operatorExample {

 

public static void main(String args[]) {

 

int x=4;

 

system.out.println(x++);

 

}

 

}

 

Ans: In this case postfix ++ operator is used which first returns the value and then increments. Hence it’s output will be 4.

Q47. A person says that he compiled a java class successfully without even having a main method in it? Is it possible?

Ans: Main method is an entry point of Java class and is required for execution of the program however; a class gets compiled successfully even if it doesn’t have a main method. It can’t be run though.

Q48. Can we call a non-static method from inside a static method?

Ans: Non-Static methods are owned by objects of a class and have object level scope and in order to call the non-Static methods from a static block (like from a static main method), an object of the class needs to be created first. Then using object reference, these methods can be invoked.

Q49. What are the two environment variables that must be set in order to run any Java programs?

Ans: Java programs can be executed in a machine only once following two environment variables have been properly set:

  1. PATH variable
  2. CLASSPATH variable

Q50. Can variables be used in Java without initialization?

Ans: In Java, if a variable is used in a code without prior initialization by a valid value, program doesn’t compile and gives an error as no default value is assigned to variables in Java.

Q51. Can a class in Java be inherited from more than one class?

Ans: In Java, a class can be derived from only one class and not from multiple classes. Multiple inheritances is not supported by Java.

Q52. Can a constructor have different name than a Class name in Java?

Ans: Constructor in Java must have same name as the class name and if the name is different, it doesn’t act as a constructor and compiler thinks of it as a normal method.

Q53. What will be the output of Round(3.7) and Ceil(3.7)?

Ans: Round(3.7) returns 4 and  Ceil(3.7) returns 4.

Q54. Can we use goto in Java to go to a particular line?

Ans: In Java, there is not goto keyword and java doesn’t support this feature of going to a particular labeled line.

Q55. Can a dead thread be started again?

Ans: In java, a thread which is in dead state can’t be started again. There is no way to restart a dead thread.

Q56. Is the following class declaration correct?

1

2

3

4

5

public abstract final class testClass {

 

// Class methods and variables

 

}

 

Ans: The above class declaration is incorrect as an abstract class can’t be declared as Final.

Q57. Is JDK required on each machine to run a Java program?

Ans: JDK is development Kit of Java and is required for development only and to run a Java program on a machine, JDK isn’t required. Only JRE is required.

Q58. What’s the difference between comparison done by equals method and == operator?

Ans: In Java, equals() method is used to compare the contents of two string objects and returns true if the two have same value while == operator compares the references of two string objects.

In the following example, equals() returns true as the two string objects have same values. However == operator returns false as both string objects are referencing to different objects:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

public class equalsTest {

 

public static void main(String args[]) {

 

String srt1 = "Hello World";

 

String str2 = "Hello World";

 

if (str1.equals(str2))

 

{// this condition is true

 

system.out.println("str1 and str2 are equal in terms of values");

 

}

 

if (str1==str2) {

 

//This condition is not true

 

system.out.println("Both strings are referencing same object");

 

}

 

else

 

{

 

// This condition is true

 

system.out.println("Both strings are referencing different objects");

 

}

 

}}

 

Q59. Is it possible to define a method in Java class but provide it’s implementation in the code of another language like C?

Ans: Yes, we can do this by use of native methods. In case of native method based development, we define public static methods in our Java class without its implementation and then implementation is done in another language like C separately.

Q60. How destructors are defined in Java?

Ans: In Java, there are no destructors defined in the class as there is no need to do so. Java has its own garbage collection mechanism which does the job automatically by destroying the objects when no longer referenced.

Q61. Can a variable be local and static at the same time?

Ans:  No a variable can’t be static as well as local at the same time. Defining a local variable as static gives compilation error.

Q62. Can we have static methods in an Interface?

Ans: Static methods can’t be overridden in any class while any methods in an interface are by default abstract and are supposed to be implemented in the classes being implementing the interface. So it makes no sense to have static methods in an interface in Java.

Q63. In a class implementing an interface, can we change the value of any variable defined in the interface?

Ans: No, we can’t change the value of any variable of an interface in the implementing class as all variables defined in the interface are by default public, static and Final and final variables are like constants which can’t be changed later.

Q64. Is it correct to say that due to garbage collection feature in Java, a java program never goes out of memory?

Ans: Even though automatic garbage collection is provided by Java, it doesn’t ensure that a Java program will not go out of memory as there is a possibility that creation of Java objects is being done at a faster pace compared to garbage collection resulting in filling of all the available memory resources.

So, garbage collection helps in reducing the chances of a program going out of memory but it doesn’t ensure that.

Q65. Can we have any other return type than void for main method?

Ans: No, Java class main method can have only void return type for the program to get successfully executed.

Nonetheless , if you absolutely must return a value to at the completion of main method , you can use System.exit(int status)

Q66. I want to re-reach and use an object once it has been garbage collected. How it’s possible?

Ans: Once an object has been destroyed by garbage collector, it no longer exists on the heap and it can’t be accessed again. There is no way to reference it again.

Q67. In Java thread programming, which method is a must implementation for all threads?

Ans: Run() is a method of Runnable interface that must be implemented by all threads.

Q68. I want to control database connections in my program and want that only one thread should be able to make database connection at a time. How can I implement this logic?

Ans: This can be implemented by use of the concept of synchronization. Database related code can be placed in a method which hs synchronized keyword so that only one thread can access it at a time.

Q69. How can an exception be thrown manually by a programmer?

Ans: In order to throw an exception in a block of code manually, throw keyword is used. Then this exception is caught and handled in the catch block.

1

2

3

4

5

6

7

8

9

10

11

12

public void topMethod(){

try{

excMethod();

}catch(ManualException e){ }

}

 

public void excMethod{

String name=null;

if(name == null){

throw (new ManualException("Exception thrown manually ");

}

}

 

Q70. I want my class to be developed in such a way that no other class (even derived class) can create its objects. How can I do so?

Ans: If we declare the constructor of a class as private, it will not be accessible by any other class and hence, no other class will be able to instantiate it and formation of its object will be limited to itself only.

Q71. How objects are stored in Java?

Ans: In java, each object when created gets a memory space from a heap. When an object is destroyed by a garbage collector, the space allocated to it from the heap is re-allocated to the heap and becomes available for any new objects.

Q72. How can we find the actual size of an object on the heap?

Ans: In java, there is no way to find out the exact size of an object on the heap.

Q73. Which of the following classes will have more memory allocated?

 

Class A: Three methods, four variables, no object

Class B: Five methods, three variables, no object

Ans:  Memory isn’t allocated before creation of objects. Since for both classes, there are no objects created so no memory is allocated on heap for any class.

Q74. What happens if an exception is not handled in a program?

Ans: If an exception is not handled in a program using try catch blocks, program gets aborted and no statement executes after the statement which caused exception throwing.

Q75. I have multiple constructors defined in a class. Is it possible to call a constructor from another constructor’s body?

Ans: If a class has multiple constructors, it’s possible to call one constructor from the body of another one using this().

Q76. What’s meant by anonymous class?

Ans: An anonymous class is a class defined without any name in a single line of code using new keyword.

For example, in below code we have defined an anonymous class in one line of code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

public java.util.Enumeration testMethod()

 

{

 

return new java.util.Enumeration()

 

{

 

@Override

 

public boolean hasMoreElements()

 

{

 

// TODO Auto-generated method stub

 

return false;

 

}

 

@Override

 

public Object nextElement()

 

{

 

// TODO Auto-generated method stub

 

return null;

 

}

 

}

 

Q77. Is there a way to increase the size of an array after its declaration?

Ans: Arrays are static and once we have specified its size, we can’t change it. If we want to use such collections where we may require a change of size ( no of items), we should prefer vector over array.

Q78. If an application has multiple classes in it, is it okay to have a main method in more than one class?

Ans:  If there is main method in more than one classes in a java application, it won’t cause any issue as entry point for any application will be a specific class and code will start from the main method of that particular class only.

Q79. I want to persist data of objects for later use. What’s the best approach to do so?

Ans: The best way to persist data for future use is to use the concept of serialization.

Q80. What is a Local class in Java?

Ans: In Java, if we define a new class inside a particular block, it’s called a local class. Such a class has local scope and isn’t usable outside the block where its defined.

Q81. String and StringBuffer both represent String objects. Can we compare String and StringBuffer in Java?

Ans: Although String and StringBuffer both represent String objects, we can’t compare them with each other and if we try to compare them, we get an error.

Q82. Which API is provided by Java for operations on set of objects?

Ans: Java provides a Collection API which provides many useful methods which can be applied on a set of objects. Some of the important classes provided by Collection API include ArrayList, HashMap, TreeSet and TreeMap.

Q83. Can we cast any other type to Boolean Type with type casting?

Ans: No, we can neither cast any other primitive type to Boolean data type nor can cast Boolean data type to any other primitive data type.

Q84. Can we use different return types for methods when overridden?

Ans: The basic requirement of method overriding in Java is that the overridden method should have same name,  and parameters.But a method can be overridden with a different return type as long as the new return type extends the original.

For example , method is returning a reference type.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

Class B extends A{

 

A method(int x){

 

//original method

 

}

 

B method(int x){

 

//overridden method

 

}

 

}

 

Q85. What’s the base class of all exception classes?

Ans: In Java, Java.lang.Throwable is the super class of all exception classes and all exception classes are derived from this base class.

Q86. What’s the order of call of constructors in inheritiance?

Ans: In case of inheritance, when a new object of a derived class is created, first the constructor of the super class is invoked and then the constructor of the derived class is invoked.

Q87. What is lazy loading in hibernate?

Ans: Lazy loading is a kind of setting that decides whether to load the child entities with the parent entities or not. When enabling this feature the associated entities will be loaded only when it is requested directly. The default value of this setting is true which stops child entities from loading.

Q88. How can we fetch records by spring JdbcTemplate?

Ans: We can fetch records from the database by the query method of JdbcTemplate. There are two interfaces to do this:

  1. ResultSetExtractor
  2. RowMapper

Q89. What is the front controller class of Spring MVC?

Ans: The Dispatcher Servlet class works as the front controller in Spring MVC.

Q90. What are the states of an object in hibernate?

Ans: The states of an object in hibernate are:

  • Transient:When objects are just created having no primary key are in transient state. Here the objects are associated with any session.
  • Persistent:When the session of an object is just opened and its instance is just saved or retrieved, it is said to be in persistent state.
  • Detached:When the session of an object is closed, it is said to be in detached state.

Q91. How to make an immutable class in hibernate?

Ans: If we mark a class as mutable=”false”, the class will be treated as an immutable class. The default value of mutable is “true”.

Q92. What is hash-collision in Hashtable? How was it handled in Java?

Ans: In Hashtable , if two different keys have the same hash value then it leads to hash -collision. A bucket of type linked list used to hold the different keys of same hash value.

Q93. Write a syntax to convert a given Collection to SynchronizedCollection ?

Ans: Collections.synchronizedCollection(Collection collectionObj) will convert a given collection to synchronized collection.

Q94. Write a code to make Collections readOnly?

Ans: We can make the Collection readOnly by using the following lines code:

General : Collections.unmodifiableCollection(Collection c)Collections.unmodifiableMap(Map m)

Collections.unmodifiableList(List l)

Collections.unmodifiableSet(Set s)

Q95. What are latest features introduced with Java 8?

Ans: The below latest features are introduced in Java 8. Lambda Expressions, Interface Default and Static Methods, Method Reference, Parameters Name, Optional Streams, Concurrency.

Q96. What is meant by binding in RMI?

Ans: Binding is the process of associating or registering a name for a remote object, which can be used as a further, in order to look up that remote object. A remote object can be associated with a name using the bind / rebind methods of the Naming class.

Q97. Name few Java 8 annotations?

Ans: @Functional Interface annotation
@Repeatable annotation,
@Functional Interface annotation: It was introduced in Java SE 8, indicates that the type declaration is intended to be a functional interface, as defined by the Java Language Specification.

@Repeatable annotation: introduced in Java SE 8, indicates that the marked annotation can be applied many times to the same declaration or type use.

Q98. Distinguish between a predicate and a function?

Ans: A predicate takes one argument and returns a Boolean value.
A function takes one argument and returns an object.
Both are useful for evaluating lambda expressions.

Q99. Write a code to sort a list of strings using Java 8 lambda expression?

Ans:

. private void sortUsingJava8(List names){

Collections.sort(names, (p1, p2) -> p1.compareTo(p2));

}

Q100. Define a StringJoiner and write a sample code?

Ans: StringJoiner is an util method to construct a string with the desired delimiter.

Sample CodeStringJoiner strJoiner = new StringJoiner(".");

strJoiner.add("AAA").add("BBB");

System.out.println(strJoiner);

OutPut:

AAA.BBB

Topics:Interview Questions with Answers

Comments

Subscribe