KEMBAR78
Top 100 Java Interview Ques & Ans | PDF | Class (Computer Programming) | Method (Computer Programming)
0% found this document useful (0 votes)
13 views15 pages

Top 100 Java Interview Ques & Ans

Uploaded by

dhruboghosh0606
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views15 pages

Top 100 Java Interview Ques & Ans

Uploaded by

dhruboghosh0606
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Top100Java 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 isa 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?


nelh
Answer: Java runs on a varietyof 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 methods 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: Apackage statement must appear asthe first line in a source code file (eliminatingblank lines
and comments).
a container's layout? layout.
used to specify
is specify
a container's
9. What method used to
method is
The setLayout()
Answer:

class?
of the Applet class.
superclass of the Applet
the immediate
10. What is
the immediate
superclass
is
class
Answer: The
Panel

no
the default one
identifier
in Java?
are the access modifiers and private, and
11.What protected
modifiers. Public, explicitly.
There are 3access specify the friendly identifier
Answer: cannot
friendly,
but programmer
is called
is specified

and
are packages? access protection
12. What is
and interfaces providing
is a collection of related classes
Answer: A package
namespacemanagement.

and What are its advantages?


13.What is meant by Inheritance all the features from a class. The advantages
of
process of inheriting by
Answer:Inheritance is the of variables and methods
of the super class

are reusability of code and accessibility


inheritance
subclasses.

same exception from catch handler?


14. Can we rethrow the
handler. we want to rethrow
rethrowthe same exception from our catch
If

Answer: Yes, wecan

catch block we need to declare that exception.


checked exception from a

initialized?
15.what value is a variable of the String type automatically

Answer:The default value of a String type is null.

When a thread blocks on i/0, what state does enter?


16.
it

Answer:When blocks on I/0, A thread enters the waiting state.


it

17. Which containers use a Flow Layout as their default layout?

Answer: The Panel and Applet classes use the Flow Layout astheir default layout.

18. Explain Java Coding Standardsfor 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?


the to control the access of multiple threads to shared
Answer: The ternm synchronization is ability

resources. And it is importantbecause, without it, it is not possible for one thread to modify a shared

object while anotherthread is in the process of using or updating that object's value. This often leads to

major errors.

20.Explain Java Coding Standardsfor variables?


Answer:
1)Variable names should start with smallletters.
2)Variable names should be nouns
3) Short meaningful names arerecommended.
4) If there are multiple words every inner world should start with Uppercase character.

Ex :string, value,empName,MEP salary

21.What is an abstract class?

a class designed with implementation gaps for subclasses to fill in and is


Answer: An abstract class is

deliberately incomplete.

22. Name three Component subclasses that supportpainting?

Answer: The Canvas,Frame, Panel, and Applet classes support painting.

23.What is the difference between JDK and JVM?


Development Kit Full Form: Java Virtual Machine
Answer: Full-Form: Java
For Development Purpose
To execute the java programs
It provides allthe tools, executables and binaries required to compile, debug and execute a Java

Program The execution part is handled by JVM toprovide machine independence.

24.Why Java doesn't support multiple inheritances?


Answer: Because of "Diamond Problem",Java doesn't supportmultiple inheritances in classes.
outer class?
that is a member of an or ahetre
with an inner class static, final,
may be used protected, private,
be declared as
modifiers
25. What may
public,
inner class
Answer: A (non-local)

event handling?
interfaces support
uticlasses and
processing.
support event
26. Which jave: the Event Listener interface
Object class and
Answer: The Event

What is a transient variable?


27.
is a variable that may not be serialized.
transient variable
Answer: A

28. Is null a keyword?


Answer: No, the null is not a keyword.

29. What is an applet?


web page displayed by a java
dynamic and interactive program that runs inside a
Answer: Applet is a

capablebrowser

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 when the browser
called 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 implementa growable array of objects.

33. What is the difference between the >> and >>> operators?
Answer: The >> operator carries the SIgn bit when shiting right while the >>> zero-fills bits that have
been shifted out.
34. What is the difference betweenthis() and super()?
be used to
whereas super() can
constructor of thesame
class

Answer: this() can be used to invoke a

constructor.
invoke a super class

What is method?
a native
a language other than
35. Java.
method that is applied in
Answer: A native method is a

has reached the end of a file?


return when it
36.What value does read Line() a
has reached the end of file.
readLine() method returns
null when it
Answer:The

37. What is the Java API?

of ready-made software componentsthat provide many


a large collection
Answer:The Java APl is

(GUI)widgets.
usefulcapabilities,
such as graphical user interface

variables in Java?
38. Why there are no global variables due
not support globally accessible
accessible.Java does
variables are globally
Answer:Global
to following reasons:
transparency
The global variables breaks the
referential

collisions in namespace.
Global variables creates

types of access modifiers?


39. What are different
from anywhere.private: Any
thing

Any thing declared as publiccan be accessed can be


Answer:public:
of its class. protected:
Any thing declared as protected
be seen outside :Can
declared asprivate can't packages. default modifier
subclasses in the other
in the same package and
accessedby classes
to classes in the same package.
beaccessed only

40. What is Constructor?


to initialize the object of its class.

a special mnethod whose task


is
is
Answer:Aconstructor name.
name the same as the class
is
It is special because
its values.
they cannot return
types, not even void and therefore
They do not have return the base class constructor.
can
though a derived class
call

They cannot be inherited, created.


of associated class is

whenever an object its


Constructor is invoked

41. What is an Iterator ?


used to step through the elements of a Collection.
Answer: TheIterator interface is
you process each elementof a Collection. Collection
no matter Define How is

it
a
Iterators let elements of
to go through all the
Iterators are a generic way

organized. way for every Collection.


an Interface implementeda different
Iterator is

Stream?
Reader/Writer and InputStream/Output
42. What isthe difference between
class is hto
class is character-oriented
and the Inputstream/OutputStream
Answer: The Reader/Writer

oriented.

43. What is servlet?

servers, such as java-enabled


extend request/response-oriented
Answer: Servlets are modulesthat order-entry form
data in an HTML
might be responsible for taking
webservers. For example, aservlet
order database.
and applying the business logic used to update a company's

44.What is clipping?

Answer: Clipping is the process of confining paint operations to a limited area or shape.

45. What is memory leak?

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

46. Can a for statementloop 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


2)1f amethod contains multiple
words, every inner word should start with an

:
Ex toString()
uppercase letter.

4)Method name must be combination of verb and noun

Ex :getCarName(),getCarNumber()
4S. Why Java is not a pure Object Oriented language?

Answer: Java supports primitive types such as int, byte, short, long,etc that 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 modifier. 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 publicstatic 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 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 aboutAutomatic type conversion in java?

Answer:
done the following conditions are met:
Java automatic type conversion is if

1)When two types are compatible

Ex: int, float

int can be assigned directly to float variable.

2) Destination type is larger than source type.

Ex: int, long.

assigned to long
to long .Automatic type conversion takes place
if int is
Int can be assigneddirectly

because long is larger datatype than int.

Widening Conversion comes under Automatic type conversion.

53.What is the difference betweenthe prefix and postfix forms of the ++ operator?

operation and returns the value of the increment


Answer: The prefix form performs the increment
all of the expression and
then performs the
the current value
operation. The postfix form returns
increment operation on that value.
handling in java?
S4. In how many ways we can do exception
Answer:
We can handle exceptions in either of the two ways :
where we can catch the exception.
1)By specifying a try-catch block
2) Declaring a method with 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: Employeeemployee;
In the above example employee obiect is not instantiate so it is pointed nowhere.

56.Can we define a packagestatementafter the importstatement in java?


Answer: We can't define a package statement after the importstatement 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
JAVAelements.
JSP page looks
using HTML, XML and
like a HTML page but is a servlet. It contains Presentation logic
andbusiness logic of. aweb application.

59.What is the purposeof apache tomcat?

Answer:Apache server isa standalone


server that is used to test servlets
and open sourcethat is integrated and create JSP pages.
in the Apache It is tree
web server. It is fast, reliable
applications but it is hard to server to configure
install. It is a servlet trne
the serverto run the container that
includes tools to
applications. It can also
configure and manag
be configured by
editing
Configuration
XML files.

60.Explain where
variables are created
in memory?
Answer: When we
declare variables are
created in the
variables get garbage stack. So when
collected. the variable is out of scope tno
we use catch statement for checked exceptions?
61. Can
our code then we can't declare catch block for
there is no chance of raising an exception in
Answer: If

raises a compile-time error if we try to handle checked exceptions


handling checked exceptions. This
when there is no possibility of causing an exception.

block will not be executed?


62. Explain a situation where finally
try
be executed wheneverJVM shutdowns. If we use system.exit(0) in
the block willnot
Answer: Finally,

block if present will not be executed.


statement finally

63.Whatis UNICODE?
and it uses 16 bits to
used for internal representation of characters and strings
Answer:Unicode is

represent each other.

in java?
64. Explain aboutthe main() method
point of execution for all java applications.
Answer: The main ()method is the starting
public static void main(String[] args) {}
command line arguments.
we need to pass from
String args[] are an array of string objects
must have at least one main method.
Every Java application

are defined in Java?


65. Define How destructors

class as there is no need to do so. Java has its


no destructors defined in the
Java, there are
Answer:In by destroying the objects when no
which does the job automatically
owngarbagecollection mechanism
longer referenced

of Round(3.7) and Ceil(3.7)?


66. What will be the output

4 and Ceil(3.7) returns 4.


returns
Answer:Round(3.7)

67.What is constructor in java?


toinitialize objects in the java.
a special method used
Answer:A constructor is
created. As and when an
all variables in the class when an object is

we use constructors to initialize

help of constructor in java.


is created it is initialized automatically with the
object
We have two types of constructors

Default Constructor

Parameterized Constructor
of an object on
the heap?
the size
the heap.
68. How can we find
actual
size of an object on
no way to find out the actual
In Java, there is
Answer:

be local and static at the same time?


69, Can a variable
variable as static
well as localat the same time. Defining a local

can't be static as
Answer: No avariable

gives compilation error.

methods in an Interface?
70. Can we have static

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

java?
71. In how rary wayswecardosyncronization in

Answer:
in java:
There are two ways to do synchronization

1) Synchronized methods

2)Synchronized blocks
To do synchronization we use the synchronized keyword.

blocks?
72. When use synchronized blocks and advantages of using synchronized
do we
then it is recommended to use synchronized
Answer: If very few lines of code require synchronization

over synchronized methods is it reduces the waiting


blocks. The main advantage of syn chronized blocks

time of threads and improves 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 nonaccess 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 modifiersfor 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 nonsubclass


4) In the different package subclass
5)Inthe different package nonsubclass.

default: class
A with default modifier can be accessed

1)In the same class


2) In the same package subclass
3) In the same package nonsubclass

4) In the different package subclass


5) In the different package nonsubclass. ()

76.Explain aboutabstract classes in java?


Sometimeswe may come across a situation where we cannot
provide implementation to all

Answer:
that extends it. In such a case,
the methods in a class. We want to leave
the implementation to a class

use keyword abstract. Any class that contains


we declare a class as abstract.To make aclass abstract we
declare a class as abstract which
one or more abstract methods is declared as abstract. If we don't
contains abstract to
We get the following error. "The type must be an abstract class
error.
methods wêget a compile-time

define abstract methods." Signature; abstract class.


to it because there may be
we take a vehicle class we cannot provide implementation
For example, if All the common
etc. At that moment
we make vehicle class abstract.

two-wheelers, four-wheelers, Any class which extends the


in vehicle class.
declared as abstract methods
features of vehicles are of subclass to provide the
implementation. It's the responsibility
vehicle willprovide its method

implementation.

classes are:
The important features of abstract

1)Abstract classes cannot


be instantiated.
or both.
abstract methods, concrete methods
2) Anabstract class contains of an abstract class.

abstract class must override all methods


3)Any class which extends
methods.
can contain either 0 or more abstract
4) An abstract class
superclass
we can create object references. Through
instantiate abstract classes
Though we cannot

references, we can point to subclass.

in abstract class? But


1.Can we create a constructor the abstract class, it doesn't give any
compilation error.

a constructor in
Answer:We can create
class.
forabstract
when we cannot a constructor
is nouse in creating
class there
instan tiate
String andStringBuffer
Can we compare
in

String objects.
both represent
78. String and 1 StringBuffer

Java? we can't compare them with


String objects,
both represent
and StringBuffer
String
Answer: Although
compare them,
we get an error.

each other and if we tryto

threads in java?
many ways we can create
79. In how
Answer:
:
java by any of the two ways
We can create threads in

1)By extending Thread class

2) By implementing the Runnable interface.

80.Explain creating threads by implementingRunnable class?


the runnable interface
Answer: This is the first and foremost way to create threads. By implementing
and implementing
the run() method we can create a new thread.

Method signature ;public void run()


Run is the starting point for execution for anotherthread within our program.
Example:
public class MyClass implementsRunnable {
@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
object, in such a scenario we can decare a manipulate the state of the
method as synchronized.

82.Can we cast any


othertypeto BooleanType
with type casting?
Answer:No,we can neither
cast any other primitive type to Boole an data
data typeto any other datatype. type nor can
primitive cast Booleai

83. What are


synchronized methods and synchronized
statements?
cwer:Synchronizedmethods are methods that are used to control access to an object. A
statement can only be executed after a thread has acquired the lock forthe object or class
synchronized
referenced in the synchronizedstatement.

84, Explain the importance of finally block in java?


up of resources such as closing connections, sockets, etc. it try
Answer: Finally block is used for cleaning

block executeswith no exceptionsthen finally is called after try block without executing catch block. If

executes immediatelyafter the catch block. If an


there is an exception thrown in try block finally block

exception is thrown, finally block will be executed even if the no catch block handles the exception.

85.Can we catch more thanone exception in a single catch block?


a single catch block. This type of
Answer: From Java 7, wWe can catch more than one exception with

handling reduces

the code duplication.


block, catch parameter is implicitly final.
than one exception in a single catch
Note: When we catch more
We cannot assign any value to catch parameter.
||ArithmeticException e)
Ex: catch(ArrayindexOutOfBoundsException

cannot assign any value or modify e in the


catch statement.
In the above example, e is final we

java?
86.What are abstract methods
in
method declared
doesn't have anybody. An
is
abstract
is a method which
Answer: An abstractmethod
in place of the method
body.
withkeyword abstractand semicolon
Signature :public abstractvoid ();

Ex : public abstractvoid get details(); to an abstractmeth od defined


in the
implementation
It is the responsibility of subclass to provide
abstract class.

java?
where exceptions may arise in
87.Statesomesituations
Answer:
not exist in the array.
1)Accessing an element that does
toa number.
of number to string and
string
<) Invalid conversion

(NumberFormat Exception)
3)The invalid casting of class
(Class cast Exception)
class
for interfaceor abstract
)Irying to create an object
(Instantiation Exception)
in java?
88. What isan exception
arise in our program.
Answer:
when abnormal situations
Exceptions are created
classes are defined
is an object. in
In java,an exception code. All Exception
by our application
can be created by JVM or
Exceptions
we can say Exception as a run time
error.

java.lang. In other words,

What is an error in Java? by our program we call


errors are caused
89.
class in java. When
Answer: Error is the subclass of Throwable environmental issues
such as
are caused due to some
but some times exceptions which cannot be
that as Exception, the exceptions. Exceptions
such cases, we can't handle
running out of memory.
In

recovered are called as errors in java.

Ex: Out of memory issues.

handling in java?
90. What are the advantages of Exception
Answer:
termination of the program.
handling code to avoid abnormal
1)Separating normal code from exception
handling all exceptions with
2) Categorizing into different
types of Exceptions so that rather than
specific exceptions. It is recommended
to handle exceptions
Exception root class we can handle with
Exception root class.
with specific Exception instead of handling with
a meth od throws an exception and it is not handled immediately, then that
3) Call stack mechanism: If

This propagation continues till it finds


exception is propagated or thrown to the caller of that method.
be handled otherwise program terminates
an appropriate exception handler, if it finds handler it would
Abruptly.

91. What's the difference betweenconstructors 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 methodscould be called many times.

92. Is there any limitation of using Inheritance?

Answer: Yes, since inheritance inheritseverything from the super class


and interface, it may make the
subclass tooclustering and sometimeserror-prone when dynamicoverriding or dynamicoverloading in
some situation.

93. Where and how can you use a private constructor?

Answer: Private constructor isused if youdo not want other classes to instantiate the obiect
prevent subclassing. andto
casting?
94. What is type

Type casting means treating a variable of one type as though it is another type.
Answer:

What is the difference between the >> and >>> operators?


95.

when The >>> bits that have been


Answer: The >> operator carries the sign bit shifting right. zero-fills

shifted
out.

a6 What is the difference between inner class and nested class?

then becomes inner class. If the


Answer: When a class is defined within a scopeof another class. it

access modifier of the inner class is static, then it becomes nested class.

from anotherif class has multiple constructors?


97.Can you call one constructor a

syntax.
Answer:Yes, use this()

classes?
98. Why do we need wrapper
also
expects an object. It

around as method parameters where a method


Answer:We can pass them
provides utility methods.

99. Does Java allow Default Arguments?

not allow Default Arguments.


Answer:No, Java does

denoted by leading zero in java?


100.Which number
is

java, example:06
leading zero in
Answer:Octal Numbers are denoted by

You might also like