0% found this document useful (0 votes)
3K views

Core Java Interview Questions - 2021 - Sample

● Concept refresher for Java (includes Java 8 and Java 9) ● Ideal prep guide for coding interviews - technical and HR rounds ● Guidance for Resume building and Aptitude tests ● Includes Scenario based questions ● Developed and recommended by industry experts and placement experts
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3K views

Core Java Interview Questions - 2021 - Sample

● Concept refresher for Java (includes Java 8 and Java 9) ● Ideal prep guide for coding interviews - technical and HR rounds ● Guidance for Resume building and Aptitude tests ● Includes Scenario based questions ● Developed and recommended by industry experts and placement experts
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

This page is intentionally left blank

Job Interview Questions Series

CORE JAVA
INTERVIEW QUESTIONS
YOU’LL MOST LIKELY BE ASKED

367
Interview Questions
CORE JAVA
INTERVIEW QUESTIONS
YOU’LL MOST LIKELY BE ASKED

© 2021, By Vibrant Publishers, USA. All rights reserved. No part of this


publication may be reproduced or distributed in any form or by any means,
or stored in a database or retrieval system, without the prior permission of
the publisher.

Paperback ISBN 10: 1-63651-040-X


Paperback ISBN 13: 978-1-63651-040-8
Ebook ISBN 10: 1-63651-041-8
Ebook ISBN 13: 978-1-63651-041-5

Library of Congress Control Number: 2021938075

This publication is designed to provide accurate and authoritative


information in regard to the subject matter covered. The Author has made
every effort in the preparation of this book to ensure the accuracy of the
information. However, information in this book is sold without warranty
either expressed or implied. The Author or the Publisher will not be liable for
any damages caused or alleged to be caused either directly or indirectly by
this book.

Vibrant Publishers books are available at special quantity discount for sales
promotions, or for use in corporate training programs. For more information
please write to [email protected]

Please email feedback / corrections (technical, grammatical or spelling) to


[email protected]

To access the complete catalogue of Vibrant Publishers, visit


www.vibrantpublishers.com
What experts say about this book!

With rapidly changing technologies, IT professionals need to


constantly update their credentials riding the latest technology
trends. The new edition of “Core Java Interview Questions You’ll Most
Likely Be Asked” is a perfect companion to enhance the interview
skills for Java programmers and developers to build their IT careers.
In addition to the standard core Java questions and answers, this
edition includes the questions about functional interfaces and lambda
expressions of Java 8 plus modules and stream of Java 9. The human
resource questions and answers would prepare the IT professionals
to nail the interviews and impress the employers. With real life
scenario-based questions, this book features the concise information
required for the working professionals to strategize and stand out in
today’s competitive job market.

– David Han
Ph.D.Associate Professor of Management Science and Statistics ,
University of Texas at San Antonio

I work closely with students especially for their placements. This


book will really help students to prepare as well as practice interview
questions. No doubt, this is going to be a real guide for the job
aspirants. Indexing is good and easy to understand. Almost all
probable mutations are included in the book. Difficulty level is from
easy to difficult which is suitable for all kinds of Java related jobs.

– Yogesh Jadhav
Professor & Training and Placement Officer, Sinhgad Institutes
What experts say about this book!

Excellent list of questionnaires. Core Java Interview Questions book


from Vibrant Publishers will be very useful for job aspirants in Java
technology. It includes HR questions too. Many job aspirants are not
clear about the HR round, so it is very nice to have HR questions in the
book. This book will help freshers and junior level aspirants of Java
jobs a lot. My final review is that it will be very helpful for fresher level
and experienced candidates looking for MNC Placements.

– Shashikanth K
Placement Coordinator & Associate Professor at CSE Department

I really liked the way each and every part of Java is touched in
the book. Plus, the in-detail explanation along with snippet code
examples makes it more clear and easy to understand.

– Barkat Amirali Jiwani


Assistant Professor/Placement Head, Vaagdevi College of
Engineering, Warangal
Contributor to this Book
Reshma Bidikar is a passionate Java engineer
and educator. With over 16 years in the IT
industry working as a Senior Java Developer/
Architect, she has worked in technologies like
Core Java, Spring, Spring Boot, Hibernate, REST,
JDBC to name a few. She is an expert Java
Trainer/Java Writer and her Java articles/
tutorials/courses have helped thousands of students/readers
worldwide. She specializes in combining her extensive Java
knowledge with her ability to explain complex concepts in easy to
understand language. She has a Bachelor of Engineering Degree in
Computer Science. Outside of work, she is an avid reader and a
zealous blogger.
This page is intentionally left blank
TABLE OF CONTENTS

Section 01– Core Java


01. OOPs Concepts.............................................................................7
02. Java Basics....................................................................................15
03. Data Types, Variables and Arrays......................................23
04. Operators.....................................................................................31
05. Control Statements..................................................................39
06. Classes and Methods...............................................................51
07. Inner Classes..............................................................................61
08. Inheritance..................................................................................67
09. Abstract Classes and Interfaces.........................................81
10. Packages and Access Control..............................................89
11. Exception Handling.................................................................97
12. String Handling.......................................................................105
13. Generics.....................................................................................111
14. Collections.................................................................................115
15. Enumerations, Autoboxing and Wrapper Classes...121
16. Threads......................................................................................127
17. Java IO API................................................................................137
18. Miscellaneous..........................................................................145

Section 02– Java 8


01. Functional Interfaces...........................................................153
02. Lambda Expressions............................................................161
TABLE OF CONTENTS

03. Streams.......................................................................................169
04. Method References...............................................................177
05. DateTime API..........................................................................183
06. Static and Default Interface Methods............................191
07. Optionals....................................................................................195
08. Collection Improvements...................................................201
09. Miscellaneous..........................................................................207

Section 03– Java 9


01. Modules......................................................................................213
02. Stream/Collection Improvements.................................219
03. Miscellaneous..........................................................................223
04. Scenario Based Questions..................................................229

Section 04– Human Resource


01. Creativity....................................................................................239
02. Leadership................................................................................243
03. Deadlines and Time Management..................................263
04. Customer Service...................................................................273
05. Communication......................................................................283
06. Job Searching and Scheduling..........................................293

Index.................................................................305
Dear Reader,

Thank you for purchasing Core Java Interview Questions You’ll Most Likely Be Asked.
We are committed to publishing books that are content–rich, concise and approachable
enabling more readers to read and make the fullest use of them. We hope this book provides
the most enriching learning experience as you prepare for your interview.

Should you have any questions or suggestions, feel free to email us at


[email protected]

Thanks again for your purchase. Good luck with your interview!

– Vibrant Publishers Team

facebook.com/vibrantpublishers
SECTION

01
CORE JAVA

JAVA 8

JAVA 9

HUMAN RESOURCE
OOPs Concepts

CHAPTER
01
001. Explain method overloading and method overriding.
Answer:
Method overloading occurs when there are two or more
methods in a class with the same name but with different
number/type of arguments. The following code demonstrates
this:

public class Calculator {


public int add (int a, int b) {
return a+b;
}
public double add (double a, double b) {
return a+b;
}
public int add (int a) {
8 Core Java Interview Questions You’ll Most Likely Be Asked

return a+a;
}
}

Method overriding occurs when there is a method in a sub–


class that has the same name and number of arguments as a
super–class method. The following code demonstrates this:

public class Animal {


public void saySomething () {
System.out.println(“I am an animal”);
}
}
public class Dog extends Animal {
public void saySomething () {
System.out.println(“I am a dog”);
}
}

002. Explain the benefits of OOPs.


Answer:
Following are the benefits of OOPs:
a. Reusability: OOPs principles like Inheritance, Composition
and polymorphism help in reusing existing code
b. Extensibility: Code written using OOPs principles like
Inheritance makes code extensible
c. Security: OOPs principles like encapsulation help to keep
the data and the code that operates on the data together and
makes the code secure
d. Simplicity: Java classes represent real world objects. This
makes code very easy to understand

www.vibrantpublishers.com
OOPs Concepts 9

e. Maintainability: Code written using OOPs principles is


easier to maintain

003. Write a code snippet that demonstrates encapsulation.


Answer:
Encapsulation refers to keeping the data and the code that
operates on the data together as a single unit. Simply creating
a class with private fields and public getter/setter methods
is an example of encapsulation. The following code snippet
demonstrates this:

public class Laptop {


private String memory;
public String getMemory () {
return memory;
}
public String setMemory (String newMemory){
memory = newMemory;
}
}

Here, there is a class called Laptop. It has a private field called


memory and public getter and setter methods to access/modify
the memory field. So, the memory field cannot be accessed
directly outside the class, it can only be accessed via its getter/
setter methods.

004. What are the types of inheritance relationships?


Answer:
Inheritance relationships specify how code can be reused.
There are two types of inheritance relationships.

www.vibrantpublishers.com
10 Core Java Interview Questions You’ll Most Likely Be Asked

They are as follows:


a. IS–A
An IS–A relationship is implemented via inheritance, that is by
creating a sub–class. Assume that, Camera is a subclass and
Electronics is a super class. In that case, we can say that,
Camera IS–A Electronic product
b. HAS–A
A HAS–A relation can be created via composition, that is by
creating a field corresponding to another class. Assume that,
inside the Camera class, there is an object called Battery.
In that case, we can say that Camera HAS–A object called
Battery

005. What is the best practice in declaring instance variables?


Answer:
Instance variable should always be declared as private. They
should have public getter/setter methods. This helps to protect
the instance variable as they can only be modified under the
programmer’s control. This is as per the Encapsulation principle.
Declaring instance variables as public violates the
encapsulation principle and poses a security issue. Public
instance variables can be maliciously modified outside your
class. If at all an instance variable needs to be accessed from a
sub–class, it can be made protected.

006. What is a singleton class?


Answer:
A class which lets you create only one instance at any given
time is termed a Singleton class. A Singleton class can be
implemented via a private constructor and a public getter
www.vibrantpublishers.com
OOPs Concepts 11

method. The following code demonstrates this.

public class MySingleton {


private static MySingleton mySingletonInstance;
private MySingleton () {
}
public static MySingleton getInstance () {
if (mySingletonInstance == null) {
mySingletonInstance = new MySingleton (); //
create the object only if it is null
}
return mySingletonInstance;
}
public void doSomething () {
System.out.println(“I am here....”);
}
public static void main(String a[]) {
MySingleton mySingleton = MySingleton.
getInstance();
mySingleton.doSomething();
}
}

Here, a private constructor and a public getInstance method


is defined. The getInstance checks if an instance exists.
If an instance does not exist, it creates one using the private
constructor. If an instance exists, it just returns it. Any external
class that needs an instance of the Singleton class, needs to
obtain it via the getInstance method. The getInstance
method ensures that there is only one instance of the Singleton
class.

www.vibrantpublishers.com
12 Core Java Interview Questions You’ll Most Likely Be Asked

007. Explain what happens when the following code is compiled


and state whether it uses method overloading or overriding.
class Electronics {
public void displayPrice (Float price) {} //Line 1
}
class Camera extends Electronics {
public void displayPrice (String price) {} //Line 2
}

Answer:
The above compiles fine. It uses method overloading. Camera
is a sub–class of Electronics and both classes have a method
called displayPrice. However, the displayPrice method
in both classes differ in the type of argument.

008. Write a Java code sample that demonstrates method


overloading.
Answer:
Method overloading occurs when there are two or more
methods in a class with the same name but with a different
number/type of arguments.The following code demonstrates
this:

class Laptop {
public void displayPixel (int width, int height) { };
//Line 1
public void displayPixel (float width, float height)
{}; //Line 2
}

The class Laptop has two method with the name as


displayPixel. The displayPixel method at Line 1 has
two arguments, both of type int. The displayPixel method
at Line 2, displayPixel method has two arguments both of

www.vibrantpublishers.com
OOPs Concepts 13

type float. So here, the displayPixel method is said to be


overloaded.

009. What is polymorphism? How does Java support


Polymorphism?
Answer:
Polymorphism literally means “many forms”. It is the ability
to use the same interface to execute different code. Java
achieves polymorphism via method overloading and method
overriding. Method overloading occurs when there are many
methods in a class with the same name but different number/
type of arguments. The version of an overloaded method that
will be invoked is determined at compile time based on the
number/type of arguments passed in. Method overriding
occurs when a sub–class has a method with the same name and
type signature as a method in the super class. The version of an
overridden method that will be invoked is determined at run
time based on the type of object that invokes the method.

010. Explain how Java achieves abstraction.


Answer:
Abstraction is an OOPs concept whereby only the necessary
information is exposed to the end user and the internal
implementation details are hidden. Java achieves abstraction
via abstract classes and interfaces. So, you can declare the
methods that you want to be exposed to the outside world in
an abstract class or interface. The actual implementation will
be within concrete classes that extend the abstract classes or
implement the interfaces. The outside code is not aware of the
implementing classes, they interact with your code via the
interfaces or abstract classes.
www.vibrantpublishers.com
This page is intentionally left blank
Java Basics

CHAPTER
02
011. What are the possible ways of declaring the Java main
method?
Answer:
Following are the possible ways of declaring the Java main
method.
a. public static void main (String argument [])
b. static public void main (String argument [])
So, while declaring the Java main method, the order of the
public, static, void keyword does not matter, they can be
written in any order.
16 Core Java Interview Questions You’ll Most Likely Be Asked

012. What are the possible ways of declaring a Java class?


Answer:
Following are the possible ways of declaring a Java class:
a. public class Class1 {}
b. class Class2 {}
c. private class Class3 {}
d. protected class Class4 {}
e. static class Class5{}
Approach a declares a class as public. Approach b does
not use any access specifier, so it has default access. It will be
accessible only within the package. Approaches c and d use the
private, protected access specifiers. Note that a high–level
class cannot have these specifiers. This can only be used for an
inner class. Approach e uses the static keyword. Again, only an
inner class can have this access specifier.

013. How will you define an Identifier?


Answer:
Identifier is the name given to a class, method, variable or
interface. There are several rules for Java identifiers. These are
as follows:
● Identifiers must start with an alphabet, the dollar sign ($), or
an underscore character (_)
● Identifiers can contain alphabets, digits, $ and _
● Identifiers cannot contain special characters
● Identifiers are case sensitive

www.vibrantpublishers.com
Java Basics 17

Some of the examples of legal identifiers are shown below:


● b
● $a
● book
● author1
● myName
● ___1_c

014. What are the modifiers that cannot be specified with an


instance variable?
Answer:
The following modifiers cannot be specified with an instance
variable:
a. abstract: is valid only for classes, interfaces and methods, it
cannot be specified with an instance variable
b. synchronized
c. native
The keywords synchronized and native are valid only for
methods and cannot be specified with an instance variable.
d. void: can only be specified as a return type, when a method
does not return any value

015. What are the modifiers that can be specified with a method
declaration?
Answer:
The following keywords can be specified with a method
declaration:
a. public
b. private

www.vibrantpublishers.com
18 Core Java Interview Questions You’ll Most Likely Be Asked

c. protected
The keywords public, private and protected are access
specifiers. They specify from where the method can be
accessed.
d. static: used to indicate that the method is a class level
method
e. final: used to indicate that the method cannot be overridden
f. abstract: used to specify that a sub–class should override
the method
g. native: used to specify that the method is implemented in
another language like C++
h. synchronized: used to indicate that the method can be
accessed by only one thread at a time

016. What will be the default value of a reference variable when


it is not explicitly initialized? How will you handle this in
code?
Answer:
When a reference variable is not explicitly initialized, then
its value is null by default. If such variables are not properly
handled, they can result in a NullPointerException. So, in
order to avoid the NullPointerException, you can do one
of the following:
● Ensure that variables are properly initialized
● Explicitly add null checks in your code
● Use Java 8 Optionals

www.vibrantpublishers.com
Java Basics 19

017. Explain the keywords “transient” and “native”.


Answer:
The keyword transient can be used as a modifier for an
instance variable. It specifies that the JVM should ignore the
variable while serializing the containing object.
The keyword native can be used as a modifier with methods. It
specifies that the method is implemented in another language
like C, C++.

018. What is a comment in Java? Explain the types of comments


supported by Java.
Answer:
A comment is some text added to the code that provides
additional information about the code. It describes what the
code does to the readers of the code. Comments are ignored by
the compiler. Java supports 3 types of comments as follows:
a. Single Line Comment: Such a comment begins with two
forward slashes (//) and ends at the end of the line. The
following code snippet demonstrates this:

int count; // This stores the number of objects

b. Multi Line Comment: This starts with /* and ends with


*/. Anything between these two is treated as a comment
and ignored by the compiler. The following code snippet
demonstrates this:

/*
This for loop repeats a block of code 10 times
*/
for (int i=0; i < 10; i++) {
}

www.vibrantpublishers.com
20 Core Java Interview Questions You’ll Most Likely Be Asked

c. Documentation comment: Documentation comments are


comments that are used to generate documentation for the
code via the JavaDoc tool. They start with /** and end with
*/. The following code demonstrates this:

/**
* Method that does something
* @param a
*/
public void myMethod (int a) {
}

019. Explain what is JVM, JRE and JDK.


Answer:
JDK stands for Java Development Kit. It consists of the tools
and libraries that are required to write and run a Java program.
So, it includes the Java compiler, JRE and other tools.
JRE stands for the Java Runtime Environment. It consists of
the tools that are required to run a Java program. It is included
with the JDK but it can also be installed by itself. If the JRE is
installed by itself without the JDK, you will be able to run a
Java program but you will not be able to write and compile
Java code. JRE includes the JVM and some other libraries.
JVM stands for the Java Virtual Machine. Java code is compiled
into byte code. This byte code is executed within the JVM. So,
the JVM just provides an execution environment to execute
code.

www.vibrantpublishers.com
Java Basics 21

020. Explain with a code sample how you will read a value
entered by a user.
Answer:
Java provides a class called java.util.Scanner. This can
be used to read an input from a user. The following code
demonstrates this:

System.out.println(“Enter a Number:”);
Scanner scanner = new Scanner (System.in);
int num = scanner.nextInt();
System.out.println(“The entered number is “:num);
scanner.close();

This code creates a Scanner corresponding to System.in


which is the standard input. It then asks the user to input a
number and reads this number into the variable num via the
scanner.nextInt method. So, this code prints the following
output:

Enter a Number:
10
The entered number is 10

Just like nextInt, the Scanner class has several other


methods that can be used to read data of different types like
String, float, long, boolean, etc.

www.vibrantpublishers.com
This page is intentionally left blank
Data Types,

CHAPTER
Variables and
Arrays

03
021. What are the possible ways of declaring an array of short
data type?
Answer:
You can declare an array of short data type in any of the
following ways:
a. short a1[];
b. short [] a2;
c. short b1[] [];
d. short [] [] b2;
e. short [] c1 = {2,3,4};
f. short c2[] = {2,3,4};
Approaches a and b declare a single dimensional short array.
Approaches c and d declare a two–dimensional short array.
Approaches e and f declare a single dimensional short array
and initialize it. In all the approaches, the square brackets
24 Core Java Interview Questions You’ll Most Likely Be Asked

can be placed either after the variable name or after the short
keyword.

022. How will you cast an int variable to byte explicitly? Is it


really necessary to cast int literal to byte?
Answer:
An int variable can be cast to byte as follows:

int i = 30;
byte bValue = (byte)i;

So, you need to specify the “byte” keyword before the int
variable. Yes, it is necessary to cast an int variable to byte
explicitly, otherwise a compilation error will occur as below:

byte bValue = i; //compilation error

This is because int is a wider type as compared to byte. So, Java


cannot automatically convert the int type to byte, you need to
specify an explicit cast.

023. Give an example of implicit casting.


Answer:
Implicit casting occurs when a value is assigned to a variable
of a wider data type. In such cases, the conversion happens by
default and there is no need of an explicit cast. For example,
if you assign an int value to a long value, an implicit cast will
occur. The following code snippet demonstrates this:

int iValue = 250;


long lValue = iValue;

The above code demonstrates that an int value can always be

www.vibrantpublishers.com
Data Types, Variables and Arrays 25

assigned to a long variable without casting and the conversion


happens by default.

024. Write a code snippet that demonstrate how you can assign a
float value to a short variable.
Answer:
The following code demonstrates converting a float value to a
short variable:

float fValue = 37000.02F;


short sValue = (short) fValue;

Here, the keyword short is specified before the float variable


fValue, this is known as explicit cast. Since float is a wider
data type than short, an explicit cast is required.

025. What is the default value for int, double, float, boolean,
long and char data types?
Answer:
The default values for the data types mentioned above are as
follows:
int = 0
double = 0.0d
float = 0.0f
boolean = false
long = 0L
char = ‘u0000’

www.vibrantpublishers.com
26 Core Java Interview Questions You’ll Most Likely Be Asked

026. In the following code snippet, explain which lines will


compile fine and which will cause a compilation error.
int [] [] add = new int [2] []; //Line 1
int [] subtract = new int [2]; //Line 2
int iValue = 2; //Line 3
add[1] = subtract; //Line 4
add[1] = iValue; //Line 5

Answer:
Line 1 compiles fine as it creates a two–dimensional array. Line
2 compiles fine as it creates a single dimensional array. Line 3
compiles fine as it declares and initializes an int variable.
Since a two– dimensional array is an array of arrays, Line 4 also
compiles fine. It assigns a single dimensional array to one of
the dimensions in the two–dimensional array. Line 5 causes a
compilation error because we cannot assign an int variable to
an int array variable.

027. Explain what happens when the following code is


compiled.
public class Car {
public Car (String carName) {}
}
Car myCar = new Car(“Benz”);
Car [] myCars = { myCar, new Car(“Ford”), new
Car(“BMW”)};

Answer:
The code compiles fine, there is no issue at all. The code first
creates a Car class. It creates a car object called myCar. Finally,
it creates a Car array called myCars which is initialized with
three values. The Car constructor is directly invoked during
array initialization.

www.vibrantpublishers.com
Data Types, Variables and Arrays 27

028. You are given an assignment to create a game of Tic Tac Toe
using a multi–dimensional array. Which of the following is
the correct way to initialize the array?
a. int ttt = new int[3][3];
b. int[]ttt = new int[3][3];
c. int[][]ttt = new int[3][3];
d. int ttt [3][3] = new int[][];
Answer:
(c) Answer c is correct. The correct syntax for declaring a
multi–dimensional array is

int[][]ttt =new int[3][3];

029. Explain the primitive data types in Java.


Answer:
There are eight primitive data types in Java. These are as
follows:

Name Width (Bits) Range


byte 8 –128 to 127
short 16 –32,768 to 32,767
int 32 –2,147,483,648 to 2,147,483,647
–9,223,372,036,854,775,808 to
long 64
9,223,372,036,854,775,807
float 32 1.4e–045 to 3.4e+038
double 64 4.9e–324 to 1.8e+308
char 16 0 to 65536
boolean 1 true/false

www.vibrantpublishers.com

You might also like