Top 100 Java Interview Questions & Answers.
Top 100 Java Interview Questions & Answers.
1. What is a class in Java?
Answer: Java encapsulates the codes in various classes which define new data types. These new data
types are used to create objects.
2. What is a JVM?
Answer: JVM is Java Virtual Machine which is a run time environment for the compiled Java class files.
3. What is the right data type to represent a price in Java?
Answer: BigDecimal, if memory is not a concern and Performance, is not critical, otherwise double with
predefined precision.
4. Does Java support multiple inheritances?
Answer: Java doesn’t support multiple inheritances.
5. What are the supported platforms by Java Programming Language?
Answer: Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of
UNIX/Linux like HP-Unix, Sun Solaris, Red Hat Linux, Ubuntu, Cent OS, etc.
6. List any five features of Java?
Answer: Some features include Object Oriented
Platform Independent
Robust
Interpreted
Multi-threaded
7. Explain method overloading?
Answer: When a Java program contains more than one method with the same name but different
properties, then it is called method overloading.
8. What restrictions are placed on the location of a package statement within a source code file?
Answer: A package statement must appear as the first line in a source code file (eliminating blank lines
and comments).
9. What method is used to specify a container’s layout?
Answer: The setLayout() method is used to specify a container’s layout.
10. What is the immediate superclass of the Applet class?
Answer: The Panel class is the immediate superclass of the Applet class.
11. What are the access modifiers in Java?
Answer: 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.
12. What are packages?
Answer: A package is a collection of related classes and interfaces providing access protection and
namespace management.
13. What is meant by Inheritance and What are its advantages?
Answer: 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.
14. Can we rethrow the same exception from the catch handler?
Answer: Yes, we can rethrow the same exception from our catch handler. If we want to rethrow
checked exception from a catch block we need to declare that exception.
15. what value is a variable of the String type automatically initialized?
Answer: The default value of a String type is null.
16. When a thread blocks on I/O, what state does it enter?
Answer: When it blocks on I/O, A thread enters the waiting state.
17. Which containers use a Flow Layout as their default layout?
Answer: The Panel and Applet classes use the Flow Layout as their default layout.
18. Explain Java Coding Standards for Constants?
Answer:
Constants in Java are created using static and final keywords.
1) Constants contain only uppercase letters.
2) If the constant name is a combination of two words it should be separated by an underscore.
3) Constant names are usually nouns.
Ex:MAX_VALUE, MIN_VALUE, MAX_PRIORITY, MIN_PRIORITY
19. What is synchronization and why is it important?
Answer: The term synchronization is the ability to control the access of multiple threads to shared
resources. And it is important because, without it, it is not possible for one thread to modify a shared
object while another thread is in the process of using or updating that object’s value. This often leads to
major errors.
20. Explain Java Coding Standards for variables?
Answer:
1) Variable names should start with small letters.
2) Variable names should be nouns
3) Short meaningful names are recommended.
4) If there are multiple words every inner word should start with a Uppercase character.
Ex: string, value, emp name, MEP salary
21. What is an abstract class?
Answer: An abstract class is a class designed with implementation gaps for subclasses to fill in and is
deliberately incomplete.
22. Name three Component subclasses that support painting?
Answer: The Canvas, Frame, Panel, and Applet classes support painting.
23. What is the difference between JDK and JVM?
Answer: Full-Form: Java Development Kit Full Form: Java Virtual Machine
For Development Purpose
To execute the Java programs
It provides all the tools, executables, and binaries required to compile, debug and execute a Java
Program The execution part is handled by JVM to provide machine independence.
24. Why Java doesn’t support multiple inheritances?
Answer: Because of the “Diamond Problem”, Java doesn’t support multiple inheritances in classes.
25. What modifiers may be used with an inner class that is a member of an outer class?
Answer: A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.
26. Which java. util classes and interfaces support event handling?
Answer: The Event Object class and the Event Listener interface support event processing.
27. What is a transient variable?
Answer: A transient variable is a variable that may not be serialized.
28. Is null a keyword?
Answer: No, the null is not a keyword.
29. What is an applet?
Answer: Applet is a dynamic and interactive program that runs inside a web page displayed by a java
capable browser
30. What is the lifecycle of an applet?
Answer:
init() method — Can be called when an applet is first loaded
start() method — Can be called each time an applet is started.
paint() method — Can be called when the applet is minimized or maximized.
stop() method — Can be used when the browser moves off the applet’s page.
destroy() method — Can be called when the browser is finished with the applet.
31. What’s new with the stop(), suspend() and resume() methods in JDK 1.2 ?
Answer:
These methods have been deprecated in JDK 1.2.
32. What is the Vector class?
Answer: The term Vector class provides the ability to implement a growable array of objects.
33. What is the difference between the >> and >>> operators?
Answer: The >> operator carries the sign bit when shifting right while the >>> zero-fills bits that have
been shifted out.
34. What is the difference between this() and super()?
Answer: this() can be used to invoke a constructor of the same class whereas super() can be used to
invoke a super class constructor.
35. What is a native method?
Answer: A native method is a method that is applied in a language other than Java.
36. What value does read Line() return when it has reached the end of a file?
Answer: The readLine() method returns null when it has reached the end of a file.
37. What is the Java API?
Answer: The Java API is a large collection of ready-made software components that provide many
useful capabilities, such as graphical user interface (GUI) widgets.
38. Why there are no global variables in Java?
Answer: Global variables are globally accessible. Java does not support globally accessible variables due
to following reasons:
The global variables break the referential transparency
Global variables create collisions in the namespace.
39. What are the different types of access modifiers?
Answer: 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.
40. What is Constructor?
Answer: 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.
Constructor is invoked whenever an object of its associated class is created.
41. What is an Iterator?
Answer: The Iterator interface is used to step through the elements of a Collection.
Iterators let you process each element of a Collection.
Iterators are a generic way to go through all the elements of a Collection no matter Define How it is
organized.
An iterator is an Interface implemented in a different way for every Collection.
42. What is the difference between Reader/Writer and InputStream/Output Stream?
Answer: The Reader/Writer class is character-oriented and the InputStream/OutputStream class is byte-oriented.
43. What is a servlet?
Answer: Servlets are modules that extend request/response-oriented servers, such as Java-enabled
webservers. 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.
44. What is clipping?
Answer: Clipping is the process of confining paint operations to a limited area or shape.
45. What is a 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.
46. Can a for statement loop indefinitely?
Answer: Yes, a for statement can loop indefinitely. For example, consider the following: for(;;)
47. Explain Java Coding standards for Methods?
Answer:
1) Method names should start with small letters.
2) Method names are usually verbs
3) If a method contains multiple words, every inner word should start with an uppercase letter.
Ex : toString()
4) Method name must be a combination of verb and noun
Ex : getCarName(),getCarNumber()
48. Why Java is not a pure Object Oriented language?
Answer: Java supports primitive types such as int, byte, short, long, etc which is why it is not said to be a
pure object-oriented language.
49. What are the access modifiers?
Answer: Java provides three access controls such as public, private, and protected access modifiers. When
none of these are used, it’s called default access modifier.
50. Can we overload the main method?
Answer:
Yes, we can overload the main method with syntax as a public static void main(String args[]).
51. What is the method in Java?
Answer: It contains the executable body that can be applied to the specific object of the class.
The method includes the method name, parameters or arguments, and return type, and a body of executable
code.
Syntax : type methodName(Argument List){
ex: public float add(int a, int b, int c)
methods can have multiple arguments. Separate with commas when we have multiple arguments.
thrown in the method are instances of their subclass.
52. Explain Automatic type conversion in Java?
Answer:
Java automatic type conversion is done if the following conditions are met:
1) When two types are compatible
Ex: int, float
it can be assigned directly to the float variable.
2) Destination type is larger than the source type.
Ex: int, long.
It can be assigned directly to Long. Automatic type conversion takes place if it is assigned to long
because long is a larger datatype than int.
Widening Conversion comes under Automatic type conversion.
53. What is the difference between the prefix and postfix forms of the ++ operator?
Answer: The prefix form performs the increment operation and returns the value of the increment
operation. The postfix form returns the current value of all of the expressions and then performs the
increment operation on that value.
54. In how many ways we can do exception handling in Java?
Answer:
We can handle exceptions in either of the two ways :
1) By specifying a try-catch block where we can catch the exception.
2) Declaring a method with a throws clause.
55. What does null mean in Java?
Answer:
When a reference variable doesn’t point to any value it is assigned null.
Example: Employee employee;
In the above example, the employee object is not instantiated so it is pointed nowhere.
56. Can we define a package statement after the import statement in Java?
Answer: We can’t define a package statement after the import statement in Java. a package statement
must be the first statement in the source file. We can have commented before the package statement.
57. 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.
58. What is JSP?
Answer: 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 the Presentation logic
and business logic of a web application.
59. What is the purpose of apache tomcat?
Answer: 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.
60. Explain where variables are created in memory?
Answer: When we declare variables are created in the stack. So when the variable is out of scope those
variables get garbage collected.
61. Can we use a catch statement for checked exceptions?
Answer: If there is no chance of raising an exception in our code then we can’t declare a catch block for
handling checked exceptions. This raises a compile-time error if we try to handle checked exceptions
when there is no possibility of causing an exception.
62. Explain a situation where the final block will not be executed?
Answer: Finally, the block will not be executed whenever JVM shutdowns. If we use system.exit(0) in try
the statement finally blocks if present will not be executed.
63. What is UNICODE?
Answer: Unicode is used for the internal representation of characters and strings and it uses 16 bits to
represent each other.
64. Explain about the main() method in java?
Answer: The main () method is the starting point of execution for all Java applications.
public static void main(String[] args) {}
String args[] are an array of string objects we need to pass from command line arguments.
Every Java application must have at least one main method.
65. Define How destructors are defined in Java?
Answer: 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
66. What will be the output of Round(3.7) and Ceil(3.7)?
Answer: Round(3.7) returns 4 and Ceil(3.7) returns 4.
67. What is a constructor in Java?
Answer: A constructor is a special method used to initialize objects in Java.
we use constructors to initialize all variables in the class when an object is created. As and when an
object is created it is initialized automatically with the help of a constructor in Java.
We have two types of constructors
Default Constructor
Parameterized Constructor
68. How can we find the actual size of an object on the heap?
Answer: In Java, there is no way to find out the actual size of an object on the heap.
69. Can a variable be local and static at the same time?
Answer: 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.
70. Can we have static methods in an Interface?
Answer: 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 implemented in the interface.
So it makes no sense to have static methods in an interface in Java.
71. In how many ways we can do synchronization in Java?
Answer:
There are two ways to do synchronization in Java:
1) Synchronized methods
2) Synchronized blocks
To do synchronization we use the synchronized keyword.
72. When do we use synchronized blocks and advantages of using synchronized blocks?
Answer: If very few lines of code require synchronization then it is recommended to use synchronized
blocks. The main advantage of synchronized blocks over synchronized methods is it reduces the waiting
time of threads and improves the performance of the system.
73. What is the difference between access specifiers and access modifiers in Java?
Answer: In C++ we have access specifiers as public, private, protected, and default and access modifiers
as static, final. But there is no such division of access specifiers and access modifiers in Java. In Java, we
have access to modifiers and non-access modifiers.
Access Modifiers: public, private, protected, default
Non-Access Modifiers: abstract, final, strip.
74. Define How objects are stored in Java?
Answer: 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.
75. What access modifiers can be used for class?
Answer: We can use only two access modifiers for class public and default.
public: A class with a public modifier can be visible
1) In the same class
2) In the same package subclass
3) In the same package non subclass
4) In the different package subclass
5) In the different package non subclass.
default: A class with a default modifier can be accessed
1) In the same class
2) In the same package subclass
3) In the same package non subclass
4) In the different package subclass
5) In the different package non subclass. ( )
76. Explain abstract classes in Java?
Answer: Sometimes we may come across a situation where we cannot provide implementation to all
the methods in a class. We want to leave the implementation to a class that extends it. In such a case,
we declare a class as abstract. To make a class abstract we use the keyword abstract. Any class that contains
one or more abstract methods is declared as abstract. If we don’t declare a class as abstract which
contains abstract
methods we get a compile-time error. We get the following error. “The type must be an abstract class to
define abstract methods.” Signature; abstract class.
For example, if we take a vehicle class we cannot provide implementation to it because there may be
two-wheelers, four-wheelers, etc. At that moment we make the vehicle class abstract. All the common
features of vehicles are declared as abstract methods in the vehicle class. Any class which extends the
vehicle will provide its method implementation. It’s the responsibility of the subclass to provide the
implementation.
The important features of abstract classes are:
1) Abstract classes cannot be instantiated.
2) An abstract class contains abstract methods, concrete methods, or both.
3) Any class which extends an abstract class must override all methods of an abstract class.
4) An abstract class can contain either 0 or more abstract methods.
Though we cannot instantiate abstract classes we can create object references. Through superclass
references, we can point to subclass.
77. Can we create a constructor in an abstract class?
Answer: We can create a constructor in the abstract class, it doesn’t give any compilation error. But
when we cannot
instantiate class there is no use in creating a constructor for an abstract class.
78. String and StringBuffer both represent String objects. Can we compare String andStringBuffer in
Java?
Answer: 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.
79. In how many ways we can create threads in Java?
Answer:
We can create threads in Java in any of the two ways :
1) By extending the Thread class
2) By implementing the Runnable interface.
80. Explain creating threads by implementing the Runnable class?
Answer: This is the first and foremost way to create threads. By implementing the runnable interface
and implementing
the run() method we can create a new thread.
Method signature: public void run()
The run is the starting point for the execution of another thread within our program.
Example :
public class MyClass implements Runnable {
@Override
public void run()
81. When do we use synchronized methods in Java?
Answer: If multiple threads try to access a method where the method can manipulate the state of the
object, in such a scenario we can declare a method as synchronized.
82. Can we cast any other type to Boolean Type with type casting?
Answer: No, we can neither cast any other primitive type to Boolean data type nor can cast Boolean
data type or any other primitive data type.
83. What are synchronized methods and synchronized statements?
Answer: Synchronized methods are methods that are used to control access to an object. A
a synchronized statement can only be executed after a thread has acquired the lock for the object or class
referenced in the synchronized statement.
84. Explain the importance of the final block in Java?
Answer: Finally block is used for cleaning up resources such as closing connections, sockets, etc. If the try
block executes with no exceptions then finally is called after the try block without executing the catch block. If
there is an exception thrown in the try block finally block executes immediately after the catch block. If an
exception is thrown, finally block will be executed even if the no-catch block handles the exception.
85. Can we catch more than one exception in a single catch block?
Answer: From Java 7, we can catch more than one exception with a single catch block. This type of
handling reduces
the code duplication.
Note: When we catch more than one exception in a single catch block, the catch parameter is implicitly final.
We cannot assign any value to the catch parameter.
Ex : catch(ArrayIndexOutOfBoundsException || ArithmeticException e)
In the above example, e is final we cannot assign any value or modify e in the catch statement.
86. What are abstract methods in Java?
Answer: An abstract method is a method that doesn’t have anybody. An abstract method is declared
with keyword abstract and semicolon in place of the method body.
Signature: public abstract void ();
Ex: public abstract void get details();
It is the responsibility of the subclass to provide implementation to an abstract method defined in the
abstract class.
87. State some situations where exceptions may arise in Java?
Answer:
1) Accessing an element that does not exist in the array.
2) Invalid conversion of number to string and string to a number.
(NumberFormatException)
3) The invalid casting of class
(Class cast Exception)
4) Trying to create an object for an interface or abstract class
(Instantiation Exception)
88. What is an exception in Java?
Answer:
In Java, an exception is an object. Exceptions are created when abnormal situations arise in our program.
Exceptions can be created by JVM or by our application code. All Exception classes are defined in
Java. lang. In other words, we can say Exception is a run time error.
89. What is an error in Java?
Answer: Error is the subclass of the Throwable class in Java. When errors are caused by our program we call
that an Exception, but sometimes exceptions are caused due to some environmental issues such as
running out of memory. In such cases, we can’t handle the exceptions. Exceptions that cannot be
recovered are called errors in Java.
Ex: Out-of-memory issues.
90. What are the advantages of Exception handling in Java?
Answer:
1) Separating normal code from exception handling code to avoid abnormal termination of the program.
2) Categorizing into different types of Exceptions so that rather than handling all exceptions with
Exception root class we can handle with specific exceptions. It is recommended to handle exceptions
with specific Exceptions instead of handling with Exception root class.
3) Call stack mechanism: If a method throws an exception and it is not handled immediately, then that
exception is propagated or thrown to the caller of that method. This propagation continues till it finds
an appropriate exception handler, if it finds a handler it would be handled otherwise program terminates
Abruptly.
91. What’s the difference between constructors and other methods?
Answer: Constructors must have the same name as the class and can not return a value. They are only
called once while regular methods could be called many times.
92. Is there any limitation to using Inheritance?
Answer: Yes, since inheritance inherits everything from the super class and interface, it may make the
subclass to clustering and sometimes error-prone when dynamic overriding or dynamic overloading in
some situation.
93. Where and how can you use a private constructor?
Answer: Private constructor is used if you do not want other classes to instantiate the object and to
prevent subclassing.
94. What is typecasting?
Answer: Type casting means treating a variable of one type as though it is another type.
95. What is the difference between the >> and >>> operators?
Answer: The >> operator carries the sign bit when shifting right. The >>> zero-fill bits that have been
shifted out.
96. What is the difference between an inner class and a nested class?
Answer: When a class is defined within the scope of another class, then it becomes an inner class. If the
the access modifier of the inner class is static, then it becomes a nested class.
97. Can you call one constructor from another if a class has multiple constructors?
Answer: Yes, use this() syntax.
98. Why do we need wrapper classes?
Answer: We can pass them around as method parameters where a method expects an object. It also
provides utility methods.
99. Does Java allow Default Arguments?
Answer: No, Java does not allow Default Arguments.
100. Which number is denoted by leading zero in Java?
Answer: Octal Numbers are denoted by leading zero in Java,