Java Interview Guide - 250+ Java Interview Questions And Answers


Java - Object Oriented Programming

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.


What is object-oriented programming? What are the key principles of object-oriented programming?

FAQKey Concept

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.

Java Interview Questions

What is Abstraction?

FAQKey Concept

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;
}

What is Encapsulation?

FAQKey Concept

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){...}
}

What is Inheritance?

FAQKey Concept

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
}

What are Interfaces in Java programming language?

FAQKey Concept

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.


What is Polymorphism?

FAQKey Concept

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.


What is generalization. What are the two forms of generalizations?

Key Concept

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.


What is the difference between aggregation and composition?

Key Concept

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.


What are SOLID principles of Object Oriented Programming?

FAQ

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.

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

Approach to white board design questions


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.


Design a parking lot using object oriented principles.

FAQ

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.

  • How many levels does the parking lot have?
  • How many parking spots are there in each parking level?
  • Are there different kinds of parking spots like compact, regular etc?
  • What kind of vehicles are allowed to park in the parking lot?
  • Is there a 'parking full' indicator for the parking structure?
  • Is there a 'parking full' indicator at the parking level?

Let's assume that you have to design for a parking structure with 3 levels, each level containing 200 parking spots, all spots are regular spots, cars only can park in this parking lot, and it has 'parking full' indicators both for the parking lot as well as for each level

Step 2 - Identify the core classes:
The core class can be identified as

  • ParkingLot
  • ParkingLevel
  • ParkingSpot
  • Vehicle

Step 3 - Identify key methods and attributes in each class:

  • ParkingLot - Contains one or more ParkingLevels (Composition/Has-A relationship) and has methods isFull(), park(), unPark().
  • ParkingLevel - Contains ParkingSpots (Composition/Has-A relationship) and has methods isFull(), park() and unPark().
  • ParkingSpot - Can have zero or one vehicle parked in it (Aggregation) and has method isOccupied().
  • Vehicle - Has unique vehicle id and parking spot id, and has methods park() and unPark().

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.

  • ParkingLot - Contains one or more ParkingLevels.
  • ParkingLotBO - Has methods isFull(), park() and unPark().
  • ParkingLevel - Contains map of spot ids to vehicle ids.
  • ParkingLevelBO - Has methods isFull(), park() and unPark().
  • Vehicle - Has methods park() and unPark().
  • ParkingLotController - Acts as a gateway to the parking lot.

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.

The Java Interview Guide lists out the above steps in detail and has the complete code for this design question.


Java - Objects & Classes

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.


What is Object class in Java programming language?

FAQKey Concept

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.


What are the non-static methods defined in the Object class that are inherited by all classes?

FAQKey Concept

Object class defines eight non-static methods that are inherited by all other classes. A Java class can override any of these eight methods.

  • clone() - If a class implements cloneable interface, then calling clone() method on its object returns a copy of the object. If a class does not implement the cloneable interface, and clone() method is called on its object, then the method throws a CloneNotSupportedException exception.

  • toString() - You can get a string representation of any Java object by calling its toString() method. The toString() method is defined in the Object class and is inherited by all Java classes. The toString() method is usually overridden so that it returns a meaningful string representation of the object.

  • equals() - You can check if an object equals another object by calling its equals() method and passing another object as a parameter to compare for equality.

    The equals() method defined in the Object class uses the identity operator (==) to determine if two objects are equal. Hence this method returns correct result for primitive data types; but returns incorrect result for objects since the identity operator checks if the object references are equal instead of checking the logical equality of objects.

    Hence equals() method is usually overridden to compare the logical equality of objects rather than their references.

  • hashcode() - You get the hash code of an object by calling its hashcode() method. An objects hash code determines its memory address.

    As a rule, if two objects are equal then their hash codes must also be equal. If you override equals() method, then you also have to override the hashcode() method to ensure that objects that are equal will have the same hash codes.

  • finalize() - The Java garbage collector calls the finalize() method of an object just before the object is garbage collected. But you cannot control when, or if, an object is garbage collected. Hence, you should not rely on this method to perform critical tasks.

  • getClass() - Calling getClass() method on an object returns a Class object which is a runtime class of this object. The Class class defines a number of methods which helps to find the metadata of a class - such as the class name, methods defined in the class, check if the class is an interface, check if the class is an interface etc.

  • wait() - wait() is one of the three methods defined in Object class that facilitates thread to thread communication in multi-threaded Java programs. Calling wait() on an object of type Thread stops the execution of current thread until the processing of the other thread is complete.

  • notify() - notify() is the second method defind in Java object class that facilitates thread to thread communication in multi-thread programming. notify() method will send an event notification or signal to a thread that is waiting in that object's waiting pool.

  • notifyAll() - notifyAll() is the third method defind in Java object class that facilitates thread to thread communication in multi-thread programming. notifyAll() is similar to notify(), except that it sends notification to all threads that are waiting in that objects waiting pool

Java Interview Questions

What is the difference between method Overloading and method Overriding?

FAQKey Concept

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.


What are final classes and final methods Java programming language?

FAQKey Concept

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.


What are Access and Non-Access modifiers that can be added to a class or class-member declaration?

FAQ

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.


What are the access modifiers that can be added to a class?

FAQ

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.


What are the Non-access modifiers that can be added to a class declaration?

FAQ

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.

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

What are the access modifiers that can be added to members of a Class?

FAQ

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.


What are the non-access modifiers that can be added to members of a Class?

FAQKey Concept

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

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.


What are primitive data types? What are the primitive data types supported by Java programming language?

FAQKey Concept

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.

TypeBitsBytesMinMaxDefault
byte81-28-128-1-1 0
short162-216-1216-1-1 0
int324-232-1232-1-1 0
long648-264-1264-1-1 0
float324>NANA0.0f
double648NANA0.0d
boolean1NANANAfalse
char16NANANA''

Java Interview Questions

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.


What are Primitive Literals?

FAQ

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;

What is Primitive Casting in Java programming language?

Key Concept

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;

How long do primitive variables exist in memory? Define the various scopes of primitive variables?

FAQKey Concept

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.


How does Java programming language pass primitive variables to methods - by value or by reference?

FAQKey Concept

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.

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

What are wrapper classes in Java programming language?

FAQKey Concept

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.


What is Autoboxing and Unboxing?

FAQKey Concept

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

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.


What is the difference between primitive variables and reference variables?

FAQKey Concept

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();
}

What are the different kinds of variables defined in java programming language?

FAQKey Concept

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++) {...}
}
}
Java Interview Questions

What are static variables in Java programming language?

FAQKey Concept

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';
}

What are instance variables in Java programming language?

FAQKey Concept

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';
}

What are local variables in Java programming language?

FAQKey Concept

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;
}
}
Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

What are block variables in Java programming language?

FAQKey Concept

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.


What are final variables in Java programming language?

FAQKey Concept

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.


What are transient variables in Java programming language?

FAQKey Concept

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.


What are volatile variables in Java programming language?

FAQKey Concept

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

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.


What do you understand by immutability of Java String objects?

FAQKey Concept

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')
Java Interview Questions

What do you mean by String constant pool?

FAQKey Concept

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.

Java Interview Questions

What is the difference between String and StringBuilder?

FAQKey Concept

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.


What is the difference between StringBuilder and StringBuffer?

FAQKey Concept

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.


How do you convert a String to an Integer in Java programming language?

FAQKey Concept

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.

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

How do you convert an Integer to a String in Java programming language?

FAQKey Concept

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.


What are some of the key methods in String class?

FAQKey Concept

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.


What are some of the key methods in StringBuilder and StringBuffer class?

FAQKey Concept

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.


How do you convert a string to a character array?


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.


How do you traverse through the characters of a string?


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.

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

How do you traverse through the characters of a string in reverse order?

FAQKey Concept

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.


How do you remove specific characters of a string?

FAQKey Concept

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.


How do you reverse the words in a string?

FAQKey Concept

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.


Write a function to check if two strings are anagrams of each other?

FAQKey Concept

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.


Java - Arrays

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.


What are arrays in Java programming language?


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.


How do you declare, instantiate and initialize arrays?

FAQKey Concept

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'};

What are multi-dimensional arrays? How do you declare, instantiate and initialize multi-dimensional arrays?

FAQKey Concept

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'}

How do you find the size of arrays?

FAQKey Concept

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);

What are the default initialization values of elements in an array?

FAQKey Concept

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.

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

How do you reverse the elements in an array?

FAQKey Concept

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.


How do you copy the elements of one array to another array?

FAQKey Concept

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.


What happens if you try to access an element with an index greater than the size of the array?

FAQKey Concept

The Java program will throw an ArrayIndexOutOfBoundsException.


How do you sort an array of primitive types using the java.util.Arrays class?

FAQKey Concept

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.

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

How do you sort an array of objects using the java.util.Arrays class?

FAQKey Concept

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

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.


What do you understand by collections framework in Java programming language?

FAQ

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.


What are the key interfaces defined in Java collections framework?

FAQ

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.


What are the core implementation classes of Set interface defined in Java collections framework?

FAQ

Java collections framework provides classes HashSet, TreeSet, LinkedTreeSet, EnumSet and CopyOnWriteArray; which are implementations of java.util.Set interface.

HashSet

  • Construction - HashSet is an implementation of the Set interface backed by a hash table.
  • Iteration Order - The iteration order in a HashSet is not guaranteed.
  • null elements - A null element is permitted in a HashSet.
  • Performance - Constant time for basic operations of add(), remove(), contains() and size(). Iteration requires time proportional to sum of the HashSet size and capacity of the backing HashMap.
  • Synchronization - HashSet is not synchronized.
  • Iteration - Iterators returned by HashSet are fail-fast, i.e. if the set is modified after the iterator is created, then the Iterator throws a ConcurrentModificationException.

TreeSet

  • Construction - TreeSet is an implementation of the Set interface backed by a TreeMap.
  • Ordering -The elements in a TreeSet are ordered using the natural ordering of elements. If a comparator is provided then the ordering is done as per the comparator.
  • Performance - The TreeSet takes log(n) times for basic operations of add(), remove(), size() and contains().
  • TreeSet is not synchronized.
  • Iteration - Iterators returned by HashSet are fail-fast, i.e. if the set is modified after the iterator is created, then the Iterator throws a ConcurrentModificationException.

LinkedHashSet

  • LinkedHashSet is an implementation of the Set interface backed by a HashMap and a LinkedList, and maintains a doubly-linked list running through all of its entries.
  • Ordering - The elements in a TreeSet are ordered using the insertion order of elements.
  • Performance - The TreeSet takes log(n) times for basic operations of add, remove, size and contains.
  • Synchronization - LinkedHashSet is not synchronized.
  • Iteration - Iterators returned by HashSet are fail-fast, i.e. if the set is modified after the iterator is created, then the Iterator throws a ConcurrentModificationException.


What are the core implementation classes of List interface defined in Java collections framework?

FAQ

Java collections framework provides classes ArrayList, LinkedList and CopyOnWriteArrayList; which are implementations of the List interface.

ArrayList

  • Construction - ArrayList is an implementation of the List interface that has the functionality of a re-sizable array.
  • Iteration Order - Elements in an ArrayList are ordered according to its index position.
  • null elements - null elements are permitted in ArrayList.
  • Performance - Constant time for basic operations of add(), remove(), contains() and size().
  • Synchronization - Methods in ArrayList are not synchronized.
  • Iteration - Iterators returned by HashSet are fail-fast, i.e. if the set is modified after the iterator is created, then the Iterator throws a ConcurrentModificationException.

LinkedList

  • Construction - LinkedList is a doubly-linked list implementation of the List interface.
  • Iteration Order - Elements in an LinkedList are ordered according to their insertion position.
  • null elements - null elements are permitted in ArrayList.
  • Performance - Constant time for basic operations of add(), remove(), contains() and size().
  • Synchronization - Methods in ArrayList are not synchronized.
  • Iteration - Iterators returned by ArrayList are fail-fast, i.e. if the set is modified after the iterator is created, then the Iterator throws a ConcurrentModificationException.


What are the core implementation classes of Map interface defined in Java collections framework?

FAQ

Java collections framework provides classes HashMap, TreeMap and LinkedHashMap; which are implementations of java.util.Map interface.

HashMap

  • Construction - HashSet is an implementation of the Map interface which maintains a generic key value pairs.
    Iteration Order - The iteration order in a HashMap is not guaranteed.
  • null elements - A null element is permitted in a HashMap.
  • Performance - Constant time for basic operations of add(), remove(), contains() and size(). Iteration requires time proportional to sum of the HashMap size and capacity of the backing HashMap.
  • Synchronization - HashMap is not synchronized.
  • Iteration - Iterators returned by HashMap are fail-fast, i.e. if the set is modified after the iterator is created, then the Iterator throws a ConcurrentModificationException.

TreeMap

  • Construction - TreeMap is an implementation of the Map interface which maintains specific order of elements.
  • Ordering -The elements in a TreeMap are ordered using the natural ordering of elements. If a comparator is provided then the ordering is done as per the comparator.
  • Performance - The TreeMap takes log(n) times for basic operations of add(), remove(), size() and contains().
  • TreeMap is not synchronized.
  • Iteration- Iterators returned by HashMap are fail-fast, i.e. if the map is modified after the iterator is created, then the Iterator throws a ConcurrentModificationException.

LinkedHashMap

    LinkedHashMap is an implementation of the Map interface backed by a doubly-linked list running through all of its entries.
  • Ordering - The elements in a TreeMap are ordered using the insertion order of elements.
  • Performance - The TreeMap takes log(n) times for basic operations of add, remove, size and contains.
  • Synchronization - LinkedHashMap is not synchronized.
  • Iteration - Iterators returned by HashMap are fail-fast, i.e. if the map is modified after the iterator is created, then the Iterator throws a ConcurrentModificationException.

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

What are the core implementation classes of Queue interface defined in Java collections framework?

FAQ

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.


What are the core implementation classes of Deque interface defined in Java collections framework?

FAQ

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.


What are the different wrapper classes that act on collections?

FAQ

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


What do you understand by Reflection in Java programming language?


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.


Where is Java Reflection commonly used?


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:


What are the disadvantages of Reflection?


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.


What is a Class object. How do you get a Class object via reflection?


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.


How do you access the package of a class?


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();
Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

How do you access the interfaces implemented by a class?


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.


How do you access the parent class of a class?


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.


How do you retrieve class access modifiers reflection?


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.


How do you access constructors defined in a class using reflection?


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.


How do you access fields defined in a class using reflection?


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.

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

How do you access annotations defined in a class using reflection?


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.


Java - Lambda Expressions


What are Lambda expressions in Java programming language?

FAQ

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.


What are functional interfaces?

FAQ

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.


What pre Java 8 code does Lambda expression simplify?

FAQ

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.


Can lambda expressions be used to implement interfaces having default and static methods?

FAQ

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.


What is the syntax of lambda expressions in Java programming language?

FAQ

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);}
Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

How many parameters can a lambda expression have?

FAQ

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);

Write a functional interface and implement it using non-lambda code and lambda expression

FAQ

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.


What criteria must be met to match a lambda expression to an interface?

FAQ

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.


What is the major difference between lambda expression vs anonymous interface implementation with regards to state?

FAQ

Anonymous interface implementations can have state (member variables), whereas lambda expressions are stateless...

*** See complete answer and code snippet in the Java Interview Guide.


Do you need to specify the type for parameters in a lambda expression?

FAQ

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.


Can you have multiple lines of code in a lambda function body?

FAQ

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 Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

Java - Streams

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.


Given a list of state objects, print the state codes.


//List of states
List<State> stateList = Util.buildStateList();
//Print list of states codes
stateList
  .stream()
  .forEach(e -> {System.out.println(e.getStateCode()));}

Given a list of state objects, print the state codes that begin with A.


//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()));}

Given a list of state objects, modify names to upper case, and print names whose codes begin with A.


//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()));}

Given a list of state objects, modify names to upper case, and print names whose codes begin with A and sorted in alphabetical order.


*** See complete answer and code snippet in the Java Interview Guide.


Given a list of state objects, create a map with code as key and name as value.


*** See complete answer and code snippet in the Java Interview Guide.

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

Given a list of state objects, print the list of cities in each state.


*** See complete answer and code snippet in the Java Interview Guide.


Java - Generics

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.


What do you understand by Generics in Java programming language? What are the benefits of Generics.

FAQKey Concept

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.

  • Compile time type checks - The Java compiler applies type checking to generic code at compile time and throes errors for type safety violations.
  • Eliminates implicit casting - Java code that uses generics do not need explicit casting, where as the code that is non-generic requires explicit casting.
  • Implementation of generic algorithms - By using generics, programmers can develop generic algorithms designed to work on collections of different types that are type safe and easier to use.


What are generic types?

FAQKey Concept

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 {...}'. The angle brackets <> is the type parameter section and specifies the type parameters T1, T2 ... for the generic class.

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 myClass = new MyClass();'. In Java 7 and later you can eliminate the type and just have the angle brackets <>. Example - 'MyClass myClass = new MyClass<>();'. The empty angular brackets <> syntax is commonly referred to as the Diamond.


What are generic methods?

FAQKey Concept

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


What are bounded type parameters?

FAQKey Concept

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.


How do you create sub-classes of generic classes?

FAQKey Concept

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.

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

Are Generics applied at compile time or run time? What is type erasure?

FAQKey Concept

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.


Can Java generics be applied to primitive types?

FAQKey Concept

No Java generics cannot be applied to primitive types....

*** See complete answer in the Java Interview Guide.


Can you create instances of generic type parameters?

FAQKey Concept

No you cannot create instances of generic type parameters...

*** See complete answer in the Java Interview Guide.


What do you understand by wildcards in generics?

FAQKey Concept

The question mark (?) is termed as wildcard in generics code...

*** See complete answer in the Java Interview Guide.

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

Java - Exceptions

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.


What are exceptions in Java programming language?

FAQKey Concept

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.


How do you handle exceptions in Java programming language?

FAQKey Concept

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.


What is the difference between checked exceptions and unchecked exceptions in Java programming language?

FAQKey Concept

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.


What is the difference between Exceptions and Errors in Java programming language?

FAQKey Concept

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


Can you have multiple catch blocks in Java programming language?

FAQKey Concept

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.

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

Can you catch more than one type of exception in a single catch block?


Yes, In Java SE 7 and later, a single catch block can handle more than one type of exception.


What is the difference between throws and throw in Java programming language?

FAQKey Concept

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.


What do you understand by finally block in Java programming language?

FAQKey Concept

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.


Can you have try and finally block without the catch block Java programming language?

FAQKey Concept

Yes you can have a finally block without the catch block...

*** See complete answer in the Java Interview Guide.


What do you understand by try-with-resources in Java programming language?

FAQKey Concept

try-with-resource is a try block that declares and initializes one or more resources...

*** See complete answer in the Java Interview Guide.

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

Java - IO

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.


What are the I/O streams Java programming language?

FAQ

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.


What are Byte Streams in Java programming language?

FAQ

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.


What are character streams in Java programming language?

FAQ

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.


What are Buffered streams in Java programming language?

FAQ

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.


What are Data streams in Java programming language?

FAQ

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

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

What are Object streams in Java programming language?

FAQ

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.


What are scanners in Java programming language?

FAQ

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.


Java - Threads


What are the different ways to define threads in Java programming language?

FAQKey Concept

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()

Describe the life-cycle of threads. What are the different states of threads? How does the thread transition from one state to the other?

FAQKey Concept

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.


How do you pause a thread from executing for a certain period of time?

FAQKey Concept

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.


What is the function of join() method in Thread class in Java programming language?

FAQKey Concept

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.


What is the function of sleep() method in Thread class in Java programming language?

FAQ

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.

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

What is the function of yeild() method in Thread class in Java programming language?

FAQ

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.


In the case of multiple threads, how do you prevent data corruption of shared data?

FAQKey Concept

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.


What are locks or monitors in Java programming language?

FAQ

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.


What do you understand by Reentrant Synchronization in Java programming language?

FAQ

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.


What is the function of wait(), notify() and notifyAll() methods in Java programming language?

FAQ

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

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.


What is Java Concurrency Framework?

FAQ

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.


What are the key classes provided in the Java concurrency framework?

FAQ

The key classes provided in the Java Concurrency framework are Executor, ExecutorSevice, Callable, and Future.


What are executors in Java programming language?

FAQ

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.


What is the purpose of ExecutorService class in Java Concurrency Framework?

FAQ

ExecutorService which extends from Executor, adds additional functionality to an Executor. ExecutorService has the ability to execute Callables and return Futures.


What is the purpose of Executors class in Java Concurrency Framework?

FAQ

Executors is a class provided in the Java concurrency framework that provides factory methods to get different kinds of executors.

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

What are the different kinds of Executors?

FAQ

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


What are callables and futures in Java programming language.?

FAQ

Callable is a functional interface similar to Runnable but return a value. Callable are submitted to ...

*** See complete answer in the Java Interview Guide


What is Parallel Fork-Join framework?

FAQ

Parallel Fork-Join framework is used for highly parallelizable tasks. Parallel Fork-Join framework increases ...

*** See complete answer in the Java Interview Guide


What is Parallel Fork-Join task?

FAQ

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


What is the difference between RecursiveTask and RecursiveAction?

FAQ

RecursiveTask’s compute() method returns a value, whereas RecursiveAction’s compute() method returns void...

*** See complete answer in the Java Interview Guide

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

What are atomic variables in Java programming language?

FAQ

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


What are Scheduled executors in Java programming language.?

FAQ

Scheduled executors enables tasks to be executed after a delay or at regular intervals...

*** See complete answer in the Java Interview Guide


What are concurrent collections?

FAQ

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


What are copy-on-write collections?

FAQ

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


Java - JDBC


What is JDBC?


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.

  • Connecting to a database.
  • Creating SQL statements.
  • Executing SQL statements against the database.
  • Navigating the results.
    Getting meta-data of the database.


What are the key steps to connect to a database using JDBC API?

FAQ

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.


What is the difference between Statement, PreparedStatement and Callable Statement?

FAQ

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.


How do you execute queries using JDBC API?


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.

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

How do you call stored procedures using JDBC API?

FAQ

You can call a stored procedure by calling the execute() method on the CallableStatement object.

*** See complete answer in the Java Interview Guide.


What are result sets?


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.


What are the ResultSet types based on cursor movement and data sensitivity defined JDBC API?

FAQ

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.


What are the ResultSet types based on concurrency defined in JDBC API?

FAQ

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.


What are the most commonly used methods to scroll a ResultSet?

FAQ

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.

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

How do you get the metadata of a result set?

FAQ

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.


What are RowSets?


RowSet objects are derived from ResultSet and adds following capabilities...

*** See complete answer in the Java Interview Guide.


What are connected and disconnected RowSets?


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.


What are the different implementations of RowSets?


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.


What is a JDBC transaction?


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 Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

Java - Networking

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.


How do you represent a URL in Java programming language?

FAQ

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);

How do you connect to a URL resource in Java programming language?

FAQ

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();

What are the key steps in reading from a URL connection?

FAQ

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


What are the key steps in writing to a URL connection?

FAQ

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


What are some of the key methods provided in the URL class?


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

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

What are sockets? How are sockets represented in the Java programming language?

FAQ

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.


What are the key steps in reading writing to sockets?

FAQ

1. Open a socket
2. Open an input stream and output stream to a socket

*** See complete answer in the Java Interview Guide.


What is the difference between TCP and UDP protocols?

FAQ

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.


What is datagram? What are some key classes defined in the Java programming language to work with datagrams?

FAQ

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.

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

How do you broadcast datagrams to multiple clients?

FAQ

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.


What is a network interface?

FAQ

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.


How do you get a list of IP addresses that are assigned to a network interface?

FAQ

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

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.


Describe the Java security architecture.

FAQ

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.


How did Java's security model evolve over time?

FAQ

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.

  • J2SE introduced the concept of 'protection domain' and 'security policy' and 'Permission'. A protection domain is configured by grouping classes by associating them with a 'security policy' which contains a set of 'permissions'. The security policy determines if a code can be run on a protection domain or not. SecurityManager enforces the required security policy.


What are the key security features provided by Java programming language?

FAQ

Java programming language has several inherent features that contribute to the security of the Java application

  • Java is designed to be a type-safe language and is easy to use. Java type safety is enforced by the java compiler and is checked by the runtime environment.This results in an overall secure environment for Java programs to run in.
  • Java language does automatic range checking on arrays which reduces the burden on developers, results in less programming errors and leads to a more safer and robust code.
  • Automatic memory management - Java has automatic memory management and the memory is freed automatically by garbage collection. Java has transparent storage allocation, which is not defined in the Java or JVM specs. This makes it difficult for anyone to perform memory hacks.

*** See complete answer in the Java Interview Guide.


What is the function of permissions class in Java programming language?

FAQ

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.

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

What are protection domains in Java programming language?

FAQ

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.


What is SecurityManager in Java programming language?

FAQ

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.


What are the key classes provided in Java API that deals with security?

FAQ

Key classes related to security are provided by the Java programming API in java.security.* package...

*** See complete answer in the Java Interview Guide.


Java - JVM Internals

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.


What is the difference between JVM, JRE and JDK?

FAQKey Concept

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.


How is Java programming language machine and platform independent?

FAQ

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.


What are Java bytecodes?

FAQ

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.


Explain how Java programs are executed by the JVM?

FAQ

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.


What are Java class loaders? What are the key features of Java class loader

FAQ

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

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

What are some of the key class loaders?

FAQ

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


Describe the key steps in which a Java class is loaded by the JVM?

FAQ

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


What are runtime data areas?

FAQ

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


How is a java program executed by JVM?

FAQ

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


Java - Performance


What are the key areas that impact the performance of Java programs?

FAQ

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

  • JVM Optimizations
  • Garbage Collection Optimizations
  • Memory Optimizations

Java program

  • Program logic optimizations
  • Algorithm and collection usage optimizations
  • Multi-threading and synchronization optimizations.

Connectivity optimizations

  • Network connectivity
  • Database connectivity


What are the benefits and dis-advantages of garbage collector?

FAQ

Benefits:

  • Garbage collector automatically manages the JVM memory by deleting objects that are no longer referenced and used. A Java developer can concentrate on program logic instead of worrying about object deletion and memory management.
  • The garbage collector has inbuilt efficient algorithms which determine when to run the garbage collector.

Dis-advantages:

  • There is a possibility that during garbage collection process the application performance may be impacted. In certain situations, called 'stop the world', the application process is completely stopped while the garbage collection process takes place.
  • You can indicate to the JVM to run the garbage collector, but it is not guaranteed. So as a developer you do not know when the garbage collection process happens.


What is 'Stop The World'?

FAQ

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'


What do you understand by generational structure of Java heap?

FAQ

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.

  • Eden Space - All new objects are put into eden space. When the eden space fills up, garbage collection runs and removes all objects that have no references. All objects that still have references are promoted to the survivor space.
  • Survivor space - Every garbage collection run in the new generation section, will remove the objects from Survivor space if the objects no longer is referenced. If the object is still referenced, it will increment the age of that object. After the increment reaches a certain number, usually starting at 15 depending on the JVM implementation, the object will be promoted to the old generation section.

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.


What are the different garbage collection algorithms? Which algorithm is better?

FAQ

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

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

What does the finalize() method do?

FAQ

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


What are the common flags that you can use to optimize the JVM and garbage collector?

FAQ

Following are some common flags you would set to tune JVM

  • -Xms512m - Sets the initial heap size to 512m
  • -Xmx1024m - Sets the maximum heap size to 1024m

*** See complete answer in the Java Interview Guide


What are memory leaks? How do you diagnose memory leaks?

FAQ

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


Java - New in Java 8


What are the key Java programming language features introduced in Java 8?


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.


What are Lambda expressions in Java programming language??


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.


What new features in Interfaces are introduced in Java 8?


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');
  }
}

What are repeating annotations?


Java 8.0 introduced a new Java language feature regarding annotations. You can now repeat an annotation multiple times on a type declaration.


What are type annotations? Name some common type annotations.


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 Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

Java - New in Java 9

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.


What are the key features and enhancements introduced in Java 9?

FAQ

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


Describe the Java platform module system introduced in Java 9?

FAQ

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.


How do you declare a Module?

FAQ

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;}

How do you declare a Module?

FAQ

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;}

Can you have two modules with the same name?

FAQ

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.

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

Can a module and a package within that module have the same name?

FAQ

Yes, a module and a package within that module have the same name.


What factory methods were added for collections in Java 9?

FAQ

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)

What changes to interfaces were introduced in Java 9?

FAQ

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() {
  ...
 }

}

What new features were added in the Streams API in Java 9?

FAQ

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.


What is JShell?

FAQ

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

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $15.00 only.
 
BUY EBOOK BUY EBOOK
 

What is JLink?

FAQ

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.


Support for HTTP/2 in Java 9?

FAQ

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 - New in Java 10

Java 10, released six months after Java 9, is the first JDK release that conforms to Oracle's new six-month release cycle.


What are the key features and enhancements introduced in Java 10?

FAQ

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 //myLocalVar3 if of type 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 - New in Java 11

Java 11 was released in Septemper 2018 six months after Java 10 conforming to Oracle's new six-month release cycle.


What are the key features and enhancements introduced in Java 11?

FAQ

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.

  • isBlank
  • lines
  • strip
  • stripLeading
  • stripTrailing
  • repeat

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.


 
Java Interview Guide

$15.00

BUY EBOOK
  SSL Secure Payment
Interview Questions - Secure Payment
TRY A CHAPTER
You're also subscribing to the interviewgrid.com email newsletter for tips, updates & promotions. Unsubscribe any time.