JAVA Interview Question



1. What is Java technology ?
Java is a programming language, application development and deployment environment. The Java programming language is similar to C++ syntax. Java development environment provides tools for Compiling, Interpreting, Packaging the Java code.
2. What are the objectives of Java Technology ?

Simple: The language syntax is based on ‘C++’ programming language. Even though the syntax of ‘C++ was adopted, some features which were troublesome were avoided to make the Java programming simple.
Object oriented: The object oriented features of Java are similar to C++. One major difference between Java and C++ lies in multiple inheritance. When C++ supports multiple inheritance, Java won't. In OOPs programming paradigm, everything is represented as Class and Objects.
Architectural Neutral: The Java compiler generates an intermediate byte code which doesn't depend on the operating system on which it is run. So the Java programs can run on any machine, irrespective of its OS/Architecture and hence the Java program is Architectural Neutral.
Portable type: The size of Data Types is always same irrespective of the system architecture. An int in Java will always be 32 bit unlike in C/C++ where the size may be 16-bit or 32-bit depending on the compiler and machine. Java have libraries that enable to port its application to any systems like UNIX, Windows & Macintosh systems.
Distributed: Java’s networking capabilities are both strong and easy to use. Java applications are capable of accessing objects across the net and local file system.
Secure: Since Java is mostly used in a network environment, a lot of emphasis has been placed on security to enable construction of virus & 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 which inturn provide high performance.

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







Java Basics Interview Questions - JVM, JRE & JDK
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.
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 JVM 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?
The classpath is an environment variable that tells the JVM where to look for user-defined classes and packages in Java programs. When a Java program is executed, JVM looks for the required classes needed for the program execution in the filesystem specified in the Classpath. Classes are loaded into the JVM, only when a call is made to use the content of the class object(Lazy Loading).
7. Explain the architecture of code execution process inside JRE ?
Java Architecture and Compilation
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/C++ application. Most widely used JVM is
Oracle Corporation's HotSpot, which is written in the C++ programming language.
8. 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).
9. 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
10. 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 provides application execution speeds near to C or C++ application.
11. What is Java Development Kit (JDK) ?
Java Development Kit (JDK) is a superset of the JRE, which contains Java Run-time Environment (JRE) , Compilers and debuggers required to develop applets and applications.
12. What is Garbage Collector ?
For executing programs, application allocate memory at runtime. After execution of programs, unused memory needs to be deallocated. Allocation and deallocation of memory is done by programmers developing application using C,/C++ programming language. Java internally uses a garbage collector to deallocate unused memory which makee the life of programmer easier.
13. What is class loader ?
Class loader is used to load all the classes required to execute the application into the Java Virtual Machine (JVM). Once the classes are loaded, the memory required for the application is determined.
14. What is byte code verifier ?
Byte code verifier checks for illegal code like forged pointers, violated access rights on objects etc. in complied byte code.
15. 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
16. 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.
17. 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
  • Java.io - System.out.print
  • Java.lang - length method for arrays; exceptions
  • Java.net - sockets
  • Java.util - System.getProperty
18. 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.
Java OOPS Interview Questions and Answers
19. What is a class?
Classes are used to define objects of a certain type. For example - Car, Person etc. To define the characteristics of a class, variables and the methods are used.
20. What is an object?
An object is an instance of a classes, which has its own private collection of properties (i.e. data) and methods (i.e. operations).
21. What an object contains?
An object has - State and Behavior
22. What is object oriented program?
An Object-Oriented Program consists of a group of cooperating objects, exchanging messages, in-order to  achieve a common objective.
23. What are the benefits of OOPS?
  • Real-world programming
  • Reusability of code
  • Modularity of code 
  • Resilience to change
  • Information hiding
24. What are the features of OOPS?
  • Encapsulation 
  • Abstraction 
  • Inheritance 
  • Polymorphism
25. What is encapsulation?
Encapsulation helps to implement one of the four fundamental Object Oriented Programming concepts, i.e. data hiding. It is the ability of an object to bind together the data (properties) and functions that manipulate the data, safe from outside manipulations. As per Grady Booch, encapsulation is defined as: “The process of hiding all of the details of an object that do not contribute to its essential characteristics.”
26. What is abstraction?
Data Abstraction is the process of hiding unnecessary details, exposing relevant information of an object suited for the system under consideration. Best example is an interface.
27. 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.
28. 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.
29. 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.
30. What are the types of inheritance?
  • Single inheritance 
  • Multiple inheritance
31. What is single inheritance?   
Subclass is derived from only one superclass
32. What is multiple inheritance?
A subclass is derived from more than one super class

33. What is polymorphism?
Polymorphism is defined as the ability of an object to take multiple forms depending on their type or class. The best example of Polymorphism is, invoking derived class methods through a base class reference at run-time.
34. Describe method overloading with example?
Java allows to define several methods with same name within a class, but with different method signature. Methods are identified with the parameters set based on:
  • the number of parameters
  • types of parameters and
  • order of parameters.
Example of Method overloading is as given below.
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[])
{
}
Java Interview Questions on Classes & Packages
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?

To refer the current object, “this” keyword is used. When we want to pass the instance of the current object to a method in another object, we pass the current instance as shown below.
otherobj1.anymethod(this);
In case, a variable of an object and parameter name of a method in the object are same, we use "this" keyword to avoid ambiguity as shown below.
String name;
public void method1(String name){
 this.name=name;
}
The "this" keyword included with parenthesis, i.e. this() with or without parameters is used to call another constructor. The default constructor for the Car class can be redefined as below
public Car(){
 this(“NoBrand”,””NoColor”,4,0);
}
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?
"To organize related set of classes and interfaces, a package is used. 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?

To access variables and methods of a class(Car) in another class(Person), we need to include the Class "Car" in Class "Person". This is done 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;
 import Java.io.*;
 // Class Definition
Above code tell JRE 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 the command prompt, Go to the 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 Person.java” . 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 files in a different location use command “javac -d ../Java/All/*.java”
44. How to run a compiled  Java file ?
Go to the location in which Java file is located from command prompt. Enter command “java” followed by the 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 methods to restrict the attributes access in a class. An example 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 ?
The default constructor is called automatically, when an object of that class is created. A constructor has the same name as the that of the class.
A constructor always returns objects of the class, 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, the default constructor is not provided by the JVM. A class can have multiple constructors.
class Car {
  String brand;
  String color;
  public Car() {
    brand=“NoBrand”;
    color=“NoColor”;
  }

public Car(String b, String c, int w, int s, int g)
{
  brand=b;
  color=c;
}

void accelerate(){}
void brake(){}
}
47. What is access modifier and what are its types?
An attribute that determines whether a class member can be accessed or not. 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, its subclass(es), and other classes in the package.
  • 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?
If a variable is declared as final, its value can't be modified. If a method is declared as final, it can't be overridden in the subclass. A class declared as final cannot be inherited.
49. What is static keyword?
We can define variables and methods of a class as "Static". If we declare a method or a variable as static, it means that the data member belongs to the class rather than any specific instance of a class. Static Methods and data members can be called without instantiating the class. A static member exists even if no objects of that class exist.
50. What is abstract keyword?
Abstract keyword is used to declare a class, when we want to expose certain functionality to the users and hide the underlying implementation. We can't create an instance of the abstract class. An abstract class can contain abstract and non-abstract methods.
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 won't be serialized.i.e JVM understands that the transient 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?
The floating point precisions vary based on the platform on which Java program is run. In order to make sure that constant results are obtained while doing operations with floating point variables, Java provides "strictfp" keyword. If not at class class level , strictfp behavior can be applied at method level, by declaring a method as strictfp.
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. The signature of a method includes the name of the method and number, sequence, type of arguments.
public class Person {
 private String name;
 private String ssn;
 public void setName(String name) {
 this.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)
   {
     this.empId=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) {
 this.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){
 this.empID=empID;
 }
 public String getID(){
 return empID;
 }
}
57. What is an interface?
If we want enforce certain behaviour on objects implementing an interface, so that all the object provides certain functionalities irrespective of its underlying implementation, we use Interface Class. The Interface is a conceptual entity. It can contain only final variables and 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 act as a base for a group of classes, which are closely related in a package.
  • If a class is declared as “final”, we can't extend that class. In some cases, properties of a class should be extended and used in sub-classes. 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 cannot be instantiated.
  • A subclass of an abstract class can be instantiated if it overrides all abstract methods by implementing 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 constructor or abstract static methods.

60. What is object class in java?
Every class that we create extends the class Object by default. It means that the Object class is at the top of the hierarchy. Due to this default inheritance of object class, we can pass an object of any class as an argument to any method.
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 & calendar operations
  • String manipulations
  • Collections Operations
63. How do we convert object to string?
For a reference type object, converting from object to string is done by calling "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.
In case of Java's primitive types, to make a conversion to a string, the compiler must wrap the primitive data type in its wrapper class, and call the "toString()" method of the wrapper class.
String arg1 = new Integer(1 + 2).toString();
For user defined class, the standard Object.toString() produce 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 Variable) 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 or Java Regex is an API to search or manipulate string based on a certain pattern. It is supported by the java.util.regex API, which provides one interface and three classes.
66. What does rejex package consists of?
The java.util.regex package primarily consists of three classes: Pattern, Matcher, and PatternSyntaxException. Let us see what each class does. To define a pattern for regex engine, Pattern class is used. An object of Pattern class is a compiled version of a regular expression. No constructors are provided by the Pattern class.
In order to create a pattern, a static method(Compile(expression)) of the pattern class is invoked, which accept a regular expression as the argument. The subsequent object returned by the pattern class is used for identifying a match.

Pattern s = Pattern.compile(".p">);// Checking single character
Matcher m = p.matcher("apple");  
Job of the matcher object is to perform the match operation against an input, after interpreting the pattern. Like the Pattern class, Matcher objects are created by invoking the "matcher" method of a Pattern object. A PatternSyntaxException is used to throw an exception, if there is 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

Core Java Interview Questions on Collections
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);
studentsByName.addAll(studentsByScore);
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
Annotation
  • 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 );
ii.hashCode()
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.
Core Java Interview Questions on Exceptions
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

101. What are the types of error?
There are two types of error:
  • Compile time error
  • Run time error

102. List some exception occurence reason?
Running out of memory, Resource allocation errors, Inability to find files, Problem in network connectivity etc.
103. What are checked exceptions?
Checked exceptions are so called because both the Java compiler and the Java virtual machine check to make sure this rule is obeyed. The checked exceptions that a method may raise are part of the method's signature. Every method that throws a checked exception must advertise it in the throws clause in its method definition.

Every method that calls a method that advertises a checked exception must either handle that exception (with try and catch) or must in turn advertise that exception in its own throws clause.
104. What are unchecked exceptions?
Raised implicitly by system because of illegal execution of program. Do not need to announce the possibility of exception occurrence. When unchecked exception occurred, if programmer does not deal with it, it would be processed by default exception handler.
105. How exception handling is implemented using try and catch statement?
Using try and catch statements. The try block encloses the statements that might raise an exception within it and defines the scope of the exception handlers associated with it. The catch block is used as an exception-handler. You enclose the code that you want to monitor inside a try block to handle a run time error.

106. What is throwing an exception?
The throw statement causes termination of the normal flow of control of the Java code and stops the execution of the subsequent statements if an exception is thrown when the throw statement is executed.
The throw clause transfers the control to the nearest catch block handling the type of exception object throws. The following syntax shows how to declare the throw statement:
public double divide(int dividend, int divisor) throws ArithmeticException {
 if(divisor == 0) {
 throw new ArithmeticException(“Divide by 0 error”);
 }
 return dividend / divisor;
}
107. What is using throws exceptions?
The throws statement is used by a method to specify the types of exceptions the method throws. If a method is capable of raising an exception that it does not handle, the method must specify that the exception has to be handled by the calling method. This is done using the throws statement.
Example: void readData() throws IOException
108. How can we create our own exceptions?
Defining your own exceptions let you handle specific exceptions that are tailor-made for your application. Steps to Create a User Defined Exception:
Create a class that extend from a right kind of class from the Exception Hierarchy. For Example,
public class DivideByZeroException extends ArithmeticException
{
 public DivideByZeroException()
 {
 super("Divide by 0 error");
 }
}
109. What are the exception occurrence levels?
Hardware/operating system level :
  • Arithmetic exceptions; divide by 0, under/overflow.
  • Memory access violations; segment fault, stack over/underflow.
Language level :
  • Type conversion; illegal values, improper casts.
  • Bounds violations; illegal array indices.
  • Bad references; null pointers.
Program level :
  • User defined exceptions.
110. What are the categories of exceptions?
There are two categories of exceptions:
  • Built in Exceptions
    • Checked Exceptions
    • Unchecked Exceptions
  • User Defined Exceptions
111. What is the use of finally clause?
The finally block is used to process certain statements, no matter whether an exception is raised or not. Generally we write code resource cleaning operations inside finally block.
112. What is an assertion?
An assertion is a statement in the JavaTM programming language that enables test the assumptions about program. Each assertion contains a boolean expression that is assumed to be true. When executed if the boolean expression is false, the system will throw an error.
Writing assertions while programming is one of the quickest and most effective ways to detect and correct bugs. As an added benefit, assertions serve as internal documentation, thus enhancing maintainability.
113. What are the forms of assertion statements?
The assertion statement has two forms.
assert Expression1 ;
Where Expression1 is a boolean expression. When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no detail message.
assert Expression1 : Expression2 ;
Where Expression1 is a boolean expression and Expression2 is an expression that has a value. (It cannot be an invocation of a method that is declared void). This form of asssert statement provides a detail message for the AssertionError. The system passes the value of Expression2 to the appropriate AssertionError constructor, which uses the string representation of the value as the error's detail message.
114. How do we enable and disable assertions?
To enable assertions use -enableassertions, or -ea, option at runtime. To disable assertions use -disableassertions, or -da. Specify the granularity with the arguments provided at runtime.
  • no arguments - Enables or disables assertions in all classes except system classes. 
  • packageName - Enables or disables assertions in the named package and any subpackages. 
  • "-" Enables or disables assertions in the unnamed package in the current working directory. 
  • className - Enables or disables assertions in the named class
Core Java Interview Questions on I/O
115. What are the basic functionalities provided by io package?
Many Java programs need to read or write data. This can be obtained by using the classes in java.io package. Your program can get input from a data source by reading a sequence characters from a InputStream attached to the source. Your program can produce output by writing a sequence of characters to an OutputStream attached to a destination.
116. What is a Stream?
A stream is a flowing set of data. Streams support many different kinds of data, including simple bytes, primitive data types. Some streams simply pass on data, others manipulate and transform the data in useful ways. A program uses an input stream to read data from a source, one item at a time and uses an output stream to write data to destination, one item at a time.
117. What is an inputstream?
The InputStream class is an abstract superclass that provides a minimal programming interface and a partial implementation of input streams. The InputStream class defines methods for reading bytes or arrays of bytes.

118. What is a FileInputStream?
It reads data from file on the native file system. It is meant for reading streams of raw bytes such as image data.
119. What is ByteArrayInputStream?
A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream. An internal counter keeps track of the next byte to be supplied by the read method.
120. What is SequenceInputStream, StringBufferInputStream, PipedInputStream?
  • SequenceInputStream : It concatenate multiple input streams into one input stream. 
  • StringBufferInputStream : It allow programs to read from a StringBuffer as if it were an input stream. 
  • PipedInputStream : In this data can be read from a thread by using PipedInputStream
121. What is FilterInputStream?
FilterInputStream is a subclass of InputStream.These classes define the interface for filtered streams which process data as it's being read or written.
122. What is BufferedInputStream?
Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty.
123. What is an Enumeration interface and what are its methods?
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.
124. What is a DataInputStream?
A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way.
125. What is an OutputStream?
The OutputStream class is an abstract superclass that provides a minimal programming interface and a partial implementation of output streams.
OutputStream defines methods for writing bytes or arrays of bytes.
126. What is a FileOutputStream?
A file output stream is an output stream for writing data to a File. Whether or not a file is available or may be created depends upon the underlying platform.
127. What is a ByteArrayOutputStream and FilterOutputStream?
ByteArrayOutputStream class implements an output stream in which the data is written into a byte array. FilterOutputStream class is the superclass of all classes that filter output streams.
These streams sit on top of an already existing output stream (the underlying output stream) which it uses as its basic sink of data, but possibly transforming the data along the way or providing additional functionality .
128. What is BufferedOutputStream and PrintStream?
A buffered lets you write to a stream without causing a write every time. The data is first written into a buffer. Data is written to the actual stream only when the buffer is full, or when the stream is flushed. A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently.
129. What is object serialization?
Serializing objects is the process of writing objects to a file. When an object is serialized, its state and other attributes are converted into an ordered series of bytes. This byte series can be written into streams.
130. Why should we use object serialization?
Writing the code for saving data, can become repetitive work. First, the programmer must create a specification document for the proposed file structure. Next, the programmer must implement save and restore functions that convert object data to & from primitive data types, and test it with sample data.
If the application later requires new data to be stored, the file specification must be modified, as well as the save and restore methods. The solution to the problems specified is Object serialization. Object serialization takes an object's state, and converts it to a stream of data. With object serialization, it's an easy task to take any object, and make it persistent, without writing custom code to save object member variables.
131. How to prevent writing some member data value during object serialization?
You use the transient keyword to indicate to the Java virtual machine that the indicated variable is not part of the persistent state of the object. Variables that are part of the persistent state of an object must be saved when the object is archived .
132. What are Reader and Writer classes?
Input and output for characters streams are handled through subclasses of the Reader and Writer classes.  These classes are abstractions that Java provides for dealing with reading and writing character data. 
133. Give few examples of simple Reader and Writer classes?
  • FileReader and FileWriter : Read data from or write data to a file on the native file system.
  • PipedReader and PipedWriter : Pipes are used to channel the output from one program (or thread) into the input of another. 
  • CharArrayReader and CharArrayWriter : Read data from or write data to a char array in memory.
134. What are FilterReader/FilterWriter, BufferedReader/BufferedWriter and PrintWriter?
  • FilterReader and FilterWriters are subclasses of Reader and Writer, respectively. These classes define the interface for filtered streams which process data as it's being read or written. 
  • BufferedReader and BufferedWriter : Buffer data while reading or writing, thereby reducing the number of accesses required on the original data source. 
  • PrintWriter : An output stream with convenient print methods
135. What is a File class?
It represents a file on the native file system. You can create a File object for a file on the native file system and then query the object for information about that file (such as its full pathname).
136. What are the functionalaties we get using File class?
The File class in the java.io package provides various methods to access the properties of a file or a directory, such as file permissions, date and time of creation, and path of a directory.
Core Java Interview Questions on Threads
137. What are the benefits of using threads in an application?
  • It improves performance .
  • It minimizes system resource usage. 
  • We can access multiple applications simultaneously. 
  • Threads simplifies the program structure.
  • We can send & receive data on network at the same time.
  • We can read & write files to disk simultaneously.
138. What are the differences between process and threads?
Process
It is executable program loaded in memory. It has its own address space – variables & data structures (in memory). Process communicates via operating system, files, network. A process may contain multiple threads.
Threads
It is sequentially executed stream of instructions. Shares address space with other threads. It has its own execution context. Multiple thread in process execute same program.
139. What are the types of thread?
There are two types of thread:
  • Single Threaded Process
  • Multi Threaded Process
140. What is single threaded and multi threaded process?
  • Single Threaded Process: A thread is defined as the execution of a program. A process that is made of one thread is known as single-threaded process.
  • Multi Threaded Process: A process that creates two or more threads is called a multithreaded process.
141. What is the basic concept of multitasking and its types?
Multitasking is the ability to execute more than one task at the same time. Multitasking can be divided into two categories:
  • Process based multitasking
  • Thread based multitasking

142. Give example and describe process and thread based multitasking?
Process based multitasking refers to working with two programs concurrently. For example, working with MS-Word, Listening to mp3 song using Windows Media Player.
Thread based multitasking refers to working with parts of one program. For example, MS-Word program can check spelling, count line numbers, column number while writing in a document.
143. What are the disadvantages of multitasking?
  • Race condition
  • Deadlock condition
  • Lock starvation
144. How to use threads in java?
By using Thread class, Java.lang.Thread class is used to construct and access individual thread in a multi threaded application?
145. What are the stages of Thread Lifecycle?
  • New : It is created byinstantiating the Thread class. Thread th = new Thread(this);
  • Runnable: By calling the start method that in turn call run method. th.start();
  • Not Runnable: Calling wait or sleep method or caused due to io interrupts. wait(); th.sleep(1000);
  • Dead or terminate: After run() method completes execution.
146. What are the two ways of creating threads in java?
Two ways of creating Thread in Java:
  • Extending from java.lang.Thread class
  • Implementing the Runnable Interface
147. Which is the first thread to be executed in a multithreaded process?
The first thread to be executed in a multithreaded process is called the main thread. The main thread is created automatically on the startup of java program execution.
148. What is thread scheduling and what does it determines?
The execution of multiple threads on a single CPU is called scheduling.
  • It determines which runnable threads to run
  • It can be based on thread priority
  • It is part of OS or Java Virtual Machine (JVM)
149. What thread scheduling does java runtime supports?
The Java runtime supports a very simple, deterministic scheduling algorithm known as fixed priority scheduling.
150. Describe thread policy in java?
  • Thread priorities are the integers in the range of 1 to 10 that specify the priority of one thread with respect to the priority of another thread. 
  • Each Java thread is given a numeric priority between MIN_PRIORITY and MAX_PRIORITY.
  • The Java Run-time system selects the runnable thread with the highest priority of execution when a number of threads get ready to execute.
  • The Java Run-time Environment executes threads based on their priority.
  • A thread with higher priority runs before threads with low priority. 
  • A given thread may, at any time, give up its right to execute by calling the yield method. Threads can only yield the CPU to other threads of the same priority attempts to yield to a lower priority thread are ignored. 
  • You can set the thread priority after it is created using the setPriority() method declared in the Thread class.
151. What is synchronization?
Synchronization of threads ensures that if two or more threads need to access a shared resource then that resource is used by only one thread at a time. Synchronization is based on the concept of monitor.
152. Why synchronization is required?
  • Problem: Race condition! Two or more threads access to same object and each call a method that modifies the state of the object. 
  • Result: Corrupted object. Solution to this is synchronization.
153. What is monitor?
A monitor is an object that can block threads and notify them when it is available.The monitor controls the way in which synchronized methods access an object or class. To enter an object’s monitor, you need to call a synchronized method.
154. How to acheive synchronization in java?
Synchronization can be acheived in java using synchronized keyword.
155. What are the two levels of acheiving synchronization?
  • Method level
  • Block level

156. What is inter thread communication?
A thread may notify another thread that the task has been completed. This communication between threads is known as interthread communication.
157. What are the various methods used in inter thread communication?
The various methods used in interthread communication are:
  • wait()
  • notify()
  • notifyAll()
158. What is garbage collection?
Garbage collection is the feature of Java that helps to automatically destroy the objects created and release their memory for future reallocation.
159. What are the various activities involved in garbage collection?
The various activities involved in garbage collection are:
  • Monitoring the objects used by a program and determining when they are not in use.
  • Destroying objects that are no more in use and reclaiming their resources, such as memory space.
  • The Java Virtual machine (JVM) acts as the garbage collector that keeps a track of the memory allocated to various objects and the objects being referenced.
160. How JDBC architecture can be categorized?
JDBC architecture can be categorized into two layers:
  • JDBC Application layer
  • JDBC Driver layer
161. In which package jdbc apli classes and interfaces are available?
The JDBC API classes and interfaces are available in the java.sql and the javax.sql packages.
162. What are the commonly used classes and interfaces in JDBC api?
The commonly used classes and interfaces in the JDBC API are:
  • DriverManager class: Loads the driver for a database. 
  • Driver interface: Represents a database driver. All JDBC driver classes must implement the Driver interface. 
  • Connection interface: Enables you to establish a connection between a Java application and a database. 
  • Statement interface: Enables you to execute SQL statements. 
  • ResultSet interface: Represents the information retrieved from a database. 
  • SQLException class: Provides information about the exceptions that occur while interacting with databases.
163. What are the steps to create JDBC application?
  • Load a driver
  • Connect to a database
  • Create and execute sql statements
  • Handle exceptions
163. How do we load a driver in jdbc?
Loading a Driver can be done in two ways:
Programmatically:
  • Using the forName() method
  • Using the registerDriver()method
Manually:
  • By setting system property
164. How do we load driver programmatically?
Using the forName() method
  • The forName() method is available in the java.lang.Class class.
  • The forName() method loads the JDBC driver and registers the driver with the driver manager. 
  • The method call to use the the forName() method is:
  • Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Using the registerDriver() method
  • You can create an instance of the Driver class to load a JDBC driver. This instance provide the name of the driver class at run time. The statement to create an instance of the Driver class is:
Driver d = new sun.jdbc.odbc.JdbcOdbcDriver();
You need to call the registerDriver() method to register the Driver object with the DriverManager. The method call to register the JDBC-ODBC Bridge driver is:
DriverManager.registerDriver(d);
165. How we connect to a database in JDBC?
Connecting to a Database Using DriverManager.getConnection() method:
Connection getConnection (String <url>)
Connection getConnection (String <url>, String <username>, String <password>)
Connects to given JDBC URL.
throws java.sql.SQLException
Returns a connection object.
Example:
Connection con=DriverManager.getConnection(“jdbc:odbc:MyDSN”,”scott”,”tiger”);
166. What are the different types of statements in JDBC?
  • Statement Interface : A Statement object is used for executing a static SQL statement and obtaining the results produced by it.
  • Statement createStatement() : returns a new Statement object.
  • Prepared Statement Interface: When you use a PreparedStatement object to execute a SQL statement, the statement is parsed and compiled by the database, and then placed in a statement cache. From then on, each time you execute the same PreparedStatement, it is once again parsed, but no recompile occurs. Instead, the precompiled statement is found in the cache and is reused.
  • PreparedStatement prepareStatement(String sql) : returns a new PreparedStatement object.
  • CallableStatement Interface : The interface used to execute SQL stored procedures.
167. What is a ResultSet interface?
A ResultSet provides access to a table of data generated by executing a Statement. Only one ResultSet per Statement can be open at once. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The 'next' method moves the cursor to the next row.

No comments:

Post a Comment