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

Java Interview Q&A

The document contains a comprehensive list of Java interview questions and answers covering various topics such as classes, JVM, data types, inheritance, access modifiers, exception handling, and more. It serves as a resource for individuals preparing for Java interviews by providing clear explanations and examples. Key concepts include method overloading, synchronization, Java coding standards, and the differences between various Java components.

Uploaded by

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

Java Interview Q&A

The document contains a comprehensive list of Java interview questions and answers covering various topics such as classes, JVM, data types, inheritance, access modifiers, exception handling, and more. It serves as a resource for individuals preparing for Java interviews by providing clear explanations and examples. Key concepts include method overloading, synchronization, Java coding standards, and the differences between various Java components.

Uploaded by

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

kasperanalytics.

com

9123820085

JAVA INTERVIEW
QNAS

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

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

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

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: 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
programmer cannot specify the friendly identifier explicitly.

12. What is are packages?

Answer: A package is a collection of related classes and interfaces


providing access protection and namespace management.

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

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 super class by subclasses.

14. Can we rethrow the same exception from 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

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

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 world should start with
Uppercase character. Ex : string,value,empName,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

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

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 “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

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

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.

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

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 usefulcapabilities, 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 breaks the referential transparency Global


variables creates collisions in namespace.

39. What are different types of access modifiers?

Answer: public: Any thing declared as public can be accessed from


anywhere. private: Any thing declared asprivate can’t be seen outside of
its class. protected: Any thing declared as protected can be
accessedby classes in the same package and subclasses in the other
packages. default modifier : Can beaccessed 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.

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

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.

Iterator is an Interface implemented 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 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.

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

45. What is memory leak?

Answer: 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 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 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
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.

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

50. Can we overload the main method?


Answer: Yes, we can overload the main method with syntax as 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 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 about 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 int can be assigned directly
to float variable.
2) Destination type is larger than source type. Ex: int, long.

Int can be assigned directly to long .Automatic type conversion takes


place if int is assigned to long because long is larger datatype than int.

Widening Conversion comes under Automatic type conversion.

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

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 all of the expression 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 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 employee object is not instantiate 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.

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

58. What is JSP?

Answer: JSP is a technology that returns dynamic content to the Web


client using HTML, XML and JAVAelements. JSP page looks like a HTML
page but is a servlet. It contains Presentation logic andbusiness 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 in the Apache web server. It is 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 catch statement for checked exceptions?

Answer: If there is no chance of raising an exception in our code then


we can’t declare 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 finally block will not be executed?

Answer: Finally, the block will not be executed whenever JVM


shutdowns. If we use system.exit(0) in try statement finally block if
present will not be executed.

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

63. What is UNICODE?

Answer: Unicode is used for 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 owngarbage 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 constructor in java?

Answer: A constructor is a special method used to initialize objects in


the 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 constructor in java.

We have two types of constructors Default Constructor Parameterized


Constructor

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

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 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 implementing 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 performance of the system.

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

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 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 nonsubclass
4. In the different package subclass
5. In the different package nonsubclass.

default: A class 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. ( )

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

76. Explain about 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 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 vehicle class abstract. All the
common features of vehicles are declared as abstract methods in
vehicle class. Any class which extends the vehicle will provide its
method implementation. It’s the responsibility of 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 abstract class must override all
methods of an abstract class.
4. An abstract class can contain either 0 or more abstract methods.
5. Though we cannot instantiate abstract classes we can create
object references. Through superclass references, we can point to
subclass.

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

77. Can we create a constructor in 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 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 by any of the two ways :
1. By extending Thread class
2. By implementing the Runnable interface.

80. Explain creating threads by implementing 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()

Run is the starting point for execution for another thread within our
program. Example :

public class MyClass implements Runnable { @Override

public void run()

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

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 typeto 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 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 finally block in java?

Answer: Finally block is used for cleaning up of resources such as


closing connections, sockets, etc. if try block executes with no
exceptions then finally is called after try block without executing catch
block. If there is an exception thrown in 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,

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

catch parameter is implicitly final. We cannot assign any value to 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 which 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 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 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 as a run time error.

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

89. What is an error in Java?

Answer: Error is the subclass of Throwable class in java. When errors


are caused by our program we call that as Exception, but some times
exceptions are caused due to some environmental issues such as
running out of memory. In such cases, we can’t handle the exceptions.
Exceptions which cannot be recovered are called as 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 Exception 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 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 of using Inheritance?

Answer: Yes, since inheritance inherits everything from the super class
and interface, it may make the subclass too clustering and sometimes

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

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 type casting?

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-fills bits that have been shifted out.

96. What is the difference between inner class and nested class?

Answer: When a class is defined within a scope of another class, then it


becomes inner class. If the access modifier of the inner class is static,
then it becomes 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.

hr@kasperanalytics.com

kasper-analytics
kasperanalytics.com

9123820085

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, example:


06

hr@kasperanalytics.com

kasper-analytics

You might also like