0% found this document useful (0 votes)
20 views24 pages

Java

java interview help
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
20 views24 pages

Java

java interview help
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 24

What is Java?

Java is a high-level programming language. It is based on the principles of


object-orient programming.
Why is Java platform independent language?
Java was developed in such a way that it does not depend on any hardware
or software since the compiler compiles the code and then converts it to
platform-independent byte code which can be run on multiple systems.
The only condition to run that byte code is for the machine to have a runtime
environment (JRE) installed in it.
Why is Java not a pure object-oriented language?
Java supports primitive data types - byte, boolean, char, short, int, float, long,
and double and hence it is not a pure object oriented language.
Difference between Heap and Stack Memory in java. And how java
utilizes this.
Stack memory is the portion of memory that was assigned to every individual
program. And it was fixed. On the other hand, Heap memory is the portion
that was not allocated to the java program, but it will be available for use by
the java program when it is required, mostly during the runtime of the
program.
Java Utilizes this memory as -
1. When we write a java program then all the variables, methods, etc are stored
in the stack memory.
2. And when we create any object in the java program then that object was
created in the heap memory. And it was referenced from the stack memory.
How is Java different from C++?
 C++ is only a compiled language, whereas Java is compiled as well as an
interpreted language.
 Java programs are machine-independent whereas a c++ program can run
only in the machine in which it is compiled.
 C++ allows users to use pointers in the program. Whereas java doesn’t allow
it. Java internally uses pointers.
 C++ supports the concept of Multiple inheritances whereas Java doesn't
support this. And it is due to avoiding the complexity of name ambiguity that
causes the diamond problem.
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.

What do you mean by data encapsulation?


 Data Encapsulation is an Object-Oriented Programming concept of hiding the
data attributes and their behaviours in a single unit.
 It helps developers to follow modularity while developing software by ensuring
that each object is independent of other objects by having its own methods,
attributes, and functionalities.
 It is used for the security of the private properties of an object and hence
serves the purpose of data hiding.
Tell us something about JIT compiler.
 JIT stands for Just-In-Time, and it is used for improving the performance
during run time. It does the task of compiling parts of byte code having similar
functionality at the same time thereby reducing the amount of compilation
time for the code to run.
 The compiler is nothing but a translator of source code to machine-executable
code. But what is special about the JIT compiler? Let us see how it works:
 First, the Java source code (.java) conversion to byte code (.class)
occurs with the help of the javac compiler.
 Then, the .class files are loaded at run time by JVM and with the help
of an interpreter, these are converted to machine understandable
code.
 JIT compiler is a part of JVM. When the JIT compiler is enabled, the
JVM analyzes the method calls in the .class files and compiles them to
get more efficient and native code. It also ensures that the prioritized
method calls are optimized.
 Once the above step is done, the JVM executes the optimized code
directly instead of interpreting the code again. This increases the
performance and speed of the execution.

Can you tell the difference between equals() method and equality
operator (==) in Java?
We are already aware of the (==) equals operator. That we have used this to
compare the equality of the values. But when we talk about the terms of
object-oriented programming, we deal with the values in the form of objects.
And this object may contain multiple types of data. So using the (==)
operator does not work in this case. So we need to go with the .equals()
method.
Both [(==) and .equals()] primary functionalities are to compare the values,
but the secondary functionality is different.
(==) Operators compares the memory location. equals() method compares
the values and returns the result accordingly.
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.
Briefly explain the concept of constructor overloading
Constructor overloading is the process of creating multiple constructors in the
class consisting of the same name with a difference in the constructor
parameters. Depending upon the number of parameters and their
corresponding types, distinguishing of the different types of constructors is
done by the compiler.

Define Copy constructor in java.


Copy Constructor is the constructor used when we want to initialize the value
to the new object from the old object of the same class.
class InterviewBit{
String department;
String service;
InterviewBit(InterviewBit ib){
this.departments = ib.departments;
this.services = ib.services;
}
}
Here we are initializing the new object value from the old object value in the
constructor. Although, this can also be achieved with the help of object
cloning.

Can the main method be Overloaded?


Yes, It is possible to overload the main method. We can create as many
overloaded main methods we want. However, JVM has a predefined calling
method that JVM will only call the main method with the definition of –
Public static void main(String[] args)

Comment on method overloading and overriding by citing relevant


examples.
In Java, method overloading is made possible by introducing different
methods in the same class consisting of the same name. Still, all the functions
differ in the number or type of parameters. It takes place inside a class and
enhances program readability.
The only difference in the return type of the method does not promote method
overloading.

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

Explain the use of final keyword in variable, method and class.


In Java, the final keyword is used as defining something as constant /final and
represents the non-access modifier.
 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.
Do final, finally and finalize keywords have the same function?
All three keywords have their own utility while programming.
Final: If any restriction is required for classes, variables, or methods, the final
keyword comes in handy. Inheritance of a final class and overriding of a final
method is restricted using the final keyword. The variable value becomes
fixed after incorporating the final keyword.
Example:
final int a=100;
a = 0; // error
Finally: It is the block present in a program where all the codes written inside
it get executed irrespective of handling of exceptions.
Example:
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:
public static void main(String[] args) {
String example = new String("InterviewBit");
example = null;
System.gc(); // Garbage collector called
}
public void finalize() {
// Finalize called
}
Is it possible that the ‘finally’ block will not be executed? If yes then list
the case.
Yes. It is possible that the ‘finally’ block will not be executed. The cases are-
 Suppose we use System.exit() in the above statement.
 If there are fatal errors like Stack overflow, Memory access error, etc.
When can you use super keyword?
 The super keyword is used to access hidden fields and overridden methods
or attributes of the parent class.
 Following are the cases when this keyword can be used:
 Accessing data members of parent class when the member names of
the class and its child subclasses are same.
 To call the default and parameterized constructor of the parent class
inside the child class.
 Accessing the parent class methods when the child classes have
overridden them.
 The following example demonstrates all 3 cases when a super keyword is
used.
Can the static methods be overridden?
 No! Declaration of static methods having the same signature can be done in
the subclass but run time polymorphism cannot 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.
Difference between static methods, static variables, and static classes in
java.
 Static Methods and Static variables are those methods and variables that
belong to the class of the java program, not to the object of the class. This
gets memory where the class is loaded. And these can directly be called with
the help of class names.
 For example - We have used mathematical functions in the java
program like - max(), min(), sqrt(), pow(), etc. And if we notice that,
then we will find that we call it directly with the class name. Like -
Math.max(), Math.min(), etc. So that is a static method. And similarly
static variables we have used like (length) for the array to get the
length. So that is the static method.
 Static classes - A class in the java program cannot be static except if it is the
inner class. If it is an inner static class, then it exactly works like other static
members of the class.
What is the main objective of garbage collection?
The main objective of this process is to free up the memory space occupied
by the unnecessary and unreachable objects during the Java program
execution by deleting those unreachable objects.
 This ensures that the memory resource is used efficiently, but it provides no
guarantee that there would be sufficient memory for the program execution.
What is a ClassLoader?
Java ClassLoader is the program that belongs to JRE (Java Runtime Environment).
The task of ClassLoader is to load the required classes and interfaces to the JVM
when required.
Example- To get input from the console, we require the scanner class. And the
Scanner class is loaded by the ClassLoader.
What are shallow copy and deep copy in java?
To copy the object's data, we have several methods like deep copy and
shallow copy.
Shallow copy - The shallow copy only creates a new reference and points to
the same object. Now by doing this what will happen is the new reference is
created will point to the same memory location. If we change the values in shallow
copy then they affect the other reference as well. Example - For Shallow copy, we
can do this by –
Rectangle r2 = r1;
Deep Copy - In a deep copy, we create a new object and copy the old object value
to the new object. Both these objects will point to different memory location. If we
change the code to deep copy, then there will be no effect on other object if it is of
type deep copy. Example –
Rectangle r3 = new Rectangle():
r3.length = r1.length;
r3.width = r1.width;

The clone() will do this deep copy internally and return a new object. And to do this
we need to write only 1 line of code. That is - Rectangle obj2 = obj1.clone().
Apart from the security aspect, what are the reasons behind making
strings immutable in Java?
A String is made immutable due to the following reasons:
String Pool: Designers of Java knew String data type is going to be majorly
used by the programmers and developers. Thus, they wanted optimization
from the beginning. They came up with the notion of using the String pool (a
storage area in Java heap) to store the String literals. They intended to
decrease the temporary String object with the help of sharing. An immutable
class is needed to facilitate sharing. The sharing of the mutable structures
between two unknown parties is not possible. Thus, immutable Java String
helps in executing the concept of String Pool.
Multithreading: The safety of threads regarding the String objects is an
important aspect in Java. No external synchronization is required if the String
objects are immutable. Thus, a cleaner code can be written for sharing the
String objects across different threads. The complex process of concurrency
is facilitated by this method.
Collections: In the case of Hash tables and HashMap, keys are String
objects. If the String objects are not immutable, then it can get modified during
the period when it resides in the HashMap. Consequently, the retrieval of the
desired data is not possible. Such changing states pose a lot of risks.
Therefore, it is quite safe to make the string immutable.
What is a singleton class in Java? And how to implement a singleton
class?
Singleton classes are those classes, whose objects are created only once.
And with only that object the class members can be accessed.
the Constructor is private so we cannot create the object of the class. But we can get
the object by calling the method getInstance(). And the getInstance is static so it can
be called without creating the object. And it returns the object. Now with that object,
we can call instance methods of the class.
We can get the single object using this getInstance(). And it is static, so it is a
thread-safe singleton class. Although there are many ways to create a thread-
safe singleton class. So, thread-safe classes can also be:
 When singletons are written with double-checked locking, they can be
thread safe.
 We can use static singletons that are initialized during class loading.
 But the most straightforward way to create a thread-safe singleton is to
use Java Enums.
How would you differentiate between a String, StringBuffer, and a
StringBuilder?
 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.
Using relevant properties highlight the differences between interfaces
and abstract classes.
 Availability of methods: Only abstract methods are available in interfaces,
whereas non-abstract methods can be present along with abstract methods in
abstract classes.
 Variable types: Static and final variables can only be declared in the case of
interfaces, whereas abstract classes can also have non-static and non-final
variables.
 Inheritance: Multiple inheritances are facilitated by interfaces, whereas
abstract classes do not promote multiple inheritances.
 Data member accessibility: By default, the class data members of
interfaces are of the public- type. Conversely, the class members for an
abstract class can be protected or private also.
 Implementation: With the help of an abstract class, the implementation of an
interface is easily possible. However, the converse is not true;
What is a Comparator in java?
Consider the example where we have an ArrayList of employees like(Eid,
Ename, Salary), etc. Now if we want to sort this list of employees based on
the names of employees. Then that is not possible to sort using the
Collections.sort() method. We need to provide something to the sort() function
depending on what values we have to perform sorting. Then in that case a
comparator is used.
Comparator is the interface in java that contains the compare method. And by
overloading the compare method, we can define that on what basis we need
to compare the values.
Example:
Collections.sort(employees, new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
return o1.getEname().compareToIgnoreCase(o2.getEname());
}
});

What makes a HashSet different from a TreeSet?


Although both HashSet and TreeSet are not synchronized and ensure that
duplicates are not present, there are certain properties that distinguish a
HashSet from a TreeSet.
 Implementation: For a HashSet, the hash table is utilized for storing the
elements in an unordered manner. However, TreeSet makes use of the red-
black tree to store the elements in a sorted manner.
 Complexity/ Performance: For adding, retrieving, and deleting elements, the
time amortized complexity is O(1) for a HashSet. The time complexity for
performing the same operations is a bit higher for TreeSet and is equal to
O(log n). Overall, the performance of HashSet is faster in comparison to
TreeSet.
 Methods: hashCode() and equals() are the methods utilized by HashSet for
making comparisons between the objects. Conversely, compareTo() and
compare() methods are utilized by TreeSet to facilitate object comparisons.
 Objects type: Heterogeneous and null objects can be stored with the help of
HashSet. In the case of a TreeSet, runtime exception occurs while inserting
heterogeneous objects or null objects.
Why is the character array preferred over string for storing confidential
information?
In Java, a string is basically immutable i.e., it cannot be modified. After its
declaration, it continues to stay in the string pool as long as it is not removed
in the form of garbage. In other words, a string resides in the heap section of
the memory for an unregulated and unspecified time interval after string value
processing is executed.
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. After 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.
What are the differences between HashMap and HashTable in Java?
HashMap
 HashMap is not synchronized thereby making it better for non-threaded
applications.
 Allows only one null key but any number of null in the values.
 Supports order of insertion by making use of its subclass
LinkedHashMap.
HashTable
 HashTable is synchronized and hence it is suitable for threaded
applications.
 This does not allow null in both keys or values.
 Order of insertion is not guaranteed in HashTable.

What are the different ways of thread usage?


We can define and implement a thread in java using two ways:
 Extending the Thread class
class InterviewBitThreadExample extends Thread{
public void run(){
System.out.println("Thread runs...");
}
public static void main(String args[]){
InterviewBitThreadExample ib = new InterviewBitThreadExample();
ib.start();
}
}

 Implementing the Runnable interface


class InterviewBitThreadExample implements Runnable{
public void run(){
System.out.println("Thread runs...");
}
public static void main(String args[]){
Thread ib = new Thread(new InterviewBitThreadExample());
ib.start();
}
}
Implementing a thread using the method Runnable interface is more preferred
and advantageous as Java does not have support for multiple inheritance of
classes.
Start() method is used for creating a separate class stack for the thread
execution. Once the call stack is created, JVM calls the run() method for
executing the thread in that call stack.
What are the different types of Thread Priorities in Java? And what is the
default priority of a thread assigned by JVM?
There are a total of 3 different types of priority available in Java.
MIN_PRIORITY: It has an integer value assigned with 1.
MAX_PRIORITY: It has an integer value assigned with 10.
NORM_PRIORITY: It has an integer value assigned with 5.
In Java, Thread with MAX_PRIORITY gets the first chance to execute. But the
default priority for any thread is NORM_PRIORITY assigned by JVM.

What is the difference between the ‘throw’ and ‘throws’ keyword in java?

The ‘throw’ keyword is used to manually throw the exception to the calling
method. And the ‘throws’ keyword is used in the function definition to inform
the calling method that this method throws the exception. So, if you are
calling, then you have to handle the exception.
What are the differences between constructor and method of a class in
Java?
Constructor
 Constructor is used for initializing the object state.
 Constructor has no return type.
 Constructor gets invoked implicitly.
 If the constructor is not defined, then a default constructor is provided
by the java compiler.
 The constructor’s name should be equal to the class name.
 A constructor cannot be marked as final because whenever a class is
inherited, the constructors are not inherited. Hence, making it final
doesn’t make sense. Java throws compilation error saying – modifier
final not allowed here.
 Final variable instantiations are possible inside a constructor and the
scope of this applies to the whole class and its objects.
Method
 Method is used for exposing the object’s behaviour.
 Method should have a return type. Even if it does not return anything,
return type is void.
 Method must be invoked on the object explicitly.
 If a method is not defined, then the compiler does not provide it.
 The name of the method can have any name or have a class name
too.
 A method can be defined as final, but it cannot be overridden in its
subclass.
 A final variable if initialised inside a method ensures that the variable
cant be changed only within the scope of the method.
Java works as “pass by value” or “pass by reference” phenomenon?
Java always works as a “pass by value”. There is nothing called a “pass by
reference” in Java. However, when the object is passed in any method, the
address of the value is passed due to the nature of object handling in Java.
When an object is passed, a copy of the reference is created by Java and that
is passed to the method. The objects point to the same memory location.
What is the ‘IS-A’ relationship in OOPs Java?
‘IS-A’ relationship is another name for inheritance. When we inherit the base
class from the derived class, then it forms a relationship between the classes.
So that relationship is termed as ‘IS-A’ relationship.
Which among String or String Buffer should be preferred when there are
lot of updates required to be done in the data?
StringBuffer is mutable and dynamic in nature whereas String is immutable.
Every updation / modification of String creates a new String thereby
overloading the string pool with unnecessary objects. Hence, in the cases of a
lot of updates, it is always preferred to use StringBuffer as it will reduce the
overhead of the creation of multiple String objects in the string pool.
How to not allow serialization of attributes of a class in Java?
To achieve this, the attribute can be declared along with the usage of
transient. There are several reasons why you might want to mark a field as
transient:
 Security: If a field contains sensitive information, you should mark it as
transient to prevent it from being stored in a file or transmitted over a
network.
 Performance: Serializing and deserializing large objects can be time-
consuming. By marking fields as transient, you can reduce the amount
of data that needs to be serialized and improve the performance of
your program.
 State management: Sometimes, the state of an object can be
reconstructed based on other information. In these cases, you can
mark the fields that represent this state as transient and avoid the
overhead of serializing and deserializing them.
What do you understand by Object Cloning and how do you achieve it in
Java?
It is the process of creating an exact copy of any object. In order to support
this, a java class has to implement the Cloneable interface of java.lang
package and override the clone() method provided by the Object class.
In case the Cloneable interface is not implemented and just the method is
overridden, it results in CloneNotSuppoertedException in Java.
Is it mandatory for a catch block to be followed by a try block?
No, it is not necessary for a catch block to be present after a try block. - A try
block should be followed either by a catch block or by a finally block. If the
exceptions likelihood is more, then they should be declared using the throws
clause of the method.
Can we call a constructor of a class inside another constructor?
Yes, the concept of calling a constructor of class inside another constructor is
called constructor chaining and can be achieved by using this().
Contiguous memory locations are usually used for storing actual values
in an array but not in ArrayList. Explain.
In the case of ArrayList, data storing in the form of primitive data types (like
int, float, etc.) is not possible. The data members/objects present in the
ArrayList have references to the objects which are located at various sites in
the memory. Thus, storing of actual objects or non-primitive data types (like
Integer, Double, etc.) takes place in various memory locations.
However, the same does not apply to 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.
How does the size of ArrayList grow dynamically? And state how it is
implemented internally.
ArrayList is implemented in such a way that it can grow dynamically. We don't
need to specify the size of ArrayList. If we need to add element into it, then
internally ArrayList will allocate the new ArrayList of size (current size + half of
the current size). And add the old elements into the new. Then the new value
will be inserted into it. And for the next time, the extra space will be available
inserting new value.
Although inheritance is a popular OOPs concept, it is less advantageous
than composition. Explain.
While inheritance is a fundamental concept in object-oriented programming, it
has certain drawbacks that make composition a more advantageous
approach in many situations.
Here's a breakdown of the key reasons why composition is often preferred
over inheritance:
1. Tight Coupling:
Inheritance: Creates a tight coupling between parent and child classes.
Changes to the parent class can unintentionally affect all its children,
potentially leading to cascading issues and maintenance challenges.
Composition: Composes objects loosely, allowing you to change one object's
implementation without affecting others. This promotes better code modularity
and maintainability.
2. Inheritance Hierarchies can become Complex:
Inheritance: Deep inheritance hierarchies can become difficult to manage and
understand, as changes in one class can ripple through multiple levels.
Composition: Enables you to create flexible and adaptable relationships
between classes without the rigid structure of inheritance hierarchies.
3. Enforces a Strict "Is-A" Relationship:
Inheritance: Models a strict "is-a" relationship, which may not always
accurately represent the real-world relationships between objects.
Composition: Offers more flexibility to model "has-a" relationships, which are
often more appropriate for modelling real-world scenarios.
4. Inheritance can Lead to Overuse of Subclasses:
Inheritance: Developers might overuse subclasses to add functionality,
leading to overly complex hierarchies and potential design issues.
Composition: Encourages thinking about objects as independent entities that
collaborate, leading to cleaner designs and better code organization.
5. Inheritance can Limit Code Reusability:
Inheritance: Code reuse is limited to members inherited from parent classes.
Composition: Allows you to reuse code from any object, promoting better
code flexibility and modularity.
6. Encapsulation and Testing:
Inheritance: Can sometimes break encapsulation, as child classes can access
and modify private members of parent classes. This can also make testing
more challenging.
Composition: Preserves encapsulation, making classes more independent
and testable.
What are Composition and Aggregation? State the difference.
Composition represents a “HAS-A” relationship. The containing object owns
the contained object and is responsible for its lifecycle. The contained object
cannot exist independently of the containing object. Example – A car has an
engine. The car cannot exist without an engine, and the engine is tightly
coupled to the car.
Aggregation represents a “USES-A” relationship. The containing object has a
reference to the contained object but does not own it. The contained object
can exist independently of the containing object. Example – A car uses a GPS
device. The car can exist without a GPS device, and the GPS device can be
used by other objects as well. GPS device is loosely coupled to the car.
Why is synchronization necessary?
Concurrent execution of different processes is made possible by
synchronization. When a particular resource is shared between many threads,
situations may arise in which multiple threads require the same shared
resource.
Synchronization assists in resolving the issue and the resource is shared by a
single thread at a time. Let’s take an example to understand it more clearly.
For example, you have a URL and you have to find out the number of
requests made to it. Two simultaneous requests can make the count erratic.
If a thread Thread1 views the count as 10, it will be increased by 1 to 11.
Simultaneously, if another thread Thread2 views the count as 10, it will be
increased by 1 to 11. Thus, inconsistency in count values takes place
between the expected final value is 12 but the actual final value we get will be
11.
With synchronized, if thread Thread1 views the count as 10, it will be
increased by 1 to 11, then thread Thread2 will view the count as 11, it will be
increased by 1 to 12. Thus, consistency in count values takes place.
Can you explain the Java thread lifecycle?
Java thread lifecycle is as follows
 New – When the instance of the thread is created and the start()
method has not been invoked, the thread is considered to be alive and
hence in the NEW state.
 Runnable – Once the start() method is invoked, before the run()
method is called by JVM, the thread is said to be in RUNNABLE (ready
to run) state. This state can also be entered from the Waiting or
Sleeping state of the thread.
 Running – When the run() method has been invoked and the thread
starts its execution, the thread is said to be in a RUNNING state.
 Non-Runnable (Blocked/Waiting) – When the thread is not able to
run despite the fact of its aliveness, the thread is said to be in a NON-
RUNNABLE state. Ideally, after some time of its aliveness, the thread
should go to a runnable state.
 A thread is said to be in a Blocked state if it wants to enter
synchronized code but it is unable to as another thread is
operating in that synchronized block on the same object. The
first thread must wait until the other thread exits the
synchronized block.
 A thread is said to be in a Waiting state if it is waiting for the
signal to execute from another thread, i.e., it waits for work until
the signal is received.
 Terminated – Once the run() method execution is completed, the
thread is said to enter the TERMINATED step and is considered to not
be alive
What are the various access specifiers in Java?
In Java, access specifiers are the keywords which are used to define the
access scope of the method, class, or a variable. In Java, there are four
access specifiers given below.
Public: The classes, methods, or variables which are defined as public, can
be accessed by any class or method.
Protected: Protected can be accessed by the class of the same package, or
by the sub-class of this class, or within the same class.
Default: Default are accessible within the package only. By default, all the
classes, methods, and variables are of default scope.
Private: The private class, methods, or variables defined as private can be
accessed within the class only.

What is object-oriented paradigm?


It is a programming paradigm based on objects having data and methods
defined in the class to which it belongs. Object-oriented paradigm aims to
incorporate the advantages of modularity and reusability. Objects are the
instances of classes which interacts with one another to design applications
and programs. There are the following features of the object-oriented
paradigm.
Follows the bottom-up approach in program design.
Focus on data with methods to operate upon the object's data.
Includes the concept like Encapsulation and abstraction which hides the
complexities from the user and show only functionality.
Implements the real-time approach like inheritance, abstraction, etc.
What is this keyword in java?
The this keyword is a reference variable that refers to the current object.
There are the various uses of this keyword in Java. It can be used to refer to
current class properties such as instance methods, variable, constructors, etc.
It can also be passed as an argument into the methods or constructors. It can
also be returned from the method as the current class instance.
There are the following uses of this keyword.
 this can be used to refer to the current class instance variable.
 this can be used to invoke current class method (implicitly)
 this() can be used to invoke the current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as an argument in the constructor call.
 this can be used to return the current class instance from the method.

What is the Inheritance?


Inheritance is a mechanism by which one object acquires all the properties
and behaviour of another object of another class. It is used for Code
Reusability and Method Overriding. The idea behind inheritance in Java is
that you can create new classes that are built upon existing classes. When
you inherit from an existing class, you can reuse methods and fields of the
parent class. Moreover, you can add new methods and fields in your current
class also. Inheritance represents the IS-A relationship which is also known
as a parent-child relationship.
There are five types of inheritance in Java.
 Single-level inheritance
 Multi-level inheritance
 Multiple Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance
Why is multiple inheritance not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is
not supported in java. Consider a scenario where A, B, and C are three
classes. The C class inherits A and B classes. If A and B classes have the
same method and you call it from child class object, there will be ambiguity to
call the method of A or B class.
Since the compile-time errors are better than runtime errors, Java renders
compile-time error if you inherit 2 classes. So, whether you have the same
method or different, there will be a compile time error.
What is String Pool?
String pool is the space reserved in the heap memory that can be used to
store the strings. The main advantage of using the String pool is whenever we
create a string literal; the JVM checks the "string constant pool" first. If the
string already exists in the pool, a reference to the pooled instance is
returned. If the string doesn't exist in the pool, a new string instance is created
and placed in the pool. Therefore, it saves the memory by avoiding the
duplicacy.

What are wrapper classes?


Wrapper classes are classes that allow primitive types to be accessed as
objects. In other words, we can say that wrapper classes are built-in java
classes which allow the conversion of objects to primitives and primitives to
objects. The process of converting primitives to objects is called autoboxing,
and the process of converting objects to primitives is called unboxing.

What is lambda expression in Java and How does a lambda expression


relate to a functional interface?
Lambda expression is a type of function without a name. It may or may not
have results and parameters. It is known as an anonymous function as it does
not have type information by itself. IT is executed on-demand.
As lambda expressions are similar to anonymous functions, they can only be
applied to the single abstract method of Functional Interface. It will infer the
return type, type, and several arguments from the signature of the abstract
method of functional interface.

What are the types and common ways to use lambda expression?
A lambda expression does not have any specific type by itself. A lambda
expression receives type once it is assigned to a functional interface. That
same lambda expression can be assigned to different functional interface
types and can have a different type.
For example consider expression s -> s.isEmpty() :
Predicate<String> stringPredicate = s -> s.isEmpty();
Predicate<List> listPredicate = s -> s.isEmpty();
Function<String, Boolean> func = s -> s.isEmpty();
Consumer<String> stringConsumer = s -> s.isEmpty();
Common ways to use the expression.
Assignment to a functional Interface —> Predicate<String> stringPredicate = s ->
s.isEmpty();
Can be passed as a parameter that has a functional type —> stream.filter(s ->
s.isEmpty())
Returning it from a function —> return s -> s.isEmpty()
Casting it to a functional type —> (Predicate<String>) s -> s.isEmpty()

What is Method Reference?


Method reference is a compact way of referring to a method of functional
interface. It is used to refer to a method without invoking it. :: (double colon) is
used for describing the method reference.
The syntax is class::methodName
For e.g.:
Integer::parseInt(str) \\ method reference
str -> Integer.ParseInt(str); \\ equivalent lambda

What are functional interfaces?


Functional interfaces are interfaces with only one abstract method. Due to
which it is also known as the Single Abstract Method (SAM) interface. It wraps
a function as an interface.
Functional interfaces can have any number of default, static and overridden
methods. For declaring Functional Interfaces @FunctionalInterface annotation
is optional to use. If this annotation is used for interfaces with more than one
abstract method, it will generate a compiler error.

Can a functional interface extend/inherit another interface?


A functional interface cannot extend another interface with abstract methods
as it will void the rule of on abstract method per functional interface. It can
extend other interfaces which do not have any abstract method and only have
the default, static, another class is overridden and normal methods.

What distinguishes a collection from a stream?


A Collection contains its elements, whereas a Stream does not, and this is the
primary distinction between the two types of data structures. Unlike other
views, Stream operates on a view whose elements are kept in a collection or
array, but any changes made to Stream do not affect the original collection.

What distinguishes Stream's intermediate and terminal operations?


You can call additional methods of the Stream class to build a pipeline
because the intermediary Stream action returns another Stream.
For instance, you can still call the filter() method on a Stream after calling
map() or flatMap().
The terminal action, on the other hand, generates results other than streams,
such as a value or a Collection.
You cannot call any other Stream methods or reuse the Stream once a
terminal method like forEach() or collect() has been called.

By "Stream is lazy," what do you mean?


When we state that a stream is lazy, we mean that the majority of its methods,
which are described in the Java.util. Stream.Stream classes, will not function
if they are simply added to the stream pipeline.
They only function when a terminal method on the Stream is called, and
rather than searching through the entire collection of data, and they stop as
soon as they locate the data they are looking for.
Stream API: What Is It? Why is the Stream API necessary?
Java 8 now has a new functionality called Stream API. Stream API is a unique
class used for handling items from sources like collections.
The Stream API is required because:
 Processing is straightforward since it offers aggregate operations.
 Programming in the functional style is supported.
 The processing speed is accelerated. It is, therefore, suitable for
greater performance.
 Parallel operations are possible.

What does Java’8 Stream pipelining mean?


Chaining together operations is the idea behind Stream pipelining. To do this,
we divide the possible operations on a stream into two groups: intermediate
operations and terminal operations.
When an intermediate action completes, it produces an instance of Stream.
As a result, we can create a processing pipeline with any number of
intermediary processes to process data.
The pipeline must then be terminated by a terminal operation that returns a
final value.

You might also like