100+ Java Interview Questions [2020, Java 10]

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.

Following are some frequently asked questions in Java – Object Oriented Programming

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

* Similar Question Recently Asked @ Amazon, American Airlines, Charles Schwab, FedEx, Geico, Honeywell, Intel, J.P Morgan, L3 Technologies, Microsoft, New York Life, Northrop Grumman, Oracle, Paycom, State Farm, Ultimate Software, Veritas, Workday,

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.


What is Abstraction?

* Similar Question Recently Asked @ Accenture, Allscripts, C.H. Robinson, Deloitte, FDM Group, Guidewire, Infosys, Microsoft, Revature, Sphere Solutions, TIBCO Software, Tribro,

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 payroll system
public class person {
	private String name;
	private int age;
	private String companyName;
	private double salary;
}

What is Encapsulation?

* Similar Question Recently Asked @ Accenture, Amazon, Apple, Atos, Avande, Bloomberg LP, Digiweb, Infosys, Microsoft, OSISoft, Panasonic, Pariveda, Paycom, Raytheon, Revature, Shure, Tallan, TCS, Thermo Fisher Scientific, Wipro, Zappo,

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?

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?

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.

In Java programming language, the keyword ‘implements’ is used to specify that a class implements an interface.

In the following example, the class Ball implements the interface Bounce. The class Ball inherits the bounce behavior and implements this behavior specific to a ball. So we can say that ball has bounce behavior.

//Interface - 
public interface Bounce {
	void bounce(); 
}

//Class implements interface
public class Ball implements Bounce {
	//Implement the interface method
	public void bounce(){...}
	}
}

What is Polymorphism?

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.

In Java programming language any object that has more than one Is-A relations is considered to be polymorphic. Technically every object in Java programming language is polymorphic since it has at at-least two Is-A relationships – Is-A relationship to itself and Is-A relationship to the class Object which is the parent class of all Java classes.

In below example an object of Ball is polymorphic because it can be reference in four different ways.

  • Referenced with its own class type ‘Ball’
  • Referenced with its parent class type ‘Toy’
  • Referenced with the super class type ‘Object’
  • Referenced with its interface type ‘Bounce’
//Interface declaration
public interface Bounce {...}
//Parent class declaration
public class Toy {...}
//Class that extends Toy and implements Bounce
public class Ball extends Toy implements Bounce {...}

Ball b = new Ball();
Toy t = new Ball();
Object o = new Ball();
Bounce b = new Ball()

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

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.

There are two forms of generalization

1. Sub-typing, or interface-inheritance, which is supported in Java programming language via interfaces.

2. Sub-classing, or implementation-inheritance, which is supported in Java programming language via class inheritance.

What is the difference between aggregation and composition?

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.

Composition is also a part-of relationship between classes. But unlike aggregation, in composition relationship a part cannot exist without the whole. An example of composition is an order and order line items. The order line items cannot exist without the order.

What are SOLID principles of Object Oriented Programming?

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.

Single Responsibility Principle – Every class should only have a single primary responsibility.

Open/Closed Principle – Software entities should be open for extension but closed for modification. Liskov Substitution Principle – Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.

Interface Segregation Principle – Many client-specific interfaces are better than one general-purpose interface Dependency Inversion Principle – one should depend upon abstractions and not concretions.

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.

Following are some frequently asked questions in Java – Objects & Classes

What is Object class in Java programming language?

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?

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

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

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
  2. Class-member access modifiers
  3. Class-member non-access modifiers.

The next four questions addresses these combinations.

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

Following access modifiers can be added to a class declaration.

public – A class declared with public access modifier is accessible to all classes.

Default or package-private (No explicit modifier) – A class that is not declared with any access modifier has default or package-private access. Only classes within the same package can see and access this class.

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

Following non-access modifiers can be added to a class declaration.

final – A class declared as final cannot be sub-classed.

abstract – A class declared as abstract contains one or more abstract methods. Abstract method is a method that is declared but not implemented. A child class that extends from the abstract class must implement the abstract methods of the parent method, else the child class must also be declared as abstract.

A class cannot be declared as both final as well as abstract. A final class cannot be extended, where as an abstract class has to be extended to create an instance.

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

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.

private – A member declared with private access modifier is visible and accessible only within the class that it is declared in.

protected – A member declared with protected access modifier is visible and accessible only to classes within the same package, and its child classes in other packages.

Default or package-private (No explicit modifier) – A class member that is not declared with any access modifier has default or package-private access. Only classes within the same package can see and access this member.

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

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.

abstract – An abstract method is a method that is declared but not implemented. An abstract method is declared in an abstract class. A sub-class of the abstract class must implement the abstract method

static – A static method, also called as a class method, exists and can be called independently of a class instance. A static method cannot access instance variables within a class.

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.

Following are some frequently asked questions in Java – Data Types

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

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-10
short162-216-1216-1-10
int324-232-1232-1-10
long648-264-1264-1-10
float324>NANA0.0f
double648NANA0.0d
boolean1NANANAfalse
char16NANANA
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?

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?

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?

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.

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.

Example:

class myclass {
  static int v1 = 100; // Static variable 
  int v2 = 200; // Instance variable
  {int v3 = 300} // Block variable in init block
  void perform() {
    int v4 = 400; //Local variable 
    for (int i=0; i 

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

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.

What are wrapper classes in Java programming language?

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. Each of the eight primitive data types has a corresponding Wrapper class as listed in below table.

Primitive Data TypeWrapper Class
byteByte
shortShort
intInteger
doubleDouble
longLong
floatFloat
charCharacter
booleanBoolean
Example:

class Myclass {
  //List of Integers
  List list = new ArrayList();
  //Add ints 1-50 to the list
  public void addToList() {
    for (int i=1; i

What is Autoboxing and Unboxing?

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, or a primitive data type is passed as an argument to a method which expects an object of the corresponding wrapper class.

Unboxing is the automatic conversion of an object of a wrapper type to its corresponding primitive value by Java compiler. Java compiler applies unboxing when a wrapper object is assigned to a variable of corresponding primitive type, or when a wrapper object is passed as an argument to a method which expects corresponding primitive type.

Example:

/* Autoboxing */
class Myclass {
  //List of Integers
  List list = new ArrayList();
  //Add ints 1-50 to the list
  public void addToList() {
    for (int i=1; i
Example:

/* Unboxing */
class myclass {
  Integer wrappedInt = new Integer(200); 
  int primitiveInt = wrappedInt; //Unboxing through assignment
  }
}

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.

Following are some frequently asked questions in Java – Variables

What is the difference between primitive variables and reference variables?

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?

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 

What are static variables in Java programming language?

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?

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?

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

What are block variables in Java programming language?

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. Block variables are stored on the stack.

class MyClass {
	//Block variable in for loop
		for (int i=0; i 

What are final variables in Java programming language?

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.

If the final variable is a reference variable and an object is assigned to it, it cannot be changed to refer to a different object. Please note that the attributes of the Object referred to by the final variable can change.

class MyClass {
	//final primitive variable var1,
	//value of var1 cannot change from 123
	final int var1 = 123;

	//final reference variable - var2
	//var2 cannot be changed to refer another Box object,
	//attributes of the Box object can change.
	final Box var2 = new Box();
}

What are transient variables in Java programming language?

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. Transient reference variables are initialized to null.

class MyClass {
	// Transient variable
	transient int var1 = 123;
}

What are volatile variables in Java programming language?

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’.

For regular (non-volatile) variables the thread caches the variable’s value in its memory and refers to this cached value when required. Any updates that are make to this variable by other threads will not be reflected in this thread.

Volatile variables tells the JVM that this variable will be updated by multiple threads, and to always take its value from the main memory. So all thread access and get the value of a volatile variable from the main memory and do not cache the value in the thread’s memory cache.

class MyClass {
	// Volatile variable
	volatile int var1 = 123;
}

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.

Following are some frequently asked questions in Java – Strings

What do you understand by immutability of Java String objects?

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

What do you mean by String constant pool?

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.

What is the difference between String and StringBuilder?

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?

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?

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.

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

You can convert an Integer to a String using two ways. Using the static methods Integer.toString() and String.valueOf().

What are some of the key methods in String class?

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.

equalsIgnoreCase() – Returns true if this string matches the text of another string object ignoring the case.

length() – Returns the length of the string.

subString() – Returns part of the string. You have to specify the start index and end index.

concat() – Appends another string to this string.

split() – Splits the string based on a delimiter.

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

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.

reverse() – Reverses the characters of a string.

toString() – Returns a string representation of the StringBuffer or StringBuilder.

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.

String myString = 'abc';
char[] charArray = myString.toCharArray();

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.

The second method to traverse the characters in a string is to create a character array of the string first and then loop through the characters. The advantage of this method is you can utilize the functionalities of an array to manipulate the characters.

String myString = 'This Is My String';
for (int i=0; i
String myString = 'This Is My String'; 
char[] myCharArray = myString.toCharArray();
for(int i=0; i

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

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.

The second method to traverse the characters in a string is to create a character array of the string first and then loop through the characters. The advantage of this method is you can utilize the functionalities of an array to manipulate the characters.

String myString = 'This Is My String';
for (int i=myString.length-1; i
String myString = 'This Is My String'; 
char[] myCharArray = myString.toCharArray();
for(int i=myCharArray.size()-1; i

How do you remove specific characters of a string?

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. If the character is not ‘s’ then append the character to StringBuffer object
If the character is ‘s’ then ignore.
Convert StringBuffer to String and print.

String myString = "This is my string";
StringBuilder builder = new StringBuilder();
for(int i=0; i

How do you reverse the words in a string?

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. Put the tokens into an array.
  4. Loop through the array in reverse order.
  5. Add each word to the StringBuilder object.
String myString = "interviewgrid.com is awesome";
StringBuilder builder = new StringBuilder();
String[] words = myString.split(" ");
for(int i=words.length-1; i>=0; i--) {
	builder.append(words[i]);
	builder.append(" ");
	}
System.out.println(builder.toString());

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

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. Check if the two strings have the same count of each character.

Below is the sample code for the first solution.

boolean checkForPermutation(String str1, String str2) {
	if(str1.length() != str2.length()) {
		return false;
	}
	return sort(str1).equals(sort(str2));
}

static String sort(String str1) {
	char[] charArray = str1.toCharArray();
	java.util.Arrays.sort(charArray);
	return new String(charArray);
}

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.

Following are some frequently asked questions in Java – Arrays

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?

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?

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?

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?

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.

How do you reverse the elements in an array?

You can reverse the elements in an array by looping through the array in reverse order and adding the elements to a new array.

//Loop through the array in reverse order and add to a new array
 int[] myArray = {1,2,3,4,5,6,7,8,9,10};
int[] myReverseArray = new int[myArray.length];
for(int i=myArray.length-1; i>=0; i--) {
  myReverseArray[myArray.length-i-1]=myArray[i];
}

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

You can reverse the elements in an array by looping through the array in reverse order and adding the elements to a new array.

//Loop through the array in reverse order and add to a new array
 int[] myArray = {1,2,3,4,5,6,7,8,9,10};
int[] myReverseArray = new int[myArray.length];
for(int i=myArray.length-1; i>=0; i--) {
  myReverseArray[myArray.length-i-1]=myArray[i];
}

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

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.

String[] arrayFrom = {'str1','str2','str3','str4','str5'};
String[] arrayTo = new String[5];
System.arraycopy(fromArray, 0, toArray, 0, 5);

//Loop through the array and copy the elements
for(int i=0; i

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

The Java program will throw an ArrayIndexOutOfBoundsException.

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

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 used the Dual-Pivot Quicksort algorithm which is typically faster than the traditional One-Pivot Quicksort algorithm.

Time Complexity – O(N log(N))

//sort an array of primitive types
int[] intArray = new int[] {1, 20, 45, 2, 4, 5, 7, 20};
Arrays.sort(intArray);

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

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

//sort an array of String objects
String[] stringArray = new String[] {'abc', 'def', 'khi', 'aac', 'ghl', 'mki', 'hji'};
Arrays.sort(stringArray);

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

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. To sort the objects in reverse order you can pass ‘Collections.reverseOrder()’ as a second parameter to the sort() method.

Collections is a utility class provided in the java.util package that provides utility methods for collections. Collections.reverseOrder() provides a comparator that imposes the reverse of natural ordering.

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

//sort an array of String objects in reverse order
String[] stringArray = new String[] {'abc', 'def', 'khi', 'aac', 'ghl', 'mki', 'hji'};
Arrays.sort(stringArray, Collections.reverseOrder());

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.

Following are some frequently asked questions in Java – Collections

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

* Similar Question Recently Asked @ Accenture, Altimetrik, Amdocs, Arm, Birst, Capgemini, Capita, Clover Infotech, Exusia, Fiserv, Headstrong, IBM, InterGlobe Technologies, ITC Infotech, Lucernex, Luxoft, MagikMinds, Maxxton, Naaptol, New York Times, Nisum, Nucleus Software, PwC, redBus, Reliance Jio Infocomm, Resilinc, Sapient, SJM Technologies, Softcell Technologies, UST Global, Zoho,

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?

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.

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

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.

String[] arrayFrom = {'str1','str2','str3','str4','str5'};
String[] arrayTo = new String[5];
System.arraycopy(fromArray, 0, toArray, 0, 5);

//Loop through the array and copy the elements
for(int i=0; i

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

The Java program will throw an ArrayIndexOutOfBoundsException.

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

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 used the Dual-Pivot Quicksort algorithm which is typically faster than the traditional One-Pivot Quicksort algorithm.

Time Complexity – O(N log(N))

//sort an array of primitive types
int[] intArray = new int[] {1, 20, 45, 2, 4, 5, 7, 20};
Arrays.sort(intArray);

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

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

//sort an array of String objects
String[] stringArray = new String[] {'abc', 'def', 'khi', 'aac', 'ghl', 'mki', 'hji'};
Arrays.sort(stringArray);

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

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. To sort the objects in reverse order you can pass ‘Collections.reverseOrder()’ as a second parameter to the sort() method.

Collections is a utility class provided in the java.util package that provides utility methods for collections. Collections.reverseOrder() provides a comparator that imposes the reverse of natural ordering.

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

//sort an array of String objects in reverse order
String[] stringArray = new String[] {'abc', 'def', 'khi', 'aac', 'ghl', 'mki', 'hji'};
Arrays.sort(stringArray, Collections.reverseOrder());

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.

Following are some frequently asked questions in Java – Collections

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

* Similar Question Recently Asked @ Accenture, Altimetrik, Amdocs, Arm, Birst, Capgemini, Capita, Clover Infotech, Exusia, Fiserv, Headstrong, IBM, InterGlobe Technologies, ITC Infotech, Lucernex, Luxoft, MagikMinds, Maxxton, Naaptol, New York Times, Nisum, Nucleus Software, PwC, redBus, Reliance Jio Infocomm, Resilinc, Sapient, SJM Technologies, Softcell Technologies, UST Global, Zoho,

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?

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?

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?

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?

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

  • 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.

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

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

LinkedBlockingQueue

ArrayBlockingQueue:

PriorityBlockingQueue:

DelayQueue:

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

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.

What are the different wrapper classes that act on collections?

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

Synchronization wrappers – Synchronization wrappers add synchronization (thread-safety) to a collection. Each of the six core collection interfaces – Collection, List, Set, Map, SortedSet and SortedMap has a corresponding wrapper method that returns a synchronized collection.

Unmodifiable wrappers – Unmodifiable wrappers make the collection immutable, i.e. the collection cannot be modified after the collection is built. Each of the six core collection interfaces – Collection, List, Set, Map, SortedSet and SortedMap has a corresponding wrapper method that returns an unmodifiable collection.

CheckedInterface wrappers – Checked interface wrappers are provided for use with generic collections. Implementations of checked interface wrappers return a dynamically type-safe view of the specified collection, which throws a ClassCastException if a client attempts to add an element of the wrong type.

Java – Date and Time

Following are some frequently asked questions in Java – Date and Time

What are the key Date and Time classes prior to Java 8?

What Date and Time classes are introduced in Java 8 and why?

Java – Reflection

Following are some frequently asked questions in 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();

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.

Class myClass = Class.forName('java.lang.String');
Package package = myClass.getInterfaces();

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.

Class myClass = Class.forName('java.lang.String');
Package package = myClass.getSuperclass();

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.

Class myClass = Class.forName('java.lang.String');
int modifier = myClass.getModifiers();

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.

Constructors of a class can be accessed by calling the method getConstructors() on the class object.

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.

Class myClass = Class.forName('java.lang.String');
Field[] fields = myClass.getFields();

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.

Class myClass = Class.forName('java.lang.String');
Annotation[] annotations = myClass.getAnnotations();

Java – Lambda Expressions

Following are some frequently asked questions in Java – Lambda Expressions

What are Lambda expressions in Java programming language?

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?

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?

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?

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?

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

How many parameters can a lambda expression have?

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

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.

//Function Interface
//Must contain one (and only one) abstract method
//Can contain multiple default and static method implementations
@FunctionalInterface
public interface EventChangeListener {
  //abstract method
  public void onEventChange(Event oldEvent, Event newEvent);
  //default method
  default void print() {...}
  //static method
  static void log() {...}
}
//Implementation using non-lambda code
EventChangeListener listener = new EventChangeListener() {
  public void onEventChange(Event event1, Event event2) {
    System.out.println('Event Changed');
  }
};
listener.onEventChange(event1, event2);
//Implementation using lambda expression
EventChangeListener listener = (e1, e2) -> {System.out.println('Event Changed');};
listener.onEventchange(event1, event2);

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

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.

2. The number of parameters of the lambda expression must match the number of parameters of the abstract method.

3. return type of the lambda expression must match the return type of the abstract method.

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

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

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

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 the compiler infers that e1 and e2 are of type ‘Event’ by matching the lambda expression with the onEventChange() method of the functional interface EventChangeListener.

EventChangeListener listener = (e1, e2) -> {System.out.println('Event Changed');};

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

Yes, lambda function body can have multiple lines of code within curly braces {}

EventChangeListener listener = (e1, e2) -> {
  System.out.println('Event Changed');
  System.out.println('Event Changed');
}

What are Lambda expressions in Java programming language?

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.

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.

Following are some frequently asked questions in Java – Streams

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

//List of states
List 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 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 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.

//List of states
List stateList = Util.buildStateList();
//Filter states and print state codes
stateList
  .stream()
  .filter(e -> e.getStateCode().startsWith('A'))
  .map(e -> e.getStateName().toUpperCase())
  .sorted((s1,s2) -> s1.compareTo(s2))
  .forEach(e -> {System.out.println(e.getStateName()));}

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

Map stateMap = 
 stateList
  .stream()
  .collect(Collectors.toMap(e -> e.getStateCode(), e -> e.getStateName()));
,>

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

stateList
 .stream()
 .flatMap(f -> f.getCities().stream())
 .forEach(f -> System.out.println(f.getCityName()));

Join the discussion on connect.worrq.com

We will be happy to hear your thoughts

Leave a reply

Community

For Professionals

For Businesses

We support and nurture talent. Learn new skills. Share your expertise. Connect with experts. Get inspired.

Community

Partnership Opportunities

worrq.com
Logo
Compare items
  • Total (0)
Compare
0