0% found this document useful (0 votes)
2 views

java_interview_questions

Uploaded by

rohitha vusa
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_questions

Uploaded by

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

Core Java Interview Questions

1. What is java?

Java is an object oriented programming language originally developed by Sun Microsystems of U.S.A in 1991 and
released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS and the various versions of UNIX.

2. Who invented Java?

Invented by a James Gosling with his co-workers, those are

1. Patrick Naughton
2. Ed frank
3. Mike Sheridon
4. Chris warth

3. Does Java is a pure Object Oriented Programming Language?

No, it is partial Object Oriented Programming Language, because here in java everything is an object except
primitive data types. So we can’t say it is pure.

4. What are the most important features of Java?


Object oriented, platform-independent, robust and secure, multithreaded, dynamic and extensible.

5. What do you mean by platform independence?


We can run the java programs in any operating system (platform).

6. Is java is a programming language or a platform?


Java is both a programming language and a platform.

7. What is a JVM?
It is a software/runtime environment/virtual machine which is used to run the java programs

8. Are JVM’s are platform independent?


No, these are platform dependent. We have to install a separate JVM for every different operating system.

9. What is the difference between a JDK and a JRE?

1 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,


Land Line: 0866-6640526
JDK: When we install JDK both JDK (set of tools) and JRE will be installed. But when we install JRE only JVM,
JCL and other supported files will be installed

10. What is a pointer and does Java support pointers?


Pointer is a reference handle to a memory location. Improper handling of pointers leads to memory leaks and
reliability issues hence Java doesn't support the usage of pointers.

11. What is an object oriented programming?


Object-Oriented Programming is an approach which provides the way of modularizing the programs by using
classes and objects. It simplifies the software development and maintenance by providing some oops concepts
like:
1. Data abstraction & encapsulation
2. Polymorphism
3. Inheritance
12. What is a class?
• A class is the blueprint from which individual objects are created.
• A class is a user defined or an abstract data type which contains data (fields/variables/properties) and
methods (functions).
• A class is nothing but collection of objects
• A class is a template or a prototype for objects
13. What is an object
• Object is an instance of a class or a runtime entity
• Object creation is nothing but memory allocation for the instance fields of a class
• Objects are created at heap memory
• We can create any number of objects for a class
• Objects are independent
• Every object has a state identity and behavior
14. In how many ways we can create an object?

We can create an object in 4 ways

1. By using new operator and constructor calling


2. By using clone() method of Object class
3. By using newInstance() method of Class class
4. By using factory method.

15. What is object state?


The data which is existed in the object is called object state, for example student no, student name, marks are
the object state of the student object.
16. What is object identity?
What makes them unique is called it’s identify for example student_id of student class object or email of
student is also treated as object identity, or sometimes the reference variable which is pointing to the object is
also called as object identity.
17. What is Object behavior?
The method of the object is called as the behavior of the object
18. What is constructor?
A constructor is a special method, which has same name as class name. There are two types of constructors.
1. Default (non-parameterized)
2 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,
Land Line: 0866-6640526
2. Parameterize
19. What is the difference between default constructor and parameterized constructor?

Difference

Default constructor Parameterized


constructor
1. It is useful to initialize all objects with I. It is useful to initialize every object
same data. with different data.
2. It contains no parameters.
3. If you don’t create any constructor in a II. It contains one or more parameters.
class the compiler creates a default III. Parameterized constructors are not
constructor for that class. created defaultly at any time.
20. What is the use of Constructors?

• Constructors are used to initialize the object (instance variables).


• In constructors we write the code to establish the data base connections.
• And also used setting background and foreground colors etc…
• constructors are used to create object

21. Data abstraction


Process of hiding unnecessary details from the end user is called data abstraction.
22. Encapsulation:

Def-1: Process of binding data with methods is called encapsulation.


Def-2: Wrapping up of data and methods in to a single unit

23. What is Inheritance?


Process of including the members of a class into another class is called inheritance. Here a class which is being
inherited by other class is called as base or super or parent class and a class which inherits the members of the
base class is called as child or sub or derived class.

24. Does Java support Multiple Inheritance?


Multiple Inheritance has a drawback that is why Java doesn’t support multiple inheritance, but we can achieve it
through interfaces. See the below explanation it helps you to know about the drawback of multiple inheritance.

Explanation:
Base-1 Base-2
Which method I
display () have to inherit,
display ()
ooooof…I can’t
understand
Child

Compiler

3 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,


Land Line: 0866-6640526
Assuming that Base-1 and Base-2 has their own implementations for the display () method. Now Child
class is inheriting both Base-1 and Base-2 classes. If u compile the program compiler shows it as ambiguity error
because it will not able to understand which method has to inherit into child class, because of this draw back Java
doesn’t support multiple inheritance.

25. What is import?


Import is a keyword which is used to import a package or static members of a class.
26. What is a package?
A Package is a folder/container which contains collection of classes, interfaces, enums and annotation. A
package declaration statement must be the first statement in a java program.

27. What is the default package?


The “java.lang” package is the default package. It is imported by the Java compiler automatically at the time of
program compilation

28. What is static import?


Static import is used to import static variables and static methods of a class. If we import static members of
class, we can access them in our program without using class name.

29. Why the main method is always public?


Here public is an access modifier which makes the main () method unprotected (any where accessible). JVM
can call the main () only if it is declared as public with in class.

30. Why the main method is static?

• In Java, JVM always calls the main () method by using main method’s class name, so we have to declare
the main method as static.
(Or)

• Static is an access modifier, and we have to declare the main() method as static then only the JVM can call
the main () method directly without any memory allocation(object creation).

31. What is the argument of main () method?


The main () method accepts a single dimensional String type array as an argument.

32. What is the return type of the main () method?


In Java main () doesn't return anything, so we have to declared the main () method return type as void

33. What is the base class of all classes?


java.lang.Object class is the base class all classes in java, i.e every class in java inherits the members(fields
and methods) of the Object class.

34. Are arrays primitive data types?


In Java, Arrays are objects.

35. What is Path?


Path is an operating system level environment variable, which is used to set the path for .exe files. When you set
the path .exe files then we can access them from anywhere within the computer.
We can set the path in 2 ways
1. Temporary(if we set the path in command prompt)
4 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,
Land Line: 0866-6640526
2. Permanent (if we set the path in environment variables)

36. What is Classpath?


Classpath is an operating system level environment variable, which is used to set the path for packages or .class
files. When you set the path .class files then we can access them from anywhere within the computer.
1. If you set the classpath for .jar file then we can access all the packages and classes existed in that jar file
from anywhere within the computer.
2. If you set the classpath for a folder then we can access all the packages and classes existed in that folder
from anywhere within the computer.
We can set the class path in two ways
1. Temporary(set in command prompt)
2. Permanent (set int environment variables)

37. What are local variables?


• Local variables are those which are declared within a block of code like methods. Local variables should be
initialized before accessing them.
• Local variable doesn’t contain default values.

38. What are instance variables?


• Instance variables are those which are defined in the class outside the method.
• These variables are not declared as static
• These variables contain default values
• These variables are created(memory allocated) during every object creation

39. What is static variable

5 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,


Land Line: 0866-6640526
• It is a variable which is declared inside the class and outside the method and which is declared as
static
• These variable are created only once at the time of class loads into the memory (method area).
• These variables are also called as class variables
• This variable contains default values.

40. How many times a class will be loaded into the memory during a program execution?
A class always loads only once during program execution. The loaded class can be used any number of times by
the program.

41. How to define a constant variable in Java?


We can declare a constant variable by using final keyword. If we declare a final (constant) variable we can’t
change the value of it during program execution.
Ex: final int PI = 2.14;

42. Should a main () method be compulsorily declared in all java classes?


No not required. main() method should be defined only if the source class is a java application.

43. What is the return type of the main() method?


Main() method doesn't return anything hence declared void.

44. Why the main () method is declared static?


JVM always calls the main method by using class name not by using object, so we have to declare the main
method as static.

45. What is the argument of main() method?


main() method accepts a single dimensional String type array as an argument. Actually it is used to handle
command line arguments.

46. What are command line arguments?


These are arguments which are given through the command prompt at the time of giving command to run the
program.

6 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,


Land Line: 0866-6640526
47. If I don't provide any arguments on the command line, then the String array of Main method will be
empty or null?
It is empty. But not null.

48. Can a main () method be overloaded?


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

49. Can a main () method be declared final?


Yes. Any inheriting class will not be able to have its own default main () method.

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

51. Can a source file contain more than one class declaration?
Yes, a single source file can contain any number of Class declarations.

52. How many public classes we can write in a program?


We can write only one public class in a program. If we write public class in a program then the public class
name and file name must be same.

53. What is a package?


Package is a folder/container which contains collection of related classes, interfaces, enums and annotations.
Packages are off two types
1. user defined
2. predefinedv

54. What is the advantage of packages?

• Package is a both name and visibility control mechanism.


• We can define classes inside a package that are not accessible by code outside that package.
• Packages provides reusability.
• Packages are useful to arrange related classes and interfaces into a group.

55. Can we write a package statement anywhere within the class?


No, the package statement must be the first statement in our program.

56. Which package is imported by default?


java.lang package is imported by default even without a package declaration.

57. Can a class not declared by using any access modifier, can be accessible outside it’s package?
No, it’s not possible. Because if u don’t declare by using any access modifier then that class is only accessible
with a package (its scope becomes package private).

58. Can a class be declared as protected?


We can’t declare a class/interface/enum/annotation as either private or protected. We can only declare them as
either public or package private (no access modifier).

59. What is an inner class?


We can write a class with in another class it is called as inner class

60. Can we declare an inner class as private?


We can declare an inner class as either private, package private (no access modifier), protected or public
7 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,
Land Line: 0866-6640526
61. Can we declare an inner class as static?
Yes we can declare an inner class as static.

62. How many access modifiers are there in Java?


There are 3 access modifiers there in Java
1. private
2. protected
3. public
63. How many access controls levels are there?
There are 4 access controls levels are there
1. private: within a class
2. package private(default): within package
3. protected: within a package and child and sub child classes of other packages.
4. public: in any package

Scope Same Samepack non Same pack Other pack child class and other pack non
class subclass sub class sub child class subclass
Private Yes No No No No
Default Yes Yes Yes No No
Protected Yes Yes Yes Yes No
Public Yes Yes Yes Yes Yes

64. Is Empty .java file name a valid source file name?


Yes, save your java file by .java only, compile it by javac .java and run by java yourclassname Let's take a
simple example:
Example:
1. //save by .java only
2. class A{
3. public static void main(String args[]){
4. System.out.println("Hello java");
5. }
6. }
7. //compile by javac .java
8. //run by java A

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


A method declared as final can't be overridden.

66. I don't want my class to be inherited by any other class. What should I do?
You should declare your class as final. Then the final class can’t be inherited by other (child) classes.

67. Can we declare an abstract class as final?


No, we can’t declare abstract classes and enums and annotations and interfaces as final.

68. What is a concrete class?


It is a class which contains all implemented methods and we can create object for it.

69. What is abstract method?


It is a method which contains no implementation and declared as abstract.

70. What is concrete method?


8 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,
Land Line: 0866-6640526
It is an implemented method and which is not declared as abstract.

71. Can you give few examples of final classes defined in Java API?
java.lang.String, java.lang.Math, java.lang.System classes are final classes.

72. How is the difference between final, finally and finalize()?


• final is a modifier which can be applied to a class or a method or a variable. final class can't be inherited,
final method can't be overridden and final variable can't be changed.
• finally is a block used in exception handling. Which gets executed whether an exception is raised or not or
handled or not.
• finalize() is a method of Object class which will be executed by the JVM just before garbage collecting
object to give a final chance for resource releasing activity.

73. When will you define a method as static?


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.
74. What is the restriction imposed on a static method or a static block of code?
A static method should not refer to instance variables without creating an instance and cannot use "this"
operator to refer the instance.

75. I want to print "Hello" even before main() is executed. How will you acheive that?
Print the statement inside a static block of code. Static blocks get executed when the class gets loaded into the
memory and even before the creation of an object. Hence it will be executed before the main() method. And it
will be executed only once.

76. What is the importance of static variable?


• Static variables are also called as class variables, because these variables are created at the time of class
loads into the method area.
• These variables behave like global variables for all the objects of a same class.

77. Can we declare a static or instance variable inside a method?


We can’t declare static or instance variables inside a method. If we declare a variable in a method then it is
called as local variable.

78. What is an Abstract Class and what is its purpose?


A Class which doesn't provide complete implementation is defined as an abstract class. Abstract classes enforce
abstraction.

79. What is use of an abstract variable?


Variables can't be declared as abstract. Only classes and methods can be declared as abstract.

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


Not possible. Abstract classes can't be instantiated.

81. Can an abstract class be defined without any abstract methods?


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

82. Class C implements Interface I containing method m1 and m2 declarations. Class C has provided
implementation for method m2. Can I create an object of Class C?
No not possible. Class C should provide implementation for all the methods in the Interface I. Since Class C
didn't provide implementation for m1 method, it has to be declared as abstract. Abstract classes can't be
instantiated.

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


9 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,
Land Line: 0866-6640526
No not possible. Doing so will result in compilation error. public and abstract are the only applicable modifiers
for method declaration in an interface.

84. Can an Interface implement another Interface?


Interfaces can’t implement another interface.

85. Can an Interface extend another Interface?


Yes an Interface can inherit any number of interfaces at a time.

86. Can a Class extend more than one Class?


Not possible. A Class can extend only one class but can implement any number of Interfaces.

87. Why is an Interface be able to extend more than one Interface but a Class can't extend more than one
Class?
We know that Java doesn't allow multiple inheritance, because it has a drawback we have discussed in the
above sections so a Class is restricted to extend only one Class. But while implementing multiple inheritance by
using interfaces we can’t face such a problem, that is why an interface can extend any number of interfaces.

88. Can a class be defined inside an Interface?


Yes it's possible.

89. Can an Interface be defined inside a class?


Yes it's possible.

90. What is a Marker Interface?


It is an interface which contains no fields and no methods.

91. Can you tell me any two predefined marker interfaces?


Cloneable and Serializable are predefined marker interfaces.

92. Which object oriented Concept is achieved by using overloading and overriding?
We can achieve Polymorphism.

93. Why does Java not support operator overloading?


Operator overloading makes the code very difficult to read and maintain. To maintain code simplicity, Java
doesn't support operator overloading.

94. Can we define private and protected modifiers for variables in interfaces?
No, all the fields and methods of an interface are by default declared as public. So we can’t declare them as
private or protected.

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


Only public and abstract modifiers are allowed for methods in interfaces.

96. What value does read() return when it has reached the end of a file?
The read() method returns -1 when it has reached the end of a file.

97. Can a Byte object be cast to a double value?


Yes, because in 1.5 version a new feature was introduced called auto boxing, so the byte object will be
converted into primitive byte and then assigned to the double type variable. But in older version it’s not
possible.

98. What is the difference between a static and a non-static inner class?

10 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,


Land Line: 0866-6640526
a) Non Static Inner class: An inner class which is declared with a class and it is not declared as static is said
to be non static inner class. A Non Static Inner class can access all the members of the outer class directly.
But an outer class can’t access inner class members directly, it can access only by using the inner class
object.
Important points
• We can’t write static methods in non-static inner class.
• We can declare only constant fields as static i.e we can’t declare static variables in non-static inner
class.
• We can create Non-static inner class object outside the outer class if it is not declared as private.
• We have to create and use the outer class object, to create non-static inner class object outside the
outer class.
b) Static Inner classes:
• It is an inner class which is declared as static
• Static inner class can access only static members of the outer class directly
• We can’t use <outer-class-name>.this pointer int static inner class
• In the static inner class we can define any type of members(fields and methods)
• We can create static inner class object outside the outer class without using outer class object.
99. What is <Outer-Class-name>.this?
It is an Outer class pointer (object) which is used to access the outer class instance members in the Inner class
even though both Outer and Inner instance member names are same.

100. Can we create an inner class object outside the outer class?
Yes we can create an inner class object (it may be a static inner class or non-static inner class) outside the outer
class, If it is not declared as private. If the inner class is private we can’t create object outside the outer class.

101. How do you create an object for non-static inner class object outside the outer class?
We can create an object for non-static inner class object outside the outer class only by using outer class object,
so we have to create outer class object first, then we can create inner class object.
Ex: Outer o=new Outer();
Outer. Inner oi=o.new Inner();
102. How do you create an object for non-static inner class outside the outer class?
We can create an object for static inner class outside the outer class directly without using outer class object.
Observe the below example.
Ex: Outer. Inner oi=new Outer. Inner();

103. Can we use this and super keywords in a static block or static method?
We can’t use this or super or <outerclassname>.this within a static method or static block or static inner class.

104. When can an object reference be cast to an interface reference?


An object reference can be cast to an interface reference when the object implements the referenced interface.

105. What restrictions are placed on method overloading?


• Method name must be same
• Signature must be different

106. What is up and down casting?


Upcasting: Process of assigning Child type reference variable (Child object) to base type reference variable
(Base object) is called as up casting.
11 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,
Land Line: 0866-6640526
Child c=new Child();
//Upcasting
Base b=c;
Down casting:
Process of assigning Base type reference variable to Child type reference variable is called as down casting.
//down casting
Child c2=(Child)b;

107. What is a native method?


A native method is a method that is implemented in a language other than Java.

108. What are order of precedence and associativity, and how are they used?
Order of precedence determines the order in which operators are evaluated in expressions. Associatity
determines whether an expression is evaluated left-to-right or right-to-left.

109. Can an anonymous class be declared as implementing an interface and extending a class?
An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

110. Is null a keyword?


The null value is not a keyword.

111. Which characters may be used as the second character of an identifier, but not as the first character of an
identifier?

The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first
character of an identifier.

112. Does a class inherit the constructors of its super class?


A class does not inherit constructors from any of its super classes.

113. Name the eight primitive Java types.


The eight primitive types are byte, short, int, long, float, double, char, and Boolean.

114. What type of argument the switch statement can take?


A switch statement can take int, char, enum or string

115. What modifiers can be used with a local inner class?


A local inner class may be final or abstract.

116. When does the compiler supply a default constructor for a class?
The compiler supplies a default constructor for a class if no other constructors are provided.

117. What is the use of instanceof operator?


It is a relational operator and it is used to compare an object to a specified type
Example:
import static java.lang.System.*;
class Bhaskar//GrandFather
{}
class Antony extends Bhaskar//Father
{}
class Nikhil extends Antony//Child
{}
class Demo
{ public static void main(String args[])
12 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,
Land Line: 0866-6640526
{ //upcasting(widening reference conversion)
Bhaskar b=new Antony();
if(b instanceof Bhaskar)//yes
//if(b instanceof Antony)//yes
//if(b instanceof Nikhil)//no
out.println("Yes");
else
out.println("No");
}
}

118. What are the legal operands of the instanceof operator?

The left operand is an object reference or null value and the right operand is a class, interface, or array type.

119. Are true and false keywords?


The values true and false are not keywords.

120. What happens when you concat a double value to a String?


The result is a String object.

121. What is the difference between inner class and nested class?
When a class is defined within another class, then it becomes inner class. If the access modifier of the inner class is
static, then it becomes nested class.

122. What is numeric promotion?

Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-
point operations may take place. In numerical promotion, byte, char, and short values are converted to int values.
The int values are also converted to long values, if necessary. The long and float values are converted to double
values, as required.

123. What is the default value for a boolean type variable?

The default value of the boolean type is false.

124. What is the difference between the prefix and postfix forms of the ++ operator?

The prefix form performs the increment operation and returns the value of the increment operation. The postfix form
returns the current value of the expression and then performs the increment operation on that value.

125. What is method overriding?

We can write a method in child class which is already existed in base class. It is called as method overriding.

126. What are the rules we have to follow at the time of overriding a method
• Method name must be same
• Type, order, and number of parameters must be same
• Return type must be same
• If the base method is public, child method must be public or higher scope
• If the base method throws an exception, child method must throw same type or child type, or nothing.

13 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,


Land Line: 0866-6640526
• If the base method throws no exception, then child method must not throw any exception

127. Can a method be overloaded based on different return type but same argument type?

No, because the methods can be called without using their return type in which case there is ambiguity for the
compiler.

128. What is the difference between method overriding and overloading?


If we write a method in child class which is already existed in the base class is nothing but method overriding,
whereas overloading means writing more than one method with same name with different signature in a class.

129. What is constructor chaining and how is it achieved in Java?

A child object constructor always first needs to construct its parent (which in turn calls its parent constructor.). In
Java it is done via an implicit call to the no-args constructor as the first statement.

130. Which Java operator is right associative?

The = operator is right associative.

131. Can a double value be cast to a byte?

Yes, a double value can be cast to a byte.

132. What is the difference between a break statement and a continue statement?

A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A
continue statement is used to end the current loop iteration and return control to the loop statement.

133. Can a for statement loop indefinitely?

Yes, a for statement can loop indefinitely. For example, consider the following: for(;;);

134. What is the default value for a variable of type String?

The default value of an String type is null.

135. How are this() and super() used with constructors?

this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

136. What is data/object persistence:

Object persistence is the ability of an object to record its state in the file this is called data persistence. So it can be
reproduced in the future, perhaps in another environment.

137. What is object serialization?


Process of converting object state into a byte stream is called object serialization.

138. What is object Deserialization?


Process of converting a byte stream int to an actual object state is nothing but Deserialization.
14 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,
Land Line: 0866-6640526
139. How many approaches are there to serialization in java?

In general there are three approaches to serialization in java

1. Implement Serializable and use default protocol.


2. Implement Serializable and get a chance to modify the default protocol by using the following methods.
• writeObject()
• readObject(ObjectInputStream in)
3. Implement Externalizable and write your own protocol to implement serialization by using the following
methods.
• writeExternal(): a writeExternal() method for storing its state during serialization.
• readExternal(): a readExternal() method for restoring its state during deserialization.

140. What is a transient variable?

Transient variable doesn’t support serialization? I.e the value existed in the transient variables can’t be converted
into binary stream.

141. What is Externalizable?


Externalizable is an interface that enables you to define custom rules and your own mechanism for serialization

142. What is concurrency?


Concurrency is the ability of a program to execute several computations simultaneously.

143. What is the difference between processes and threads?


A process is a program in execution that has its own set of private resources (e.g. memory, open files, etc.). Threads,
in contrast to processes, live within a process and share their resources (memory, open files, etc.) with the other
threads of the process. The ability to share resources between different threads makes thread more suitable for tasks
where performance is a significant requirement.

144. Why a thread is called as light weight process?


Because these live within a process and share their resources (memory, open files etc.) with the other threads of the
process

145. In Java, what is a process and a thread?

In Java, processes correspond to a running Java Virtual Machine (JVM) whereas threads live within the JVM and
can be created and stopped by the Java application dynamically at runtime.

146. What is a scheduler?

A scheduler is the implementation of a scheduling algorithm that manages access of processes and threads to some
limited resource like the processor or some I/O channel.

147. How many threads does a Java program have at least?

Each Java program is executed within the main thread; hence each Java application has at least one thread.

15 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,


Land Line: 0866-6640526
148. How can a Java application access the current thread?
The current thread can be accessed by calling the static method currentThread() of the JDK class java.lang.Thread:

Example:
public static void main(String[] args)
{ long id = Thread.currentThread().getId();
String name = Thread.currentThread().getName();
out.println(id);
}

149. What properties does each Java thread have?

Each Java thread has the following properties:

• an identifier of type long that is unique within the JVM


• a name of type String
• a priority of type int
• a state of type java.lang.Thread.State
• a thread group the thread belongs to

150. What is the purpose of thread groups?

Each thread belongs to a group of threads. The JDK class java.lang.ThreadGroup provides some methods to handle
a whole group of Threads. With these methods we can, for example, interrupt all threads of a group or set their
maximum priority.

151. What are the different states of a thread?


States of a thread: every thread exists in some of the following five states, between it’s creation and destruction
those are.
1. New Born
2. Runnable
3. Running
4. Blocked
5. Dead

152. How do we set the priority of a thread?

The priority of a thread is set by using the method setPriority(int). To set the priority to the maximum value, we use
the constant Thread.MAX_PRIORITY and to set it to the minimum value we use the constant
Thread.MIN_PRIORITY because these values can differ between different JVM implementations.

153. How is a thread created in Java?

Basically, there are two ways to create a thread in Java.

We can create threads in two ways


• By extending a Thread class
• By Implementing a Runnable interface

16 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,


Land Line: 0866-6640526
Example: By extending Thread class

class MyThread extends Thread


{ public void run()
{ out.println(getName()+" Start");
for(int i=1;i<=10;i++)
{out.println(i);
}
out.println(getName()+" End");
}
}
class ThreadDemo1
{ public static void main(String args[])
{ MyThread mt=new MyThread();
mt.start();
}
}

Example: creation of a thread by implementing Runnable interface.

import static java.lang.System.*;


class MyThread implements Runnable
{ public void run()
{ Thread t=Thread.currentThread();
out.println(t.getName()+" Start");
for(int i=1;i<=10;i++)
{out.println(i);
}
out.println(t.getName()+" End");
}
}
public class RunnableDemo
{ public static void main(String args[])

17 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,


Land Line: 0866-6640526
{ MyThread mt=new MyThread();
Thread t=new Thread(mt);
t.start();
}
}

154. How do we stop a thread in Java?

To stop a thread one can use a volatile reference pointing to the current thread that can be set to null by other threads
to indicate the current thread should stop its execution:
Example:
private static class MyStopThread extends Thread
{ private volatile Thread stopIndicator;
public void start() {
stopIndicator = new Thread(this);
stopIndicator.start();
}
public void stopThread() {
stopIndicator = null;
}
@Override
public void run()
{
Thread thisThread = Thread.currentThread();
while(thisThread == stopIndicator) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}

155. Is it possible to start a thread twice?


No, after having started a thread by invoking its start() method, a second invocation of start() will throw an
IllegalThreadStateException.

156. What is the output of the following code?


public class MultiThreading
{ private static class MyThread extends Thread
{ public MyThread(String name)
{super(name);
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String[] args) {
MyThread myThread = new MyThread("myThread");
myThread.run();
}
}

18 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,


Land Line: 0866-6640526
The code above produces the output “main” and not “myThread”. As can be seen in line two of the main() method,
we invoke by mistake the method run() instead of start(). Hence, no new thread is started, but the method run() gets
executed within the main thread.

157. What is a daemon thread?


A daemon thread is a thread whose execution state is not evaluated when the JVM decides if it should stop or not.
The JVM stops when all user threads (in contrast to the daemon threads) are terminated. Hence daemon threads can
be used to implement for example monitoring functionality as the thread is stopped by the JVM as soon as all user
threads have stopped:
Example: MyThread mt=new MyThread();
mt. setDaemon(true);

158. How to convert a daemon thread to user thread?


Example: mt. setDaemon(false);

159. Is it possible to convert a normal user thread into a daemon thread after it has been started?

A user thread cannot be converted into a daemon thread once it has been started. Invoking the method
thread.setDaemon(true) on an already running thread instance causes a IllegalThreadStateException.

160. What is thread synchronization?


Synchronization is the way to see only one thread access one resource at a time.

161. In how many ways we can achieve synchronization in java

We can achieve synchronization In two ways

• By declaring methods as synchronized


• By using synchronized block

Examples

SynchDemo1.java(By declaring methods as synchronized)

19 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,


Land Line: 0866-6640526
import static java.lang.System.*;
class Monitor
{ synchronized public void display()
{ Thread t=Thread.currentThread();
out.print(t.getName()+" [");
for(int i=1;i<=10;i++)
out.print(i+" ");
out.println("]");
}
}
class MyThread1 extends Thread
{ Monitor m;
MyThread1(Monitor m)
{this.m=m;
}
public void run()
{m.display();
}
}
class MyThread2 extends Thread
{ Monitor m;
MyThread2(Monitor m)
{this.m=m;
}
public void run()
{m.display();
}
}
class SynchDemo1
{ public static void main(String arg[])
{ Monitor m=new Monitor();
MyThread1 t1=new MyThread1(m);
MyThread2 t2=new MyThread2(m);
t1.setName("First");
t2.setName("Second");
t1.start();t2.start();
}
}
SynchDemo2.java(by using synchronized block
SynchDemo2.java
import static java.lang.System.*;
class Monitor
{ public void display()
{ Thread t=Thread.currentThread();
out.print(t.getName()+" [");
for(int i=1;i<=10;i++)
out.print(i+" ");
out.println("]");
}
}
class MyThread1 extends Thread
{ Monitor m;
MyThread1(Monitor m)
{this.m=m;

20 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,


Land Line: 0866-6640526
}
public void run()
{ synchronized(m)
{m.display();
}
}
}
class MyThread2 extends Thread
{ Monitor m;
MyThread2(Monitor m)
{this.m=m;
}
public void run()
{ synchronized(m)
{m.display();
}
}
}
class SynchDemo2
{ public static void main(String arg[])
{ Monitor m=new Monitor();
MyThread1 t1=new MyThread1(m);
MyThread2 t2=new MyThread2(m);
t1.setName("First");
t2.setName("Second");
t1.start();
t2.start();
}
}

162. What is a deadlock?

Dead Lock: In a multithreaded program, if we do not synchronize multiple threads properly, a deadlock situation
may arise and if such a situation comes, the program simply hangs. Deadlock comes between synchronized threads
only. It occurs when two or more threads wait indefinitely for each other to obtain locks (that is, two threads
depends on each other).

163. Can we get a thread into Runnable state which is in blocked state.

Yes, by calling interrupt() method we can get a thread into Runnable state but an interrupted exception will be
thrown by the JVM.

164. What is inter-thread communication?

It is all about making synchronized threads communicate with each other cooperation is a mechanism in which a
thread is paused running in its critical section and another thread is allowed to run (or lock) in the same critical
section to be executed. It is implemented by following methods, which are existed in the java.lang.Object class.

• wait()
• notify()
• notifyAll()

21 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,


Land Line: 0866-6640526
165. What is the use of wait() method?

It causes current thread to release the lock and wait until either another thread invokes the notify () method or
notifyAll() method for this object, or a specified amount of time has elapsed.

166. What is the use of notify () method?


It makes the thread to move from blocked state to Runnable state.

167. What is the use of notifyAll() method?


It makes all the threads to move which are in blocked state to Runnable state

168. What is the use of join () method?

It makes the parent thread to wait until the present thread completes its task

169. What is difference between wait() and sleep() method?


wait() sleep()
1) The wait() method is defined in Object class. The sleep() method is defined in Thread class.
2) wait() method releases the lock. The sleep() method doesn't releases the lock.

170. Can we call the run() method instead of start()?

Yes, but it will not work as a thread rather it will work as a normal object so there will not be context-switching
between the threads.

171. What is static synchronization?


If you make any static method as synchronized, the lock will be on the class not on object.

172. What is Volatile?

Volatile is a modifier and it is useful in multi threaded program. In multi thread program each program maintains
cache of local variables for fast computing purpose. Updating the value will be done in cache not in main memory.
Declaring a variable volatile means
* There will be no cache maintained by each program that means all the changes made in main memory.
* Access to this variable acts as synchronized block.

163. What is exception handling?


Exception handling is a mechanism which is used to handle runtime errors. If we handle runtime errors the program
will not be terminated in middle of program execution.

173. What is an Exception?


An exception is an abnormal condition or an object thrown by the JVM at the run time error occurs. This exception
object contains runtime error information like what is the exception, where it was occurred, why it was occurred
etc…

174. Can you give me some cases when abnormal condition happens (runtime error occurs)?
There are many cases when abnormal conditions happen during execution of a program such as.
• If you try to read the data from a file which is not existed
• If you try to load a class dynamically, which is not existed
22 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,
Land Line: 0866-6640526
• Try to establish the connection to the data base by giving wrong URL or userid or password.
• If you try to divide a number by zero.
• When u r trying to parse non integer String into integer etc…

175. What is difference between Checked Exception and Unchecked Exception?


1) Checked Exception

• The direct child classes of Exception class are called as checked exceptions.
• Checked exceptions are checked at compile-time.
• These exceptions are also called as UnReported Exceptions.

2) Unchecked Exception

• These classes (Exceptions) are direct subclasses of RuntimeException class e.g.


ArithmeticException,NullPointerException etc
• Unchecked exceptions are not checked at compile-time.
• These exceptions are also called as reported exceptions.

176. What is the base class for Error and Exception?

Throwable.

177. What are the keywords which are used to manage exception handling in Java?

• try
• catch
• finally
• throw
• throws

178. What is the use of try block?


Try block is used to enclose the code or statements which might throw an exception.
179. What is the use of catch block?
We write a catch block to handle the exception, i.e a catch block can catch an exception thrown by the JVM.

180. Is it necessary that each try block must be followed by a catch block?

It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch
block OR a finally block.

181. What is finally block?

• finally block is a block that is always executed

182. Can finally block be used without catch?

• We can write a try block, with finally block without using catch block.

23 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,


Land Line: 0866-6640526
183. Is there any case when finally will not be executed?

finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that
causes the process to abort)

184. What is difference between throw and throws?


Throw Throws
It is used to throw an exception by the programmer explicitly Throws is used to throw unreported (checked)
exceptions out of a method.

185. Can an exception be re-thrown?


Yes. We can throw an exception which is already caught.

186. Can we write a try block without using catch or finally block.
Yes we can write because in 1.7 version of java a new feature was introduced called try with resources. For that no
need to write catch or finally block with try block.

187. What is exception propagation?

Forwarding the exception which is occurred in one method to the invoking method is known as exception
propagation.
188. Can we create our own exceptions?
Yes, we can create our own exceptions. If you create an exception by extending Exception class it will be a checked
exception and if we create an exception by extending RuntimeException class then it is called as un-checked
exception.
189. What is string?
It is nothing but collection of characters, to handle string in java we have different types of classes those are.

a. java.lang.String class(immutable & unsynchronized)


b. java.lang.StringBuffer(mutable & Synchronized) class
c. java.lang.StringBuilder(mutable & not Synchronized) class
d. java.util.StringTokenizer class(used to divide a string into no.of tokens)

190. What is the meaning of immutable in terms of String?

The simple meaning of immutable is unmodifiable or unchangeable. Once string object has been created, its value
can't be changed.
191. What is the difference between String and StringBuffer?
In case of strings, if a string is reassigned with a new value, a new location is created where the new value is stored
and the old location (where old value is stored) is garbage collected. That is, a string value cannot be changed in the
same location. This is called immutable and is an overhead to the processor and a negative point for performance.

In case of a String Buffer, if a value is changed, the location is not changed and in the old location only the
value changed.

192. Why string objects are immutable in java?

Because java uses the concept of string literal. Suppose there are 5 reference variables,all referes to one object
"sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables.
That is why string objects are immutable in java.

24 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,


Land Line: 0866-6640526
193. How many ways we can create the string object?

There are two ways to create the string object, by string literal and by new keyword.
Ex-1: String str=”MadhuTechSkills”;//using string literal
Ex-2: String str=new String(“MadhuTechSkills”);//using new operator

194. How many objects will be created in the following code?

1. String s1="Welcome"; // object will be created in the string constant pool and its address
stored in s1 variable
2. String s2="Welcome"; // JVM assigns the address the first object to the s2 variable
3. String s3="Welcome"; // JVM assigns the address the first object to the s3 variable also

195. What is string constant pool


It contains pool of string stored in Java Heap Memory. See the below example

196. Why java uses the concept of string literal?

To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).

197. What is the difference between StringBuffer and StringBuilder ?

Both are mutable objects but StringBuffer is synchronized whereas StringBuilder is not synchronized.

198. is it possible to call a private method of one class in another class?

• You can call the private method from outside the class by changing the runtime behaviour of the class.
• By the help of java.lang.Class class and java.lang.reflect.Method class, we can call private method from any
other class.

import java.lang.reflect.Method;
import static java.lang.System.*;
class One
{ private void sayHello()
{out.println("Hello... MadhuTechSkills");
}
25 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,
Land Line: 0866-6640526
}
public class Demo
{ public static void main(String[] args)throws Exception
{ Class c= Class.forName("One");
Method m =c.getDeclaredMethod("sayHello");
m.setAccessible(true);
m.invoke(c.newInstance());
}
}

199. How many types of memory areas are allocated by JVM?

JVM memory is divided into 5 types:

1. Class(Method) Area: classes are loaded into this memory


2. Heap: objects are created here
3. Stack: local fields are created here
4. Program Counter Register: it maintains the address of the next statement
5. Native Method Stack: local fields of native method are created here.

200. What is JIT compiler?


Just-in-Time compiler is a partial compiler, which translates the parts of the byte code like looping constructs into
machine code. It was especially introduced to make the program translation faster so performance will be increased.

201. What gives Java its 'write once and run anywhere' nature?
The bytecode, Java is compiled to be a byte code which is the intermediate language between source code and
machine code. This byte code is not platform specific and hence can be fed to any platform.

202. What is a class-loader?

The classloader is a subsystem of JVM that is used to load classes and interfaces.There are many types of
classloaders e.g. Bootstrap classloader, Extension classloader, System classloader, Plugin classloader etc.

203. What is an object class?

It is the base class for every class in java. That is the methods and fields existed in the object class will be inherited
by every class in java.

204. What a hashCode () method of Object class returns?

It returns the hashCode value which is generated based on the object’s address. This hashCode value is used to
compare objects but it returns true if both objects addresses are same.
Drawback: it can’t return true if two different objects contains same data.
To compare two object based on the data we have to override the hashCode() method.

205. What is the use of equals() method of object class?

It compares two objects based on the address and then returns either true or false.
Drawback: it can’t return true if two different objects contains same data.
To compare two object based on the data we have to override the equals () method.
26 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,
Land Line: 0866-6640526
206. When you are writing equals() method, which other method you need to override?

hashcode is the right answer. Since equals and hashCode have their contract, so overriding one and not other will
break the contract between them.
Here contract is nothing but in the Collection Framework we have two classes which store key value pairs as
elements called Hashtable and HashMap. These two classes use both the hashCode() method and equals() method
to compare objects.
See the below point to know how these two classes are compare two objects
1. There's no need to call hashCode if (obj1 == obj2)
2. If obj1!=obj2 then there’s a need to call the hashCode method
3. There's no need to call equals if hashCode differs
4. If hashCode is same, there’s a need to call calls the equals method also

207. What a toString() method of Object class returns?

It also returns the hashCode value in hexadecimal format.

208. Why we override the toString() method in child class?

We override the toString() method to see the object state.

209. Which method is automatically invoked if you try to print the object?

The toString() is automatically invoked. When you print object.

210. What is the use of clone() method of Object class.

It creates the copy for the present object.

211. What is garbage collector?

Garbage collector is a thread which de-allocates the objects which are in out of scope.

212. Can we invoke Garbage Collection explicitly?

Yes by using gc() method of System class we can call explicitly. Ex: System.gc();

213. Which method will be invoked by the Garbage collector at the time of object destruction?

The finalize() method.

214. What is Collection ?


Collection : A collection (also called as container) is an object that groups multiple elements into a single unit.

215. What is a Collections Framework?

27 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,


Land Line: 0866-6640526
Collections Framework: Collections framework provides unified architecture for manipulating and representing
collections.

216. What are the benefits of Java Collections Framework?


• Improves program quality and speed
• Increases the chances of reusability of software
• Decreases programming effort.

217. What is the Difference between Collection and Collections?

Collection Collections
It is an interface, which can be used to represent group It is a utility class, existed in java.util package it
of objects contains several utility methods which are used to sort,
search objects etc... of a collection.

218. What are the 9 key interfaces of collection Framework


• Collection
• List
• Set
• Sorted Set
• Navigable Set
• Queue
• Map
• Sorted Map
• Navigable Map

219. What do you know about collection interface?


1. If you want to represent group of objects as a single entity then we have to use collection interface.
2. It contains the methods which are applicable for any collection object. Some of those methods are used to
a. Add element
b. Remove element
c. Replace element
d. Is element is existed or not
e. Etc...
3. In general collection interface is consider as root interface of collection framework.
4. There is no concrete class which implements collection interface directly

220. What is a collection class?

It is a class which implements collection interface

221. What do you know about List interface?

List (I): It is the child interface of Collection, if we want to represent a group of individual objects as a single entity,
where duplicates are allowed and insert order must be preserved then we should go for list.

1. Duplicate are allowed.


2. It supports Insertion order.
3. It accepts null values.

28 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,


Land Line: 0866-6640526
222. What do you know about Set interface?

Set (I): It is the child interface of Collection, if we want to represent a group of individual objects as a single entity,
where duplicates are not allowed and insertion order not required. Then we should go for set interface.

• where duplicates are not allowed and insertion order not required
• it accepts null values

223. What is the difference between HashSet and LinkedHashSet?

A HashSet is unordered and unsorted Set. LinkedHashSet is the ordered version of HashSet.The only
difference between HashSet and LinkedHashSet is that LinkedHashSet maintains the insertion order. When we
iterate through a HashSet, the order is unpredictable while it is predictable in case of LinkedHashSet.
Note: TreeSet is sorted, it supports ascending order.

224. What type of objects we can store in a TreeSet?


• We can store objects which implements Comparable interface
• We can also pass objects which doesn’t implement Comparable interface, but in such a case we have to
pass the Comparator object to the constructor at the time of TreeSet Object creation.

225. Differences between List and Set

List Set
1. Duplicates are allowed 1. Duplicates are not allowed
2. Insertion order preserved 2. Insertion order not preserved
29 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,
Land Line: 0866-6640526
226. What do you know about Queue?

Queue (I): Queue is child interface of Collection; if we want to represent a group of individual objects prior to
processing () then we should go for queue. Usually queue follows first in first out order but Based on our
requirement we can implement our own priority order also.

227. Can u give me one example where we use queue?

Ex: before sending a mail we have to store all mail id’s in some data structure, in which order we added mail id’s in
the same order only mail should be delivered for this requirement queue is the best choice.

228. What is the difference between List,Set and Queue?

List Queue set


A list is an ordered list of objects, A queue is also ordered, but you'll A set is not ordered and cannot
where the same object may well only ever touch elements at one end. contain duplicates. Any given object
appear more than once. For All elements get inserted at the either is or isn't in the set. {7, 5, 3,
example: [1, 7, 1, 3, 1, 1, 1, 5]. It "end" and removed from the 1} is the exact same set as {1, 7, 1,
makes sense to talk about the "third "beginning" (or head) of the queue. 3, 1, 1, 1, 5}. You again can't ask for
element" in a list. You can add an You can find out how many the "third" element or even the
element anywhere in the list, change elements are in the queue, but you "first" element, since they are not in
an element anywhere in the list, or can't find out what, say, the "third" any particular order. You can add or
remove an element from any element is. You'll see it when you remove elements, and you can find
position in the list. get there. out if a certain element exists (e.g.,
"is 7 in this set?")
229. What is priority Queue?

An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to
their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is
used. A priority queue does not permit null elements. A priority queue relying on natural ordering also does not
permit insertion of non-comparable objects (doing so may result in ClassCastException).

230. What is blocking queue?

A normal Queue will return null when accessed if it is empty, while a BlockingQueue blocks if the queue is empty
until a value is available.
30 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,
Land Line: 0866-6640526
231. What is PriorityBlockingQueue?

An unbounded blocking queue that uses the same ordering rules as class Priority Queue and supplies blocking
retrieval operations. While this queue is logically unbounded, attempted additions may fail due to resource
exhaustion (causing OutOfMemoryError). This class does not permit null elements. A priority queue relying on
natural ordering also does not permit insertion of non-comparable objects (doing so results in ClassCastException).

232. What is LinkedBlockingQueue?

An optionally-bounded blocking queue based on linked nodes. This queue orders elements FIFO (first-in-first-out).
The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that
element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the
queue retrieval operations obtain elements at the head of the queue. Linked queues typically have higher throughput
than array-based queues but less predictable performance in most concurrent applications.

233. What is a map?

1. It is not child interface of Collection interface but it is the part of Collection Framework
2. If you want to represent a group of objects a key value pairs then we should go for Map
3. Duplicate keys are not allowed but the values can be duplicated
4. Both key and values are objects only

234. What is SortedMap?

it is the child interface of Map. If we want to represent a group of key, value pairs according to some sorting order of
keys, then we should go for sorted map.

1. In SortedMap the sorting should be based on key but not based on value.

235. What is Navigable Map?

It is the child interface of SortedMap. It defines several methods for Navigation Purposes.

236. What is TreeMap?

It is the implemented class for Navigable Map interface; it is sorted according to the natural ordering of its keys or
by a Comparator provided at map creation time, depending on which constructor is used.

31 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,


Land Line: 0866-6640526
237. What is the difference between ArrayList and Vector?
No. ArrayList Vector
1) ArrayList is not synchronized. Vector is synchronized.
2) ArrayList is not a legacy class. Vector is a legacy class.
3) ArrayList increases its size by 50% of the array size. Vector increases its size by doubling the array size.

238. What is the difference between ArrayList and LinkedList?


No. ArrayList LinkedList
1) ArrayList uses a dynamic array. LinkedList uses doubly linked list.
2) ArrayList is not efficient for manipulation because a lot of shifting is LinkedList is efficient for
required. manipulation.
3) ArrayList is better to store and fetch data. LinkedList is better to manipulate
data.

239. What is the difference between Iterator and ListIterator?

Iterator traverses the elements in forward direction only whereas ListIterator traverses the elements in forward and
backward direction.

No. Iterator ListIterator


1) Iterator traverses the elements in forward ListIterator traverses the elements in backward and forward
direction only. directions both.
2) Iterator can be used in List, Set and Queue. ListIterator can be used in List only.

240. What is the difference between Iterator and Enumeration?


No. Iterator Enumeration
1) Iterator can traverse legacy and non-legacy elements. Enumeration can traverse only legacy elements.
2) Iterator is fail-fast. Enumeration is not fail-fast.
3) Iterator is slower than Enumeration. Enumeration is faster than Iterator.

241. What is fail-fast?


When a problem occurs, a fail-fast system fails immediately. In Java, we can find this behavior with iterators. In
case, you have called iterator method on a collection object, and another thread tries to modify the collection object,
then concurrent modification exception will be thrown.

242. What is the difference between HashSet and TreeSet?


HashSet maintains no order whereas TreeSet maintains ascending order.

243. What is the difference between Set and Map?


Set contains values only whereas Map contains key and values both.

244. What is the difference between HashSet and HashMap?


HashSet contains only values whereas HashMap contains entry(key,value). HashSet can be iterated but HashMap
need to convert into Set to be iterated.

245. What is the difference between HashMap and TreeMap?


HashMap maintains no order but TreeMap maintains ascending order.

246. What is the difference between HashMap and Hashtable?


No. HashMap Hashtable
1) HashMap is not synchronized. Hashtable is synchronized.
32 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,
Land Line: 0866-6640526
2) HashMap can contain one null key and multiple null Hashtable cannot contain any null key or null
values. value.

247. What is the difference between Collection and Collections?


Collection is an interface whereas Collections is a class. Collection interface provides normal functionality of data
structure to List, Set and Queue. But, Collections class is to sort and synchronize collection elements.

248. What is the difference between Comparable and Comparator?


No. Comparable Comparator
1) Comparable provides only one sort of sequence. Comparator provides multiple sort of
sequences.
2) It provides one method named compareTo(). It provides one method named compare().
3) It is found in java.lang package. it is found in java.util package.
4) If we implement Comparable interface, actual class is Actual class is not modified.
modified.

249. How to synchronize List, Set and Map elements?


Yes, Collections class provides methods to make List, Set or Map elements as synchronized:

public static List synchronizedList(List l){}


public static Set synchronizedSet(Set s){}
public static SortedSet synchronizedSortedSet(SortedSet s){}
public static Map synchronizedMap(Map m){}
public static SortedMap synchronizedSortedMap(SortedMap m){}

250. What is the advantage of generic collection?


If we use generic class, we don't need typecasting. It is typesafe and checked at compile time.

251. What is hash-collision in Hashtable and how it is handled in Java?


Two different keys with the same hash value is known as hash-collision. Two different entries will be kept in a
single hash bucket to avoid the collision.

252. What is a Dictionary class?


It is a class, which provides the capability to store key-value pairs.

253. What is Dynamic Binding?


At the time of running the program JVM decides which member has to execute. This is nothing but Dynamic binding.
Only instance methods support dynamic binding. Dynamic binding depends on the object type. It is also called as late
binding.

254. What is Static Binding?


At the time of program compilation compiler decides which member has to call and execute at run time, this is
nothing but Static binding. All the members except instance methods support static binding. Static binding
depends on the reference variable type. It is also called as early binding.

255. Can we synchronize the run method?

33 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,


Land Line: 0866-6640526
Synchronizing the run() method of a Runnable is completely pointless unless you want to share the Runnable among
multiple threads and you want to sequentialize the execution of those threads. This is basically a contradiction in
terms.
There is in theory another much more complicated scenario in which you might want to synchronize the run()
method, which again involves sharing the Runnable among multiple threads but also makes use of wait() and
notify(). I've never encountered it in 14+ years of Java.
Example:
import static java.lang.System.*;
class One implements Runnable
{ synchronized public void run()
{ for(int i=1;i<=10;i++)
out.println(Thread.currentThread().getName()+":\t"+i);
}
}
class ThreadDemo1
{
public static void main(String args[])
{ One o=new One();
Thread t1=new Thread(o);
Thread t2=new Thread(o);
Thread t3=new Thread(o);
t1.start();
t2.start();
t3.start();
}
}

256. How to run the code? Is it compiled or executed?

class Outer {
private static class Inner {
public static void main(String[] args) {
System.out.println("Hello from Inner!");
}
}
}

Ans: yes it will be compiled and execute successfully


C:\ >javac Outer.java
C:\ >java Outer$Inner
Hello from Inner!

257. Can we call a public static method of One class (class is not public) of package p1 in another class of
package p2?

Yes, we can do it by using reflections concept, see the below example


package p1;
import static java.lang.System.*;
class One
{ public One()
{}
int add(int a,int b)
34 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,
Land Line: 0866-6640526
{return a+b;
}
float add(int a,float b)
{return a+b;
}
public static String hai()
{return "Hello";
}
}

Compile: E:\NUBatch>javac -d . One.java

Demo2.java
package p2;
import static java.lang.System.*;
import java.lang.reflect.*;
class Demo2
{ public static void main(String args[])throws Exception
{ Class c=Class.forName("One");
out.println(c.getName());
Method m=c.getMethod("hai");
//out.println(c.newInstance());
m.setAccessible(true);
out.println(m);
out.println(m.invoke(c));
//One o1=new One();
}
}

E:\NUBatch>javac -d . Demo2.java
E:\NUBatch>java p2.Demo2
p1.One
public static java.lang.String p1.One.hai()
Hello

258. Why a class containing a main method doesn't need to be public in Java?
Because the JVM uses reflections concept to call the main method, by using reflections we can bypass the access
privileges.

35 Dno: 39-8-39, Pidaih Street,Labbipet, BandarRoad,Vijayawada-10, Ph.No:99124 86062,99489 63306,


Land Line: 0866-6640526

You might also like