Core Java Interview Questions

Top most important Core Java interview questions and answers by Experts:

Here is a list of Top most important Core Java interview questions and answers by Experts.If you want to download Core Java interview questions pdf free ,you can register with RVH techguru. Our experts prepared these Core Java interview questions to accommodate freshers level to most experienced level technical interviews.

If you want to become an expert in Core Java ,Register for Core Java online training here.


1. What is Java technology ?
Java is a programming language, application development and deployment environment. Java programming language is similar to C++ syntax. Java development environment provides tools – Compiler, Interpreter, Packaging Tool etc.

2. What are the objectives of Java Technology ?
Simple: The language syntax is based on the familiar programming language ‘C++’. Though the syntax of ‘C++ was adopted, some features which were troublesome were avoided making the Java programming simple.
Object oriented: The object oriented features of Java are comparable to C++. One major difference between Java and C++ lies in multiple inheritance. Object oriented design is a technique that focuses design on data (i.e.objects) and on the interfaces to it.
Architectural Neutral: The Java compiler generates an intermediate byte code which does not depend on any architecture of a computer i.e., whether it is an IBM PC, a Macintosh, or a Solaris system. So the Java programs can be used on any machine irrespective of its architecture and hence the Java program is Architectural Neutral.
Portable type: The size of data types are always same irrespective of the system architecture. That is an int in Java is always 32 bit unlike in C/C++ where the size may be 16-bit or 32-bit depending on the compiler and machine. Hence when ported on different machines, there does not occur any change in the values the data types can hold. And also Java has libraries that enables to port its application on any systems like UNIX, Windows and the Macintosh systems.
Distributed: Java’s networking capabilities are both strong and easy to use. Java applications are capable of accessing objects across the net, via URLs as easy as a local file system.
Secure: Since Java is mostly used in network environment, a lot of emphasis has been placed on security to enable construction of virus free and tamper free systems.
Smaller code: The Java compiler generates an intermediate byte code to make it architecture neutral. Though Java interpreter is needed to run the byte code, it is one copy per machine and not per program.
Multithreaded: Multithreading is the ability for one program to do more than one task at once. Compared to other languages it is easy to implement multithreading in Java.
Interpreted: The Java Interpreter can execute Java byte code, directly on any machine to which the interpreter has been ported. Interpreted code is slower than compiled code.
High performance: The byte codes can be translated at run time into machine code for the particular CPU on which the application is running.

Applet programming: is one of the important features which has attracted the users of the Internet. Applets are Java programs that are typically loaded from the Internet by a browser.
3. What are the Major Features of Java Technology Architecture ?
• Java Run Time Environment
• Java Virtual Machine
• Just in Time Compiler
• Java Tools
• Garbage Collector
4. What is Java Virtual Machine (JVM) ?
A self-contained operating environment that behaves as if it is a separate computer. For example, Java applets run in a Java virtual machine (VM) that has no access to the host operating system.
Java Compilers compile JAVA source code into byte code. Java Virtual Machine(JVM) interpreters Java byte code and send necessary commands to underlying hardware or Just in time compiled to native machine code and execute it directly on the underlying hardware . Most JVM’s use Just in time compilation which provides execution speeds near to C or C++ application. Most widely used JVM is Oracle Corporations HotSpot, which is written in the C++ programming language.
5. What are the advantages of JVM?

This design has two advantages:
• System Independence: A Java application will run the same in any Java VM, regardless of the hardware and software underlying the system.
• Security: Because the VM has no contact with the operating system, there is little possibility of a Java program damaging other files or applications.
6. What are classpath variables?
Classpath is an environment variable that tells the Java Virtual Machine where to look for user-defined classes and packages in Java programs. The Classpath is the connection between the Java runtime and the filesystem. It defines where the compiler and interpreter look for .class files to load. The basic idea is that the file system hierarchy mirrors the Java package hierarchy, and the Classpath specifies which directories in the filesystem serve as roots for the Java package hierarchy.
7. What is Java Run Time Environment ?
Java Virtual Machine (JVM) along with Java Class Libraries which implement the Java application programming interface (API) form the Java Runtime Environment (JRE).
8. What are the steps involved in Java Application Execution ?
• Compiling Java Source Files into *.class file. (Byte Code)
• Loading class file into Java Run Time (JRE) using class loader
• Use Bytecode verifier to check for byte code specification
• Use Just In time Code Generator or Interpreter for byte code execution
9. What is Just in Time Compiler ?
Just in time Compiler (JIT) compiles JAVA byte code to native machine code and execute it directly on the underlying hardware. Just in time compilation which provides application execution speeds near to C or C++ application.
10. What is Java Development Kit (JDK) ?
Java Development Kit (JDK) is a super set of the JRE, which contains Java Run-time Environment (JRE) , Compilers and debuggers required to develop applets and applications.
11. What is Garbage Collector ?
For executing programs, application are allocated memory at runtime. After execution of programs, unused memory need to be allocated. Allocation and deallocation of memory is done by programmers developing application using C, C++ programming language . Java internally uses garbage collector to deallocate unused memory which make the life of programmer easy.
12. What is class loader ?
Class loader is used to load all the classes required execute the application into Java Virtual Machine (JVM). After the class is loaded memory required for the application is determined.
13. What is byte code verifier ?
Byte code verifier checks for illegal code like forges pointers, violated access rights on objects etc. in complied byte code.
14. What are the java verifications done by byte code verifier ?
1. Check whether classes follow JVM specification for classes
2. Check for stack overflows
3. Check for access restriction violations
4. Illegal data conversions
15. What is Java API?

An application programming interface (API) is a library of functions that Java provides for programmers for common tasks like file transfer, networking, and data structures.
16. Give Some examples of Java API.
• Java.applet – Applet class
• Java.awt – Windows, buttons, mouse, etc.
• Java.awt.image – image processing
• Java.awt.peer – GUI toolkit
• – System.out.print
• Java.lang – length method for arrays; exceptions
• – sockets
• Java.util – System.getProperty
17. What is an applet?

An applet is a small Java program that runs within a web page on your browser. Unlike a traditional desktop application, an applet is severely limited as to what it can perform on your desktop.
• Applet read and write files.
• Applet integrates with desktop services (e.g., e-mail).
• It is connected to other servers.
• It is also built with security in mind.
• If the user allows, an applet can be given more authority.
18. What is a class?

A class is a blueprint or prototype that defines the variables and the methods common to all objects of a certain kind.
19. What is an object?

An object is a software construct that encapsulates data, along with the ability to use or modify that data, into a software entity. An object is a self-contained entity which has its own private collection of properties (ie. data) and methods (i.e. operations) that encapsulate functionality into a reusable and dynamically loaded structure.
20. What an object contains?

An object has – State and Behavior
21. What is object oriented program?
An Object-Oriented Program consists of a group of cooperating objects, exchanging messages, for the purpose of achieving a common objective.
22. What are the benefits of OOPS?
• Real-world programming
• Reusability of code
• Modularity of code
• Resilience to change
• Information hiding
23. What are the features of OOPS?
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism

24. What is encapsulation?
Encapsulation is the ability of an object to place a boundary around its properties (i.e. data) and methods (i.e. operations). Grady Booch, defined the encapsulation feature as:
“Encapsulation is the process of hiding all of the details of an object that do not contribute to its essential characteristics.”
25. What is abstraction?
An Abstraction denotes the essential characteristics of an object that distinguishes it from all other kinds of objects and thus provides crisply defined conceptual boundaries, relative to the perspective of the viewer.
26. What is the difference between encapsulation and abstraction?
Encapsulation hides the irrelevant details of an object and Abstraction makes only the relevant details of an object visible.
27. What is inheritance?

Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. It enables you to add new features and functionality to an existing class without modifying the existing class.
28. What is superclass and subclass?
• A superclass or parent class is the one from which another class inherits attributes and behavior.
• A subclass or child class is a class that inherits attributes and behavior from a superclass.

29. What is JIT compiler?

Just-In-Time(JIT) compiler:It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.
30. What are the types of inheritance?
• Single inheritance
• Multiple inheritance

31.What is platform?

A platform is basically the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-based. Java provides software-based platform.

32. What is classloader?

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.

33. What is polymorphism?
Derived from two Latin words – Poly, which means many, and morph, which means forms.
• It is the capability of an action or method to do different things based on the object that it is acting upon.
• In object-oriented programming, polymorphism refers to a programming language’s ability to process objects differently depending on their data type or class.
34. Describe method overloading with example?
Java allows to define several methods with same name within a class. Methods are identified with the parameters set based on:
• the number of parameters
• types of parameters and
• order of parameters.
Compiler selects the proper method. This is called as Method overloading. Method overloading is used perform same task with different available data. For Example:
int sum(int a,int b) { return a+b;}
int sum(int a,int b,int c) { return a+b+c;}
float sum(float a, float b, float c) { return a+b+c;}
35. How to identify starting method of a program ?
Method starting with following code
public static void main (String args[])

36. How do we access data members of a class in java?
Dot Operator(.) is used to access the data members of a class outside the class by specifying the data member name or the method name.

37. What is “this” reference in java?

“this” is a reference to the current object. “this” is used to refer to the current object when it has to be passed as a parameter to a method.
refer to the current object when it has to be returned in a method. Refer the instance variables if parameter names are same as instance variables to avoid ambiguity.
public void method1(String name){;
The this keyword included with parenthesis i.e. this() with or without parameters is used to call another constructer. The default construct for the Car class can be redefined as below
public Car(){
The this() can be called only from a constructor and must be the first statement in the constructor
38. What are the uses of Java packages?
“A package is a namespace that organizes the a set of related classes and interfaces. It also defines the scope of a class. An application consists of thousands of classes and interfaces, and therefore, it is very important to organize them logically into packages. By definition, package is a grouping of related types providing access protection and name space management.” Packages enable you to organize the class files provided by Java.
39. What is the significance of import keyword?

The classes in the packages are to be included into the applications as required. The classes of a package are included using import keyword. The import keyword followed by fully qualified class name is to be placed before the application class definition.
import classname ;
// Class Definition.
Ex: import Java.util.Date;
// Class Definition
above indicates to import all the classes in a package.
All the classes in Java.lang package are included implicitly.
40. What is user defined package in java?
When you write a Java program, you create many classes. You can organize these classes by creating your own packages. The packages that you create are called user-defined packages. A user-defined package contains one or more classes that can be imported in a Java program.
package land.vehicle;
public class Car
String brand;
String color;
int wheels;
41. How to compile a Java Source file ?
From command prompt, Go to location in which Java file is located. Enter command “javac” followed by Java source file name. For example, To compile person class, type command “javac” . Class files will be generated in the same location
42. How to compile all the files in a Folder?
javac *.java”
43. How to place compiled Java file in a different location ?
To compile Java classes and place all the file in a different location use command “javac -d ../Java/All/*.java”
44. How to run a compiled Java file ?
Go to location in which Java file is located from command prompt. Enter command “java” followed by class name . For example to execute Employee class, type command “java Employee”
45. Why Information hiding is used and how Information hiding is implemented in Java ?
In order to avoid direct access of an attribute in a class, attributes are defined as private and use getter and setter to restrict the access of attributes in a class. Example class is given below
public class Person {
private String FirstName;

public String getFirstName()
return FirstName;
public void setFirstName(String FirstName)
this.FirstName = FirstName;
46. What is a Constructor ?
A constructor is a special method that initializes the instance variables. The method is called automatically when an object of that class is created. A constructor method has the same name as the that of the class.
A constructor always returns objects of the class type hence there is no return type specified in its definition. A constructor is most often defined with the accessibility modifier “public” so that every program can create an instance but is not mandatory. A constructor is provided to initialize the instance variables in the class when it is called.
If no constructor is provided, a default constructor is used to create instances of the class. A default Constructor initializes the instance variables with default values of the data types. If at least one constructor is provided , default constructor is not provided by JVM. A class can have multiple constructors.
class Car {
String brand;
String color;
int wheels;
int speed;
int gear;
public Car() {

public Car(String b, String c, int w, int s, int g)

void accelerate(){}
void brake(){}
void changeGear(){}
47. What is access modifier and what are its types?
An attribute that determines whether or not a class member is accessible in an expression or declaration. Different types of access modifiers are:
• Public – Members are accessible to the class and to other classes.
• Private – Members are accessible only to the class.
• Protected – Members are accessible only to the class and its subclass(es).
• Default – Members are accessible only to the class and other classes within that package. This is the default access specifier.

48. What is final keyword?
A final data members cannot be modified. A final method cannot be overridden in the subclass. A class declared as final cannot be inherited .
49. What is static keyword?
Static keyword is used to define data members and methods that belongs to a class and not to any specific instance of a class. Static Methods and data members can be called without instancing the class.A static member exists when no objects of that class exist.
50. What is abstract keyword?
Abstract keyword is used to declare class that provides common behavior across a set of subclasses. Abstract class provides a common root for a group of classes. An abstract keyword with a method does not have any definition.
51. What is synchronized keyword?

It controls the access to a block in a multithreaded environment.
52. What is native keyword?

Native keyword is used only with methods. It signals the compiler that the method has been coded in a language other than Java. It indicates that method lies outside the Java Runtime Environment.
53. What is a transient variable?

A transient variable is a variable that may not be serialized.i.e JVM understands that the indicated variable is not part of the persistent state of the object. For example
class A implements Serializable {
transient int i; // will not persist
int j; // will persist
Here, if an object of type A is written to a persistent storage area, the contents of i would not be saved, but the contents of j would.
54. What is sctrictfp keyword?
strictfp can be used to modify a class or a method, but never a variable. Marking a class as strictfp means that any method code in the class will conform to the IEEE 754 standard rules for floating points. Without that modifier floating points used in the methods might behave in a platform-dependent way.
If not at class class level , strictfp behavior can be applied at method level, by declaring a method as strictfp. Usage of strictfp is required when floating point values should be consistent across multiple platforms.
55. Explain method overriding with an example?
Method overriding is defined as creating a non-static method in the subclass that has the same return type and signature as a method defined in the superclass. Signature of a method includes name of method and number, sequence, type of arguments.
public class Person {
private String name;
private String ssn;
public void setName(String name) { = name;

public String getName() {
return name; }

public String getId() {
return ssn;}
getId method is overridden in subclass:
public class Employee extends Person
private String empId;

public void setId(String empId)

public String getId() {
return empId;
56. What is the use of super keyword. Give an example?

It allows you to access methods and properties of the parent class.
public class Person {
private String name;

public Person(String name) { = name; }

public String getName() {
return name;
} }

public class Employee extends Person {
private String empID;

public Employee(String name) {
super(name); // Calls Person constructor
public void setID(String empID){
public String getID(){
return empID;
57. What is an interface?
A programmer’s tool for specifying certain behaviors that an object must have in order to be useful for some particular task.Interface is a conceptual entity. It can contain only constants (final variables) and non-implemented methods (Non – implemented methods are also known as abstract methods).
For example, you might specify Driver interface as part of a Vehicle object hierarchy. A human can be a Driver, but so can a Robot.
58. What is an abstract class?
• An Abstract class is a conceptual class.
• An Abstract class cannot be instantiated – objects cannot be created.
• Abstract classes provides a common root for a group of classes, nicely tied together in a package.
• When we define a class to be “final”, it cannot be extended. In certain situation, we want properties of classes to be always extended and used. Such classes are called Abstract Classes.

59. What are the properties of abstract class?
• A class with one or more abstract methods is automatically abstract and it cannot be instantiated.
• A class declared abstract, even with no abstract methods can not be instantiated.
• A subclass of an abstract class can be instantiated if it overrides all abstract methods by implementation them.
• A subclass that does not implement all of the superclass abstract methods is itself abstract; and it cannot be instantiated.
• We cannot declare abstract constructors or abstract static methods.

60. What is object class in java?
Every class that we create extends the class Object by default. That is the Object class is at the highest of the hierarchy. This facilitates to pass an object of any class to be passed as an argument to methods.
61. What are the methods of object class?
The methods in this class are:
• equals(Object ref) – returns if both objects are equal
• finalize( ) – method called when an object’s memory is destroyed
• getClass( ) – returns class to which the object belongs
• hashCode( ) – returns the hashcode of the class
• notify( ) – method to give message to a synchronized methods
• notifyAll( ) – method to give message to all synchronized methods
• toString() – return the string equivalent of the object name
• wait() – suspends a thread for a while
• wait(…) – suspends a thread for specified time in seconds
62. What does java.util package provides?
The java.util package provides various utility classes and interfaces that support date and calendar operations, String manipulations and Collections manipulations.
63. How do we convert object to string?
Any Java reference type or primitive that appears where a String is expected will be converted into a string.
System.out.println(“1 + 2 = ” + (1 + 2));
For an reference type (object) this is done by inserting code to call String toString() on the reference.
All reference types inherit this method from java.lang.Object and override this method to produce a string that represents the data in a form suitable for printing.
To provide this service for Java’s primitive types, the compiler must wrap the type in a so-called wrapper class, and call the wrapper class’s toString method.
String arg1 = new Integer(1 + 2).toString();
For user defined classes they will inherit the standard Object.toString() which produces something like “ClassName@123456” (where the number is the hashcode representation of the object). To have something meaningful the classes have to provide a method with the signature public String toString().
public class Car() {

String toString()
return brand + ” : ” + color + ” : ”+wheels+” : “+ speed;
64. How can we convert string to object?
Many data type wrapper classes provide the valueOf(String s) method which converts the given string into a numeric value. The syntax is straightforward. It requires using the static Integer.valueOf(String s) and intValue() methods from the java.lang.Integer class.
To convert the String “22” into the int 22 you would write
int i = Integer.valueOf(“22”).intValue();
Doubles, floats and longs are converted similarly. To convert a String like “22” into the long value 22 you would write
long l = Long.valueOf(“22”).longValue();
To convert “22.5” into a float or a double you would write:
double x = Double.valueOf(“22.5”).doubleValue(); float y = Float.valueOf(“22.5”).floatValue();
If the passed value is non-numeric like “Four” it will throw a NumberFormatException.
65. What is Regular expression?
Regular expressions are a way to describe a set of strings based on common characteristics shared by each string in the set. They can be used to search, edit, or manipulate text and data.
The regular expression syntax supported by the java.util.regex API
66. What does rejex package consists of?
The java.util.regex package primarily consists of three classes: Pattern, Matcher, and PatternSyntaxException. A Pattern object is a compiled representation of a regular expression. The Pattern class provides no public constructors.
To create a pattern, you must first invoke one of its public static compile methods, which will then return a Pattern object. These methods accept a regular expression as the first argument; the first few lessons of this trail will teach you the required syntax.
A Matcher object is the engine that interprets the pattern and performs match operations against an input string. Like the Pattern class, Matcher defines no public constructors. You obtain a Matcher object by invoking the matcher method on a Pattern object. A PatternSyntaxException object is an unchecked exception that indicates a syntax error in a regular expression pattern.
67. What is StringBuffer class is used for?
• It is used for creating and manipulating dynamic string data i.e., modifiable Strings.
• It can store characters based on capacity. Capacity expands dynamically to handle additional characters. It cannot use operators + and += for string concatenation.
• It has fewer utility methods (e.g. substring, trim, ….)
68. What is the difference between StringBuffer and StringBuilder class?
StringBuffer class is not threadsafe whereas StringBuilder class is threadsafe. That means the methods of StringBuilder class are synchronized.
69. What is matcher in regex package?

A matcher is created from a pattern by invoking the pattern’s matcher method. Once created, a matcher can be used to perform three different kinds of match operations:
• The matches method attempts to match the entire input sequence against the pattern.
• The looking at method attempts to match the input sequence, starting at the beginning, against the pattern.
• The find method scans the input sequence looking for the next subsequence that matches the pattern

70. How to add comments in Java File ?
Comments can be inserted in 3 ways as shown below

// Comment Type1

/* Multi Line Comments
* Comment Line 2 */

/* Documentation Comment
* Comment Line 2 */

This comment will be added in the automatic document generation
71. What are the limitations of array?
Arrays do not grow while applications demand. It has inadequate support for inserting, deleting, sorting, and searching operations.
72. What is collection framework?
Collections Framework provides a unified system for organizing and handling collections and is based on four elements:
• Interfaces that characterize common collection types
• Abstract Classes which can be used as a starting point for custom collections and which are extended by the JDK implementation classes.
• Classes which provide implementations of the Interfaces.
• Algorithms that provide behaviors commonly required when using collections i.e. search, sort, iterate, etc.
Another item in collections framework is the Iterator interface. An iterator gives you a general-purpose, standardized way of accessing the elements within a collection, one at a time.
73. What is set interface about?
Mathematically a set is a collection of non-duplicate elements.The Set interface is used to represent a collection which does not contain duplicate elements. The Set interface extends the Collection interface. It stipulates that an instance of Set contains no duplicate elements.
The classes that implement Set must ensure that no duplicate elements can be added to the set. That is no two elements e1 and e2 can be in the set such that e1.equals(e2) is true.
74. What is HashSet, LinkedHashSet and TreeSet?
The Java platform contains three general-purpose Set implementations: HashSet, TreeSet, and LinkedHashSet.
• HashSet: This is an unsorted, unordered Set. This may be chosen when order of the elements are not important .
• LinkedHashSet: This is ordered. The elements are linked to one another (Double-Linked). This will maintain the list in the order in which they were inserted.
• TreeSet: This is a sorted set. The elements in this will be in ascending order in the natural order. You can also define a custom order by means of a Comparator passed as a parameter to the constructor.
75. Which one to choose and when among HashSet, LinkedHashSet and TreeSet?
• HashSet is a good choice for representing sets if you don’t care about element ordering. But if ordering is important, then LinkedHashSet or TreeSet are better choices. However, LinkedHashSet or TreeSet come with an additional speed and space cost.
• Iteration over a LinkedHashSet is generally faster than iteration over a HashSet.
• Tree-based data structures get slower as the number of elements get larger
• HashSet and LinkedHashSet do not represent their elements in sorted order
• Since TreeSet keeps its elements sorted, it can offer other features such as the first and last methods,i.e the lowest and highest elements in a set, respectively.

76. What is Enumeration interface?
The Enumeration interface defines a way to traverse all the members of a collection of objects. The hasMoreElements() method checks to see if there are more elements and returns a boolean.

If there are more elements, nextElement() will return the next element as an Object. If there are no more elements when nextElement() is called, the runtime NoSuchElementException will be thrown.
77. Explain Iterator interface?
Iterator is a special object to provide a way to access the elements of a collection sequentially. Iterator implements one of two interfaces: Iterator or ListIterator. An Iterator is similar to the Enumeration interface, Iterators differ from enumerations in two ways:
Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
Method names have been improved.
boolean hasNext() Returns true if the iteration has more elements. Object next() Returns the next element in the iteration. void remove() Removes from the underlying collection the last element returned by the iterator (optional operation).
78. What is SortedSet interface?
SortedSet is a subinterface of Set, which guarantees that the elements in the set are sorted. TreeSet is a concrete class that implements the SortedSet interface. You can use an iterator to traverse the elements in the sorted order.
79. How elements can be sorted in java collections?

The elements can be sorted in two ways. One way is to use the Comparable interface. Objects can be compared using by the compareTo() method. This approach is referred to as a natural order.
The other way is to specify a comparator for the elements in the set if the class for the elements does not implement the Comparable interface, or you don’t want to use the compareTo() method in the class that implements the Comparable interface. This approach is referred to as order by comparator
80. What is a list interface?
• A list allows duplicate elements in a collection where duplicate elements are to be stored in a collection, list can be used. A list also allows to specify where the element is to be stored. The user can access the element by index.
• The List interface allows to create a list of elements.The List interface extends the Collection interface.
81. Compare ArrayList vs LinkedList?
• ArrayList provides support random access through an index without inserting or removing elements from any place other than an end.
• LinkedList provides support for random access through an index with inserting and deletion elements from any place .
• If your application does not require insertion or deletion of elements, the Array is the most efficient data structure.
82. What is a vector class?
The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.
83. What is a Stack class?

The Stack class represents a last-in-first-out (LIFO) stack of objects. The elements are accessed only from the top of the stack. You can retrieve, insert, or remove an element from the top of the stack.
84. What is a Map interface?
A Map is a storage that maps keys to values. There cannot be duplicate keys in a Map and each key maps to at most one value. The Map interface is not an extension of Collection interface. Instead the interface starts of it’s own interface hierarchy. for maintaining key-value associations. The interface describes a mapping from keys to values, without duplicate keys, by definition. The Map interface maps keys to the elements. The keys are like indexes. In List, the indexes are integer. In Map, the keys can be any objects.
85. Describe about HashMap and TreeMap?

The HashMap and TreeMap classes are two concrete implementations of the Map interface. Both will require key &value. Keys must be unique. The HashMap class is efficient for locating a value, inserting a mapping, and deleting a mapping. The TreeMap class, implementing SortedMap, is efficient for traversing the keys in a sorted order.
HashMap allows null as both keys and values.TreeMap is slower than HashMap. TreeMap allows us to specify an optional Comparator object during its creation. This comparator decides the order by which the keys need to be sorted.
86. What is the purpose of Collections class in util package?
The Collections class contains various static methods for operating on collections and maps, for creating synchronized collection classes, and for creating read-only collection classes.
87. How do we order/sort objects in collections?

To provide for ordering/sorting of the objects Java API provides two interfaces Comparable and Comparator
• Comparable interface is in java.lang
• Comparator interface is in java.util
88. When to use Comparable and Comparator in code?
The Comparable interface is simpler and less work
• Your class implements Comparable
• You provide a public int compareTo(Object o) method
• Use no argument in your TreeSet or TreeMap constructor
• You will use the same comparison method every time
The Comparator interface is more flexible but slightly more work
• Create as many different classes that implement Comparator as you like
• You can sort the TreeSet or TreeMap differently with each
• Construct TreeSet or TreeMap using the comparator you want
• For example, sort Students by score or by name
Suppose you have students sorted by score, in a TreeSet you call studentsByScore. Now you want to sort them again, this time by name
Comparator<Student> myStudentNameComparator = new MyStudentNameComparator();
TreeSet studentsByName = new TreeSet(myStudentNameComparator);
89. What are the new features added in Java 1.5?
Generic classes
• New approach to loops – Enhanced for loop
• Static imports
• Arrays, string builder, queues and overriding return type
• Output formatting – format() and printf()
• Autoboxing of primitive types
• Enumerated types
• Variable length of arguments

90. What is Generic classes?

Similar in usage to C++ templates, but do not generate code for each implementation. It ensure stored/retrieved type of objects.Check done at compile-time – avoid nasty casting surprises during runtime. Generics are removed from compiled classes. Java 5 is upwardly compatible with Java 1.4, so old programs must continue to work. It can be used in legacy code to check for place where incorrect type is inserted
91. What is the big advantage of Generics?
Big advantage: collections are now type safe. For example, you can create a Stack that holds only Strings as follows:
Stack<String> names = new Stack<String>();
You can write methods that require a type-safe collection as follows:
void printNames(Stack<String> names) {
String nextName = names.pop(); // no casting needed!
names.push(“Hello”); // works just the same as before
names.push(Color.RED); // compile-time error!
92. What is StringBuilder class?
It is an improvement upon StringBuffer. It allows quicker concatenation of strings. It is not safe for use by multiple threads at the same time since the methods are not synchronized.
Why use it?
Creating new Strings in a loop can be inefficient because of the number new objects that are created and discarded.
StringBuilder.append(<type> <value>)
StringBuilder.insert(<type> <value>)
93. What is Queue interface?
• It extends Collection interface. It is designed for holding elements prior to processing. It is typically ordered in a FIFO manner.
• Main Methods are – remove() and pull(). Both return the head of the queue. When empty, the remove() method throws an exception while poll() returns null.
94. Describe covariant return types with an example?
It allows the user to have a method in inherited class with same signature as in parent’s class but differing only in return types. It makes programs more readable and solves casting problem.
class Shape
public Shape transform(int x, int y)
class Rectangle extends Shape
public Rectangle transform(int x, int y)
95. What is boxing and unboxing ?
Converting a primitive data type to its corresponding wrapper class object is called boxing or autoboxing. Example of boxing,
int i = 0;
Integer O = new Integer(i);
Unboxing is the exact opposite of boxing where wrapper class object is converted into primitive data type. Example of unboxing,
i = O.intValue();
96. How autoboxing was done before java 5 and in java 5 version?
Before 5.0
ArrayList<Integer> list = new ArrayList<Integer>();list.add(0, new Integer(42)); int total = (list.get(0)).intValue();
From 5.0 version:
ArrayList<Integer> list = new ArrayList<Integer>();list.add(0, 42);int total = list.get(0);
97. How java distinguishes between primitive types and objects?
Java distinguishes between primitive types and Objects.
• Primitive types, i.e., int, double, are compact, support arithmetic operators.
• Object classes (Integer, Double) have more methods: Integer.toString()
You need a “wrapper” to use Object methods:
Integer ii = new Integer( i );
Similarly, you need to “unwrap” an Object to use primitive operation
int j = ii.intValue() * 7;
Java 1.5 makes this automatic:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, 42);
int total = list.get(0);
98. What is Enum?

An enumeration, or “enum,” is simply a set of constants to represent various values. Here’s the old way of doing it:
public final int SPRING = 0;
public final int SUMMER = 1;
public final int FALL = 2;
public final int WINTER = 3;
This is a nuisance, and is error prone as well. Here’s the new way of doing it,
enum Season { winter, spring, summer, fall }
Enums are classes, extends java.lang.Enum.Enums are final, can’t be subclassed. Only one Constructor and is protected. It implement java.lang.Comparable: compareTo() and implements Serializable.
99. What is an exception?
An exception can be defined as an abnormal event that occurs during program execution and disrupts the normal flow of instructions.
100. What are the uses of exceptions?
• Consistent error reporting style.
• Easy to pass errors up the stack.
• Pinpoint errors better in stack trace.
• As long as you “fail fast” and throw as soon as you find a problem.
• Wrap useful information up in your exception classes, use that information later when handling the exception.
• Exceptions don’t always have to be errors, maybe your program can cope with the exception and keep going!
• Separating error handling code from Regular code