Best 47 Java Programming Interview Questions And Answers

1. Explain throw keyword in java?
Answer: Generally, JVM throws the exception and we handle the exceptions by using try-catch block. But there are
situations where we have to throw user-defined exceptions or runtime exceptions. In such a case, we use
throw keyword to throw an exception explicitly.
Syntax: throw throwableInstance;
The throwable instance must be of type throwable or any of its subclasses.
After the throw statement, execution stops and subsequent statements are not executed. Once exception
object is thrown JVM checks is there any catch block to handle the exception. If not then the next catch
statement till it finds the appropriate handler. If the appropriate handler is not found, then default exception
handler halts the program and prints the description and location of exception.
In general, we use throw keyword for throwing a user-defined or customized exception.

2. Difference between this() and super() in java?
Answer: this() is used to access one constructor from another with in the same class while super() is used to
access superclass constructor. Either this() or super() exists it must be the first statement in the

3. Explain the importance of finally over return statement?
Answer: finally block is more important than return statement when both are present in a program. For example, if
there is any return statement present inside try or catch block, and finally block is also present first
finally statement will be executed and then the return statement will be considered.

4. Can we use a Switch statement with Strings?
Prior to Java 7, we can use only int values and enum constants in Switch. Starting with Java 7 we can use
strings in a Switch statement. If we use strings in switch statement prior to Java 7 we will get compile-time
error “only int and enum constants are permitted”.

5. In java how do we copy objects?
Answer: In Java, we cannot copy two objects but by assigning one reference to others we can copy objects. For
example, if we have a reference r1 that point to object .so when we declare r2=r1, we are assigning
reference r1 to r2 so now r2 points to the same object where r1 points. Any changes done by one
reference on an object will reflect others.
Oops concepts interview questions

6. Why main() method is public, static and void in java?
Answer: public: “public” is an access specifier which can be used outside the class. When main method is declared
public it means it can be used outside the class.
static: To call a method we require an object. Sometimes it may be required to call a method without the
help of an object. Then we declare that method as static. JVM calls the main() method without creating
an object by declaring keyword static.
void: the void return type is used when a method doesn’t return any value. main() method doesn’t return
any value, so main() is declared as void.
Signature: public static void main(String[] args)

7. What is the difference between length and length() method in java?
length(): In String class, we have length() method which is used to return the number of characters in
Ex : String str = “Hello World”;
Str.length() will return 11 characters including space.
length : we have length instance variable in arrays which will return the number of values or objects in
For example :
String days[]={” Sun”,” Mon”,” wed”,”thu”,” Fri”,” sat”};
Will return 6 since the number of values in the day’s array is 6.

8. Can an object’s finalize() method be invoked while it is reachable?
Answer: An object’s finalize() method cannot be invoked by the garbage collector while the object is still accessible. Though, an object’s finalized () method may be invoked by other objects.

9. What is ‘IS-A ‘ relationship in java? Answer: ‘is a’ relationship is also known as inheritance. We can implement ‘is a’ relationship or inheritance in java
using extends keyword. The advantage of inheritance or is a relationship is reusability of code instead of
duplicating the code.
Ex: Motorcycle is a vehicle
Car is a vehicle Both car and motorcycle extends vehicle.

10. Difference between Character Constant and String Constant in java?
A character constant is enclosed in single quotes. String constants are enclosed in double-quotes. Character
constants are single-digit or character. String Constants are a collection of characters.
Ex: ’2’, ‘A’
Ex: “Hello World”

11. What is ASCII Code?
Answer: ASCII stands for American Standard Code for Information Interchange. ASCII character range is 0 to 255.
We can’t add more characters to the ASCII Character set. ASCII character set supports only English. That

is the reason, if we see C language we can write c language only in English we can’t write in other
languages because it uses ASCII code.

12. What is Unicode?
Answer: Unicode is a character set developed by Unicode Consortium. To support all languages in the world Java
supports Unicode values. Unicode characters were represented by 16 bits and its character range is 0-

Java uses ASCII code for all input elements except for Strings, identifiers, and comments. If we want to
use telugu we can use Telugu characters for identifiers. We can enter comments in Telugu.

13. What happens if we don’t override run method?
Answer: If we don’t override the run method. Then default implementation of Thread class run() method will be
executed and hence the thread will never be in runnable state. (Java Training Online)

14. Compare Overloading and Overriding?
Answer: Overloading refers to the case of having two methods of the 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 the parent class.

15. What are the implicit objects?
Answer: Implicit objects also called as pre-defined variables are created by JSP Engine inside the service method so that it can be accessed directly without being declared explicitly.

16. What is a class?
Answer: Classes are the fundamental or basic unit in Object-Oriented Programming. A class is kind of blueprint or
template for objects. The class defines variables, methods. A class tells what type of objects we are creating.
For example, take the Department class tells us we can create department type objects. We can create any
a number of department objects.
All programming constructs in java reside in class. When JVM starts running it first looks for the class
when we compile. Every Java application must have at least one class and one main method.
Class starts with the class keyword. A class definition must be saved in a class file that has the same as the class name.
Filename must end with the .java extension.
public class FirstClass
{public static void main(String[] args)
{System.out.println(“My First class”);

If we see the above class when we compile JVM loads the FirstClass and generates a .class
file(FirstClass.class). When we run the program we are running the class and then executes the main

17. Explain the importance of throws keyword in java?
Answer: Throws statement is used at the end of method signature to indicate that an exception of a given type
maybe thrown from the method.
The main purpose of throws keyword is to delegate the responsibility of exception handling to the caller
methods, in the case of checked exception.
In the case of unchecked exceptions, it is not required to use throws keyword.
We can use throws keyword only for throwable types otherwise compile-time error saying incompatible
An error is unchecked, it is not required to handle by try-catch or by throws.
Syntax: Class Test{
Public static void main(String args[]) throws IE

Note: The method should throw only checked exceptions and subclasses of checked exceptions.
It is not recommended to specify exception superclasses in the throws class when the actual exceptions

18. What is the purpose of finalization?
Answer: The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

19. What are the important features of Java 8 release?
Answer: it is one of the frequently asked questions in java interview. And, Some of the important features of Java 8 are as provided below:

Interface changes with the default and static methods
Functional interfaces and Lambda Expressions
Java Stream API for collection classes
Java Date Time API

20. What is multitasking?
Answer: Multitasking means performing more than one activity at a time on the computer. Example Using
a spreadsheet and using the calculator at the same time.

21. What are the different types of multitasking?
There are two different types of multitasking:

1) Process-based multitasking
2) Thread based multitasking
Process-based multitasking: It allows to run two or more programs concurrently. In process
based multitasking a process is the smallest part of code.
Example: Running Ms word and Ms powerpoint at a time.
Thread based multitasking: It allows to run parts of a program to run concurrently.
Example: Formatting the text and printing word document at the same time.
Java supports thread-based multitasking and provides built-in support for multithreading.

22. What is the final keyword?
Answer: The final keyword is used with Class to make sure no other class can extend it, for instance, String class is final and we can’t extend it.

23. Why java is platform-independent?
The most unique feature of java is platform-independent. In any programming language, source code is
compiled into executable code. This cannot be run across all platforms. When javac compiles a java
program it generates an executable file called .class file.
class file contains byte codes. Byte codes are interpreted only by JVMs. Since these JVM’s are made
available across all platforms by Sun Microsystems, we can execute this byte code in any platform. Byte
code generated in windows environment can also be executed in Linux environment. This makes the java
platform independent.

24. What is method overloading in java?
Answer: A class having two or more methods with the same name but with different arguments then we say that those
methods are overloaded. Static polymorphism is achieved in java using method overloading.
Method overloading is used when we want the methods to perform similar tasks but with different inputs
or values. When an overloaded method is invoked java first checks the method name, and the number of
arguments, type of arguments; based on this compiler executes this method.
The compiler decides which method to call at compile time. By using overloading static polymorphism or static
binding can be achieved in java.
Note: Return type is not part of the method signature. we may have methods with different return types but
return type alone is not sufficient to call a method in java.

25. What is ‘HAS A’’ relationship in java?
Answer: ‘Has a ‘ relationship is also known as “composition or Aggregation”. As in inheritance we have ‘extends’
keyword we don’t have any keyword to implement ‘Has a’ relationship in java. The main advantage of
‘Has-A‘ relationship in java code reusability.

26. Can we restart a thread already started in java?
Answer: A thread can be started in java using start() method in java. If we call start method second time once it is
started it will cause Run-Time Exception (Illegal Thread State Exception). A runnable thread cannot be

27. Which containers use a border Layout as their default layout?
Answer: The Window, Frame and Dialog classes use a border layout as their default layout.

28. What do you understand by Java? Answer: Java is an object-oriented computer language. Java is a fast, secure and reliable language used for many games, devices, and applications.

29. What is the Collections API?
Answer: The Collections API is a set of classes and interfaces that support operations on collections of objects.

30. How does Java handle integer overflows and underflows?
Answer: It uses those low order bytes of the consequence that can fit into the size of the type allowed by the operation.

31. Explain enumeration in java?
Answer: Enumeration is a new feature from Java 5.0. Enumeration is set of named constants. We use the enum
keyword to declare enumeration. The values defined in enumeration are enum constants. Each enum
constant declared inside an enum class is by default public, static and final.
Example :
package javaexamples;
public enum Days {
SUN,MON,TUE,WED,THU,FRI,SAT are enum constants.

32. What is class level lock?
Acquiring a lock on the class instance rather than the object of the class is called class level lock. The difference
between a class level lock and the object-level lock is in the class level lock is acquired on class .class instance
and in the object-level lock, the lock is acquired on the object of class.  (Interview Questions and Answers)

33. Can we synchronize static methods in java?
Answer: Every class in Java has a unique lock associated with it. If a thread wants to execute static synchronize
method it needs to acquire the first-class level lock. When a thread was executing static synchronized method
no other thread can execute a static synchronized method of class since the lock is acquired on class.
But it can execute the following methods simultaneously :
1) Normal static methods
2) Normal instance methods
3) synchronize instance methods
Signature :

34. What are thread priorities and importance of thread priorities in java?
Answer: When there are several threads in waiting, thread priorities determine which thread to run. In java
programming language every thread has a priority. A thread inherits the priority of its parent thread. By
default, the thread has a normal priority of 5. Thread scheduler uses thread priorities to decide when each
thread is allowed to run. Thread scheduler runs higher priority threads first.

35. How to change the priority of thread or how to set the priority of thread?
Answer: Thread class has a set method to set the priority of thread and get method to get the priority of the
Signature: final void setPriority(int value);
The setPriority() method is a request to jvm to set the priority. JVM may or may not oblige the request.
We can get the priority of the current thread by using get priority() method of Thread class.
final int get priority()

36. Explain yield() method in Thread class?
Answer: Yield() method makes the currently running thread to move into the runnable state from running state giving
chance to remaining threads of equal priority which are in waiting state. yield() makes a current thread to
sleep for a specified amount of time. There is no guarantee that moving a current running thread from
runnable to running state. It all depends on thread scheduler it doesn’t guarantee anything.

Calling yield() method on the thread does not have any effect if the object has a lock. The thread doesn’t lose
any lock if it has acquired a lock earlier.
Signature :
public static native void yield()

37. Is it possible for a yielded thread to get chance for its execution again?
Answer: Yield() causes the current thread to sleep for a specified amount of time giving an opportunity for other threads of
equal priority to execute. Thread scheduler decides whether it get chance for execution again or not. It all
depends on the mercy of thread scheduler.

38. Explain about interrupt() method of thread class?
Answer: Thread class interrupt() method is used to interrupt the current thread or another thread. It does not mean
the current thread to stop immediately, it is a polite way of telling or requesting to continue your present
work. That is the reason we may not see the impact of the interrupt call immediately.
Initially, the thread has a boolean property(interrupted status) false. So when we call interrupt() method
status would set to true. This causes the current thread to continue its work and does not have an impact
If a thread is in sleeping or waiting status (i.e thread has executed wait () or sleep() method) thread gets
interrupted it stops what it is doing and throws an interrupted exception. This is the reason we need to handle
interrupted exception with throws or try/ catch block._inner]_inner]

39. Explain wait(), notify() and notifyAll() methods of object class?
Answer: wait(): wait for the () method() makes the thread current thread sleeps and releases the lock until some other
thread acquires the lock and calls notify().
notify(): notify() method wakes up the thread that called wait on the same object.
notify all(): notifyAll() method wakes up all the threads that are called wait() on the same object. The
highest priority threads will run first.
All the above three methods are in object class and are called only in synchronized context.
All the above three methods must handle InterruptedException by using throws clause or by using a try-catch clause.

40. Explain why wait(), notify() and notifyAll() methods are in Object class rather than in the reading class?
Answer: First, to know why they are in object class we should know what wait(), notify(), notifyAll() methods do.
wait() , notify(), notifyAll() methods are object-level methods they are called on same object.wait(),
notify(), notifyAll() are called on a shared object so to they are kept in object class rather than thread

41. Difference between ‘>>’ and ‘>>>’ operators in java?
>> is a right shift operator shifts all of the bits in value to the right to a specified number of times.
int a =15;
a= a >> 3;
The above line of code moves 15 three characters right.
>>> is an unsigned shift operator used to shift right. The places which were vacated by shift are filled
with zeroes.

42. Explain about procedural programming language or structured programming language and its features?
Answer: In traditional programming language to solve a problem, we use a set of procedures. Once the procedures or
functions are determined next they concentrate on storing data.
Features :
1) In this top-down approach is followed. First procedures were determined and then concentrate on
minute details.
2) Concentrate more on functions and procedure rather than data.
3) In traditional programming language procedures manipulate global data without knowing to other
4) Very little concentration on minute details
The main drawback of traditional programming languages works well only for small problems. But not
suitable for larger problems.
Ex: C language, Pascal

43. When a thread is executing a synchronized method, then is it possible for the same thread to access other synchronized methods of an object?
Answer: Yes, it is possible for thread executing a synchronized method to execute another synchronized method of
an object.
public synchronized void methodName()
To execute the synchronized method first lock has to be acquired on that object. Once the synchronized method
is called lock will be automatically acquired on that method when no other thread has a lock on that
method. once the lock has been acquired then synchronized method gets executed. Once synchronized
method execution completes automatically lock will be released. The prerequisite to executing a
synchronized method is to acquire a lock before method execution. If there is a lock already acquired by
any other thread it waits till the other thread completes.

44. Why we used Vector class?
Answer: The Vector class provides the ability to execute a growable array of objects. Vector proves to be very useful if you don’t know the size of the array in advance, or we need one that can change sizes over the lifetime of a program.

45. What are thread-local variables?
Answer: Thread local variables are variables associated with a particular thread rather than an object. We declare
ThreadLocal object as a private static variable in a class. Every time a new thread accesses the object by using
getter or setter we are accessing a copy of the object. Whenever a thread calls get or set method of
ThreadLocal instance a new copy is associated with a particular object.

46. What are daemon threads in java?
Answer: Daemon threads are threads which run in the background. These are service threads and works for the
benefit of other threads. The garbage collector is one of a good example for daemon threads.
By default, all threads are nondaemon. Daemon nature of a thread can be inherited. If parent thread is
a daemon, child thread also inherits daemon nature of the thread.

47. What are unchecked exceptions in java?
Answer: All subclasses of RuntimeException are called unchecked exceptions. These are unchecked exceptions
because the compiler does not check if a method handles or throws exceptions.
Program compiles even if we do not catch the exception or throws the exception.
If an exception occurs in the program, the program terminates. It is difficult to handle these exceptions
because there may be many places causing exceptions.
Example : 1) Arithmetic
3) ArrayIndexOutOfBoundsException
4) ClassCastException
5) IndexOutOfBoundException
6) NullPointerException
7) NumberFormatException
8) StringIndexOutOfBounds
9) UnsupportedOperationException

Leave a Comment

Scroll to Top