125 Top Java Job Interview Questions and Answers

1. Define what do you know about Java?

Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

2. Define what are the supported platforms by Java Programming Language?

Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX/Linux like HP-Unix, Sun Solaris, Redhat Linux, Ubuntu, CentOS, etc.

3. List any five features of Java?

  1. Some features include Object Oriented
  2. Platform Independent
  3. Robust
  4. Interpreted
  5. Multi-threaded

4. Why is Java Architectural Neutral?

Its compiler generates an architecture-neutral object file format, which makes the compiled code to be executable on many processors, with the presence of Java runtime system.

5. Define what is a singleton class? Give a practical example of its usage.

  • A singleton class in Java can have only one instance and hence all its methods and variables belong to just one instance. Singleton class concept is useful for the situations when there is a need to limit the number of objects for a class.
  • The best example of singleton usage scenario is when there is a limit of having only one connection to a database due to some driver limitations or because of any licensing issues.

6. Define what are the access modifiers in Java?

There are 3 access modifiers. Public, protected and private, and the default one if no identifier is specified is called friendly, but the programmer cannot specify the friendly identifier explicitly.

7. Define what is are packages?

A package is a collection of related classes and interfaces providing access protection and namespace management.

8. Define what is meant by Inheritance and Define what are its advantages?

Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are reusability of code and accessibility of variables and methods of the superclass by subclasses.

9. Define what is the difference between superclass and subclass?

A superclass is a class that is inherited whereas subclass is a class that does the inheriting.

10. Define what is an abstract class?

An abstract class is a class designed with implementation gaps for subclasses to fill in and is deliberately incomplete.

11. Define what are the states associated in the thread?

The thread contains ready, running, waiting and dead states.

12. Define what is synchronization?

Synchronization is the mechanism that ensures that only one thread is accessed the resources at a time.

13. Define what is deadlock?

When two threads are waiting for each other and can’t precede the program is said to be deadlock.

14. Define what is an applet?

The applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser

15. Define what is the lifecycle of an applet?

  1. init() method – Can be called when an applet is first loaded
  2. start() method – Can be called each time an applet is started.
  3. paint() method – Can be called when the applet is minimized or maximized.
  4. stop() method – Can be used when the browser moves off the applet’s page.
  5. destroy() method – Can be called when the browser is finished with the applet.

16. Define How do you set security in applets?

using setSecurityManager() method

17. Define what is a layout manager and Define what are different types of layout managers available in java AWT?

A layout manager is an object that is used to organize components in a container. The different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout, and GridBagLayout

18. Define what is JDBC?

JDBC is a set of Java API for executing SQL statements. This API consists of a set of classes and interfaces to enable programs to write pure Java Database applications.

19. Define what are drivers available?

  • JDBC-ODBC Bridge driver
  • Native API Partly-Java driver
  • JDBC-Net Pure Java driver
  • Native-Protocol Pure Java driver

20. Define what is stored procedure?

A stored procedure is a group of SQL statements that form a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters.

21. Define what is the Java API?

The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.

22. Why there are no global variables in Java?

Global variables are globally accessible. Java does not support globally accessible variables due to the following reasons:

  1. The global variables break the referential transparency
  2. Global variables create collisions in a namespace.

23. Define what are Encapsulation, Inheritance, and Polymorphism?

Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safes from outside interference and misuse. Inheritance is the process by which one object acquires the properties of another object. Polymorphism is the feature that allows one interface to be used for general class actions.

24. Define what is the use of bin and lib in JDK?

The bin contains all tools such as javac, appletviewer, art tool, etc., whereas lib contains API and all packages.

25. Define what is method overloading and method overriding?

Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading. Method overriding: When a method in a class having the same method name with the same arguments is said to be method overriding.

26. Define what is the difference between this() and super()?

this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a superclass constructor.

27. Define what is Domain Naming Service(DNS)?

It is very difficult to remember a set of numbers(IP address) to connect to the Internet. The Domain Naming Service(DNS) is used to overcome this problem. It maps one particular IP address to a string of characters. For example, www. mascot. com implies com is the domain name reserved for US commercial sites, Moscow is the name of the company and www is the name of the specific computer, which is mascot’s server.

28. Define what is URL?

URL stands for Uniform Resource Locator and it points to resource files on the Internet. URL has four components: http://www. address. com:80/index.html, where HTTP – protocol name, address – IP address or hostname, 80 – port number and index.html – file path.

29. Define what is RMI and steps involved in developing an RMI object?

Remote Method Invocation (RMI) allows java object that executes on one machine and to invoke the method of a Java object to execute on another machine. The steps involved in developing an RMI object are: a) Define the interfaces b) Implementing these interfaces c) Compile the interfaces and their implementations with the java compiler d) Compile the server implementation with RMI compiler e) Run the RMI registry f) Run the application.

30. Define what is RMI architecture?

RMI architecture consists of four layers and each layer performs specific functions: a) Application layer – contains the actual object definition. b) Proxy layer – consists of stub and skeleton. c) Remote Reference layer – gets the stream of bytes from the transport layer and sends it to the proxy layer. d) Transportation layer – responsible for handling the actual machine-to-machine communication.

31. Define what is a Java Bean?

A Java Bean is a software component that has been designed to be reusable in a variety of different environments.

32. Define what have checked exceptions?

The checked exception are those which the Java compiler forces you to catch. e.g. IOException has checked Exceptions.

33. Define what are runtime exceptions?

Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.

34. Define what is the difference between error and an exception?

An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases, it is possible to recover from an exception (probably by giving the user feedback for entering proper values, etc.).

35. Define what is the purpose of finalization?

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. For example, closing an opened file, closing an opened database Connection.

36. Define what is the difference between yielding and sleeping?

When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.

37. Define what is the difference between preemptive scheduling and time slicing?

Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

38. Define what is a mutable object and an immutable object?

If an object value is changeable then we can call it a Mutable object. (Ex., StringBuffer, …) If you are not allowed to change the value of an object, it is an immutable object. (Ex., String, Integer, Float, …)

39. Define what is the purpose of the Void class?

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the primitive Java type void.

40. Define what is JIT and its use?

Really, just a very fast compiler… In this incarnation, pretty much a one-pass compiler — no offline computations. So you can’t look at the whole method, rank the expressions according to which ones are re-used the most, and then generate code. In theory terms, it’s an online problem.

41. Define what is nested class?

If all the methods of an inner class are static then it is a nested class.

42. Define what is HashMap and Map?

A map is Interface and Hashmap is a class that implements that.

43. Define what are different types of access modifiers?

public: Anything declared as public can be accessed from anywhere. private: Anything declared as private can’t be seen outside of its class. protected: Anything declared as protected can be accessed by classes in the same package and subclasses in the other packages. default modifier: Can be accessed only to classes in the same package.

44. Define what is the difference between Reader/Writer and InputStream/Output Stream?

The Reader/Writer class is character-oriented and the InputStream/OutputStream class is byte-oriented.

45. Define what is servlet?

Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database.

46. Define what is Constructor?

A constructor is a special method whose task is to initialize the object of its class.
It is special because its name is the same as the class name.
They do not have return types, not even void and therefore they cannot return values.
They cannot be inherited, though a derived class can call the base class constructor.
The constructor is invoked whenever an object of its associated class is created.

47. Define what is an Iterator?

  1. The Iterator interface is used to step through the elements of a Collection.
  2. Iterators let you process each element of a Collection.
  3. Iterators are a generic way to go through all the elements of a Collection no matter Define How it is organized.
  4. Iterator is an Interface implemented a different way for every Collection.

48. Define what is the List interface?

  • The List interface provides support for ordered collections of objects.
  • Lists may contain duplicate elements.

49. Define what is memory leak?

A memory leak is where an unreferenced object that will never be used again still hangs around in memory and doesn’t get garbage collected.

50. Define what is the difference between the prefix and postfix forms of the ++ operator?

The prefix form performs the increment operation and returns the value of the increment operation. The postfix form returns the current value all of the expression and then performs the increment operation on that value.

JAVA Questions and Answers pdf free download::

51. Define what is the difference between a constructor and a method?

  • A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
  • A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

52. Define what will happen to the Exception object after exception handling?

Exception object will be garbage collected.

53. Difference between static and dynamic class loading.

Static class loading: The process of loading a class using new operator is called static class loading. Dynamic class loading: The process of loading a class at runtime is called dynamic class loading.
Dynamic class loading can be done by using Class.forName(….).newInstance().

54. Explain the Common use of EJB

The EJBs can be used to incorporate business logic in a web-centric application.
The EJBs can be used to integrate business processes in Business-to-business (B2B) e-commerce applications. In Enterprise Application Integration applications, EJBs can be used to house processing and mapping between different applications.

55. Define what is JSP?

JSP is a technology that returns dynamic content to the Web client using HTML, XML and JAVA elements. JSP page looks like an HTML page but is a servlet. It contains Presentation logic and business logic of a web application.

56. Define what is the purpose of apache tomcat?

Apache server is a standalone server that is used to test servlets and create JSP pages. It is free and open source that is integrated into the Apache web server. It is a fast, reliable server to configure the applications but it is hard to install. It is a servlet container that includes tools to configure and manage the server to run the applications. It can also be configured by editing XML configuration files.

57. Where pragma is used?

Pragma is used inside the servlets in the header with a certain value. The value is of no-cache that tells that a servlet is acting as a proxy and it has to forward a request. Pragma directives allow the compiler to use machine and operating system features while keeping the overall functionality with the Java language. These are different for different compilers.

58. Briefly explain daemon thread.

Daemon thread is a low priority thread which runs in the background performs garbage collection operation for the java runtime system.

59. Define what is a native method?

A native method is a method that is implemented in a language other than Java.

60. Explain the different way of using thread?

A Java thread could be implemented by using the Runnable interface or by extending the Thread class. The Runnable is more advantageous when you are going for multiple inheritances.

61. Define what are the two major components of JDBC?

One implementation interface for database manufacturers, the other implementation interface for application and applet writers.

62. Define what kind of thread is the Garbage collector thread?

It is a daemon thread.

63. Define what are the different ways to handle exceptions?

There are two ways to handle exceptions,

  1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and
  2. List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions.

64. Define How many objects are created in the following piece of code?

MyClass c1, c2, c3;
c1 = new MyClass ();
c3 = new MyClass ();
Answer: Only 2 objects are created, c1 and c3. The reference c2 is only declared and not initialized.

65.Define what is UNICODE?

Unicode is used for internal representation of characters and strings and it uses 16 bits to represent each other.

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

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

67. Define what will be the output of Round(3.7) and Ceil(3.7)?

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

68: Can we use goto in Java to go to a particular line?

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

69. Can a dead thread be started again?

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

70. Is the following class declaration correct?

public abstract final class testClass {

// Class methods and variables

}

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

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

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.

72. Which object-oriented Concept is achieved by using overloading and overriding?

Polymorphism

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

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

74. Define How destructors are defined in Java?

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.

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

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

76. Can we have static methods in an Interface?

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.

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

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.

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

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.

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

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 the main method, you can use System.exit(int status)

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

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

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

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

82. 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. Define How can I implement this logic?

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

83. Can an Interface extend another Interface?

Yes, an Interface can inherit another Interface, for that matter, an Interface can extend more than one Interface.

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

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.

85. Define How objects are stored in Java?

In Java, each object when created gets 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.

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

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

87. 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

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

88. Define what happens if an exception is not handled in a program?

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

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

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

90. Define what’s meant by the anonymous class?

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

For example, in below code we have defined an anonymous class in one line of code:
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;

}

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

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 an array.

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

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

93. I want to persist data of objects for later use. Define what’s the best approach to do so?

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

94. Define what is a Local class in Java?

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 it’s defined.

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

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.

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

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.

97. Can we cast any other type to Boolean Type with typecasting?

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.

98. Define what are synchronized methods and synchronized statements?

Synchronized methods are methods that are used to control access to an object. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

99. Define How does a try statement determine which catch clause should be used to handle an exception?

When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored.

100. Define what will be the default values of all the elements of an array defined as an instance variable?

If the array is an array of primitive types, then all the elements of the array will be initialized to the default value corresponding to that primitive type.

JAVA Programs for Interview:-

101. Define How to reverse the Singly Linked List?
102. Find out duplicate number between 1 to N numbers.
103. Find out middle index where the sum of both ends is equal.
104. Write a singleton class.
105. Write a program to create deadlock between two threads.
106. Write a program to reverse a string using a recursive algorithm.
107. Write a program to reverse a number.
108. Write a program to convert decimal number to binary format.
109. Write a program to find a perfect number or not.
110. Write a program to implement ArrayList.
111. Write a program to find maximum repeated words from a file.
112. Write a program to check the given number is a prime number or not?
113. Write a program to find the given number is Armstrong number or not?
114. Write a program to convert binary to decimal number.
115. Write a program to check the given number is a binary number or not?
116. Write a program for Bubble Sort in java.
117. Write a program for Insertion Sort in java.
118. Write a program to implement hashcode and equals.
119. Define How to get distinct elements from an array by avoiding duplicate elements?
120. Write a program to get a distinct word list from the given file.
121. Write a program to get a line with max word count from the given file.
122. Write a program to convert string to number without using Integer.parseInt() method.
123. Write a program to find two lines with max characters in descending order.
124. Write a program to find the sum of the first 1000 prime numbers.
125. Find the longest substring without repeating characters.