0% found this document useful (0 votes)
5 views

Query OverFlow

The document details a series of interview questions and answers related to Java programming, focusing on topics such as the 'final' keyword, AtomicInteger, data structures like HashSet and TreeSet, and the differences between various collection classes. It also covers concepts like JavaBeans and serialization, providing explanations and examples to illustrate the candidate's understanding. The dialogue format highlights the interaction between the interviewer and candidate, showcasing the candidate's knowledge and the interviewer's feedback.

Uploaded by

bhavanipriy73
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Query OverFlow

The document details a series of interview questions and answers related to Java programming, focusing on topics such as the 'final' keyword, AtomicInteger, data structures like HashSet and TreeSet, and the differences between various collection classes. It also covers concepts like JavaBeans and serialization, providing explanations and examples to illustrate the candidate's understanding. The dialogue format highlights the interaction between the interviewer and candidate, showcasing the candidate's knowledge and the interviewer's feedback.

Uploaded by

bhavanipriy73
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

QueryOverFlow

QOF Series

Date : Oct 13th to Oct 27th


Topic : Java Collections, Concurrent and Miscellaneous

Documented By,
Sakkthivel T
2021PECCB223
CODERS FORUM
QUERY:

Interviewer : What's the purpose of "final" keyword in Java ?


Candidate : Once the value is assigned to the variable
using "final" keyword that value can't be
changed further. If you try to change, it results in
an error

Interviewer : Absolutely correct !!


This is what I learned in 3rd sem.
But there's more to it.

Candidate : We can say for example if the value of pi should


not be changed we can use this keyword.

Candidate : It prevents overriding and inheritance when used


with methods

Interviewer : It prevents overriding when used with methods.


This is correct.
What you mean by "inheritance" ?
This, I learned in 5th sem.

Candidate : Sorry I didn't mention class....it prevents


inheritance when used with class.

Interviewer : Correct!!
This, I learned last week only..
Thanks
Interviewer : So, final keyword can be used for variable,
method & class (ALL 3).
final int a;
final int m(String s) {}
final class Z {}
So, if someone asks it's purpose, say all 3... not just about
final variables...

Candidate : Guys this question was asked to me in CTS


technical interview(in-person)

---------------------------------------------------------------------------
QUERY:
Interviewer : What is AtomicInteger in Java ?

Candidate : I don't know exactly but it's used for auto


increment a number is that correct

Interviewer : That's one of the use-cases of it.You are right.


But that doesn't answer the Query..
What's AtomicInteger in Java ?

Candidate : achieves synchronization without using


synchronization in a multithreaded environment. so values
actually get updated. funny enough these atomic operations
remind me of transactions in DBMS . I'm not so sure if it's
alr to relate them

Interviewer : You are absolutely right !!


As usual, your words are quite confusing...
But it's okay.
EXPLANATION:
Usually, when 2 Threads update the value of anything
SIMULTANEOUSLY, Disaster happens.
So, we use the keyword "synchronized" to enclose a block of
code. All those inside it will be executed sequentially only,
ensuring ATOMIC Operations ( Remember ACID Properties
in DBMS? ).
But, since this can sometimes become tedious and people may
forget to use the keyword "synchronized", this particular class
is defined inside:
java.util.concurrent
This is an important package.
This class automatically ensures Atomic Property and can be
confidently used in multi-threaded applications.
One of the Day-To-Day applications is Counters, as
Candidate said.

Candidate : Wait is this the same theory as acid property

Interviewer : yes.

---------------------------------------------------------------------------
QUERY:

Interviewer : Why use int when there is Integer class?


Also, why use Integer class when int is there? ( IN JAVA )
Same doubt for double, float, long, byte, boolean...... ?

Candidate : int is primitive datatype, its used for its fast


execution. whereas Integer is wrapper class, its used because
of the availability of more in-built methods.

Interviewer : Integer class has one more MAIN advantage...


(That's why I asked the question).
CLUE: The Answer is in the Question.

Candidate : Only Integer can be used in collections

Interviewer : Yes, that's correct.


In Java, everything is a class and Object is the super-class of
all of that. (super-confusing).
This has some advantages.
For example, you can write a method like:
void m(Object obj) {
this.s = obj.toString();
}
This method can accept instance of any class and convert it to
String.
But the problem is, primitive datatypes (like int ) are NOT
classes.
They are directly understood as datatypes by Java.
So, they can't be treated as normal objects in many cases......
That's why Java introduced the wrapper classes like Integer.
In Java, there's a class called Class , but the Universal
SuperClass is Object.

--------------------------------------------------------------
QUERY:

Interviewer : What's the difference between HashSet and


TreeSet in Java ?

Candidate : Both HashSet and TreeSet are used to store


unique elements. The difference is that HashSet does not
maintain any order, while TreeSet stores the elements
in sorted order.

Interviewer : You're right.


Then what's the use of HashSet ?
Nothing special about it ?

Candidate : Hashset is faster than Treeset.


Time complexity of HashSet:O(1)
Time complexity of TreeSet:O(log n)

Interviewer : Okay...
You're right.
O(1) is faster than Speed Of Light !!
Then why would anyone need TreeSet.... ? When do the order
of elements matter the most?
Because, anyways Set doesn't offer indexes to access the
elements... then why care about Order Of Elements ?
Candidate : TreeSet is more suitable than a HashSet for
problems like this one, where we need to maintain a sorted
order of unique elements while also considering their
frequency.
This problem is "Remove Duplicates" which is asked in
codeblitz.
Given an integer array in any order, remove some duplicates
in-place such that each unique element appears at most
twice.which means if element appears more than 2 times,
remove all extra element and make them pair.

Input Format
First line contains integer n(length of Array) Second line
contains n integer

Constraints : 1 <=num.length<=10

Output Format : Print a Updated Array

Sample Input 0:
10
4555667641
Sample Output 0:
14455667
Solution using TreeSet

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Map<Integer,Integer> m=new HashMap<>();
Set<Integer> s3=new TreeSet<>();
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
sc.nextLine();
String s=sc.nextLine();
String s1[]=s.split(" ");
int a[]=new int[n];
for(int i=0;i<n;i++){
s3.add(Integer.parseInt(s1[i]));
a[i]=Integer.parseInt(s1[i]);
if(m.containsKey(a[i])){
m.put(a[i],m.get(a[i])+1);
}
else{
m.put(a[i],1);
}
}
List<Integer> l=new ArrayList<>();
for(int i:s3){
if(m.get(i)>1){
l.add(i);
l.add(i);
}
else{
l.add(i);
}
}
for(int i:l){
System.out.print(i+" ");
}
}
}

Interviewer: Okay 🫡
In this, the order of Set elements is important.
Eventhough Set doesn't support Indexes, when iterating
through FOR loop, it's fetched as per the order.
This is an Excellent Point, Candidate.

Another usecase I thought of is, when applying MIN & MAX


operations, TreeSet returns in O(1), Since it already maintains
the order.
But for HashSet, it will iterate through the entire set for
finding MIN & MAX elements, thus O(n).

Isn't it Strange & Opposite?


So, depending on the usecase, you have to choose the
datastructure:
If you are using contains method a lot, then HashSet will
deliver results in O(1).
If you are using min or max methods, or iterating through a
for loop, then TreeSet is more suitable and O(1).
Thanks Candidate for answering patiently..

Interviewer : One last question:

How these 2 internally works??


How HashSet MAGICALLY returns results in O(1) ?
How TreeSet MAGICALLY Auto-Sorts everything
eventhough we insert elements in random order ?
Candidate : hashset uses hashing. treeset uses red black trees,
which is a self balancing BST
thats why the difference in insert, retrieval is O(log n) in
treeset and O(1) in hashset.

Interviewer : TreeSet explanation is okay.


It's Self-Balancing.
It's Red-Black Tree.
So, it auto-sorts all the elements.

But, hold on
I need more than "hashset uses hashing"........🫡

Candidate : it uses a hashmap, key-value pairs. a hash


function is used to convert the key into an index [hashing] and
the value is stored at that index.

Interviewer : Yes. Correct.


So, at last, it works like an array.
For example, let's assume the HashFunction is:
f(x)=x/10

Then, if you store {20, 40, 70}


It will be like:
__ __ 20 __ 40 __ __ 70
0 1 2 3 4 5 6 7

So, if you check: setObj.contains(40)

It does: 40 / 10 = 4
Is there any element at index 4 ? => True . So, O(1)

Everyone, are you following all the information provided in


the group or not?
(For the Past 4 days)

---------------------------------------------------------------------------
QUERY:

Interviewer: What's the difference between these four:


HashMap ,HashTable , ConcurrentHashMap
SynchronizedMap ?
What guys, no sound from you ?
Complete Silent.. ?
Hold on, one sec
Today, I need Leads_2.0 to answer the question.

---------------------------------------------------------------------------
QUERY:

Interviewer : What's the difference between these four:


Array , List, ArrayList, LinkedList ?

Today there's no constraint.


Anyone can answer.

Candidate : array is a contiguous block of memory, where


multiple elements of same data type can be stored.
(QSpider Memories)

Interviewer : Absolutely correct.

Candidate : List is a data type which can store data in order

Interviewer : Correct. Whether List is an Interface or Class ?

Candidate : Okay. What about ArrayList & LinkedList ?

Candidate : HashMap is used to store key value pairs but our


insertion order is not maintained in HashMap and it's not
thread safe .
HashTables are just liske HashMaps but they are thread safe
and does not allow null keys or values like HashMap(Note
hashMap can have one null key and multiple null values);
ConcurrentHashMap are like thread safe HashMaps they are
divided to 16 segments so that when one thread is accessing
or updating a segment only that segment is locked other
threads can work with unlocked segments parallely (i.e 16
threads can update a ConcurrentHashMap at the same time).
SynchronizedMap It is also used to make hashMaps thread
safe but the catch here is only one thread can access/update it
at a time unlike ConcurrentHashMap .

Interviewer : Correct
No more counter questions.
Everything well-explained. What about this ? 🫡

Candidate : Array is a fixed size and basic data structure in


java, stores elements of the same data type
List is an interface which provides a way to store the ordered
collection
ArrayList is a resizable array ,which means no need to specify
the size. (implementation of the List interface)
LinkedList is a doubly linked list implementation of the List
interface(Very efficient to insert and deletion)

Interviewer : Are List & ArrayList different?


Candidate : In simple word ,list is an Interface ArrayList and
LinkedList are concrete class that implements the List
interface
List
|
|_ArrayList
|
|_LinkedList

Interviewer : If LinkedList is so cool, then why use array?


What's the advantage array is having (over LinkedList)?

Candidate : Accesing the element takes more time in


Linkedlist
In Array we can use indexing for that.
Also it took extra memory for pointer(address of next node)

Interviewer : Time Complexity for both of them ?

Candidate : O(n) for LinkedList


Because we iterate untill we reach that specific node
O(1) for Array

Interviewer : Which of those classes are Serializable ?


Quoting your statements:
"array is fixed size"
"ArrayList is resizable"
So, you mean it's not possible to create a fixed size ArrayList?
If it's a doubly-linked list, then when will O(n) will arise?

Accessing first element ?


Or accessing last element ?
Or middle element ?
Or is it actually singly-linked list?

Candidate : Since linkedlist don't have indexes like


array...traversing the list takes O(n) time...O(n) arises while
accessing middle element

Interviewer : That's correct !! Still 2 to go.

Candidate : No, after initializing arraylist we can avoid


resizing i.e(We can create fixedsize array list)

Interviewer: Then how can we do it ?


That's correct !!
But, how can we create a fixed size ArrayList ?
Oh.. Can you please provide a sample code snippet ?

Candidate : Arrays.aslist() method creats arraylist of


fixed size
List<Integer> fixedList = Arrays.asList(10, 20, 30, 40, 50);
here the arraysize is fixed so you cannot either remove or add
elements in this arraylist
Interviewer : EXACTLY !!
As far as I know, this is the only method of doing it...
Last week, I was trying to add few elements to the result of
.asList().......
It threw back Error...

---------------------------------------------------------------------------

Interviewer: Array ,ArrayList ,LinkedList


Interviewer: Let this have as a Separate Query (for today).
QUERY:

Interviewer: What's Serializable? Why do we need that?


Also, whether array, ArrayList & LinkedList come under it?
Interviewer:
Interviewer: I think the problem is with the group name...
We named it "QueryOverFlow".....
Should have named it "AnswerOverFlow" or something...
Interviewer: Btw, example of single-loop code.
I will send the solution you asked for soon in LeetCoders
group.

---------------------------------------------------------------------------
QUERY:
Interviewer: What's Bean in Java?
(Note: It's NOT coffee bean)
Interviewer: CLUE: To answer this, you will need some idea
about Serializability (yesterday's Query).
Candidate: It is a reusable software in Java. In Java, beans
are classes that encapsulate multiple classes into a single
object.
Interviewer: Hmm... not straight to the point...
50% correct
50% wrong
Interviewer: You have slightly mixed Applet definition with
Bean.
Candidate: It's any Java class that follows certain
conventions, implementing serializable, having private fields,
and public getter setters for 'em with a no-argument
constructor. It's a conceptual concept that standardizes
components so they are reusable and maintainable.
Interviewer: The "definition" is correct.
But assume I am just a layman. I wouldn't understand a single
word...
I mean, what's the purpose of a Bean?
Interviewer: In which part of the Java application is this
'Bean' most used?
Candidate: Spring Framework, Spring Boot, Java Persistence
API (JPA), Java EE mostly use beans.
Interviewer: Wow... I didn't expect the direct answer...
But yes, you're right!
Beans come into play in Database Code, especially when it
comes to Persistence.
Interviewer: But these are all huge things...
Persistence... Spring... JPA...
Can you please simplify and say how these Beans are exactly
used in simple Database Terms?
Candidate: Data Encapsulation:
A JavaBean can represent a table row from a database. Each
field in the JavaBean corresponds to a column in the database.
Getter and Setter Methods:
The bean has getter and setter methods to get and set the
values of these fields, just like how you'd read and write data
in the database.
Candidate: This is how JavaBean is used in terms of the
database.
Interviewer: Okay.
Interviewer: I can understand the concepts.
Interviewer: But let's just check if others do too.
Interviewer: We can check the Poll results exactly at 7:00
PM today.
If they are still confused, someone might have to give a more
simpler/shorter explanation.
Interviewer: Meanwhile, anybody's free to answer Sunday's
Question (which was a carry-forward from Saturday...)
Candidate: Serializable is a marker interface in Java, i.e., it
has no methods. It serves to "mark" Java objects that can be
serialized, i.e., converted into a byte stream that can then be
saved to a file, sent over a network, or stored in a database.
Candidate: Just asking out of curiosity...
Is Entity Class and Java Bean the same?
Candidate: Even Entity Class represents a table row... am I
right?
Candidate: No, it seems they are not the same... An entity
class maps a Java object to a database table for persistence,
but a JavaBean is a general-purpose object often used for UI
and data transfer.
Candidate: All the classes come under Serializable.
Candidate: For UI, ah?
Candidate: Any project examples? Where should I use the
entity class, and where should I use Java Bean?
Interviewer: Exactly correct
No more cross-questions for this Query.
Interviewer: Oh...
Now I am confused...
Candidate: For transferring and storing data between UI
components to backend logic.
Candidate: Usually, I transfer data by HTTP request-
response... Where is JavaBean used there?
Candidate: Me too 🫡
Candidate: Entity class:
In a registration form where the user wants to sign in using
their data such as email ID, password, name, etc., here the
details are stored in the database, and the UI shows validation
and success messages.
JavaBean:
JavaBean can be used to represent the form data. It holds the
user input temporarily and interacts with the form in the UI
layer.
Interviewer: Difference between JSON and Java Bean then?
Candidate: Yeah... what's the difference? 🫡
Candidate: In simple words, JavaBeans are used for handling
temporary data, and entity classes are used for persistent data
in the database.
Candidate: JSON is a data format used for data interchange.
JavaBeans are Java-specific components used for
encapsulating data and behavior in an object-oriented way.
Interviewer: Actually, I will give this info for free (before
this becomes a war zone).
JSON AND JAVABEAN ARE THE SAME.
JSON is for JavaScript.
Java Bean is for Java.
Candidate: JavaBeans are used in the frontend, and entity
classes are used in the backend.
Interviewer: End Result...
Interviewer: ?
Candidate: Is my friend correct?
Interviewer: Candidate, dude...
This is the first answer given.
Interviewer: Read existing chat first...
Candidate: Ohh
Candidate: Anyhow, I got clarity. Thank you, Candidate .
Interviewer: Then answer this Poll, Candidate.
Candidate: This explained clearly... Adding an example
would make it perfect.
Interviewer: It's 7 PM...
Apparently, more got confused than cleared...
I will type & send an answer in my words (maybe it can help).
Interviewer: NOTE: Candidate's ANSWERS ARE
ABSOLUTELY GREAT.
I am just sending for those 7 members who are still confused.
Interviewer: Explanation for Today's Query.
Interviewer: Serializability is the ability of an object to be
able to convert to Binary (byte[]).
If converted, it's easy to store in the database (Persistence).
Interviewer: Explanation for Yesterday's Query.
Interviewer: Once you have read the explanation, update in
the Poll.
If still confused, maybe we can discuss this in a MeetUp
Interviewer: Yesterday, we have been using this buzzword
quite a lot of times...
So, today's Query is on that:

---------------------------------------------------------------------------
Query :

Interviewer: What’s Persistence in Java?


Candidate: Persistence in Java refers to maintaining the state
of an object beyond the application's lifetime by saving it to a
database. This helps in data storage and retrieval between
application restarts.
Interviewer: What are the frameworks available for
Persistence in Java?
Candidate:Some popular frameworks are:
• Hibernate
• Java Persistence API (JPA)
• Spring Data JPA
Others include EclipseLink, MyBatis, and Apache OpenJPA.
Interviewer:Let’s take Hibernate as an example. How does
Persistence help there? Do we use normal SQL to Query the
database?
Candidate:In Hibernate, Persistence simplifies database
interactions. Instead of SQL, Hibernate uses HQL (Hibernate
Query Language), which is object-oriented and operates on
Java objects.
If required, we can also use native SQL queries with
Hibernate by using the createNativeQuery() method.
Interviewer:What is ORM?
Candidate: ORM stands for Object-Relational Mapping.
Interviewer: Can you explain ORM in simple terms?
Candidate: ORM maps objects in a programming language
(like Java) to tables in a database. For example, an object’s
fields correspond to a table’s columns, allowing developers to
interact with the database without writing SQL queries
directly.

Interviewer: So, what exactly are we mapping in ORM?


Candidate: We are mapping the objects of the
programming language to the tables in the database. This
makes the database interaction more intuitive and aligned with
object-oriented programming principles.

Wrap-Up: ORM and Persistence streamline the handling of


database operations by abstracting SQL and integrating
database functionality directly into the programming
language.

---------------------------------------------------------------------------
Query :

Interviewer: Explain the concept of Thread Pooling.


Candidate: Thread Pooling in Java is a technique to manage
multiple threads by reusing a fixed number of threads from a
pool to execute tasks, instead of creating a new thread every
time a task is submitted.
Interviewer: What is ExecutorService in Java?
Candidate: ExecutorService is an interface in Java, part of
the java.util.concurrent package. It is used to manage and
control threads efficiently in concurrent applications.
Interviewer: What are the concrete implementations of the
ExecutorService interface?
Candidate: One of the most commonly used implementations
is ThreadPoolExecutor. It manages a pool of threads and
allows control over the number of threads and task execution
strategies.
Interviewer: Let’s go through an example.
Tasks and their start times:
• Task A: 1s
• Task B: 2s
• Task C: 4s
• Task D: 6s
• Task E: 10s
• Task F: 12s
• Task G: 13s
• Task H: 14s
Assume all tasks take 5 seconds to execute. We have a fixed
thread pool of 3 threads: Tr1, Tr2, and Tr3.
Tell me the state of threads for each second.
Candidate: Here’s how the thread assignments would look:
• Second 0:
Tr1: IDLE
Tr2: IDLE
Tr3: IDLE
• Second 1:
Tr1: A
Tr2: IDLE
Tr3: IDLE
• Second 2:
Tr1: A
Tr2: B
Tr3: IDLE
• Second 3:
Tr1: A
Tr2: B
Tr3: IDLE
• Second 4:
Tr1: A
Tr2: B
Tr3: C
• Second 5:
Tr1: A
Tr2: B
Tr3: C
• Second 6:
Tr1: D
Tr2: B
Tr3: C
• Second 7:
Tr1: D
Tr2: IDLE (B completes)
Tr3: C
• Second 8:
Tr1: D
Tr2: IDLE
Tr3: C
• Second 9:
Tr1: D
Tr2: IDLE
Tr3: IDLE (C completes)
• Second 10:
Tr1: D
Tr2: E
Tr3: IDLE
• Second 11:
Tr1: D
Tr2: E
Tr3: IDLE
• Second 12:
Tr1: D
Tr2: E
Tr3: F
• Second 13:
Tr1: G
Tr2: E
Tr3: F
• Second 14:
Tr1: G
Tr2: E
Tr3: H

---------------------------------------------------------------------------
Query :
Interviewer: What’s the use of the pipeline operator (|) in
Java?
Candidate: The pipeline operator (|) is primarily used for:
1. Bitwise OR operations in Java.
2. Handling multiple exceptions in a single catch block.
Interviewer: How does the pipeline operator help in handling
multiple exceptions?
Candidate: If a try block throws multiple exceptions, the
pipeline operator allows grouping those exceptions in a single
catch block. This simplifies the code and avoids redundancy.
Interviewer: Can you provide a sample code for this?
Candidate: Here’s an example:
public class Example {
public static void main(String[] args) {
try {
int[] num = {1, 2, 3};
System.out.println(num[4]); // Throws
ArrayIndexOutOfBoundsException
int result = 10 / 0; // Throws ArithmeticException
} catch (ArrayIndexOutOfBoundsException |
ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
This reduces repetitive code and makes exception handling
concise and readable.

---------------------------------------------------------------------------
Query :
Interviewer: What are inner classes and anonymous classes?
Can classes be declared as "static"?
Candidate: Inner Classes:
Inner classes are classes defined within another class. They
have access to the members (both static and non-static) of
their enclosing class. They are categorized as:
1. Member Inner Classes – Non-static inner classes
defined inside a class but outside any method.
2. Static Nested Classes – Declared using the static
keyword.
3. Local Inner Classes – Defined inside a method or block.
4. Anonymous Inner Classes – Classes without a name,
usually used for one-time usage or when implementing
interfaces.
Static Classes: A class can be declared as static if and only if
it is a nested class. Static nested classes can access only the
static members of the outer class and do not require an
instance of the outer class.

Interviewer: Can you provide an example of inner classes?


Candidate: Here’s an example of a member inner class:
class OuterClass {
private String outerField = "Outer field";

class InnerClass {
void display() {
System.out.println("Accessing from InnerClass: " +
outerField);
}
}
void createInnerInstance() {
InnerClass inner = new InnerClass();
inner.display();
}
}
public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
outer.createInnerInstance();
}
}

Output:
Accessing from InnerClass: Outer field
Query :
Interviewer: What is an anonymous class? Can you provide
an example?
Candidate: An anonymous class is a nested class without a
name. It is declared and instantiated in a single expression and
is used when a class is needed for immediate use, such as
implementing an interface or extending a class.
Example of an Anonymous Class:
public class Main {
public static void main(String[] args) {
// Anonymous class implementing Runnable interface
Runnable task = new Runnable() {
@Override
public void run() {
System.out.println("Anonymous class implementing
Runnable running!");
}
};
new Thread(task).start();
}
}
Output:
Anonymous class implementing Runnable running!
These classes are particularly useful for concise and specific
implementations of functionality.
---------------------------------------------------------------------------

You might also like