Java is an object-oriented programming language. Hence questions regarding the object oriented principles of Java programming language are commonly asked in interviews - for beginner as well as for senior level positions; and for all job roles including Java programmers, designers, architects and managers.
Object-oriented programming is a programming methodology based on the concept of 'objects' which contain data, in the form of fields, also called as attributes; and code, in the form of procedures, also called as methods or functions.
Java is a class based object-oriented programming language, which means objects in Java are instances of classes. Think of a class as a blueprint, and object as an instance of this blueprint.
Object-oriented programming is based on 4 key principles - Abstraction, Encapsulation, Inheritance and Polymorphism.
Abstraction is one of the four key principles of object-oriented programming.
Abstraction is the principle of object-oriented programming in which unimportant characteristics of an object are refined, removed or hidden; and only the key set of characteristics are represented to the outside world.
In other words, Abstraction is the principle of perceiving real life things from a particular perspective, based on the system we are designing; focusing only on those aspects that are relevant to this system and ignoring all other aspects.
For Example - If we are modeling a person in a payroll system, we would capture and focus on the name, age, title, company and salary attributes. We would ignore other attributes such as weight, height etc. which are not relevant in this context
Whereas, if we are modeling a person in a hospital patient system, we would capture and focus on the name, age, height, weight etc. We would ignore attributes such as company and salary of the person.
//Model of person in a payroll system
public class person {
private String name;
private int age;
private String companyName;
private double salary;
}
//Model of person in a hospital patient system
public class person {
private String name;
private int age;
private float height;
private float weight;
}
Encapsulation is one of the four key principles of object-oriented programming
Encapsulation is the principle of object-oriented programming in which methods, and the data that those methods act on, are bundled together into the same component. In Java programming language, related methods and fields are bundled together in Classes, instances of which are Objects.
Encapsulation enables data hiding in Java. i.e. the data in one object can be hidden from other objects. Methods act as intermediaries that access and modify the data within its containing object. Objects can access or manage data of other objects by calling methods of the other object.
Example:
public class person {
//private - name is hidden from other classes
private String name;
//private - age is hidden from other classes
private int age
//private - companyName is hidden from other classes
private String companyName;
//private - salary is hidden from other classes
private double salary;
//Setters and getters to access and modify companyName
public String getCompanyName(){...}
public String setCompanyName(String companyName){...}
}
Inheritance is one of the four key principles of object-oriented programming
Inheritance is the principle of object-oriented programming in which one or more classes can inherit their fields and methods from another class. The class whose fields and methods are inherited by other classes is called the super class or parent class. The class (or classes) inheriting the state and functionality of the super class or parent class is called the child class.
In Java programming language, the keyword 'extends' is used to specify that a class is a child of another class.
In the following example, the class Car extends from the class Vehicle. The class Car inherits the fields and methods of the class Vehicle. The class Car is the child class, the class Vehicle is the parent class.
This relationship in object-oriented programming language is commonly termed as 'Is-A' relationship. In this example, we can say that a Car Is-A Vehicle.
//Parent Class - Vehicle
public class Vehicle {
public double speed;
public void start(){...}
public void stop(){...};
}
//Child Class - Car
public class Car extends Vehicle{
//Inherits fields and methods of class Vehicle
}
Interfaces are reference types in Java programming language. Interfaces declares methods, i.e. behaviors, but do not implement them. A class inherits the methods of an interface and implements the methods...
*** Complete answer and code snippet in the Java Interview Guide.
Polymorphism is one of the four key principles of object oriented programming.
Polymorphism, which means 'having multiple forms' in Greek, is the principle of object oriented programming in which an object can have multiple forms. In Java programming language polymorphism is enabled by the use of inheritance and interface types. Polymorphism is in effect whenever we use a parent class reference or interface type to refer to a child object...
*** See complete answer and code snippet in the Java Interview Guide.
Generalization is the concept of object-oriented programming in which common properties and behaviors of two or more types can be defined in a single type; which can be inherited and reused...
*** See complete answer in the Java Interview Guide.
Aggregation is a relationship between classes, in which one class is a part of another class. This relationship is also called as part-of whole relationship. In aggregation, the part can exist independently of the whole. An example of aggregation is car and engine. Engine is part of a car, but can exist without the car.
*** See complete answer in the Java Interview Guide.
SOLID is an acronym for five Object Oriented Design principles that make software designs more understandable, flexible and maintainable. The SOLID acronym was introduced by Michael Feathers. Following are the five SOLID principles...
*** See complete answer in the Java Interview Guide.
For senior roles, specially for designer and architect roles, you will most likely be asked to design a real world system using object-oriented principles. This involves white boarding the design with UML diagrams, usually the class diagram, followed by implementation code using appropriate data structures, efficient algorithms and design patterns. Your solution will be evaluated for application of object-oriented principles, application of design patterns, appropriate use of data structures, use of efficient algorithms etc.
The interviewer typically starts off with a simple question such as 'design an elevator system using object-oriented principles' or 'design a parking lot using object-oriented principles'. You will usually be given half hour to one hour to design the solution. The interviewer will evaluate how you approach the problem and design your solution.
The following six step approach usually helps in solving these type of design questions.
1. Confirm the scope and assumptions with interviewer.
2. Identify the core classes.
3. Identify key methods and attributes in each class.
4. Identify the relationships between the classes utilizing OOD and design patterns.
5.Summarize the design using design diagrams.
6. Develop the code using appropriate data structures and algorithms.
Below questions and high level answers will highlight this six step approach.
We can tackle the problem using the six step approach as follows.
Step 1 - Confirm the scope and assumptions with interviewer:
Following are some of the questions you would want to ask the interviewer.
Step 2 - Identify the core classes:
The core class can be identified as
Step 3 - Identify key methods and attributes in each class:
Step 4 - Refine using OOD and design patterns:
Remove business logic from domain objects and add them to new business objects. Eliminate ParkingSpot class and instead maintain list of spot id and vehicle ids in the PrakingLevel class.
Step 5 - Summarize the design using design diagrams:
Based on information from above steps draw a high level design diagram. Usually a UML class diagram is expected by the interviewer.
Step 6 - Develop the code using appropriate data structures and algorithms.
Objects and classes are the building blocks of Java programming language. Numerous FAQs in Java interviews are based on your knowledge of Java classes and objects; on topics such as access modifiers, non-access modifiers, classes, class members, extension of classes, abstract classes, interfaces, constructors, overriding and overloading of methods etc.
Object class defined in java.lang package is the superclass of all other classes defined in Java programming language. Every class extends from the Object class either directly or indirectly. All classes inherit the instance methods defined in the Object class.
Object class defines eight non-static methods that are inherited by all other classes. A Java class can override any of these eight methods.
Methods having same name and return types but different arguments types can be declared within a class. These methods are called overloaded methods. This concept is known as method overloading
*** See complete answer and code snippet in the Java Interview Guide.
Final classes are Java classes that cannot be sub-classed. Final classes are declared using the keyword 'final'.
Final methods are methods that cannot be overridden by sub-classes. Final methods are declared using the keyword 'final'...
*** See complete answer and code snippet in the Java Interview Guide.
Access modifiers control how a class or its members can be accessed. Non-access modifiers control other aspests of a class and its members.
For your interview you have to know the following combination of modifiers.
1. Class access modifiers
Class non-access modifiers
3. Class-member access modifiers
4. Class-member non-access modifiers.
The next four questions addresses these combinations.
Following access modifiers can be added to a class declaration.
public - A class declared with public access modifier is accessible to all classes.
*** See complete answer and code snippet in the Java Interview Guide.
Following non-access modifiers can be added to a class declaration.
final - A class declared as final cannot be sub-classed...
*** See complete answer and code snippet in the Java Interview Guide.
Following are the access modifiers that can be added to members of a class,
public - A class member declared with public access modifier is visible and accessible to all classes.
*** See complete answer and code snippet in the Java Interview Guide.
Following are the non-access modifiers that can be added to methods of a class.
final - A final method cannot be overridden by a sub-class...
*** See complete answer and code snippet in the Java Interview Guide.
Java data types form the building blocks of a Java program and is an important and core topic in Java programming language. Java data types interview questions are frequently asked in Java programming interviews; on topics such as primitive data types, wrapper classes, scope of primitive data type, memory footprint of primitive data types, pass by reference vs pass by value etc.
Primitive data types are data types that are predefined in Java programming language and named by a reserved keyword. Java programming language supports eight different primitive types - byte, short, int, long, float, double, boolean and char.
byte, short, int and long are integer number types. byte has 8 bits and is the smallest integer number type. long has 64 bits and is the biggest integer number type. The default value for all integer number types is 0.
float and double are floating-point number types. doubles are bigger than floats. The default value for floating-point number types is 0.0
boolean has a true or false value.
char contains a single, 16-bit unicode value.
Type | Bits | Bytes | Min | Max | Default |
---|---|---|---|---|---|
byte | 8 | 1 | -28-1 | 28-1-1 | 0 |
short | 16 | 2 | -216-1 | 216-1-1 | 0 |
int | 32 | 4 | -232-1 | 232-1-1 | 0 |
long | 64 | 8 | -264-1 | 264-1-1 | 0 |
float | 32 | 4 | >NA | NA | 0.0f |
double | 64 | 8 | NA | NA | 0.0d |
boolean | 1 | NA | NA | NA | false |
char | 16 | NA | NA | NA | ' ' |
Memorize the data types, its bit sizes and the default values. An interviewer may not ask you questions directly on bits or ranges of data types, specially for a senior level position. But knowledge of this information is important in interviews where you are asked to write code, algorithms, etc.
You just need to memorize the data types and bit sizes. The minimum range value can be derived as -2bits-1. The maximum range value can be derived from 2bits-1-1.
Primitive Literals are the code representation of values of primitive data types. For example 'a' is a char literal, 100 is an int literal, 'false' is a boolean literal and 2345.456 is a double literal.
Integer Literals: Integer number types in the Java programming language can be representer in four different ways - decimal (base 10), octal (base 8), hexadecimal (base 16) and binary (base 2). You will use decimal representation in most cases; and rarely, if ever, use the other representations.
Floating-point Literals: Floating point literals are defined by a number, followed by a decimal point and then followed by more numbers representing the fraction. Example: 23435363.4336633. Floating-point literals are of type double by default which is 64 bits. If you want to assign a floating-point literal to a float variable you have to suffix the literal with either 'F' or 'f' (like 23435363.4336633F), else you will get a compilation error of a possible loss of precision. If you want to assign a floating-point literal to a double variable can optionally suffix the literal with either 'D' or 'd' (like 23435363.4336633D). It is optional since floating-point literals are of type double by default.
Boolean Literals: Boolean literals are code representations of boolean data types and can be defined only as either 'true' or 'false'. Some programming languages use numbers, usually 0 and 1, to represent boolean data type. But in Java programming language numbers are not allowed to represent boolean data types.
Char literals: char literals are represented by a single character in single quotes
Example:
//Decimal literal assigned to int data type
int i1 = 200;
//Binary literal assigned to int data type
int i2 = 0B00011;
//Octal literal assigned to int data type
int i3 = 011;
//Hexadecimal literal assigned to an int data type
int i4 = 0x071ff;
//Floating-point literal assigned to float data type
float f = 23435.45637F;
//Floating-point literal, with explicit suffix, assigned to double data type
double d = 43536376.3455365D
//Floating-point literal, without explicit suffix, assigned to double data type
double d1 = 4253636.4536;
//Character literal assigned to char data type
char c = 'a';
//Boolean literal assigned to boolean data type
boolean b = true;
Primitive Casting is used to convert primitive values from one data type to another. For example, an int value can be assigned to a float data type, or a double value can be assigned to an int data type. Casting can be either implicit or explicit.
Implicit Casting: In implicit casting the conversion happens automatically, without writing specific code to do the conversion. Implicit casting happens when you convert or assign a smaller value, like a byte, to a larger data type such as an int.
Explicit Casting: In explicit casting code has to be specifically written to perform the conversion from one primitive type to another. Explicit casting is done by using the syntax (data_type) where data_type is the data type that the cast is being applied to. Explicit casting happens when you convert or assign a larger value to a smaller data type.
Example:
//Implicit cast - smaller value is assigned to bigger data type
int i = 200;
long l = i;
//Explicit cast - larger value assigned to smaller data type
float f = 234.345f;
int i = (int)f;
After a primitive variable is declared and initialized; how long it lives in memory is dependent on the scope of the variable. Scope of a variable is determined based on where it is declared within a java class. Following are the various scopes of a variable in a java program based on where they are declared.
1. Class variable (Static fields) - Class variables are variables declared within the class body, outside of any methods or blocks, and declared with 'static' keyword.
Class variables have the longest scope. They are created when the class is loaded, and remain in memory as long as the class remains loaded in JVM.
2. Instance variables (Non-static fields) - Instance variable are variables declared within the class body, outside of any method or block, and declared without 'static' keyword.
Instance variables have the second highest scope. Instance variables are created when a new class instance is created, and live until the instance is removed from memory...
*** See complete answer and code snippet in the Java Interview Guide.
In Java, primitive variables are passed to methods by value. More specifically, a copy of the primitive value is passed to the method. If the passed value changes in the method, it does not change the original value.
There are many cases where we cannot directly use primitive data types. For example, We cannot put primitives into Java collections since Java collections (Lists, Sets etc.) can only store objects.
Wrapper classes are classes provided by java programming language that enable us to wrap primitive data in Objects....
*** See complete answer and code snippet in the Java Interview Guide.
Autoboxing is the automatic conversion of primitive data types into their corresponding wrapper classes by Java compiler. Java compiler applies autoboxing when a primitive data type is assigned to a variable of the corresponding wrapper class...
*** See complete answer and code snippet in the Java Interview Guide.
Java variables is an important, fundamental and core java programming topic. Many FAQs in Java interviews are based on your knowledge of Java variables. These include questions on topics such as primitive variables vs reference variables, variables types, static vs non-static variables, access modifiers and non-access modifiers that can be applied to variables, scope of variables, transient variables, volatile variables, variables vs primitive data types etc.
There are basically two different kinds of variables in Java programming language - Primitive variables and Reference variables. Primitive variables contain primitive literal values, where as reference variables contain a reference to an Object.
class MyClass {
//Primitive variable declaration - var1,
//var1 contains literal value 123.
int var1 = 123;
//Reference variable declaration - var2,
//var2 contains reference to object of type 'Box'.
Box var2 = new Box();
}
There are basically two different kinds of variables in Java programming language - Primitive variables and Reference variables. Primitive variables contain primitive literal values, where as reference variables contain a reference to an Object.
Based on scope, variables can be of four different types - Class variables, Instance variables, Local variables and Parameters. Scope of a variable is determined based on where it is declared within a java class.
1. Class variable (Static fields) - Class variables are variables declared within the class body, outside of any methods or blocks, and declared with 'static' keyword.
Class variables have the longest scope. They are created when the class is loaded, and remain in memory as long as the class remains loaded in JVM.
2. Instance variables (Non-static fields) - Instance variable are variables declared within the class body, outside of any method or block, and declared without 'static' keyword.
Instance variables have the second highest scope. Instance variables are created when a new class instance is created, and live until the instance is removed from memory.
3. Local Variables - Local variables are variables declared within a method body. They live only as long as the method in which it is declared remains on the stack.
4. Block variables - Block variables are variables declared within a block such as an init block or within a for loop. They live only during the execution of the block and are the shortest living variables.
class MyClass {
//Static variable
static String string1 = 'test string 1';
//Instance variable
String string2 = 'test string 2';
//Block variable in init block
{String string3 = 'test string 3'}
void perform() {
//Local variable
String string4 = 'test string 4'
//Block variable in for loop
for (int i=0; i < 4; i++) {...}
}
}
Static variables (or fields) are variables declared within the class body, outside of any methods or blocks, and declared with 'static' keyword.
Static variables have the longest scope. They are created when the class is loaded, and remain in memory as long as the class remains loaded in JVM.
Static variables are,essentially, global variables. A single copy of the static variable is created and shared among all objects at class level. All instances of the class share the same static variable.
A static variable can be accessed using the class, and without creating an object instance.
Class variables are stored on the heap.
class MyClass {
//Static variable
static String string1 = 'test string 1';
}
Instance variable are variables declared within the class body, outside of any method or block, and declared without 'static' keyword.
Instance variables have the second highest scope. Instance variables are created when a new class instance is created, and live until the instance is removed from memory.
Instance variables are stored on the heap.
class MyClass {
//instance variable
String string1 = 'test string 1';
}
Local variables are variables declared within a method body.
Local variables live only as long as the method in which it is declared remains on the stack.
Local variables are stored on the stack.
class MyClass {
void perform() {
//Local variable
Integer speed = 100;
}
}
Block variables are variables declared within a block such as an init block or within a for loop.
Block variables live only during the execution of the block and are the shortest living variables...
*** See complete answer and code snippet in the Java Interview Guide.
Final variables are variables declared with keyword 'final'. Once a value is assigned to a final variable it cannot be changed.
If final variable is a primitive variable, the primitive literal cannot be changed once it is assigned to the primitive variable...
*** See complete answer and code snippet in the Java Interview Guide.
Transient variable is a variable whose value is not serialized during serialization of the object. During de-serialization of the object, transient primitive variables are initialized to their default values...
*** See complete answer and code snippet in the Java Interview Guide.
Volatile variables are relevant in multi-threaded Java programming, in which multiple threads access the variables of an object. A volatile variable is declared with the keyword 'volatile'...
*** See complete answer and code snippet in the Java Interview Guide.
Java strings is a very important topic if you are preparing for a Java interview. Numerous FAQs in Java interviews are either directly or indirectly based on your knowledge of Java strings, including topics such as string builders, string buffers, string constant pools, immutability of strings, performance and efficiencies of string manipulations etc.
Strings in Java programming language are immutable, i.e. once a string object is created its value cannot be changed. When you change the value of a string reference variable, internally the java virtual machine creates a new string in memory and returns that value. The old string still exists in memory but is not being referenced.
//create new string 'abc'
String s = 'abc'; //'abc' is put into memory
//Modify string to 'abcdef'
s = s.concat('def')
Strings literals in Java programming language are immutable. Once a string is created in memory it cannot be changed. If a string literal has to be changed, the Java virtual machine creates the new string literal in memory and returns it.
To make it more memory efficient, the Java virtual machine has a special area of memory called the String constant pool. When a new string is required, the Java virtual machine first checks if the string literal exists in the string constant pool. If it exists then the string reference variable will refer to this string literal, a new literal in not created in memory. If the string literal does not exists in memory then a new string literal is created in the string constant pool.
String objects are immutable. Once a string object is created then its value cannot change. Every time you want to get a modified string value, the Java virtual machine will create a new string object. So if you modify a string 100 times, 100 string objects are created in memory.
Unlike string objects, StringBuilder objects are mutable. You can change the value of a string builder object without creating a new object. So you can modify a StringBuilder object many times, but only a single instance of the StringBuilder object is created.
StringBuilder is not thread safe, i.e it's methods are not synchronized; whereas StringBuffer is thread safe, i.e it's methods are synchronized.
Since the methods of StringBuilder are not synchronized, it is faster than StringBuffer.
If thread safety is not a requirement, you should use StringBuilder instead of StringBuffer.
The Integer wrapper class Java.lang.Integer provides two static methods, Integer.parseInt() and Integer.valueOf() that convert Strings to Integers. Integer.parseInt() returns a primitive int value whereas Integer.valueOf() returns an Integer object.
You can convert an Integer to a String using two ways. Using the static methods Integer.toString() and String.valueOf()...
*** See complete answer and code snippet in the Java Interview Guide.
Following are some of the commonly used methods in the String class
toCharArray() - Returns an array of the string's characters
chatAt() - Returns the character at a specific index position of the string
equals() - Returns true if this string matches the text of another string object.
*** See complete answer and code snippet in the Java Interview Guide.
Following are some of the key methods in StringBuilder and StringBuffer classes.
append() - Appends another string to this string.
insert() - Inserts another string into this string. You have to specify the index at which the string has to be included.
delete() - Deletes part of the string.
*** See complete answer and code snippet in the Java Interview Guide.
You can convert a string to a character of arrays by using the method toCharArray() on the String...
*** See complete answer and code snippet in the Java Interview Guide.
You can traverse a string two ways.
You can traverse through the characters of a string by using the index position of the string using string.charAt() method. The advantage of this method is that you are traversing the string in memory and are not creating a copy or buffer in memory.
*** See complete answer and code snippet in the Java Interview Guide.
You can traverse the characters of a string in reverse order in two ways.
You can traverse through a string by using the index position of the string using string.charAt() method. The advantage of this method is that you are traversing the string in memory and are not creating a copy or buffer in memory...
*** See complete answer and code snippet in the Java Interview Guide.
You are given a string. You have to remove specific characters from the string and print the string.
Lets say the string is 'This is my string' and you have to write a function that takes this string and prints out 'Thi i my tring'.
Your approach will be as follows.
1. Loop through the characters of the string.
2. Check if the character is 's'.
3. ...
*** See complete answer and code snippet in the Java Interview Guide.
You are given a string. You have to reverse the words in the string. Let's say the string is 'interviewgrid.com is awesome'. You have to write a function that takes this string as input and prints 'awesome is interviewgrid.com'. Assume that the words are separated by a single space.
Your approach to this function could be as follows.
1. Create a new StringBuilder object that will store the output string.
2. Tokenize the string into tokens, i.e. words, with single space as delimiter.
3. ...
*** See complete answer and code snippet in the Java Interview Guide.
Definition - Two string are anagrams of each other if they contain the same count of each character. For example - "interview grid" is an anagram of "view intergrid"
Assumption - Let's make the assumption that upper case and spaces are relevant for the comparison. i.e. "Interview Grid" is different from "interview grid". Check with the interviewer before making this assumption.
We can solve this problem two ways.
1. Sort the two strings and check if they are equal.
2. ...
*** See complete answer and code snippet in the Java Interview Guide.
Arrays are the most commonly used data structures in most programming languages. It is no different in Java programming language. Java Arrays, which are objects in Java programming language, are the most commonly used data structures in Java programs too. Java Arrays interview questions are very frequently asked both in telephonic screening interviews as well as in face-to-face interviews.
Arrays are objects in Java programming language that store multiple variables of the same type. Arrays can store either primitive data types or object references.
You declare arrays by prefixing square brackets [] to either primitive data type, or to reference data type whose objects that the array will contain.
Just like any other Java object, you instantiate array objects with the new keyword followed by the array type. In addition when you instantiate an array you have to specify the size of the array, i.e. how many objects the array will contain. After you instantiate the array, the array will be created in memory. If the array contains primitive data types then the array elements will be populated with the default values of the data type. If the array contains objects, then the array elements contain null values.
You initialize an array with actual values by adding the values to the array. You can add the value either at the time of installation or later by accessing the elements index.
//Declaration of an array containing string objects
String[] stringArray;
//Instantiation of an array
stringArray = new String[10];
//Initialize the elements of array by its index position
stringArray[5]='Test String';
//Declare, Instantiate and Initialize an array
String[] stringArray = {'Str1','Str2','Str3','Str4','Str5'};
Multi-dimensional arrays are arrays whose elements are themselves arrays. Similar to single dimensional arrays; multi-dimensional arrays can be declared, instantiated and initialized either separately or in a single statement.
// Declare, instantiate and initialize a multi-dimensional array separately
//Declare a multi-dimensional array
String[][] stringArray;
//Instantiate multi-dimensional array
stringArray = new String[2][5];
//Initialize multi-dimensional array
stringArray[1][2]='Test String';
//Declare, instantiate and initialize a multi-dimensional array
String[][] stringArray = {'Str1','Str2','Str3','Str4','Str5'},{'abc','efg'}
You can find the size of arrays by using the length property of arrays.
String[] stringArray = {'Str1','Str2','Str3','Str4','Str5'};
//Prints 5
system.out.println(stringArray.length);
For arrays containing primitive data types, the elements in the array are defaulted to the default values. So elements in an int array will be defaulted to 0, elements in a boolean array will be defaulted to false. For arrays containing object data types, the elements will have a default value of null.
You can reverse the elements in an array by looping through the array in reverse order and adding the elements to a new array...
*** See complete answer and code snippet in the Java Interview Guide.
You can copy the elements of one array to another array in two ways. Either by using the arraycopy() method provided in the System class Or by looping through the array and copying each element to the other array...
*** See complete answer and code snippet in the Java Interview Guide.
The Java program will throw an ArrayIndexOutOfBoundsException.
The java.util.Arrays class provides the sort() method that sorts an array of primitive data types in ascending numerical order.
Implemenation Algorithm - The sort() method for sorting primitive data types uses the Dual-Pivot Quicksort algorithm which is typically faster than the traditional One-Pivot Quicksort algorithm.
Time Complexity - O(N log(N))
*** See complete answer and code snippet in the Java Interview Guide.
The java.util.Arrays utility class provides the sort() method that sorts an array of objects in ascending order, according to the natural ordering of its elements.
Implemenation Algorithm - The sort() method for sorting arrays containing objects uses Mergesort algorithm instead of the Quicksort algorithm used for sorting arrays containg primitive data types.
Time Complexity - O(N log(N))
*** See complete answer and code snippet in the Java Interview Guide.
Java programming language provides numerous kinds of data structures and packages them within the Collections API. Java collections interview questions are very frequently asked both in telephonic screening interviews as well as in face-to-face interviews.
A collection is an object that groups or stores multiple objects of similar types. The objects that are stored in the collection are also called as elements of the collection.
Collections framework in Java programming language consists of the following.
1. Interfaces that represent different types of collections.
2. Concrete implementations of the collection interfaces.
3. Algorithmic implementations that perform useful computations, sorting, searching etc. on objects implementing the collection interfaces.
Java collections framework includes the following key interfaces.
1. Collection - java.util.Collection interface is the root of the Java collections framework hierarchy. All other core collection interfaces in the Java collections framework, except for maps, extend from the java.util.Collection interface either directly or indirectly.
2. Set - java.util.Set represents a collection of unique elements. A set cannot contain duplicate elements. A set can contain one null element.
7. SortedSet - java.util.SortedSet extends from Set interface, and maintains its elements in ascending order. The sorting is done according to the natural order of the elements. If a comparator is provided, then sorting is done according to the comparator.
3. List - java.util.List represents an ordered collection of elements. Lists are ordered based on their index position. List can contain duplicate elements. Elements in a list can be accessed, inserted or deleted by their index position.
4. Queue - java.util.Queue represents a collection that is typically ordered in a FIFO (first-in first-out) manner. i.e. an element which is first put into the queue will be the first to be removed when a call to remove or poll is made. In a FIFO queue, new elements are inserted to the tail of the queue and elements are removed from the head of the queue.
5. Dequeue - java.util.Deque represent collections that can be either in a FIFO manner or in a LIFO manner. In dequeues elements can be inserted, retrieved and removed from both ends of the queue.
6. Map - java.util.Map represents a collection object that maps keys to values. A map cannot contain duplicate keys, and each key can map only to one value. Unlike other core collection interfaces, Map does not extend from the Collection interface.
8. SortedMap - java.util.SortedMap extends from Map interface, and maintains its elements in ascending order. The sorting is done according to the natural order of the keys. Or, if a comparator is provided, then sorting is done according to the comparator on the keys.
Java collections framework provides classes HashSet, TreeSet, LinkedTreeSet, EnumSet and CopyOnWriteArray; which are implementations of java.util.Set interface.
HashSet
TreeSet
LinkedHashSet
Java collections framework provides classes ArrayList, LinkedList and CopyOnWriteArrayList; which are implementations of the List interface.
ArrayList
LinkedList
Java collections framework provides classes HashMap, TreeMap and LinkedHashMap; which are implementations of java.util.Map interface.
HashMap
TreeMap
LinkedHashMap
Java collections framework provides classes LinkedList and PriorityQueue; which are implementations of the Queue interface. In addition the java.util.concurrent package provides classes LinkedBlockingQueue, ArrayBlockingQueue, PriorityBlockingQueue, DelayQueue, SynchronousQueue...
*** See complete answer and code snippet in the Java Interview Guide.
Java collections framework provides classes LinkedList and ArrayDeque; which are implementations of the Deque interface. In addition the java.util.concurrent package provides the class LinkedBlockingDeque which extends from the Deque interface...
*** See complete answer and code snippet in the Java Interview Guide.
Java programming language provides wrapper functionality that adds additional functionality on top of that of collection classes. Wrapper functionality follows the decorator design pattern. Implementations of these wrapper methods are defined in the java.utils.Collections class.
Three main categories of wrappers are provided in the java.utils.Collections class. Synchronization wrappers, Unmodifiable wrappers and Checked Interface wrappers...
*** See complete answer and code snippet in the Java Interview Guide.
Java Reflection is an API provided in Java programming language that makes it possible to inspect classes, methods, fields etc. at runtime; without knowing their names at compile time. In addition to inspecting classes and its members, it is also possible to instantiate objects, call methods and set field values using reflection.
Java Reflection API is commonly used in the development of developer tools.
Visual Development Environments:Visual development environments use Java reflection to make the development process easier and more efficient by prompting the correct types and values to the developer
Class Browsers:Class browsers inspect class and its members
Debuggers and Testing Tools:
Performance overhead: Reflection works by dynamically resolving and inspecting classes and its members. with this flexibility comes its disadvantage - certain java virtual machine optimizations cannot be performed when types are resolved dynamically leading to slower performance as compared to normal class and method operations. When an operation can be performed non-reflective as well as reflective operation, always prefer the non-reflective operation. In performance sensitive applications, reflective operations must be avoided in loops and frequently called sections of code.
Security Restrictions: There are certain security impacts to using Reflection. Reflection needs a runtime permission which may not be available when running under a security manager, such as in an Applet.
Exposure of Internals: Java reflection enables us to perform certain operations which are illegal in non-reflective operations. For example - We can access the private members of a class which is illegal with non-reflective operations. This leads to dysfunctional and unportable code, and breaks the object oriented principle of abstraction and containment.
Every type; including reference types, primitive types (int, char etc.) and arrays have an associated java.lang.Class object. To perform reflection operation on a class, we have to first get its associated class object. Following are the different ways to get a Class object, depending on what the code has access to - object, type, class or name of class.
Class.forName(): If the code has access to a fully-qualified class name you can use 'Class.forName()' to get the class object of the fully-qualified class name.
Object.getClass(): If the code has access to an instance object you can use 'Object.getClass()' syntax to get the class object for the object instance.
Type.class:If the code has access to the type of class, you can use 'Type.class' syntax to get the class object for the type.
The package of a class can be accessed by calling the method getPackage() on the class object.
Class myClass = Class.forName('java.lang.String');
Package package = myClass.getPackage();
The interfaces of a class can be accessed by calling the method getInterfaces() on the class object...
*** See complete answer and code snippet in the Java Interview Guide.
The parent or super class of a class can be accessed by calling the method getSuperClass() on the class object...
*** See complete answer and code snippet in the Java Interview Guide.
Class access modifiers are the access modifiers such as public, private etc. that a class is declared with. Class modifiers can be accessed calling the method getModifiers() on the class object...
*** See complete answer and code snippet in the Java Interview Guide.
Constructors of a class can be accessed by calling the method getConstructors() on the class object...
*** See complete answer and code snippet in the Java Interview Guide.
Fields of a class can be accessed by calling the method getFields() on the class object...
*** See complete answer and code snippet in the Java Interview Guide.
Annotations of a class can be accessed by calling the method getAnnotations() on the class object...
*** See complete answer and code snippet in the Java Interview Guide.
Lambda expression is a Java programming language feature introduced in Java 8 that provides functional programming constructs to the Java programming language, which simplifies the Java code in certain cases such as with Java anonymous inner classes. Lambda expressions blends functional programming features with object oriented programming features of Java resulting in simplified and more powerful concurrency features.
Lambda expressions are blocks of Java code that can be defined and passed as data which can be executed at a later time.
Functional interfaces are Java interfaces which have only one declared (abstract) method. Functional interfaces can have other implemented methods such as default methods and static methods. Some of the common functional interfaces in Java are Runnable, Comparable, ActionListner etc.
Functional interfaces are generally implemented as inner classes and anonymous inner classes, which results in bulky code with many lines. This is sometimes referred to as 'Vertical' problem.
Lambda expressions are used to implement functional interfaces which define a single method. Lambda expressions avoid the vertical problem by simplifying the code of the traditional inner classes and anonymous inner classes.
Lambda expression simplifies the inner class and anonymous inner class code, which usually suffer from the 'vertical' problem (Too many lines of code required to implement a basic logic). Lambda expressions avoid the 'vertical' problem by simplifying and reducing the number of lines required to implement the inner class functionality.
Lambda expressions can be used implement interfaces having default and static methods only if there is a single abstract method in the interface. This called a functional interface.
From Java 8 onwards, an interface can contain default methods and static methods whose implementation is defined directly in the interface declaration.
A lambda expression consists of three parts
First - A parenthesized set of parameters, Second - An arrow pointing to right, Third - A body, which can be a block of Java code or a single expression.
//Passes an integer argument i, and returns 10+i
(int i) -> 10+i;
//Passes no arguments and returns 50
() -> 50;
//Passes string argument s and returns nothing
(String s) -> {system.out.println(s);}
A lambda expression can have zero, one or multiple parameters.
//Zero parameter lambda expression
() -> System.out.println('No parameters');
//One parameter lambda expression
(i) -> i*10;
//Multiple parameter lambda expression
(i1, i1) -> System.out.println(i1+i2);
This is a good exercise to clearly understand the concepts and advantages of lambda expressions. In below example we declare a functional interface 'EventChangeListener' that has one abstract method 'onChange()'. We then implement the interface to print the text 'Event Changed' when the onChange() method is invoked. For comparison, we implement the code using non-lambda code as well as with lambda expression...
*** See complete answer and code snippet in the Java Interview Guide.
Following three criteria must be met to match a lambda expression to an interface.
1. The interface must have one (and only one) abstract method...
*** See complete answer and code snippet in the Java Interview Guide.
Anonymous interface implementations can have state (member variables), whereas lambda expressions are stateless...
*** See complete answer and code snippet in the Java Interview Guide.
In most cases you do not need to specify the type for parameters in a lambda expression. The java compiler infers the type for the parameters by matching them with the parameter types of the abstract method of the functional interface.
For example, in below lambda expression ...
*** See complete answer and code snippet in the Java Interview Guide.
Yes, lambda function body can have multiple lines of code within curly braces {}...
*** See complete answer and code snippet in the Java Interview Guide.
Java arrays and collections are a core part of any Java program. Almost every Java application makes use of arrays or collections to process data, group data, summarize data and gather intelligence from data.
//List of states
List<State> stateList = Util.buildStateList();
//Print list of states codes
stateList
.stream()
.forEach(e -> {System.out.println(e.getStateCode()));}
//List of states
List<State> stateList = Util.buildStateList();
//Filter states and print state codes
stateList
.stream()
.filter(e -> e.getStateCode().startsWith('A'))
.forEach(e -> {System.out.println(e.getStateCode()));}
//List of states
List<State> stateList = Util.buildStateList();
//Filter states and print state codes
stateList
.stream()
.filter(e -> e.getStateCode().startsWith('A'))
.map(e -> e.getStateName().toUpperCase())
.forEach(e -> {System.out.println(e.getStateName()));}
*** See complete answer and code snippet in the Java Interview Guide.
*** See complete answer and code snippet in the Java Interview Guide.
*** See complete answer and code snippet in the Java Interview Guide.
Java generics was first introduced into the Java programming language in J2SE 5.0. Generics extends the Java type capabilities by enabling a Java type or method to operate on objects of different types. Generics also provides compile time safety, by identifying invalid types and throwing errors at compile time.
Generics in Java programming language enable Java types, i.e. classes and interfaces, to be declared as parameters to classes, interfaces and methods. Generics provide a way to reuse the same code with different inputs, i.e different types. Code that uses generics has many advantages over code that is non-generic.
A generic type is a generic class or interface that is parameterized over types.
Declaration of generic types - A generic class is declared using the format 'class MyClass
Instantiation of generic types - You instantiate a generic class using the new keyword as usual, but pass actual types within the parameter section. Example - 'MyClass
Generic methods are methods that are declared with type parameters. Generic methods can be static, non-static or constructors.
Declaration of generic methods -
Instantiation of generic methods
Bounded type parameters enable you to restrict the types that you can use as arguments for a parameterized type. For example if a method acts only on numbers, then you can use bounded parameters to specify that the method accepts only instances of Number or its sub-classes.
Similar to regular classes and interfaces, you can create sub-types of generic classes or interfaces by extending or implementing from the generic classes or interfaces.
For example, in Java collections API, ArrayList implements List and List implements Collections. The sub-type relation is preserved as long as the type argument does not vary. So, ArrayList implements List and List implements Collections.
Generics are applied at compile time provider stronger type checks. Once the type checks are complete, the compiler erases the type check code so that generics do not incur runtime over head...
*** See complete answer in the Java Interview Guide.
No Java generics cannot be applied to primitive types....
*** See complete answer in the Java Interview Guide.
No you cannot create instances of generic type parameters...
*** See complete answer in the Java Interview Guide.
The question mark (?) is termed as wildcard in generics code...
*** See complete answer in the Java Interview Guide.
Java programming language provides a robust error handling mechanism and is a core part of Java programming language. Proper and efficient error handling is required for any stable Java program. Java exceptions interview questions are very frequently asked both in telephonic screening interviews as well as in face-to-face interviews; on topics such as exceptions vs errors, runtime vs compile time errors, checked exceptions vs unchecked exceptions etc.
Java exceptions are problematic events that occur during the execution of Java programs, that disrupt the normal flow program. Examples - A java program that has to reads a file but the file does not exist in the file system during program execution,
A java program that tries to get an object from an array at an index position that is greater than the array
In java programing language exceptions are objects of type Exception. The exception object wraps details of the problem such as type of problem, state of program when the problem occurred etc. When an exception happens within a method, an exception object is created send to the Java runtime system
Creating an exception object and handing it over to the runtime system is termed as throwing an exception. A method hands over an exception to the Java runtime system by using the keyword throw followed by exception object. This method must also declare that it throws an exception by using the keyword throws in the method declaration followed by the type of exception that is thrown.
Java programming language provides three exception handling components - try block, catch block and finally block - that facilitate the handling of exceptions in java programming language.
1. Any Java code that may throw an exception can be enclosed within the try block.
2. An exception handler is tied to the try block in the form of the catch block which follows the try block. The catch block catches the exception, and handles or processes the exception.
3. finally block follows the catch block. The code in finally block always executes, irrespective of whether an exception is thrown in the try block or not. finally block is commonly used to close resources that were opened within the try block.
There are two kinds of exceptions in Java programming language - checked exceptions and unchecked exceptions.
Checked exceptions are compile time exceptions, i.e. the exceptions occur during compile time of the program, and the program has to handle these exceptions before it can be compiled.
Unchecked exceptions are run time exceptions, i.e the exception occurs during the program runtime.
Exceptions are problematic events that are caused by user or programmatic error. Exceptions are typically handled by the Java program in order to prevent abnormal termination of the program
Errors are problematic events that are beyond the control of user or programmer. Errors are not usually handled within the Java program
Yes, you can have multiple catch blocks in Java programming language. Each catch block handles a specific exception. The catch block specified first must catch an exception that is lower in the exception hierarchy, than an exception caught by the lower catch block.
Yes, In Java SE 7 and later, a single catch block can handle more than one type of exception.
throws is a keyword used in Java programming language that indicates that a method may return one or more specific types of exceptions...
*** See complete answer in the Java Interview Guide.
finally block is a block of code that is defined either after a try and catch block, or after a try block that is always executed.
*** See complete answer in the Java Interview Guide.
Yes you can have a finally block without the catch block...
*** See complete answer in the Java Interview Guide.
try-with-resource is a try block that declares and initializes one or more resources...
*** See complete answer in the Java Interview Guide.
Java provides the Java IO Api to read from and write to data sources through input and output classes. Java IO interview questions are frequently asked in Java interview, especially during telephonic screening and initial rounds.
I/O streams in Java programming language represent input sources from which data is read, and output destinations to which data is written. Streams support different kinds of data including bytes, characters, primitive types and objects.
Byte Streams - java.io package has two abstract classes InputStream and OutputStream that represents input stream and output stream of byte data type.
Character Streams - java.io package has two abstract classes Reader and Writer that represents input stream and output stream of character data type.
Primitive data streams- java.io package has two interfaces classes DataInput and DataOutput that represents input stream and output stream of primitive data type.
Object streams- java.io package has two interfaces ObjectInput and ObjectOutput that represents input stream and output stream of object data type.
Byte streams handle the I/O of raw binary data. Byte streams represent low-level I/O which are usually used for primitive I/O operations.
All byte stream classes in Java programming language extend from InputStream and OutpotStream. Some of the classes provided in Java programming language that are based on byte streams are - FileInputStream and FileOutputStream which handle the byte I/O of files, ByteArrayInputStream and ByteArrayOutputStream which perform byte I/O operations on a byte array, StringBufferInputStream and StringBufferOutputStream which perform byte I/O operations on strings, ObjectInputStrean and ObjectOutputStream which perform byte I/O operations on objects.
Character streams handle the I/O operations of character data sets.
All character stream classes in Java programming language implements from Reader and Writer interfaces. Some of the classes provided in Java programming language that are based on character streams are - InputStreamReader and InputStreamWriter which are byte-to-character 'bridge' streams, CharArrayReader and CharArrayWriter which perform byte I/O operations on a char arrays, StringReader and StringWriter which perform character I/O operations on strings, FileReader and FileWriter which perform byte I/O operations on character files.
Buffered streams provide buffered functionality to unbuffered streams by wrapping them.
Buffered streams perform I/O operations on buffers, and call native OS API only when the buffer is empty. This makes buffered streams highly more efficient than unbuffered streams.
Java I/O follows decorator pattern by enabling wrapping of one stream with another, i.e an unbuffered stream is wrapped with a buffered stream to provide buffered I/O operations.
Java programming language provides BufferdInputStream and BufferedOutputStream classes that wrap byte streams, and BufferedReader and BufferedWriter classes that wrap character streams.
Data streams provide binary I/O operations on primitive data (short, int, long, float, double, char, byte and boolean) and on strings. All data streams implement either the DataInput interface or the DataOutput interface
Object streams provide I/O operations on objects. Objects have to be serializable in order for object streams to operate on them...
*** See complete answer in the Java Interview Guide.
Java programming language provides the Scanner class that enables splitting of string and primitive data into separate tokens...
*** See complete answer in the Java Interview Guide.
There are two ways to define and run threads in Java programming language.
First way to define threads is to extend from java.lang.Thread class, and override its run() method. You instantiate and start this thread by creating a new instance of your class and calling the start() method
Second way to define threads is to implement java.lang.Runnable interface, and implement its run method. You can instantiate and start this thread by creating a creating a new instance of your class that implements Runnable interface, and passing this instance of Runnable to a new Instance of Thread.
Defining a thread by implementing the Runnable is the preferred way, since if you make your class extend from the Thread class, you will not be able to extend from any other class.
/** Extending from java.lang.Thread */
//Define
Class MyThread extends Thread {
public void run() {...}
}
//Instantiate
MyThread t = new MyThread();
//Start
t.start();
/** Implementing java.lang.Runnable interface */
//Define
Class MyRunnable implements Runnable {
public void run() {...}
}
//Instantiate
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
//Start
t.start()
A thread can be in one of five states
New - A thread is in 'New' state when it has been instantiated, but the start() method is not yet called on the thread instance. In this state the thread is a Thread object, but it is not yet a thread of execution.
Runnable - A thread is in Runnable state when the start() method has been called on the thread instance but it is not yet picked up by the thread scheduler for execution.
Running - A thread is in Running state when it is currently executing . The thread scheduler picks up the thread from the thread pool and executes it.
Waiting, Blocked, Sleeping - In this state the thread is not eligible for execution and is not in the running pool. A thread may be ineligible for execution for a variety of reasons. The thread may be blocked waiting for an IO resource or on a lock. The thread may be sleeping since the code tells it to sleep for a specific period of time. Or the thread may be waiting on another thread to send it a notification.
Dead - A thread is in dead state when the execution of its run() method is complete. Once a thread is dead it cannot be run again, hence a thread cannot transition from dead state to any other state.
You can pause the execution of a thread for a certain period of time by calling its sleep() method and passing the time that the thread has to stop executing.
Though you specify the time period that the thread should sleep for, there is no guarantee that the thread will pause executing exactly for that period of time.
The thread may start executing sooner than the specified time - if it gets an interrupt from another thread. Or the thread may start executing later than the specified time - After the specified sleep period of time has elapsed, the thread is put into the runnable pool of threads from where it will be picked up by the scheduler. The scheduler may pick up this thread for execution immediately or if there are higher priority threads then it will be executed later.
The join() method allows one thread to wait for the completion of another thread. For example - If t is a Thread instance, then calling t.join() in the current thread, say the main thread, will cause the main thread to wait until the t thread has completed its execution.
Sleep() method is used to delay the execution of the thread for a specific period of time...
*** See complete answer in the Java Interview Guide.
Yeild() method stops a running thread so that other threads which are in the waiting state and are of the same priority as the running thread will get a chance to execute...
*** See complete answer in the Java Interview Guide.
Java programming language provides the 'synchronized' keyword which allows only one thread at a time to access the shared resource...
*** See complete answer in the Java Interview Guide.
Synchronization is based on internal entities called intrinsic locks or monitor locks. Every object has an intrinsic lock associated with it...
*** See complete answer in the Java Interview Guide.
A thread cannot acquire a lock that is held by another thread. But a thread can acquire a lock that it already owns...
*** See complete answer in the Java Interview Guide.
Java programming language provides the wait(), notify() and notifyAll() methods that facilitate thread to thread communication.
wait() method lets a running thread, say Thread A, stop execution and wait on a specific action to complete in another thread, say Thread B. Thread A releases its locks and goes into waiting state while waiting for the specific action to complete on Thread B...
*** See complete answer in the Java Interview Guide.
Java programming language provides the Concurrency API which provides a high-level threading facility that is easier to use compared to the low-level threading facility using Thread and Runnable. Though most of the java concurrency interview questions are related to low-level threading, you will also find questions related to the Java concurrency API.
Java Concurrency framework contains classes in the java.util.concurrent package that provide a high-level abstraction for creating and executing multi-threaded programs, instead of low-level multithreading via explicit thread creation and execution.
The key classes provided in the Java Concurrency framework are Executor, ExecutorSevice, Callable, and Future.
Executor is a class provided in the Java Concurrency Framework that is used to submit a task for execution without controlling how or when the task is executed. Executor decouples the task that needs to be executed from the creation and starting of threads.
ExecutorService which extends from Executor, adds additional functionality to an Executor. ExecutorService has the ability to execute Callables and return Futures.
Executors is a class provided in the Java concurrency framework that provides factory methods to get different kinds of executors.
There are four kinds of Executors.
1. Cached Thread Pool Executors – A cached thread pool executor will create new threads when they are needed and will reuse existing threads in the pool that are free. Threads that are not used for 1 min are removed from the pool.
*** See complete answer in the Java Interview Guide
Callable is a functional interface similar to Runnable but return a value. Callable are submitted to ...
*** See complete answer in the Java Interview Guide
Parallel Fork-Join framework is used for highly parallelizable tasks. Parallel Fork-Join framework increases ...
*** See complete answer in the Java Interview Guide
A parallel fork-join task represents the problem to solve. When executed by a fork-join pool ...
*** See complete answer in the Java Interview Guide
RecursiveTask’s compute() method returns a value, whereas RecursiveAction’s compute() method returns void...
*** See complete answer in the Java Interview Guide
Atomic variables are thread-safe variable classes provided in Java Concurrency framework in the java.util.concurrent.atomic package. Atomic variables can be used for ...
*** See complete answer in the Java Interview Guide
Scheduled executors enables tasks to be executed after a delay or at regular intervals...
*** See complete answer in the Java Interview Guide
Concurrent collections are collection classes provided in the Java concurrency framework that are thread-safe, and in addition are ...
*** See complete answer in the Java Interview Guide
Copy-on-write collections are thread-safe and lock-safe collections provided in the Java concurrency framework. These collections are implemented ...
*** See complete answer in the Java Interview Guide
JDBC, which stands for Java Database Connectivity, is an API provided by the Java programming languages that provides a standard way to connect to relational databases. Following are the key database-independent tasks that are standardized by the JDBC API.
There are two key steps to connecting to a database using Java JDBC API
1. Load JDBC Driver - Every database that can be connected using JDBC API must have a corresponding JDBC Driver class that implements java.sql.Driver interface. Before you can make a connection to the database you must load the driver. From JDBC 4.0 onwards any JDBC driver found in the classpath is automatically loaded. Prior to JDBC 4.0 you have to load the driver specifically using Class.forName(JDBC Driver).
2. Open database connection -After loading the driver, you can open a connection to the database by calling getConnection() method on DriverManager class and passing the database connection URL, user id and password as arguments.
A Statement is an interface provided by the Java programming language that represents a SQL statement. You execute a statement object which returns a ResultSet object, which contains the database data returned by that query.
There are three kinds of statements. Statement, PreparedStatement and CallableStatement.
Statement is used to represent simple SQL queries that have no parameters.
PreparedStatement which extends Statement represents pre-compiled SQL statements that may contain input parameters.
CallableStatement which extends from PreparedStatement is used to execute stored procedures that may contain both input and output parameters.
You execute SQL queries by calling the execute() method on the statement object. Based on the type of query you can call either execute(), executeQuery() or executeUpdate().
execute() returns true if the query returns a result set. Use execute() if the query returns more than one result set. You can then get each result set by calling Statement.getResultSet().
executeQuery() returns one ResultSet object.
executeUpdate() is used to execute insert, delete or update SQL statements which update the rows of the database. execute() returns an integer representing the number of rows that were updated.
You can call a stored procedure by calling the execute() method on the CallableStatement object.
*** See complete answer in the Java Interview Guide.
ResultSet object contains the database data that is returned by the query. You can iterate and access the data from the result set via cursor which is a pointer pointing to one row in the ResultSet object.
*** See complete answer in the Java Interview Guide.
The ResultSet can be of three different types based on the flexibility of cursor movement and sensitivity of data in the database.
1. TYPE_FORWARD_ONLY - The result set cannot be scrolled. Its cursor can move forward only from before the first row to after the last row. You can move from one row to the next by calling next() on the result set.
*** See complete answer in the Java Interview Guide.
The concurrency of a ResultSet object defines if a ResultSet object can be updated or not. There are two types of ResultSet objects based on concurrence.
1. CONCUR_READ_ONLY - The ResultSet object cannot be updated using the ResultSet interface.
*** See complete answer in the Java Interview Guide.
Following are some commonly used methods to scroll a ResultSet.
next() - Moves the cursor forward one row from its current position.
previous() - Moves the cursor to the previous row in this ResultSet object.
first() - Moves the cursor to the first row in this ResultSet object.
*** See complete answer in the Java Interview Guide.
ResultSetMetaData object contains information regarding the types and properties of columns in ResultSet object. ResultSetMetaData object is retrieved by calling ...
*** See complete answer in the Java Interview Guide.
RowSet objects are derived from ResultSet and adds following capabilities...
*** See complete answer in the Java Interview Guide.
A RowSet object is considered either as connected or disconnected.
1. A connected RowSet is connected to a database, via a JDBC driver, throughout its life span.
*** See complete answer in the Java Interview Guide.
There are five different RowSet implementations.
1. JdbcRowSet – JdbcRowSet is an implementation of connected RowSet object. JdbcRowSet is similar to ResultSet. JdbcRowSet is commonly used to wrap a non-scrollable and read-only ResultSet object to add the scrolling and update capabilities to the ResultSet.
*** See complete answer in the Java Interview Guide.
A transaction is a set of statements that executes as a unit. So either all of the statements in a transaction are executed successfully or none of them are.
*** See complete answer in the Java Interview Guide.
Java programming language provides the networking API to connect to external URLs, clients and systems. Java networking interview questions are commonly asked for senior level java programming positions or if the job role requires networking experience.
The Java API provides the URL class which can be used to represent the URL address. You can create the URL object if you have the URL address string. The URL class provides getter methods to get the components of the URL such as host name, port, path, query parameters etc.
String urlString = 'http://www.codinggrid.com';
URL url = new URL(urlString);
The Java API provides the 'URLConnecton' class which can be used to create a connection to a URL. If you have a URL object, you can get the URLConnection object by calling openConnection() method on the URL object. Once you have the URLConnection object you can connect to the URL resource by calling the connect() method on the URLConnection object. You can use the URLRequest object to setup parameters and properties that you may need for making the URL connection.
String urlString = 'http://www.codinggrid.com';
URL myUrl = new URL(urlString);
URLConnection myUrlConnection = myUrl.openConnection();
myUrlConnection.connect();
1. Create the URL object
2. Create URLConnection object
3. Open connection to URL
4. Get input stream from connection
5. Read from input stream
6. Close input stream
1. Create the URL object
2. Create URLConnection object
3. Open connection to URL
4. Get output stream from connection
5. Write to output stream
6. Close output stream
Following are some key methods provided in the URL class
openConnection() – Returns a URLConnection object that represents a connection to the URL
getContent() – Gets the contents of the URL
getHost() – Gets the host name of the URL
getPath() – Gets the path of the URL
getPort() – Gets the port of the URL
getProtocol() – Gets the protocol name of the URL
Sockets are end points in the communication link between a client program and a server program exchanging data over a network.
On the server side: a socket is bound to a specific port number. The server listens to the socket, waiting for a client to make a connection request.If a connection from a client is successful, the existing socked is used to communicate with that client. In addition a new socket is created and ties to the same port so that the server can listen to new connections from other clients.A new
On the client side: ...
*** See complete answer in the Java Interview Guide.
1. Open a socket
2. Open an input stream and output stream to a socket
*** See complete answer in the Java Interview Guide.
TCP is a protocol that provides a reliable, point-to-point communication channel that client-server application use to communicate with each other. To communicate over TCP, a client program and server program must first establish a connection to each other through sockets at each end of the communication channel. To communicate, the client and server reads from and writes to the sockets bound to the connection.
Like TCP, UDP is protocol that provides a communication channel that client-server applications use to communicate with each other. But unlike TCP...
*** See complete answer in the Java Interview Guide.
Datagram is an independent, self-contained packet of information send over the network between server and client programs in UDP protocol. The delivery of datagrams to their destinations in not guaranteed. The order of arrival...
*** See complete answer in the Java Interview Guide.
Using UDP protocol, a server can send or broadcast datagrams to multiple clients. Java programming language provides java.net.MultigramSocket which can be used to broadcast datagrams to multiple client programs...
*** See complete answer in the Java Interview Guide.
A network interface is the point of interconnection between a computer and a private or public network.
*** See complete answer in the Java Interview Guide.
You can get a list of IP addresses that are assigned to a network interface using the NetworkInterface class.
*** See complete answer in the Java Interview Guide.
Java provides a robust security platform that makes it easy for Java developers to develop secure Java applications. But Java security is a difficult topic to prepare or master for Java programming interviews. Java security is a huge and complex topic, with security features available at different levels and layers of the platform. Often times, when your are preparing for a Java interview, it is even difficult to figure out where to begin.
Security is provided by the Java platform through a number of mechanisms.
Secure environment - Java programs run in a secure and restricted environment. The level of access that a Java program can have to important system resources can be restricted based on the trustfulness of the program
Java language features - Java programming language provides a number of in-built features such as automatic memory management, garbage collection array and string range checking etc. which enhances the security of a Java application.
JVM features JVM is designed to provide secure environment for Java applications to be run in - JBytecode verifiers ensure that only legitimate and valid Java bytecodes are executed by the JVM. Java class loaders ensure that only legitimate and secure Java class files, which do not interfere with the running of other Java programs are loaded into the JVM. Access to important resources is provided through the JVM, and is pre-checked by SecurityManager class to ensure that access or restrictions of a resource to a specific resource.
Plugins - Additional security features can be plugged in into the platform and used by Java programs.
Security has been an integral part of Java platform since its introduction.
Java 1.0.x - Java started with a security model, commonly known as the sandbox security model. In this model all Java programs run locally are considered trusted, and can access local resources. Java applets, which are downloaded over the network, are considered untrusted and cannot access resources beyond the sandbox. Access to resources is mediated through the SecurityManager class
Java 1.1.x - Java 1.1.x introduced the concept of 'signed applets', which allowed downloading and running Java applets as trusted code after verifying the applet signer's information.
Java 2 (J2SE) - Java 2 platform provided significant changes and enhancements to security.
Java programming language has several inherent features that contribute to the security of the Java application
*** See complete answer in the Java Interview Guide.
Java API provides the java.security.Permission class which represents access to system resources such as files, sockets etc. and is a core part of Java security platform.
A number of specific permission classes, such as FilePermission, AWTPermission and SocketPermission are sub-classes of java.security.Permission class.
Protection domains are groups of classes having the same permissions. Classes are grouped into protective domains, and...
*** See complete answer in the Java Interview Guide.
The Java programming API provides the java.lang.SecurityManager class which mediates access to all resources. The SecurityManager class has a number of check() methods which determines if a class can access a specific resource. For example ...
*** See complete answer in the Java Interview Guide.
Key classes related to security are provided by the Java programming API in java.security.* package...
*** See complete answer in the Java Interview Guide.
Many people have trouble answering JVM interview questions. This is due to a couple of reasons. Firstly, one could be an experienced Java programmer, programming for years, without knowing the internals of JVM. Secondly, one usually deals with JVM internals only when there are some performance issues, or if the job role or the company product necessitates dealing with JVM internals.
JVM - JVM, which stands for Java Virtual Machine, is a virtual machine that understands and runs java bytecodes.
When you compile a java program, the output is a .class file which contains bytecodes. JVM understands bytecodes and can execute the .class Java files.
There are specific implementations of the JVM for specific platforms - Windows, Linux etc. The same Java .class file can be run for any of the JVM implementations. This is how Java programming language is platform independent and make the Java programs portable i.e write once, run anywhere.
JRE - JRE, which stands for Java Runtime Environment, provides an implementation of the JVM, supporting libraries and other components required to run Java programs. JRE also provides components that enable two kinds of deployment of Java programs. Java plug-in, which enables java programs to run on browsers and Java Web Start, which deploys standalone java applications.
JDK - JDK, which stands for Java Development Kit, contains the JRE plus tools such as compilers, debuggers etc. which are required for developers to develop Java programs.
When you compile a Java program, the output is a .class file which contains bytecodes that are machine and platform independent. JVM understands the bytecode and runs Java programs. Specific JVMs are implemented for specific platforms. The same .class file can run on any JVM implemented on any platform and machine. So you write a Java program once, compile it once, and run it in any platform.
Java bytecode is an intermediate language between Java which is the language in which the developer develops the program, and the machine language which runs the program. When a Java program is compiled, the output is a .class file which contains bytecodes. JVM loads the Java classes through class loader and executes them.
Java program (.java files) are compiled into bytecodes (.class files) using the Java compiler (javac). A class loader, which is a component of the JVM loads the compiled Java bytecodes into specific areas called runtime data areas. Java execution engine, which is also a component of the JVM executes the Java bytecodes.
Java class loaders are components in JVM that load Java class file at runtime, when they are referenced for the first time. Each class loader has its own specific namespace, in which it stores the classes that it loads.
Following are the key characteristics of Java class loaders
Hierarchy - Java class loaders in JVM are hierarchal with a parent-child relationship. Bootstrap class loader is the parent of all class loaders.
Delegation model - Before a class loader loads a class, it checks if its parent class loader has already loaded that class. If the parent class loader has loaded that class, then that class is used. If the parent class loader has not loaded the class, then the child class loader loads the class and uses it.
Visibility - ...
*** See complete answer in the Java Interview Guide
There are four main Java class loaders in the JVM. Bootstrap class loader, Extension class loader, System class loader, User defined class loader
Bootstrap class loader - Bootstrap class loader is the parent class loader in the class loader hierarchy in JVM. Bootstrap class loader loads Java API classes.
Extension class loader - ...
*** See complete answer in the Java Interview Guide
Following are the key steps by which a class is loaded and initialized by the JVM
Load - The class file is loaded to JVM memory.
Verify - Verifies that...
*** See complete answer in the Java Interview Guide
Runtime data areas are memory areas assigned when the JVM runs on the OS. Runtime data areas are of two kinds - Those that are created for each thread and those that are shared by all threads...
*** See complete answer in the Java Interview Guide
Java class files or bytecodes that are loaded to the runtime data areas are executed by the execution engine, which is a component of the JVM. Before executing, the execution engine reads and transforms the bytecodes into ...
*** See complete answer in the Java Interview Guide
A lot of factors can impact the performance of an application developed in Java programming language. At a high level following areas can be optimized to improve Java application performance.
JVM
Java program
Connectivity optimizations
Benefits:
Dis-advantages:
During garbage collection process, the JVM may stop all the application process threads from execution. This freezing of application processes is termed as 'Stop The World'
Java heap is structured into following sections, also called as generations.
New Generation - All new objects created by a Java program are put into the new generation section of the heap. Garbage collection runs on the new generation and removes all short-lived objects.
New generation section is further split into two sections. Eden space and Survivor space.
Old Generation - Objects that survive the survivor section of the new generation section are promoted to the old generation section. The old generation section is much larger than the new generation. A separate garbage collection process, also called as FullGC, happens in the Old generation section.
PermGen - JVM uses PermGen to store the meta-data about classes.
Following are some of the algorithms available for garbage collection
Serial GC - Designed for single CPU machines. Stops all application processes during garbage collection. Goes through all objects, marks objects for garbage collection, removes them.
Parallel GC - Similar to Serial, except used multiple threads for garbage collection.
Concurrent Mark Sweep - Concurrent Mark Sweep does most of the garbage collection concurrently with the application processes. Hence, the amount of time that all application process are completely stopped are greatly reduced.
G1GC (Garbage first garbage collector) - ...
*** See complete answer in the Java Interview Guide
The finalize() method is called by the garbage collector on an object before it releases the object from memory. The garbage collector releases an object ...
*** See complete answer in the Java Interview Guide
Following are some common flags you would set to tune JVM
*** See complete answer in the Java Interview Guide
Memory leaks in a Java program happen when references to objects are not released. This fills up the heap space and ...
*** See complete answer in the Java Interview Guide
Following are some of the key features introduced in Java 8
1. Lambda Expressions: Functional programming constructs introduced in Java programming language to simplify java code.
2. Method references: Feature that enables reference to methods and method constructors without executing them.
3. Default and Static methods in Interfaces: Enables to add new functionality to interfaces, without impacting implementing classes.
4. Repeating annotations: Enables to repeat the same annotation multiple times to a declaration or type.
5. Type annotations: Annotations that can be used anywhere where a type is used.
6. Collections - Streams API: Functional-style operations that act on streams of data elements.
7. Security: New features and enhancements to Java Security API.
8. Concurrency: New interfaces and classes added to Concurrency API.
Lambda expressions is a Java programming language feature introduced in Java 8 that provides functional programming constructs to the Java programming language, which simplifies the Java code in certain cases such as with Java anonymous inner classes. Lambda expressions blends functional programming features with object oriented programming features of Java resulting in simplified and more powerful concurrency features.
Lambda expressions are blocks of Java code that can be defined and passed as data which can be executed at a later time.
Prior to Java 8, Interfaces could contain only method declarations in the form of abstract methods.
In Java 8, interfaces can contain method implementations in the form of static methods and default methods.
Static methods, similar to the class static methods, can now be implemented in interfaces. Interface static methods cannot be overridden by implementing classes. Similar to a class static method, an interface static method can be invoked outside of the interface by using interface name.
Default methods are declared using the 'default' keyword, and can be added either to new interfaces or to existing interfaces. New classes implementing the interface can override the default methods. Existing classes already implementing the interface are not impacted.
//interface with abstract, default and static methods
public class MyInterface() {
//abstract method
abstract void logAbstract();
//default method
default void logDefault() {
System.out.println('default method invoked');
}
//static method
static void logStatic() {
System.out.println('static method invoked');
}
}
Java 8.0 introduced a new Java language feature regarding annotations. You can now repeat an annotation multiple times on a type declaration.
Java 8.0 introduced a new Java language feature regarding annotations. In addition to using annotations on type declarations, you can now apply annotations whenever you use types.
Following are some examples of Type annotations
@NonNull
@ReadOnly
@Regex,
@Tainted
@Untainted
Java 9 is a major release of Java which introduced the concept of Java platform module system. In addition Java 9 includes enhancements to the Java core libraries, JVM tuning, Security, Deployment and JDK Tools.
Java 9 is a major enhancement release of the platform containing enhancements to the Java core libraries, JVM, security, tools etc. Following are some of the key features and enhancements introduced in Java 9.
1. Java Platform Module System
2. Factory Methods for Collections
3. Private methods in Interfaces
4. Improvements to Streams API
5. New tool JShell
6. New tool JLink
7. Support for HTTP/2
Java 9 introduced a new concept and component called 'Module' which adds a higher level of aggregation over packages. A module consists of a group of related packages and resources which are reusable. In addition, the module specifies the list of external modules that it is dependent on, and also list of its packages that it makes available to other modules.
Java 9 divides the JDK into several modules that support different configurations. The Java command 'java --list-modules' lists out all the modules in the JDK. Modularization in JDK enables to greatly reduce the runtime size of Java application. For example, if you have a java application for IoT devices and does not have the need for Java GUI classes, then you can create a specific runtime that does not include the GUI modules.
A module declaration begins with the keyword 'module' followed by the module name and curly braces {..} for the body. The module body can contain various module directives such as requires, exports, uses etc.
Following code snippet highlights the module declaration syntax.
module moduleA {
//module dependency
requires moduleB;
//packages made available to other modules
export packageA;
export packageB;}
A module is defined in a module declaration file, which is a file named 'module-info.java' in the project’s root folder. The module declaration gets compiled into module-info.class in the JAR’s root. This is called the module descriptor.
A module has three properties - name, dependencies and exports
A module declaration begins with the keyword 'module' followed by the module name and curly braces {..} for the body. The module body can contain various module directives such as requires, exports, uses etc.
Following code snippet highlights the module declaration syntax.
module moduleA {
//module dependency
requires moduleB;
//packages made available to other modules
export packageA;
export packageB;}
No, module names have to be unique. if multiple modules have the same name at compile time, a compilation error occurs. If multiple modules have the same name at runtime, an exception occurs.
Yes, a module and a package within that module have the same name.
Java 9 added static factory methods for collections that can be used to easily create small immutable collections with minimum lines of code.
Examples of these methods are List.of(), Set.of() and Map.of().
List.of('US','UK','CA')
Set.of('US','UK','CA')
Map.of('US','United States','UK','United Kingdom','CA',''Canada)
In Java 9 we can define private and private static methods. These methods can be used by other methods in the interface, hence it prevents code duplication and enables code reuseability. By defining them as private we prevent the sub-classes from accessing these methods.
Private methods must contain a body and they cannot be abstract.
Prior to Java 7 Interfaces could contain only 'public abstract' methods.
Since Java 8, in addition to 'public abstract' methods you could also have 'public static' methods and 'public default' methods.
Since Java 9, in addition to 'public abstract', 'public static' and 'public default' methods; you can have 'private' methods. Private methods can be called from static methods and default methods from within the interface. private methods in interfaces are not accessible to the implementation class.
public interface MyInterface {
//abstract method
public abstract void method1();
//default method
public void method2() {
...
}
//static method
public void method3() {
...
}
//private method
private void method4() {
...
}
}
Java 9 introduced the following new features to the Streams API
1. takeWhile(Predicate p): If the stream is ordered, then this method returns a stream consisting of the longest prefix of elements taken from this stream that match the given predicate. If the stream is unordered, then this method returns a stream consisting of a subset of elements taken from this stream that match the given predicate.
2. dropWhile(Predicate p): If the stream is ordered, then this method returns a stream consisting of the remaining elements of this stream after dropping the longest prefix of elements that match the given predicate. If this stream is unordered, then this method returns a stream consisting of the remaining elements of this stream after dropping a subset of elements that match the given predicate.
3. iterate():
4. ofNullable(): This method returns a sequential Stream containing a single element, if non-null, otherwise returns an empty Stream.
JShell is an interactive REPL (Read-Eval-Print-Loop) tool provided in Java 9 which is useful for learning the Java programming language and prototyping Java code. You can launch JShell from the console and directly type and execute Java code. The immediate feedback of JShell makes it a great tool to explore new APIs and try out language features.
To start JShell, enter the command 'jshell' on the command line.
% jshell
| Welcome to JShell -- Version 9
| For an introduction type: /help intro
jshell>
To exit JShell enter the command '/exit' on the command line.
jshell> /exit
| Goodbye
JLink is Java’s new command line tool through which you can create you own customized JRE by linking sets of modules (and their transitive dependencies) to create a run-time image.
JLink will allow you to both simplify and reduce the size of deployment.
Java 9 introduced new class that handles http/2 connections.
These classes are
1. HttpClient - which handles the creation and send of requests.
2. HttpRequest which is used to construct a request to be sent via the HttpClient.
3. HttpResponse which holds the response from the request that has been sent.
Java 10, released six months after Java 9, is the first JDK release that conforms to Oracle's new six-month release cycle.
Following are the new features of Java 10.
1. Local variable type inference - Java 10 introduces the keyword 'var' which enables you to declare a local variable without specifying its type. The type for the variables is determined based on the type of object assigned to the local variable.
Example:
var myLocalVar1 = 1 //myLocalVar1 is of type int;
var myLocalVar2 = 'Ace Your Interview' //myLocalVar2 is of type String;
var myLocalVar3 = new HashMap
This is the only feature interesting from a developer point of view.
2. Unmodifiable collection enhancements - Java 10 introduces new static methods 'copyOf()' on the List, Set and Map interfaces to create unmodifiable collections. if you attempt to modify this collection then you get an UnsupportedOperationException.
3. Application class-data sharing - Class data sharing (CDS) feature has been a part of JDK since Java 8. CDS helps reduce the startup time and memory footprint between multiple Java Virtual Machines (JVM).
Java 10 introduced Application class-data sharing (ApsCDS) that extends the CDS to include selected classes from the application class path.
4. Other changes - Includes improvements to Garbage Collection, New just-in-time compiler, Consolidation of JDK to a single repository, Thread-local handshakes, Time based release versioning, and removal of javah tool from the the JDK.
Java 11 was released in Septemper 2018 six months after Java 10 conforming to Oracle's new six-month release cycle.
Following are some key new features of Java 11.
1. New methods in String class - Following new methods are added in the String class which help in manipulating String objects and reduce boilerplate code.
2. Local-Variable Syntax for Lambda Parameters The reserved type name 'var' (local variable syntax) can now be used when declaring the formal parameters of a lambda expression. This enables us to apply modifiers such as type annotations to lambda parameters.
New dafault toArray() method in Collection - A new default method toArray(IntFunction) has been added to the java.util.Collection interface. This method allows the collection's elements to be transferred to a newly created array of a desired runtime type.
String[] strArray = list.toArray(String[]::new)
HttpClient - The new HTTP client introduced in Java 9 which supports HTTP2 is now a standard feature in Java 11.