Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
70 views

Top Java Interview Q/A

Uploaded by

Sample One
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views

Top Java Interview Q/A

Uploaded by

Sample One
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

THE NEWEST DEMO RELEASE FROM 

IDKARTIK.TECH

AV A
P J
T O

V IEW
TER
IN

Q / A

T O P 2 5 0 0 + J A V A   IN T E R V I E W   T E C H N I CA L
QUESTION ANSWER

IDKARTIK
Top 2500+ Java Interview Technical Question Answer

Top
2500+
Java
Interview
Technical
Question
Answer
IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

RISFRUTZZ

For your very generous contribution to our project, we at Idkartik.tech want


to send warm thanks and appreciation and hope you know how much you
are valued.

This Is a Sample e-book for the reader Containing only the Basic Questions which I think gives an
idea of the quality of content and the main course E-book will released on 7th of May, 2020.

Copyright © 2020 By (IDKartik)

All rights reserved. This book or any portion thereof may not be reproduced or used in any
manner whatsoever without the express written permission of the Author IDKartik except for the
use of brief quotations in a book review or scholarly journal.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

Author side:

“This book is dedicated to all those who make the daily sacrifices, Especially those who’ve made
sacrifice, to ensure our freedom & security.”

‘‘... I am just now beginning to discover the difficulty of expressing one’s ideas on paper. As long as it
consists solely of description it is pretty easy; but where reasoning comes into play, to make a proper
connection, a clearness & a moderate fluency, is to me, as I have said, a difficulty of which I had no
idea ...’’

- IDKartik (idkartik.tech)

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

BASIC CORE JAVA INTERVIEW QUESTIONS

Q1. What are the core OOPs concept?


Ans. There are mainly 4 core OOPs concepts:
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism

Q2. What is an object?


Ans. Object is an instance of a class. It has state, behaviour and identity. It is also called an
instance of a class.

Q3. What is the difference between object and object reference?


Ans. An object is an instance of a class. Object reference is a pointer to the object. There can
be many references to the same object.
Q4. What is the difference between JDK and JRE?
Ans. JDK stands for Java Development Kit. It contains the tools and libraries for development
of Java programs. It also contains compilers and debuggers needed to compile Java
program,
JRE stands for Java Runtime Environment. This is included in JDK. JRE provides
libraries and JVM that is required to run a Java program.

Q5. What is Java Virtual Machine (JVM)?


Ans. Java Virtual Machine (JVM) is an abstract machine that executes Java Bytecode. There
are different JVM for different hardware and software platforms. So JVM is platform
dependent. JVM is responsible for loading, verifying and executing the Bytecode on a
platform.

Q6. What are the different types of memory areas allocated by JVM?
Ans. In java, JVM allocates memory to different processes, methods and objects. Some of
the memory areas allocated by JVM are:
1. Class Loader: It is a component of JVM used to load class files.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

2. Class (Method) Area: It stores per-class structures such as the runtime constant pool, field
and method data, and the code for methods.
3. Heap: Heap is created a runtime and it contains the runtime data area in which objects
are allocated.
4. Stack: Stack stores local variables and partial results at runtime. It also helps in method
invocation and return value. Each thread creates a private JVM stack at the time of thread
creation.
5. Program Counter Register: This memory area contains the address of the Java virtual
machine instruction that is currently being executed.
6. Native Method Stack: This area is reserved for all the native methods used in the
application.

Q7. What is JIT compiler?


Ans. Just in Time compiler also known as JIT compiler is used for performance improvement
in Java. It is enabled by default. It is compilation done at execution time rather earlier. Java
has popularized the use of JIT compiler by including it in JVM.

Q8. How Java platform is different from other platforms?


Ans. Java is a platform independent language. Java compiler converts Java code in to byte
code that can be interpreted by JVM. There are JVM written for almost all the popular
platforms in the world.
Java byte code can run on any supported platform in same way. Whereas other
languages require libraries compiled for a specific platform to run.

Q9. Why people say that Java is 'write once and run anywhere' language?
Ans. You can write Java code on Windows and compile it in Windows platform. The class
and jar files that you get from Windows platform can run as it is on Unix environment. So it
is a truly platform independent language.
Behind all this portability is Java byte code. Byte code generated by Java compiler can be
interpreted by any JVM. So it becomes much easier to write programs in Java and expect
those to run on any platform.
Java compiler javac compiles java code and JVM java runs that code.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

Q10. What will trim() method of String class do?


Ans. Trim() eliminates spaces from both ends of the string

Q11. What is the difference between String, Stringbuffer and Stringbuilder?


Ans. String is immutable whereas StringBuffer and StringBuilder can change their values.
The only difference between StringBuffer and StringBuilder is that StringBuilder is
unsynchronized whereas StringBuffer is synchronized. So when the application needs to be
run only in a single thread then it is better to use StringBuilder. StringBuilder is more
efficient than StringBuffer.

Q12. What is the difference between Path and Classpath?


Ans. Path and Classpath are operating system level environment variales. Path is used
define where the system can find the executables(.exe) files and classpath is used to specify
the location .class files.

Q13. What are the default values of primitive data types?


Ans. For boolean data type, it is false. For byte,short,int and long, it is 0. For float and
double, it is 0.0. For char, the default value is 'u000'.

Q14. Can char be manipulated like integers?


Ans. Yes possible. The below is an example.char ch = 'A'; System.out.println(ch++);
The above statement will print B. ++ is a numeral operand and since char is internally
represented as integer, ++ operand can be applied on char value.

Q15. What is the difference between static and non-static variables?


Ans. A static variable is associated with the class as a whole rather than with specific
instances of a class. Non-static variables take on unique values with each object instance.

Q16. Why is the main method declared static?


Ans. main method is the entry point for a Java application and main method is called by the
JVM even before the instantiation of the class hence it is declared as static. static methods
can be called even before the creation of objects.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

Q17. Can a main method be overloaded?


Ans. Yes. You can have any number of main methods with different method signature and
implementation in the class.

Q18. Does the order of public and static declaration matter in main method?
Ans. No it doesn't matter but void should always come before main().

Q19. Can a source file contain more than one Class declaration?
Ans. Yes. A single source file can contain any number of Class declarations but only one of
the class can be declared as public.

Q20. Explain Inheritance?


Ans. Inheritance is a concept where the properties and behavior of a class is reused in
another class. The class which is being reused or inherited is called the super class or the
parent class. The class which is inheriting is called the subclass or the child class of the
inherited class.

Q21. Can a subclass be referenced for a super class object?


Ans. No. If Vehicle is super class and Car is the subclass then the following reference would
be wrong – Car c = new Vehicle();

Q22. Can a parent class be referenced for a subclass object?


Ans. Yes. The below is an example :Vehicle v = new Car();

Q23. Can an interface be referenced for any object?


Ans. Yes. We can create a object reference for an interface. The object should have provided
the implementation for the object. Runnable r = new Test();
Test class should have implemented the runnable interface and overridded the run method.

Q24. What are constructors?


Ans. Constructors are used to initialize an object. Constructors are invoked when the new
operator on the class are called.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

Q25. What is the sequence of constructor invocation?


Ans. When you instantiate a subclass, the object will begin with an invocation of the
constructor in the base class and initialize downwards through constructors in each subclass
till it reaches the final subclass constructor.
Note: This top down imagery for class inheritance, rather than a upward tree-like approach,
is standard in OOP but is sometimes confusing to newcomers.

Q26. Explain Polymorphism?


Ans. The dictionary definition of polymorphism refers to a principle in biology in which an
organism or species can have many different forms or stages. This principle can also be
applied to object-oriented programming and languages like the Java language. Subclasses of
a class can define their own unique behaviors and yet share some of the same functionality
of the parent class. Polymorphism is the capability of an action or method to do different
things based on the object that it is acting upon. Overloading and overriding are two types
of polymorphism.

Q27. Do you think ‘main’ used for main method is a keyword in Java?
Ans. No, main is just a name of method. There can be multiple methods with same name
main in a class file. It is not a keyword in Java.

Q28. Can we write main method as public void static instead of public static void?
Ans. No, you cannot write it like this. Any method has to first specify the modifiers and then
the return value. The order of modifiers can change.
We can write static public void main() instead of public static void main().

Q29. In Java, if we do not specify any value for local variables, then what will be the default
value of the local variables?
Ans. Java does not initialize local variables with any default value. So these variables will be
just null by default.

Q30. What is the difference between byte and char data types in Java?
Ans. Both byte and char are numeric data types in Java. They are used to represent numbers
in a specific range.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

Major difference between them is that a byte can store raw binary data where
as a char stores characters or text data.
Usage of char is E.g. char ch = ‘x’;
Byte values range from -128 to 127.
A byte is made of 8 bits. But a char is made of 16 bits. So it is equivalent to 2 bytes.

Q31. What is the difference between Object Oriented Programming language and Object
Based Programming language?
Ans. Object Oriented Programming languages like Java and C++ follow concepts of OOPS
like- Encapsulation, Abstraction, Polymorphism and Inheritance etc.
Object Based Programming languages follow some features of OOPS but they do not
provide support for Polymorphism and Inheritance. Egg. JavaScript, VBScript etc.
Object Based Programming languages provide support for Objects and you can build
objects from constructor. They languages also support Encapsulation. These are also known
as Prototype-oriented languages.
Q32. In Java what is the default value of an object reference defined as an instance variable
in an Object?
Ans. All the instance variable object references in Java are null.

Q33. Why do we need constructor in Java?


Ans. Java is an object-oriented language, in which we create and use objects. A constructor
is a piece of code similar to a method. It is used to create an object and set the initial state
of the object.
A constructor is a special function that has same name as class name.
Without a constructor, there is no other way to create an object.
By default, Java provides a default constructor for every object. If we overload a
constructor then we have to implement default constructor.

Q34. Why do we need default constructor in Java classes?


Ans. Default constructor is the no-argument constructor that is automatically generated by
Java if no other constructor is defined.
Java specification says that it will provide a default constructor if there is no
overloaded constructor in a class. But it does not say anything about the scenario in which
we write an overloaded constructor in a class.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

We need at least one constructor to create an object, that’s why Java provides a default
constructor.

When we have overloaded constructor, then Java assumes that we want some custom
treatment in our code. Due to which it does not provide default constructor. But it needs
default constructor as per the specification. So it gives error.

Q35. What is the value returned by Constructor in Java?


Ans. When we call a constructor in Java, it returns the object created by it. That is how we
create new objects in Java.

Q36. Can we inherit a Constructor?


Ans. No, Java does not support inheritance of constructor.

Q37. Why constructors cannot be final, static, or abstract in Java?


Ans. If we set a method as final it means we do not want any class to override it. But the
constructor (as per Java Language Specification) cannot be overridden. So there is no use of
marking it final.

If we set a method as abstract it means that it has no body and it should be implemented in
a child class. But the constructor is called implicitly when the new keyword is used.
Therefore it needs a body.

If we set a method as static it means that it belongs to the class, but not a particular object.
The constructor is always called to initialize an object. Therefore, there is no use of marking
constructor static.

Q38. What is the purpose of ‘this’ keyword in java?


Ans. In Java, ‘this’ keyword refers to current instance of the object. It is useful for
differentiating between instance variables and local variables.
It can be used to call constructors. Or it can be used to refer to the instance.
In case of method overriding, this is used for falling the method of current class.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

Q39. Explain the concept of Inheritance?


Ans. Inheritance is an important concept in Object Oriented Programming. Some objects
share certain characteristics and behaviour.
By using Inheritance, we can put the common behaviour and characteristics in a base class
which also known as super class. And then all the objects with common behaviour inherit
from this base class.
It is also represented by IS-A relationship.
Inheritance promotes, code reuse, method overriding and polymorphism.

Q40. Which class in Java is superclass of every other class?


Ans. Java is an objectoriented programming language. In Java, Object class is the superclass
of every other class.

Q41. Why Java does not support multiple inheritance?


Ans. Multiple Inheritance means that a class can inherit behaviour from two or more parent
classes.

The issue with Multiple Inheritance is that both the parent classes may have different
implementation for the same method. So they have different ways of doing the same thing.
Now which implementation should the child class choose?

This leads to ambiguity in Multiple Inheritance. This is the main reason for Java not
supporting Multiple Inheritance in implementation.

Lets say you have a class TV and another class AtomBomb. Both have method switchOn()
but only TV has switchOff() method. If your class inherits from both these classes then you
have an issue that you can switchOn() both parents, but switchOff will only switchOff() TV .

But you can implement multiple interfaces in Java.

Q42. In OOPS, what is meant by composition?


Ans. Composition is also known as “has-a” relationship. In composition, “has-a” relation
relates two classes. E.g. Class Car has a steering wheel.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

If a class holds the instance of another class, then it is called composition.

Q43. How aggregation and composition are different concepts?


Ans. In OOPS, Aggregation and Composition are the types of association relations. A
composition is a strong relationship. If the composite object is destroyed, then all its parts
are destroyed. E.g. A Car has a Steering Wheel. If Car object is destroyed, then there is no
meaning of Steering Wheel.

In Aggregation, the relationship is weaker than Composition.

E.g. A Library has students. If a Library is destroyed, Students still exist. So Library and
Student are related by Aggregation. A Library has Books. If Library is destroyed, the Books
are also destroyed. Books of a Library cannot exist without the Library. So Book and Library
are related by Composition.

Q43. Why there are no pointers in Java?


Ans. In Java there are references instead of pointers. These references point to objects in
memory. But there is no direct access to these memory locations. JVM is free to move the
objects within VM memory.

The absence of pointers helps Java in managing memory and garbage collection effectively.
Also it provides developers with convenience of not getting worried about memory
allocation and deallocation.

Q44. If there are no pointers in Java, then why do we get NullPointerException?


Ans. In Java, the pointer equivalent is Object reference. When we use a . it points to object
reference. So JVM uses pointers but programmers only see object references.

In case an object reference points to null object, and we try to access a method or member
variable on it, then we get NullPointerException.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

Q45. What is the purpose of ‘super’ keyword in java?


Ans. ‘super’ keyword is used in the methods or constructor of a child class. It refers to
immediate parent class of an object.

By using ‘super’ we can call a method of parent class from the method of a child class.

We can also call the constructor of a parent class from the constructor of a child class by
using ‘super’ keyword.

Q46. Is it possible to use this() and super() both in same constructor?


Ans. No, Java does not allow using both super() and this() in same constructor. As per Java
specification, super() or this() must be the first statement in a constructor.

Q47. What is the meaning of object cloning in Java?


Ans. Object.clone() method is used for creating an exact copy of the object in Java. It acts
like a copy constructor. It creates and returns a copy of the object, with the same class and
with all the fields having same values as of the original object.

One disadvantage of cloning is that the return type is an Object. It has to be explicitly cast to
actual type.

Q48. In Java, why do we use static variable?


Ans. Whenever we want to have a common property for all objects of a class, we use a class
level variable i.e. a static variable.

This variable is loaded in memory only once at the time of class loading. So it saves memory,
since it is not defined per object in Java.

Q49. Why it is not a good practice to create static variables in Java?


Ans. Static variables are common to all the objects of a class. If a new object is created,
there is no need to test the value of static variable. Any code that uses static variable can be
in any state. It can be within a new object or at a class level. So the scope of static variable is
open ended in a Java class.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

If we want tighter control on scope, then variables should be created at the object creation
level.

Also defining static variables is not a good practice because they go against the principles of
Object Oriented Programming.

Q49. What is the purpose of static method in Java?


Ans. Java provides the feature of static method to create behavior at the class level. The
static method is common to all the objects of a class. We do not need to create any object
of a class to call a static method. So it provides convenience of not creating an object for
calling it.

Also a static method can access and modify static data members. This also helps in keeping
the behavior as well as state at the class level.

Q50. Why do we mark main method as static in Java?


Ans. The main method in Java is marked as static, so that JVM can call it to start the
program. If main method is not static, then which constructor will be called by Java process?

As such it is a known as convention to mark main method static in Java. But if we remove
the static, then there will be ambiguity. Java process may not know which method of a class
to call to start the program.
So this convention helps in Java process to identify the starting code for a program in class
that is passed as an argument to java process.

Q51. In what scenario do we use a static block?


Ans. At times, there is a class that has static member variables. These variables need some
complicated initialization. At this time static block helps as a tool to initialize complex static
member variable initialization.

The static block is executed even before the execution of main.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

Sometimes, we can also replace static block with a static method of class.

Q52. Is it possible to execute a program without defining a main() method?


Ans. No, with Java 7 onwards, you need a main() method to execute a program. In earlier
versions of Java, there was a workaround available to use static blocks for execution. But
now this gap has been closed.

Q53. What happens when static modifier is not mentioned in the signature of main
method?
Ans. As per Java specification, main method has to be marked as static. It needs only one
argument that is an array of String.
A program can compile with a non-static method. But on execution it will give
NoSuchMethodError.

Q54. What is the difference between static method and instance method in Java?
Ans. Often, there is a need to define a behaviour for a class that is not dependent on
member variables of an object. Such behaviour is captured in a static method. If there is a
behaviour dependent upon the member variables of an object, then we do not mark it
static, it remains as instance method.

To call as static method, we do not need to create an object. We just call it with class name.
But to call an instance method, we need to create/get an object first.

Instance member variables cannot be accessed by a static method. But an instance method
can call both instance variables and static variables.

Q55. What is Overloading?


Ans. In a class, if two methods have the same name and a different argument, it is known as
overloading in Object oriented concepts.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

Q56. Explain Overriding?


Ans. When a class defines a method using the same name, return type, and arguments as a
method in its superclass, the method in the class overrides the method in the superclass.
When the method is invoked for an object of the class, it is the new definition of the method
that is called, and not the method definition from superclass.

Q57. What is the other name of Method Overloading?


Ans. Method Overloading is also known as Static Polymorphism.

Q58. How will you implement method overloading in Java?


Ans. In Java, a class can have multiple methods with same name but different arguments. It
is called Method Overloading. To implement method overloading we have to create two
methods with same name in a class and do one/more of the following:

1. Different number of parameters


2. Different data type of parameters
3. Different sequence of data type of parameters

Q59. What kinds of argument variations are allowed in Method Overloading?


Ans. Method Overloading allows two methods with same name to differ in:
1. Number of parameters
2. Data type of parameters
3. Sequence of data type of parameters

Q60. Why it is not possible to do method overloading by changing return type of method in
java?
Ans. If we change the return type of overloaded methods then it will lead to ambiguous
behaviour. How will clients know which method will return what type. Due to this different
return type are not allowed in overloaded methods.

Q61. Is it allowed to overload main() method in Java?


Ans. Yes, Java allows users to create many methods with same name ‘main’. But only public
static void main(String[] args) method is used for execution.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

Q62. How do we implement method overriding in Java?


Ans. To override a method, we just provide a new implementation of a method with same
name in subclass. So there will be at least two implementations of the method with same
name. One implementation is in parent class. And another implementation is in child class.

Q63. Are we allowed to override a static method in Java?


Ans. No. Java does not allow overriding a static method. If you create a static method with
same name in subclass, then it is a new method, not an overridden method.

Q64. Why Java does not allow overriding a static method?


Ans. To override a method, you need an instance of a class. Static method is not associated
with any instance of the class. So the concept of overriding does not apply here.

Therefore, Java does not allow overriding a static method.

Q65. Is it allowed to override an overloaded method?


Ans. Yes. You can override an overloaded method in Java.

Q66. What is the difference between method overloading and method overriding in Java?
Ans. Differences between method overloading and overriding are:

1. Method overloading is static polymorphism. Method overriding is runtime


polymorphism.
2. Method overloading occurs within the same class. Method overriding happens in
two classes with hierarchy relationship.
3. Parameters must be different in method overloading. Parameters must be same in
method overriding.
4. Method overloading is a compile time concept. Method overriding is a runtime
concept.

Q67. Does Java allow virtual functions?


Ans. Yes. All instance methods in Java are virtual functions by default. Only class methods
and private instance methods are not virtual methods in Java.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

Q68. What is meant by covariant return type in Java?


Ans. A covariant return type of a method is one that can be replaced by a "narrower" type
when the method is overridden in a subclass.

Let say class B is child of class A. There is a get() method in class A as well as class B. get()
method of class A can return an instance of A, and get() method of class B return an
instance of B. Here class B overrides get() method, but the return type is different.

Before Java 5, any method that overrides the method of parent class would have same
return type.

From Java 5 onwards, a child class can override a method of parent class and the child class
method can return an object that is child of object return by parent class method.

Q69. What is Runtime Polymorphism?


Ans. Runtime Polymorphism or Dynamic Polymorphism is the polymorphism that exists at
runtime. In case of method overriding it is not known which method will be called at
runtime. Based on the type of object, JVM decides the exact method that should be called.

So at compile time it is not known which method will be called at run time.

Q70. Is it possible to achieve Runtime Polymorphism by data members in Java?


Ans. No. We need to create Runtime Polymorphism by implementing methods at two levels
of inheritance in Java.

Q71. Explain the difference between static and dynamic binding?


Ans. In Static binding references are resolved at compile time. In Dynamic binding
references are resolved at Run time.

E.g. Person p = new Person(); p.walk(); // Java compiler resolves this binding at compile
time.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

public void walk(Object o){


((Person) o).walk(); // this is dynamic binding.
}

Q72. What is Abstraction in Object Oriented programming?


Ans. Abstraction is the process of hiding certain implementation details of an object and
showing only essential features of the object to outside world.
It is different from Abstract class in Java.
Abstraction process identifies commonalities and hides the complexity of implementation. It
helps us in focusing on the interface that we share with the outside world.

Q73. How is Abstraction different from Encapsulation?


Ans. Abstraction happens at class level design. It results in hiding the implementation
details. Encapsulation is also known as “Information Hiding”. An example of encapsulation
is marking the member variables private and providing getter and setter for these member
variables.

Q74. What is an abstract class in Java?


Ans. An abstract class in Java has one or more abstract methods. An abstract method is just
declared in the abstract class, but it is not implemented.

An abstract class has to be extended in Java and its abstract methods have to be
implemented by a child class. Also Java does not allow new instance of Abstract class.

Q75. Is it allowed to mark a method abstract method without marking the class abstract?
Ans. No. Java specification says that if there is at least one abstract method in a class, the
class has to be marked abstract.

Q76. Is it allowed to mark a method abstract as well as final?


Ans. No. It will be contradictory statement to mark a method abstract as well as final.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

An abstract method has to be overridden by a child class. And a final method cannot be
overridden. Therefore a method can be either abstract or final in Java.

Q77. What is the access scope of a protected method?


Ans. A protected method can be accessed by the classes within the same package or by the
subclasses of the class in any package.

Q78. What is the impact of marking a constructor as private?


Ans. Nobody can instantiate the class from outside that class. Traditional uses is used for
singleton pattern.

Q79. What is the impact of declaring a method as final?


Ans. A method declared as final can't be overridden. A sub-class doesn't have the
independence to provide different implementation to the method. A method can be
overloaded.

Q80. How to define a constant variable in Java?


Ans. The variable should be declared as static and final. So only one copy of the variable
exists for all instances of the class and the value can't be changed also. static final int PI =
3.14; is an example for constant.

Q81. What is static in java?


Ans. Static means one per class, not one for each object no matter how many instance of a
class might exist. This means that you can use them without creating an instance of a class.
Static methods are implicitly final, because overriding is done based on the type of the
object, and static methods are attached to a class, not an object. A static method in a
superclass can be shadowed(override) by another static method in a subclass, as long as the
original method was not declared final. However, you can't override a static method with a
non-static method. In other words, you can't change a static method into an instance
method in a subclass. Static varibales are not serialized.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

Q82. Can a class be declared as static?


Ans. No a class cannot be defined as static in fact every class is “static”. Only a method, a
variable or a block of code can be declared as static. But inner class can be static!

Q83. When will you define a method as static?


Ans. When a method needs to be accessed even before the creation of the object of the
class then we should declare the method as static.

Q84. Can we declare a static variable inside a method?


Ans. Static varaibles are class level variables and they can't be declared inside a method. If
declared, the class will not compile.

Q85. What is an Abstract Class and what is it's purpose?


Ans. A Class which doesn't provide complete implementation is defined as an abstract class.
It serves as a template. A class that is abstract may not be instantiated (ie, you may not call
its constructor), abstract class may contain static data. Any class with an abstract method is
automatically abstract itself, and must be declared as abstract. A class may be declared
abstract even if it has no abstract methods. This prevents it from being instantiated.

Q86. Can we instantiate an abstract class in Java?


Ans. No. We cannot create an instance of an abstract class in Java.

Q87. What is an interface in Java?


Ans. An Interface in Java is an abstract type blueprint of a class. It contains the methods that
a class must implement. It is like a protocol.

It has method signatures and constant declarations.

Q88. Is it allowed to mark an interface method as static?


Ans. Yes, from Java 8 onwards, we can define static and default methods in an interface.
Prior to Java 8, it was not allowed.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

Q89. Why an Interface cannot be marked as final in Java?


Ans. A final method cannot be overridden. But an interface method has to be implemented
by another class. So the interface method cannot be marked as final.

Q90. What is a marker interface?


Ans. There are interfaces that do not have any data member or methods. These interfaces
are called Marker interface. E.g. Serializable, Cloneable, Remote etc.

Q91. What can we use instead of Marker interface?


Ans. We can use annotations instead of Marker interface.
Q92. What is the difference between interface and abstract class?
Ans.

• interface contains methods that must be abstract; abstract class may contain
concrete methods.
• interface contains variables that must be static and final; abstract class may contain
non-final and final variables.
• members in an interface are public by default, abstract class may contain non-public
members. interface is used to "implements"; whereas abstract class is used to
"extends".
• interface can be used to achieve multiple inheritance; abstract class can be used as a
single inheritance.
• interface can "extends" another interface, abstract class can "extends" another class
and "implements" multiple interfaces.
• interface is absolutely abstract; abstract class can be invoked if a main() exists.
• interface is more flexible than abstract class because one class can only "extends"
one super class, but "implements" multiple interfaces.
• If given a choice, use interface instead of abstract class.

Q93. Can a abstract class be defined without any abstract methods?


Ans. Yes it's possible. This is basically to avoid instance creation of the class.

Q94. What happens if a subclass has inherited a abstract class but has not provided
implementation for all the abstract methods of the super class?
Ans. Then the subclass also becomes abstract. This will be enforced by the compiler.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

Q95. What happens if a class has implemented an interface but has not provided
implementation for a method in a interface?
Ans. Its the same as the earlier answer. The class has to be marked as abstract. This will be
enforced by the compiler.

Q96. Can you create an object of an abstract class?


Ans. Not possible. Abstract classes are not concrete and hence can't be instantiated. If you
try instantiating, you will get compilation error.

Q97. What are the states of a Thread ?


Ans. Four state: Ready, Running, Waiting and Dead.

Q98. Can I create a reference for an abstract class?


Ans. Yes. You can create a reference for an abstract class only when the object being
provided the implementation for the abstract class - it means that the object should be of a
concrete subclass of the abstract class. This applies to interfaces also. Below is an example
for interface referencing an
object:java.sql.Connection con = java.sql.DriverManager.getConnection("");

Q99. Can a class be marked as native?


Ans. No. Only methods can be marked as native. The native keyword is applied to a method
to indicate that the method is implemented in native code using JNI(Java Native Interface).
Q100. What is the disadvantage of native methods?
Ans. Since Java runs faster, native method is less common. By using native methods, the
java program loses platform independence - the accessed platform might be tightly coupled
with an operating system hence java program also loses OS independence. Potential
security risk,Loss of portability.

Q101. Can a method inside an Interface be declared as final?


Ans. Not possible. Doing so will result in compilation error. Final method can not be
override. public and abstract are the only applicable modifiers for method declaration in an
interface.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

Q102. Why is an Interface able to extend more than one Interface but a Class can't extend
more than one Class?
Ans. Basically Java doesn't allow multiple inheritance, so a Class is restricted to extend only
one Class. But an Interface is a pure abstraction model and doesn't have inheritance
hierarchy like classes (do remember that the base class of all classes is Object). So an
Interface is allowed to extend more than one Interface.

Q103. Can an Interface be final?


Ans. Not possible. Doing so will result in compilation error. Final method can not be
override.

Q104. Can a class be defined inside an Interface?


Ans. Yes it's possible.

Q105. Can an Interface be defined inside a class?


Ans. Yes it's possible.

Q106. How Annotations are better than Marker Interfaces?


Ans. Annotations serve the purpose of conveying metadata about the class to its consumers
without creating a separate type for it.

Annotations are more powerful than a Marker interface. They allow programmers to pass
more sophisticated information to classes that "consume" it.

Q107. What are the modifiers in Java ?


Ans.

• public : Public class is visible in other packages, field is visible everywhere (class must
be public too)
• private : Private variables or methods may be used only by an instance of the same
class that declares the variable or method, A private feature may only be accessed by
the class that owns the feature.
• protected : Is available to all classes in the same package and also available to all
subclasses of the class that owns the protected feature. This access is provided even

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

to subclasses that reside in a different package from the class that owns the
protected feature.
• default :What you get by default without any access modifier (ie, public private or
protected).It means that it is visible to all within a particular package.

Q108. Does Java allow us to use private and protected modifiers for variables in interfaces?
Ans. No. Always all variables declared inside an interface are of public access.

Q109. What modifiers are allowed for methods in an Interface?


Ans. Only public and abstract modifiers are allowed for methods in interfaces. In this case,
an interface is intended to serve as a public protocol for communicating with an object.

Q110. How can we cast to an object reference to an interface reference?


Ans. An Object that implements an Interface can be cast to the same Interface. Since An
Object implementing an Interface already provides implementation for the methods of that
Interface, it is allowed to do so as per the rules of Inheritance.

Q111. How can you change the value of a final variable in Java?
Ans. Java does not allow changing the value of a final variable. Once the value is set, it
cannot be changed.

Q112. Can a class be marked final in Java?


Ans. Yes a class can be marked final in Java. Once a class is marked final, it cannot be
extended.

Q113. How can we create a final method in Java?


Ans. To mark a method, add modifier final to that method. A final method can not be
overridden by a child class.
Q114. How can we prohibit inheritance in Java?
Ans. If you mark a class final, it cannot be extended. This will prohibit the inheritance of that
class in Java.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

Q115. Why Integer class in final in Java?


Ans. Integer class is a wrapper for int. If it is not marked final, then any other class can
extend it and modify the behavior of Integer operations. To avoid this Integer wrapper class
is marked as final.

Q116. What is a blank final variable in Java?


Ans. When we declare a final variable without giving any initial value, then it is called blank
final variable.

Q117. How can we initialize a blank final variable?


Ans. A blank final instance variable can be initialized in a constructor.

A blank final static variable can be initialized in the static block of class.

Q118. Is it allowed to declare main method as final?


Ans. Yes, we can mark the main method as final.

Q119. What are the disadvantages of Inner classes?


Ans.

• Inner classes are not reusable hence defeats one of the Encapsulation feature of
Java.
• Highly confusing and difficult syntax which leads poor code maintainability.

Q120. What is difference between shallow copy and deep copy?


Ans. Only instances of classes that implement the Cloneable interface can be cloned. Trying
to clone an object that does not implement the Cloneable interface throws a
CloneNotSupportedException. Both shallow copy and deep copy object need to implement
Cloneable Interface.

Q121. What is the difference between int and Interger? You can have question like why we
need Wrapper Class(Integer )?
Ans. int is primitive type and Integer is Wrapper Class; if you are using Collection objects like
Hashtable etc. you can't use int as a key. you have to use object so you can use Integer class.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

Q122. What is serialization?


Ans. Serialization involves saving the current state of an object to a stream, and restoring an
equivalent object from that stream.
Serialization is the process of converting an object into a stream of bytes in order to store
the object or transmit it to memory, a database, or a file. Its main purpose is to save the
state of an object in order to be able to recreate it when needed. The reverse process is
called deserialization.

Q123. When you serialize an object, what happens to the object references included in the
object?
Ans. The serialization mechanism generates an object graph for serialization. Thus it
determines whether the included object references are serializable or not. This is a recursive
process. Thus when an object is serialized, all the included objects are also serialized along
with the original obect.

Q124. What is the difference between declaring a variable and defining a variable?
Ans. In declaration we just mention the type of the variable and it's name. We do not
initialize it.
But defining means declaration + initialization.

Q125. What is the purpose of package in Java?


Ans. A package is used to encapsulate a group of classes, interfaces and sub-packages.
Often, it is a hierarchical structure of storing information. It is easier to organize the related
classes and subpackages in this manner.

A Package also provides access protection for classes and interfaces. A package also helps in
removing naming collision.

Q126. What is java.lang package?


Ans. In Java, java.lang package contains the classes that are fundamental to the design of
Java programming language. The most important class in this package is Object class.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

It also contains wrapper classes like- Integer, Boolean, Character etc. It provides Math class
for mathematical operations.

Q127. Which is the most important class in Java?


Ans. It is an open-ended question with many answers. In my view, Object class is the most
important class of Java programming language. It is the root of all the classes in Java. It
provides some very important and fundamental methods.

Q128. Is it mandatory to import java.lang package every time?


Ans. No. By default, JVM loads it internally.

Q129. Can you import same package or class twice in your class?
Ans. If we import same package multiple times in a class, compiler includes it only once. So
neither JVM nor Compiler gives any error/warning on including a package multiple times.

If you have two classes with same name, then you may get name collision on importing the
class erroneously.

JVM internally loads the class only one time.

Q130. What is a static import in Java?


Ans. Static import is similar to normal import declaration. Normal import allows us to import
classes from packages without using package qualifier. Static import allows us to import
static members from a class without using class qualifier.

Q131. What is the difference between import static com.test.Fooclass and import
com.test.Fooclass?
Ans. First import is a static import and the second import is normal import of a class. First
import allows us to import static members of class.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

Q132. What is Locale in Java?


Ans. A Locale object represents a specific geographical, political, or cultural region. It is used
to locale-sensitive operations in Java.

It helps is following the local conventions of a country, native or region. These conventions
can be for formatting the dates, money, numbers etc.

Q133. How will you use a specific Locale in Java?


Ans. To use a specific Locale, we need to load that Locale. We can use
ResourceBundle.getBundle("Locale.UK") method to load a Locale.

Q134. Define serialization?


Ans. Serialization is a process converting an object into a byte array. This byte array
represents the class, version and internal state of the object. JVM can use this byte array to
transmit/read the object over a network.

Q135. What is the purpose of serialization?


Ans. Some of the uses of serialization are:

1. Communication: It is used for transmitting an object over network between two


machines.
2. Persistence: We can store the object’s state in a database and retrieve it from
database later on.
3. Caching: Serialization can be used for caching to improve performance. We may
need 10 minutes to build an object, but it may take just 10 seconds to de-serialize
the object.
4. Cross JVM Synchronization: It can be used in same way across multiple JVM that
follow different architecture.

Q136. What is Deserialization?


Ans. Deserialization is the process of reconstructing the object from the serialized state. It is
the reverse process of serialization.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

Q137. What is Serialization and Deserialization conceptually?


Ans. Serialization is to convert Object data into a stream of bytes

Deserialization is to convert a stream of bytes back into a copy of the original object.

Q138. What is Externalizable interface in Java?


Ans. Externalizable interface extends Serializable interface in Java. It is used for giving the
Class control over saving and restoring the contents of its instances.
A class implements methods writeExternal() and readExternal() to store and restore the
object.

Q139. What is the difference between Serializable and Externalizable interface?


Ans. Serializable is a marker interface but Externalizable is not a marker interface.
When we implement Serializable interface, the class is serialized automatically by default.
We can override writeObject() and readObject()methods to control more complex object
Serialization process.
In case of Externalizable, we use readExternal() and writeExternal() methods to give control
to class for class's serialization process.
Serializable interface is based on recursive algorithm.
Serializable gives you two options. One option is to provide custom way of serialization, the
other default way. In Externalizable, you have to always implement readExternal() and
writeExternal() methods.
A public no-arg constructor is needed while using Externalizable interface.
In Serialization, we need to define serialVersionUID. If it is not explicitly defined it will be
generated automatically based on all the fields, methods of the class.

IDKartik – idkartik.tech
Top 2500+ Java Interview Technical Question Answer

Hey Reader,

I hope you like this e-book.


If you wanna to get notified when the main course of e-book launch, then fill the form.

IDKartik – idkartik.tech

You might also like