Java
Interview Questions
 
MASTER Java  

Top ranked courses to help you master Java skills.
Java Programming Masterclass

iconicon

Offered By - Tim Buchalka
Platform - Udemy
Rating - * * * * *
Students Enrolled - 575,000 +

RECOMMENDED RESOURCES
Behaviorial Interview
Top resource to prepare for behaviorial and situational interview questions.

STAR Interview Example

200+ 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?

FAQKey Concept

* 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?

FAQKey Concept

* 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 hospital patient system
public class person {
private String name;
private int age;
private float height;
private float weight;
}

What is Encapsulation?

FAQKey Concept

* 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?

FAQKey Concept

* Similar Question Recently Asked @ Absolute, Accenture, Antra, BetterCloud, Bloomberg LP, CGI, Continental, CSX, Deloitte, Fidelity Investments, General Atomics, Goldman Sachs, Kronos Incorporated, Lockheed Martin, Maverick Software, Morgan Stanley, Norfolk Southern, Northrop Grumman, Raytheon, Solstice, USAA,

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

* Similar Question Recently Asked @ Accenture, Addteq, Amazon, Cisco Systems, Expedia, General Motors, J.P. Morgan, Majesco, Morgan Stanley, OrderDynamics, Revature, Sapient, Stingray Digital, Tuenti, VMWare, Yahoo,

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?

FAQKey Concept

* Similar Question Recently Asked @ Amazon, BAE Systems, Barclays Capital, CGI, Credit Suisse, FDM Group, Goldman Sachs, Hamilton, Harris, Honeywell, IBM, ICF, Infosys, J.P. Morgan, Micron, Microsoft, Nokia, Northrop Grumman, Paychex, SAP, Sears, Vanguard, Viasat, Vyom Labs, Yahoo,

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?

Key Concept

* Similar Question Recently Asked @ Saama Technologies,

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?

Key Concept

* Similar Question Recently Asked @ PTC, TechnoGen, Virtusa,

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?

FAQ

* Similar Question Recently Asked @ Citi, Dell, Honeywell, Luxoft, OnTrac, Paycom, Qualcomm, Schroders, Spryker, Target,

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

FAQKey Concept

* Similar Question Recently Asked @ Accenture, Citi, Expeditors, GlobalLogic, Google, Morgan Stanley, Oracle, Software AG, Vanguard,

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

* Similar Question Recently Asked @ Amadeus, Amdocs, Campus Labs, Deloitte, Ducat, Expeditors, FieldEZ, Goldman Sachs, Google, PWC, Rakuten, VirtUSA, Yodlee,

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?

FAQ

* Similar Question Recently Asked @ ADP, Argonne National Laboratory, BAE Systems, Guidewire, Impetus Technologies, Polaris, Virtusa,

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.

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?

FAQ

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?

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.

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?

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.

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

FAQKey Concept

* Similar Question Recently Asked @ Ancestry, Antra, avaloq, Bloomberg L.P., Charles River, Nokia, Peri Software Solutions, Pinnacle Infotech, Synechron, Unicode Systems, Visa Inc, Vocalink,

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

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

* Similar Question Recently Asked @ Agero, Cavium, CGI, Elliot Management, EquityZen, FDM Group, GitLab, J.P. Morgan, Kayak, OpticsPlanet, PhishMe, ResearchGate, SAP, Vanguard, Yahoo,

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 < 4; i++) { //Block variable in for loop
...
}
}
}

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.


What are wrapper classes in Java programming language?

FAQKey Concept

* Similar Question Recently Asked @ Cloudaction, CSL, Daffodil, KTree, Salesforce, Virtusa, Xoriant,

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<Integer> list = new ArrayList();
//Add ints 1-50 to the list
public void addToList() {
for (int i=1; i<=50; i++) {
//Convert to Integer object and add to list
list.add(Integer.valueOf(i));
}
}
}

What is Autoboxing and Unboxing?

FAQKey Concept

* Similar Question Recently Asked @ ABC, AvidXchange, BNP Paribas, Citrix, DataMetica, Deloitte, Deltatre, Hotwire, Indus Valley Partners, Deloitte, InnerWorkings, Innoviti, Lockheed Martin, Luxoft, Mindtree, Naaptol, Quovantis, TSO,

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<Integer> list = new ArrayList();
//Add ints 1-50 to the list
public void addToList() {
for (int i=1; i<=50; i++) {
//Convert to Integer object and add to list
list.add(Integer.valueOf(i));
}
}
}
Example:

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

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

FAQKey Concept

* Similar Question Recently Asked @ American Express, Calsoft, Citadel, Fidelity Investments, Morgan Stanley, NVIDIA, NVR, Synergy,

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

* Similar Question Recently Asked @ BT, Cerner, DEKA, EchoStar, Goldman Sachs, HCL, Infogain, Intuit, Karsum, Norfolk Southern,

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

What are static variables in Java programming language?

FAQKey Concept

* Similar Question Recently Asked @ Abhra, Apple, Bloomberg LP, BMW, Broadcom, Citi, Citrix, Coviam, Equifax, F5 Networks, FedEx, FreshWorks, Google, Lenovo, Marlabs, Nokia, Nvidia, PayPal, Qualcomm, Subex, Synapse, Home Depot, Tradeweb, Twilo, Wipro,

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

* Similar Question Recently Asked @ Altisource, Cerner, DraftKings, Genpact, Reddwerks, Unbxd,

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

* Similar Question Recently Asked @ Arista Networks, Asana, Bloomberg L.P., Broadcom, Capgemini, Cisco Systems, eBay, Global Relay, Intel, Mathworks, Nuance, Qualcomm, Splunk, Veeva Systems, VMware, Worldquant, Yahoo,

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?

FAQKey Concept

* Similar Question Recently Asked @ Arista Networks, Asana, Broadcom, Capgemini, Cisco Systems, eBay, Intel, Mathworks, Qualcomm, Splunk, Veeva Systems, VMware, Worldquant,

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 < 4; i++) {...}
}
}

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.

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?

FAQKey Concept

* Similar Question Recently Asked @ Abhra, Calypso Technology, Citi, Eroad, RPM Technologies, Velopsys Technologies,

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?

FAQKey Concept

* Similar Question Recently Asked @ NVIDIA, OpenText, Qualcomm, Square, Uber, Valeo, ZF Group,

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

FAQKey Concept

* Similar Question Recently Asked @ ABS, Allston Trading, Atlassian, Barclays, Bitwise, Cloudera, Expicient, Fidelity Investments, Full Creative, Gamesys, Goldman Sachs, IHS Markit, Jungo Connectivity, Man Group, Oracle, Revature, SAS, Sears, State Street, Subex, TCS, TransPerfect, VenturePact, Zalando,

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?

FAQKey Concept

* Similar Question Recently Asked @ Capgemini, Conversant, Deloitte , Evergent , Genesys , Guidewire, HCL, IBM , IVY Comptech , Nuance,

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?

FAQKey Concept

* Similar Question Recently Asked @ Appcino Technologies, Applied Systems, Citrix, Credit Suisse, eBay, Fidelity Investments, Glassdoor, GlobalLogic, IBM, Infogain, IXL Learning, Ludia, Myntra, Nexient, PayPal, Riversand Technologies, SoftCo, Symantec, Tech Mahindra, ThoughtWorks, Titanium Software, Verbat Technologies, Western Digital,

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.


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


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.

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?

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.

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<=myString.length(); i++) {
system.out.println(myString.charAt(i));
}
String myString = 'This Is My String'; 
char[] myCharArray = myString.toCharArray();
for(int i=0; i<=myCharArracy.size(); i++) {
System.out.println(myCharArray[i])}

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.

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<=0; i--) {
system.out.println(myString.charAt(i));
}
String myString = 'This Is My String'; 
char[] myCharArray = myString.toCharArray();
for(int i=myCharArray.size()-1; i<=0; i--) {
System.out.println(myCharArray[i])}

How do you remove specific characters of a string?

FAQKey Concept

* Similar Question Recently Asked @ Amazon Lab126, Arista Networks, Bloomberg LP,

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<myString.length(); i++) {
if(myString.charAt(i) != 's'){
builder.append(myString.charAt(i));
}
}
System.out.println(builder.toString());
}

How do you reverse the words in a string?

FAQKey Concept

* Similar Question Recently Asked @ Addepar, Amazon, Amazon Lab126, Aristocrat Technologies, Bloomberg L.P., Cisco Systems, Electronic Arts, GoDaddy, Goldman Sachs, Google, MathWorks, Microsoft, Motorola Mobility, NAVEX Global, NetApp, NICE inContact, Redfin, Salesforce, Tek Travels, Teradata, Tintri, Uber,

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?

FAQKey Concept

* Similar Question Recently Asked @ Amazon, BlackRock, CA Technologies, EPIC Systems, Google, Microsoft, Opera Solutions, Oracle, Sixt, Veeva Systems, Workday,

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

FAQKey Concept

* Similar Question Recently Asked @ Amazon, Google,

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.


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.

//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?

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.

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<fromArray.length; i++) {arrayTo[i] = fromArray[i]}

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

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

//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?

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

FAQ

* 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?

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.


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

LinkedBlockingQueue

ArrayBlockingQueue:

PriorityBlockingQueue:

DelayQueue:


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.


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

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 Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $49.95 only.
 
BUY EBOOK
 
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 Jaca 8 and why?



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

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

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.

//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?

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.

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?

FAQ

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?

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

FAQ

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?

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.


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

Following are some frequently asked questions in Java - Streams


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.


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

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

Following are some frequently asked questions in Java - Generics


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 throws 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? How are they declared and instantiated?

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. The type parameters are defined by the Generic method, and its scope is limited to the method that it is defined in. Generic methods can be static, non-static or constructors.


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


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

FAQKey Concept

Generics are applied at compile time to provide 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.

The compiler performs type erasure as follows.

  • Replace all type type parameters with their bounds type if bounded, or with 'object' type if unbounded.
  • Inserts casts if necessary to preserve type safety.


Can Java generics be applied to primitive types?

FAQKey Concept

No Java generics cannot be applied to primitive types. But you can use wrapper classes of primitive type to use Java generics.


Can you declare static fields whose types are generic type parameters?

FAQKey Concept

No static fields are declared at the class level and are shared by all instances of the class. You cannot declare static fields whose types are generic types.


Can you create instances of generic type parameters?

FAQKey Concept

No you cannot create instances of generic type parameters.


What do you understand by wildcards in generics?

FAQKey Concept

The question mark (?) is termed as wildcard in generics code. The wildcard represents an unknown type. For example List can refer to a list of any Java object.


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

Following are some frequently asked questions in Java - Exceptions


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.


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. The method is declared with the throws keyword followed by one or more exception types.

throw is a keyword used in java programming language to send a specific type of exception from within a method's body. A method that has a throw within its body must be declared with throws keyword


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.


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.


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. The resources are automatically closed at the end of execution of the block. An object must implement java.lang.AutoCloseable interface in order for it to be used as a resource.

try-with-resource block was introduced in Java SE 7.0. Prior to that you have to use a finally block to close all resources.


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

Following are some frequently asked questions in Java - IO


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


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. All object streams implement either ObjectInput interface or ObjectOutput interface.

Java programming language provides two classes ObjectInputStream and ObjectOutputStream that provide object stream functionality.


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, based on a delimiter that can be a regular expression.


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

Following are some frequently asked questions in 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.

The sleep() method guarantees that the thread will stop executing for at least the specified period of time. It can sleep for more than the specified time since there is no guarantee when the thread will return to running state.

When a thread goes to sleep, any locks that the thread holds are not released.


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.

There is no guarantee that this will always happen, there is no guarantee that there are other threads of same priority in waiting state.


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.

Synchronized keyword can be applied to methods as well as statements or blocks.


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.

Synchronized methods - When a thread invokes a synchronized method, it acquires the intrinsic lock of the method's object and releases it after the method is completed.

Synchronized Static Methods - When a thread invokes a static synchronized method, it acquires the intrinsic lock of the Class object associated with the class.

Synchronized blocks - Synchronized statements specifies the object that provides the intrinsic lock.


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. This happens when a synchronized code calls a method that itself has synchronized code, and both sets of code use the same code.


What are the different kinds of liveness problems in Java programming language?

FAQ

Deadlock - Deadlock is a condition in multi-threaded programming in which two or more threads are blocked indefinitely, waiting on each other to acquire locks.

Starvation - Starvation is a condition in multi-threaded programming in which a thread is unable to get access to a shared resource. This occurs when a shared resource provides a synchronized method that takes a long time to complete. If one thread accesses this method frequently, then other threads does not get access to the shared resource.

Livelock - Livelock is a condition in multi-threaded programming in which a thread acts in response to another thread, and the other thread in turn acts in response to the action of another thread. The constant thread to thread communication prevents any work to happen on the threads.


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.

notify() method is used by a thread to communicate to another thread waiting on it for a specific action to complete. In above example, Thread B uses notify() method to communicate to Thread A that a specific action is complete. Once Thread B receives the notification, it goes back to running state and is eligible for execution.

notifyAll() is similar to the notify() method. notifyAll() is used by a thread to communicate to all threads waiting on it for a specific action to complete.


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

Following are some frequently asked questions in Java - Concurrency


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, Executors, 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 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 executor service's submit method for execution, but since submit method does not wait for the execution to complete, it will return a result of type Future which can be used to retrieve the actual result at a later point.


What is Parallel Fork-Join framework?

FAQ

Parallel Fork-Join framework is used for highly parallelizable tasks. Parallel Fork-Join framework increases performance of parallel tasks by enabling work stealing among worker threads and hence keeps all CPUs utilized efficiently.


What are Scheduled executors in Java programming language?

FAQ

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


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

Java programming language provides the JDBC (Java Database Connectivity) API to connect to data sources in a standard and vendor independent way. The JDBC API consists of two packages – java.sql and javax.sql

Following are some frequently asked questions in 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 interfaces and classes of the JDBC API?

FAQ

JDBC API provides the following key interfaces and classes.

Driver -

Driver Manager -

Driver -

Connection -

Statement -

ResultSet -

SQLException -


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.


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.


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.


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.

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.

TYPE_SCROLL_INSENSITIVE: The result set can be scrolled. The cursor can move both forward as well as backward relative to the current position. After the result set is created any updates made to the underlying database are not reflected to the result set object

TYPE_SCROLL_SENSITIVE: The result set can be scrolled. The cursor can move both forward as well as backward relative to the current position. After the result set is created any updates made to the underlying database are reflected to the result set object.


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.

CONCUR_READ_ONLY: The ResultSet object cannot be updated using the ResultSet interface.

CONCUR_UPDATABLE: The ResultSet object can be updated using the ResultSet interface.


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

FAQ

next()

previous()

first()

last()

beforeFirst()

beforeLast()

relative()

absolute()


How do you get the metadata of a result set?

FAQ


How do you get information about a database?



What are RowSets?



JDBC Transactions, starting transactions, committing, rollback?



What are SavePoints?



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

Following are some frequently asked questions in Java - Networking


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.interviewgrid.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 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: The client makes a connection request to the server, specific to the port number that the server socket is tied to. To successfully connect to the server, the client has to identify itself to the server along with its port number. Hence the client binds itself to a local port before making the connection request.If the connection is successful, a socket is created on the client side that is tied to the port and is used for communicating with the server.

The Java programming language provides two classes to represent sockets. Class 'java.net.Socket' represents a socket at the client side. Class 'java.net.ServerSocket' represents a socket on the server side.


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
3. Read from and write to the stream
4. Close the streams
5. Close the socket


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, the message content and arrival time of communication sent via UDP are not guaranteed. In UDP messages are sent via datagrams, which are independent, self-contained packets of data.


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 of datagrams to their destinations is not guaranteed. Datagrams can be send or broadcast to multiple recipients.

Java programming language provides three main classes that can be used to program datagrams - java.net.DatagramPacket, java.net.DatagramSocket, java.net.MultigramSocket


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


What is a network interface?

FAQ

A network interface is the point of interconnection between a computer and a private or public network. A network interface is generally a network interface card (NIC). Network interfaces can either have a physical form or can be implemented in software.

The Java networking API provides the java.net.NetworkInterface class which represents both these types of interfaces.


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. You can obtain this information from a NetworkInterface instance by using one of two methods.

1. getInetAddresses() - returns an Enumeration of InetAddress.

2. getInterfaceAddresses() - returns a list of java.net.InterfaceAddress instances. This method is used when you need more information about an interface address beyond its IP address such as it subnet mask.


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

Following are some frequently asked questions in Java - Security


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.
  • Java has access control features to control access to variables methods and classes. This is implemented via the public, private, protected and default access modifiers.
  • Final classes and methods - Classes and methods that you do not want to be sub-classed can be defined as final. This protects the code from malicious attacks via creating sub-classes and overriding the methods.


What are the key security features provided by JVM?

FAQ

JVM has many in-built and inherent security features in its design.

Class loaders - Class loaders which are responsible for loading class files into the JVM have many inherent security features.

  • Class loaders load classes into distinct name-spaces based on the class loader that loads the class and the source of the class files. Class loader provide a shield between classes in different name-spaces, essentially preventing a class in one name-space from corrupting a class in another name-space.
  • Class loaders guard the boundaries of trusted code libraries such as the Java API libraries from untrusted code. For example, the class loader will not load any class that claims to be a part of the Java API library.

Class-file verifiers - The JVM has class-file verifiers that ensure that untrusted class files loaded into the JVM are not corrupted and are safe for the JVM to use.

  • The class-file verifier checks that the class adheres to the Java programming language specifications.
  • The class-file verifier checks the integrity of the bytecodes within the class file. It checks that the bytecodes are internally consistent and structurally correct.

Bytecode verifiers - After the class-file verifiers ensure that the file is safe to use, bytecode verifiers in the JVM checks the bytecode within the class-files and ensures that the class-files are safe to run in the JVM.

  • Bytecode verifies performs a data-flow analysis on the bytecodes and verifies the integrity of the bytecodes
  • The bytecode verifier ensures that symbolic links to other classes, methods and fields are valid; else it throws an error.


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.


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 permissions are associated to those domains.


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. Example - checkRead() method determines if a class has read access to a file. checkPermissions() checks if the requested access has the permission based on the policy.


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

Following are some frequently asked questions in Java - 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 - A child class loader can find a class from the parent class holder, but a parent class loader cannot find a class from a child class loader.

Deletion - Once a Java class is loaded by a Java class loader it cannot be un-loaded. Only option is to delete the Java class loader and create a new one.


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 - Extension class loader loads Java API extension classes.

System class loader - System class loader loads all application specific class files from the class-path defined by the user or application

User defined class loader - User defined class loaders are customized class loaders defined by frameworks and application servers.


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 the class follows the Java language and JVM specifications.

Prepare -

Resolve - Change symbolic references to direct references.

Initialize - Initializes class variable and static variables.


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

Memory areas created for each thread - There are three data areas that are created for each thread - PC Register, JVM Stack and Native method stack.

  • PC Register - PC (Program Counter) register has the address of a JVM instruction that is currently being executed. Each JVM thread has PC register which is created when the thread starts.
  • JVM Stack - A JVM stack is created for each JVM thread, and stores the strut or the stack frame. A stack frame is created when a method is executed, added to the JVM stack, and removed from the JVM stack when the method ends.
  • Native Method Stack - Native method stack is a stack for native data written in a language other than Java, and invoked through JNI. Each JVM thread has its own native method stack.

Memory areas shared by all threads - There are three runtime data areas that are shared by all threads. Heap, Method area and Runtime Constant Pool.

  • Heap - Heap is the memory area in which java object instances are stored, and removed by Java garbage collector. This is one of the memory areas that is commonly tuned for to improve JVM performance.
  • Method area - The method area stores runtime constant pool, field and method information, static variables and method bytecodes for all classes and interfaces that are loaded in the JVM.
  • Runtime constant pool - Runtime constant pool contains the constant for each class and interface, and all references for methods and fields. When a method or field is referenced, the JVM gets the actual address of the method or field from the Runtime constant pool.


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 native code that the underling OS can understand.

Execution engine can transform the bytecodes into native code two ways.

Interpreter - Execution engine reads, interprets and executes the bytecode one by one. Since it has to interpret and then execute the bytecodes, execution is slow.

JIT (Just In Time) Compiler - The execution engine runs as an interpretor first, while the JIt compiler compiles the entire byte code to native code. Once the native code is generated, the execution engine no longer interprets the bytecodes, it executes the native code directly.


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

Following are some frequently asked questions in 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) - G1GC is a concurrent parallel connector, that does not have the same fragmentation problems as the CMS.


Can you force the JVM to perform garbage collection from a Java program? How?

FAQ

You cannot force the JVM to perform garbage collection. you can only suggest or indicate to the JVM to perform garbage collection using 'System.gc()'.


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 from memory when it determines that there are no more references to the object.

We cannot control when garbage control happens and should not depend on the finalize() method to perform clean up activities.


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
  • -XX:PermSize64m - Set initial PermGen Size.
  • -XX:MaxPermSize128m - Set the maximum PermGen Size.
  • -XX:NewSize -
  • XX:MaxNewSize -
  • XX:NewRatio -
  • XX:SurvivorRatio -

Flags for setting the garbage collection algorithms.

  • -XX:UseParallelGC - Enable Parallel GC algorithm
  • -XX:UseParallelOldGC - Enable Parallel GC algorithms for full collections
  • -XX:UseConcMarkGC - Enable concurrent mark sweep algorithm


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 new objects cannot be allocated in the heap. This eventually crashes the program with an OutOfMemoryError error.

The OutOfMemoryError contains detailed information that helps us to determine the root cause for the memory leak. Following are some causes for the OutOfMemoryError.

1. Resources cannot be allocated for an object in the heap - This can be because the heap size is lower than what the program requires or it could be a memory leak.
2. The PermGen space where methods and objects are stored is full.
3. The program tries to create an array greater than the heap size.

Sometimes the application crashes without the OutOfMemoryError. In such cases we can take heap dumps to further analyze the problem.


Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $49.95 only.
 
BUY EBOOK
 
Java - New in Java 8

Following are some frequently asked questions in 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 $49.95 only.
 
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.

Following are some frequently asked questions in Java - New in Java 9


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.


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


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

Following are some frequently asked questions in Java - New in Java 10


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

Java Interview Guide has over 250 REAL questions from REAL interviews. Get the guide for $49.95 only.
 
BUY EBOOK
 
 
Thank You For Reading

This site tries to follow the principle of 'Master the Concepts -> Ace the Interview'. Focus on mastering the concepts while preparing for the interview, Success will follow naturally in interviews as well as in your career.

This same philosophy is followed in the Java Interview Guide. The guide has 200 plus REAL interview questions, separated into key chapters or focus areas. Each of the questions has detailed answers and most with code snippets that will help you in white-boarding interview sessions. The guide is structured to give you a definite and focused edge over other candidates.

Good Luck!
Java Interview Guide

$49.95

BUY EBOOK
  SSL Secure Payment
Java Interview Quesiuons - Secure Payment
Ad
LEARN HOW TO EARN PASSIVE INCOME AND SIDE INCOME.

Hundreds of people are transitioning out of their full-time jobs every day by creating businesses that they are passioniate about.

You can be the next. Click below to learn more.

Java Interview Guide

$49.95

BUY EBOOK
  SSL Secure Payment
Java Interview Quesiuons - Secure Payment
Subscribe to our Newsletter

Ad
EARN SIDE INCOME

Earn income using your skills and hobbies that you are passioniate about.

Earn Side Income with Photos
Earn Side Income with Writing
Ad
FINANCIAL INDEPENDENCE

Transition out of you full-time job by creating businesses that you are passioniate about.