Java Interview Questions
Java Interview Questions
Java Interview Questions
© Copyright by Interviewbit
Contents
19. Apart from the security aspect, what are the reasons behind making strings
immutable in Java?
20. How would you differentiate between a String, StringBuffer, and a
StringBuilder?
21. Using relevant properties highlight the differences between interfaces and
abstract classes.
22. In Java, static as well as private method overriding is possible. Comment on the
statement.
23. What makes a HashSet different from a TreeSet?
24. Why is the character array preferred over string for storing confidential
information?
25. What are the differences between JVM, JRE and JDK in Java?
26. What are the differences between HashMap and HashTable in Java?
27. What is the importance of reflection in Java?
28. What are the different ways of threads usage?
29. What are the differences between constructor and method of a class in Java?
30. Java works as “pass by value” or “pass by reference” phenomenon?
31. Which among String or String Buffer should be preferred when there are lot of
updates required to be done in the data?
32. How to not allow serialization of attributes of a class in Java?
33. What happens if the static modifier is not included in the main method
signature in Java?
34. What happens if there are multiple main methods inside one class in Java?
35. What do you understand by Object Cloning and how do you achieve it in Java?
36. How does an exception propagate in the code?
37. Is it mandatory for a catch block to be followed a er a try block?
38. Will the finally block get executed when the return statement is written at the
end of try block and catch block as shown below?
Page 2 © Copyright by Interviewbit
Conclusion
61. Conclusion
3. Pointers are used in C/ C++. Why does Java not make use of
pointers?
Pointers are quite complicated and unsafe to use by beginner programmers. Java
focuses on code simplicity, and the usage of pointers can make it challenging. Pointer
utilization can also cause potential errors. Moreover, security is also compromised if
pointers are used because the users can directly access memory with the help of
pointers.
Thus, a certain level of abstraction is furnished by not including pointers in Java.
Moreover, the usage of pointers can make the procedure of garbage collection quite
slow and erroneous. Java makes use of references as these cannot be manipulated,
unlike pointers.
class Athlete {
public String athleteName;
public double athleteSpeed;
public int athleteAge;
}
Local variables are those variables present within a block, function, or constructor
and can be accessed only inside them. The utilization of the variable is restricted to
the block scope. Whenever a local variable is declared inside a method, the other
class methods don’t have any knowledge about the local variable.
Example:
equals() ==
Note:
In the cases where the equals method is not overridden in a class, then the class
uses the default implementation of the equals method that is closest to the
parent class.
Object class is considered as the parent class of all the java classes. The
implementation of the equals method in the Object class uses the == operator to
compare two objects. This default implementation can be overridden as per the
business logic.
for (;;)
{
// Business logic
// Any break logic
}
while(true){
// Business logic
// Any break logic
}
do{
// Business logic
// Any break logic
}while(true);
class Hospital {
int variable1, variable2;
double variable3;
public Hospital(int doctors, int nurses) {
variable1 = doctors;
variable2 = nurses;
}
public Hospital(int doctors) {
variable1 = doctors;
}
public Hospital(double salaries) {
variable3 = salaries
}
}
Three constructors are defined here but they differ on the basis of parameter type
and their numbers.
class OverloadingHelp {
public int findarea (int l, int b) {
int var1;
var1 = l * b;
return var1;
}
public int findarea (int l, int b, int h) {
int var2;
var2 = l * b * h;
return var2;
}
}
Both the functions have the same name but differ in the number of arguments. The
first method calculates the area of the rectangle, whereas the second method
calculates the area of a cuboid.
Method overriding is the concept in which two methods having the same method
signature are present in two different classes in which an inheritance relationship is
present. A particular method implementation (already present in the base class) is
possible for the derived class by using method overriding.
Let’s give a look at this example:
class HumanBeing {
public int walk (int distance, int time) {
int speed = distance / time;
return speed;
}
}
class Athlete extends HumanBeing {
public int walk(int distance, int time) {
int speed = distance / time;
speed = speed * 2;
return speed;
}
}
Both class methods have the name walk and the same parameters, distance, and
time. If the derived class method is called, then the base class method walk gets
overridden by that of the derived class.
11. A single try block and multiple catch blocks can co-exist in a
Java Program. Explain.
Yes, multiple catch blocks can exist but specific approaches should come prior to the
general approach because only the first catch block satisfying the catch condition is
executed. The given code illustrates the same:
Here, the second catch block will be executed because of division by 0 (i / x). In case x
was greater than 0 then the first catch block will execute because for loop runs till i =
n and array index are till n-1.
final variable:
When a variable is declared as final in Java, the value can’t be modified
once it has been assigned.
If any value has not been assigned to that variable, then it can be assigned
only by the constructor of the class.
final method:
A method declared as final cannot be overridden by its children's classes.
A constructor cannot be marked as final because whenever a class is
inherited, the constructors are not inherited. Hence, marking it final
doesn't make sense. Java throws compilation error saying - modifier final
not allowed here
final class:
No classes can be inherited from the class declared as final. But that final
class can extend other classes for its usage.
try {
int variable = 5;
}
catch (Exception exception) {
System.out.println("Exception occurred");
}
finally {
System.out.println("Execution of finally block");
}
Finalize: Prior to the garbage collection of an object, the finalize method is called so
that the clean-up activity is implemented. Example:
Parent(){
System.out.println("Parent class default constructor.");
}
Parent(String x){
System.out.println("Parent class parameterised constructor.");
}
Child(){
System.out.println("Child class default Constructor");
void printNum(){
System.out.println(num);
System.out.println(super.num); //prints the value of num of parent class
}
@Override
public void foo(){
System.out.println("Parent class foo!");
super.foo(); //Calls foo method of Parent class inside the Overriden foo
}
}
No! Declaration of static methods having the same signature can be done in the
subclass but run time polymorphism can not take place in such cases.
Overriding or dynamic polymorphism occurs during the runtime, but the static
methods are loaded and looked up at the compile time statically. Hence, these
methods cant be overridden.
Storage area: In string, the String pool serves as the storage area. For
StringBuilder and StringBuffer, heap memory is the storage area.
Mutability: A String is immutable, whereas both the StringBuilder and
StringBuffer are mutable.
Efficiency: It is quite slow to work with a String. However, StringBuilder is the
fastest in performing operations. The speed of a StringBuffer is more than a
String and less than a StringBuilder. (For example appending a character is
fastest in StringBuilder and very slow in String because a new memory is
required for the new String with appended character.)
Thread-safe: In the case of a threaded environment, StringBuilder and
StringBuffer are used whereas a String is not used. However, StringBuilder is
suitable for an environment with a single thread, and a StringBuffer is suitable
for multiple threads.
Syntax:
// String
String first = "InterviewBit";
String second = new String("InterviewBit");
// StringBuffer
StringBuffer third = new StringBuffer("InterviewBit");
// StringBuilder
StringBuilder fourth = new StringBuilder("InterviewBit");
Interface example:
As a result, vital information can be stolen for pursuing harmful activities by hackers
if a memory dump is illegally accessed by them. Such risks can be eliminated by using
mutable objects or structures like character arrays for storing any variable. A er the
work of the character array variable is done, the variable can be configured to blank
at the same instant. Consequently, it helps in saving heap memory and also gives no
chance to the hackers to extract vital data.
25. What are the differences between JVM, JRE and JDK in Java?
Definition JVM is a
platform-
dependent,
abstract
machine
JDK is a comprising of 3
complete JRE is a specifications -
so ware so ware document
development package describing the
kit for providing JVM
developing Java class implementatio
Java libraries, requirements,
applications. JVM and all computer
It comprises the required program
JRE, components meeting the JV
JavaDoc, to run the requirements
compiler, Java and instance
debuggers, applications. object for
etc. executing the
Java byte code
and provide the
runtime
environment fo
execution.
HashMap HashTable
Constructor Method
Method should
have a return
type. Even if it
Constructor has no return type.
does not return
anything, return
type is void.
Method has to be
Constructor gets invoked implicitly. invoked on the
object explicitly.
If a method is not
If the constructor is not defined, then a
defined, then the
default constructor is provided by the
compiler does not
java compiler.
provide it.
class InterviewBitTest{
int num;
InterviewBitTest(int x){
num = x;
}
InterviewBitTest(){
num = 0;
}
}
class Driver {
public static void main(String[] args)
{
//create a reference
InterviewBitTest ibTestObj = new InterviewBitTest(20);
//Pass the reference to updateObject Method
updateObject(ibTestObj);
//After the updateObject is executed, check for the value of num in the object.
System.out.println(ibTestObj.num);
}
public static void updateObject(InterviewBitTest ibObj)
{
// Point the object to new reference
ibObj = new InterviewBitTest();
// Update the value
ibObj.num = 50;
}
}
Output:
20
Case 2: When object references are not modified: In this case, since we have the
copy of reference the main object pointing to the same memory location, any
changes in the content of the object get reflected in the original object.
For example:
class InterviewBitTest{
int num;
InterviewBitTest(int x){
num = x;
}
InterviewBitTest(){
num = 0;
}
}
class Driver{
public static void main(String[] args)
{
//create a reference
InterviewBitTest ibTestObj = new InterviewBitTest(20);
//Pass the reference to updateObject Method
updateObject(ibTestObj);
//After the updateObject is executed, check for the value of num in the object.
System.out.println(ibTestObj.num);
}
public static void updateObject(InterviewBitTest ibObj)
{
// no changes are made to point the ibObj to new location
// Update the value of num
ibObj.num = 50;
}
}
Output:
50
In order to achieve this, the attribute can be declared along with the usage of
transient keyword as shown below:
In the above example, all the fields except someInfo can be serialized.
In case the Cloneable interface is not implemented and just the method is
overridden, it results in CloneNotSupportedException in Java.
finally block will be executed irrespective of the exception or not. The only case
where finally block is not executed is when it encounters ‘System.exit()’ method
anywhere in try/catch block.
However, the same does not apply to the arrays. Object or primitive type values can
be stored in arrays in contiguous memory locations, hence every element does not
require any reference to the next element.
package comparison;
public class Top {
public int start() {
return 0;
}
}
class Bottom extends Top {
public int stop() {
return 0;
}
}
In the above example, inheritance is followed. Now, some modifications are done to
the Top class like this:
If the new implementation of the Top class is followed, a compile-time error is bound
to occur in the Bottom class. Incompatible return type is there for the Top.stop()
function. Changes have to be made to either the Top or the Bottom class to ensure
compatibility. However, the composition technique can be utilized to solve the given
problem:
class Bottom {
Top par = new Top();
public int stop() {
par.start();
par.stop();
return 0;
}
}
The checking() function will return true as the same content is referenced by both the
variables.
Conversely, when a String formation takes place with the help of a new() operator,
interning does not take place. The object gets created in the heap memory even if
the same content object is present.
The checking() function will return false as the same content is not referenced by
both the variables.
package anonymous;
public class Counting {
private int increase_counter;
public int increase() {
increase_counter = increase_counter + 1;
return increase_counter;
}
}
package anonymous;
public class Counting {
private int increase_counter;
public synchronized int increase() {
increase_counter = increase_counter + 1;
return increase_counter;
}
}
If a thread Thread1 views the count as 10, it will be increased by 1 to 11, then the
thread Thread2 will view the count as 11, it will be increased by 1 to 12. Thus,
consistency in count values takes place.
fooBarMethod("foo", "bar");
fooBarMethod("foo", "bar", "boo");
fooBarMethod(new String[]{"foo", "var", "boo"});
public void myMethod(String... variables){
for(String variable : variables){
// business logic
}
}
import java.util.HashSet;
import java.util.Set;
doSomething(stringSets);
}
In the above example, we see that the stringSets were initialized by using double
braces.
The first brace does the task of creating an anonymous inner class that has the
capability of accessing the parent class’s behavior. In our example, we are
creating the subclass of HashSet so that it can use the add() method of HashSet.
The second braces do the task of initializing the instances.
Care should be taken while initializing through this method as the method involves
the creation of anonymous inner classes which can cause problems during the
garbage collection or serialization processes and may also result in memory leaks.
The length method returns the number of Unicode units of the String. Let's
understand what Unicode units are and what is the confusion below.
We know that Java uses UTF-16 for String representation. With this Unicode, we
need to understand the below two Unicode related terms:
Code Point: This represents an integer denoting a character in the code
space.
Code Unit: This is a bit sequence used for encoding the code points. In order
to do this, one or more units might be required for representing a code
point.
Under the UTF-16 scheme, the code points were divided logically into 17 planes
and the first plane was called the Basic Multilingual Plane (BMP). The BMP has
classic characters - U+0000 to U+FFFF. The rest of the characters- U+10000 to
U+10FFFF were termed as the supplementary characters as they were contained
in the remaining planes.
The code points from the first plane are encoded using one 16-bit code unit
The code points from the remaining planes are encoded using two code
units.
Now if a string contained supplementary characters, the length function would count
that as 2 units and the result of the length() function would not be as per what is
expected.
In other words, if there is 1 supplementary character of 2 units, the length of that
SINGLE character is considered to be TWO - Notice the inaccuracy here? As per the
java documentation, it is expected, but as per the real logic, it is inaccurate.
“bit” would have been the result printed if the letters were used in double-quotes (or
the string literals). But the question has the character literals (single quotes) being
used which is why concatenation wouldn't occur. The corresponding ASCII values of
each character would be added and the result of that sum would be printed.
The ASCII values of ‘b’, ‘i’, ‘t’ are:
‘b’ = 98
‘i’ = 105
‘t’ = 116
98 + 105 + 116 = 319
Second Approach: Point the reference variable to another object. Doing this, the
object which the reference variable was referencing before becomes eligible for GC.
/*
* Java program to check if a given inputted string is palindrome or not using recursion
*/
import java.util.*;
public class InterviewBit {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String word = s.nextLine();
System.out.println("Is "+word+" palindrome? - "+isWordPalindrome(word));
}
import java.util.Arrays;
import java.util.Scanner;
public class InterviewBit {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
//Input from two strings
System.out.print("First String: ");
String string1 = s.nextLine();
System.out.print("Second String: ");
String string2 = s.nextLine();
// check for the length
if(string1.length() == string2.length()) {
// convert strings to char array
char[] characterArray1 = string1.toCharArray();
char[] characterArray2 = string2.toCharArray();
// sort the arrays
Arrays.sort(characterArray1);
Arrays.sort(characterArray2);
// check for equality, if found equal then anagram, else not an anagram
boolean isAnagram = Arrays.equals(characterArray1, characterArray2);
System.out.println("Anagram: "+ isAnagram);
}
}
Idea is to find the sum of n natural numbers using the formula and then finding the
sum of numbers in the given array. Subtracting these two sums results in the number
that is the actual missing number. This results in O(n) time complexity and O(1) space
complexity.
int[] array={4,3,8,7,5,2,6};
int missingNumber = findMissingNum(array);
System.out.println("Missing Number is "+ missingNumber);
}
Conclusion
61. Conclusion
Java is one of the simple high-level languages that provides powerful tools and
impressive standards required for application development. It was also one of the
first languages to provide amazing threading support for tackling concurrency-based
problems. The easy-to-use syntax and the built-in features of Java combined with the
stability it provides to applications are the main reasons for this language to have
ever-growing usage in the so ware community.
Join our community and share your java interview experiences.
Recommended tutorials:
Java Tutorial
Puzzles
Css Interview Questions Laravel Interview Questions Asp Net Interview Questions