Uipath
Uipath
Uipath
Yes, you can make an array volatile in Java but only the reference which is
pointing to an array, not the whole array. What I mean, if one thread changes the
reference variable to points to another array, that will provide a volatile
guarantee, but if multiple threads are changing individual array elements they
won't be having happens before guarantee provided by the volatile modifier.
One example I have seen is having a long field in your class. If you know that a
long field is accessed by more than one thread e.g. a counter, a price field or
anything, you better make it volatile. Why? because reading to a long variable is
not atomic in Java and done in two steps, If one thread is writing or updating long
value, it's possible for another thread to see half value (fist 32-bit). While
reading/writing a volatile long or double (64 bit) is atomic.
False sharing is very hard to detect because the thread may be accessing completely
different global variables that happen to be relatively close together in memory.
Like many concurrency issues, the primary way to avoid false sharing is careful
code review and aligning your data structure with the size of a cache line.
15) What is an immutable object? How do you create an Immutable object in Java?
(answer)
Immutable objects are those whose state cannot be changed once created. Any
modification will result in a new object e.g. String, Integer, and other wrapper
class. Please see the answer for step by step guide to creating Immutable class in
Java.
17) What is the right data type to represent a price in Java? (answer)
BigDecimal if memory is not a concern and Performance is not critical, otherwise
double with predefined precision.
20) Can we cast an int value into byte variable? what will happen if the value of
int is larger than byte?
Yes, we can cast but int is 32 bit long in java while byte is 8 bit long in java so
when you cast an int to byte higher 24 bits are lost and a byte can only hold a
value from -128 to 128.
21) There are two classes B extends A and C extends B, Can we cast B into C e.g. C
= (C) B; (answer)
25) Can I store a double value in a long variable without casting? (answer)
No, you cannot store a double value into a long variable without casting because
the range of double is more that long and you we need to type cast. It's not
dificult to answer this question but many develoepr get it wrong due to confusion
on which one is bigger between double and long in Java.
26) What will this return 3*0.1 == 0.3? true or false? (answer)
This is one of the really tricky questions. Out of 100, only 5 developers answered
this question and only of them have explained the concept correctly. The short
answer is false because some floating point numbers can not be represented exactly.
27) Which one will take more memory, an int or Integer? (answer)
An Integer object will take more memory an Integer is the an object and it store
meta data overhead about the object and int is primitive type so its takes less
space.
28) Why is String Immutable in Java? (answer)
One of my favorite Java interview question. The String is Immutable in java because
java designer thought that string will be heavily used and making it immutable
allow some optimization easy sharing same String object between multiple clients.
See the link for the more detailed answer. This is a great question for Java
programmers with less experience as it gives them food for thought, to think about
how things works in Java, what Jave designers might have thought when they created
String class etc.
32) The difference between Serial and Parallel Garbage Collector? (answer)
Even though both the serial and parallel collectors cause a stop-the-world pause
during Garbage collection. The main difference between them is that a serial
collector is a default copying collector which uses only one GC thread for garbage
collection while a parallel collector uses multiple GC threads for garbage
collection.
33) What is the size of an int variable in 32-bit and 64-bit JVM? (answer)
The size of int is same in both 32-bit and 64-bit JVM, it's always 32 bits or 4
bytes.
37) How do you find if JVM is 32-bit or 64-bit from Java Program? (answer)
You can find that by checking some system properties like sun.arch.data.model or
os.arch
38) What is the maximum heap size of 32-bit and 64-bit JVM? (answer)
Theoretically, the maximum heap memory you can assign to a 32-bit JVM is 2^32 which
is 4GB but practically the limit is much smaller. It also varies between operating
systems e.g. form 1.5GB in Windows to almost 3GB in Solaris. 64-bit JVM allows you
to specify larger heap size, theoretically 2^64 which is quite large but
practically you can specify heap space up to 100GBs. There are even JVM e.g. Azul
where heap space of 1000 gigs is also possible.
39) What is the difference between JRE, JDK, JVM and JIT? (answer)
JRE stands for Java run-time and it's required to run Java application. JDK stands
for Java development kit and provides tools to develop Java program e.g. Java
compiler. It also contains JRE. The JVM stands for Java virtual machine and it's
the process responsible for running Java application. The JIT stands for Just In
Time compilation and helps to boost the performance of Java application by
converting Java byte code into native code when the crossed certain threshold i.e.
mainly hot code is converted into native code.
42) How do you find memory usage from Java program? How much percent of the heap is
used?
You can use memory related methods from java.lang.Runtime class to get the free
memory, total memory and maximum heap memory in Java. By using these methods, you
can find out how many percents of the heap is used and how much heap space is
remaining. Runtime.freeMemory() return amount of free memory in bytes,
Runtime.totalMemory() returns total memory in bytes and Runtime.maxMemory() returns
maximum memory in bytes.
43) What is the difference between stack and heap in Java? (answer)
Stack and heap are different memory areas in the JVM and they are used for
different purposes. The stack is used to hold method frames and local variables
while objects are always allocated memory from the heap. The stack is usually much
smaller than heap memory and also didn't shared between multiple threads, but heap
is shared among all threads in JVM.
47) What is a compile time constant in Java? What is the risk of using it?
public static final variables are also known as a compile time constant, the public
is optional there. They are replaced with actual values at compile time because
compiler know their value up-front and also knows that it cannot be changed during
run-time. One of the problem with this is that if you happened to use a public
static final variable from some in-house or third party library and their value
changed later than your client will still be using old value even after you deploy
a new version of JARs. To avoid that, make sure you compile your program when you
upgrade dependency JAR files.
48) The difference between List, Set, Map, and Queue in Java? (answer)
The list is an ordered collection which allows duplicate. It also has an
implementation which provides constant time index based access, but that is not
guaranteed by List interface. Set is unordered collection which
49) Difference between poll() and remove() method?
Both poll() and remove() take out the object from the Queue but if poll() fails
then it returns null but if remove fails it throws Exception.
52) What is a couple of ways that you could sort a collection? (answer)
You can either use the Sorted collection like TreeSet or TreeMap or you can sort
using the ordered collection like a list and using Collections.sort() method.
58) Write code to remove elements from ArrayList while iterating? (answer)
Key here is to check whether candidate uses ArrayList's remove() or Iterator's
remove(). Here is the sample code which uses right way o remove elements from
ArrayList while looping over and avoids ConcurrentModificationException.
59) Can I write my own container class and use it in the for-each loop?
Yes, you can write your own container class. You need to implement the Iterable
interface if you want to loop over advanced for loop in Java, though. If you
implement Collection then you by default get that property.
61) Is it possible for two unequal objects to have the same hashcode?
Yes, two unequal objects can have same hashcode that's why collision happen in a
hashmap.
the equal hashcode contract only says that two equal objects must have the same
hashcode it doesn't say anything about the unequal object.
62) Can two equal object have the different hash code?
No, thats not possible according to hash code contract.
64) What is the difference between Comparator and Comparable in Java? (answer)
The Comparable interface is used to define the natural order of object while
Comparator is used to define custom order. Comparable can be always one, but we can
have multiple comparators to define customized order for objects.
65) Why you need to override hashcode, when you override equals in Java? (answer)
Because equals have code contract mandates to override equals and hashcode
together .since many container class like HashMap or HashSet depends on hashcode
and equals contract.
66) In my Java program, I have three sockets? How many threads I will need to
handle that?
71) The difference between direct buffer and non-direct buffer in Java? (answer)
74) What is the difference between TCP and UDP protocol? (answer)
76) What best practices you follow while writing multi-threaded code in Java?
(answer)
Here are couple of best practices which I follow while writing concurrent code in
Java:
a) Always name your thread, this will help in debugging.
b) minimize the scope of synchronization, instead of making whole method
synchronized, only critical section should be synchronized.
c) prefer volatile over synchronized if you can can.
e) use higher level concurrency utilities instead of waitn() and notify for inter
thread communication e.g. BlockingQueue, CountDownLatch and Semeaphore.
e) Prefer concurrent collection over synchronized collection in Java. They provide
better scalability.
77) Tell me few best practices you apply while using Collections in Java? (answer)
Here are couple of best practices I follow while using Collectionc classes from
Java:
a) Always use the right collection e.g. if you need non-synchronized list then use
ArrayList and not Vector.
b) Prefer concurrent collection over synchronized collection because they are more
scalable.
c) Always use interface to a represent and access a collection e.g. use List to
store ArrayList, Map to store HashMap and so on.
d) Use iterator to loop over collection.
e) Always use generics with collection.
78) Can you tell us at least 5 best practice you use while using threads in Java?
(answer)
This is similar to the previous question and you can use the answer given there.
Particularly with thread, you should:
a) name your thread
b) keep your task and thread separate, use Runnable or Callable with thread pool
executor.
c) use thread pool
d) use volatile to indicate compiler about ordering, visibility, and atomicity.
e) avoid thread local variable because incorrect use of ThreadLocal class in Java
can create a memory leak.
Look there are many best practices and I give extra points to the developer which
bring something new, something even I don't know. I make sure to ask this question
to Java developers of 8 to 10 years of experience just to gauge his hands on
experience and knowledge.
83) How do you format a date in Java? e.g. in the ddMMyyyy format? (answer)
You can either use SimpleDateFormat class or joda-time library to format date in
Java. DateFormat class allows you to format date on many popular formats. Please
see the answer for code samples to format date into different formats e.g. dd-MM-
yyyy or ddMMyyyy.
84) How do you show timezone in formatted date in Java? (answer)
86) How to you calculate the difference between two dates in Java? (program)
90) How to do you test a method for an exception using JUnit? (answer)
91) Which unit testing libraries you have used for testing Java programs? (answer)
92) What is the difference between @Before and @BeforeClass annotation? (answer)
97) How to find the word with the highest frequency from a file in Java? (solution)
98) How do you check if two given String are anagrams? (solution)
100) How do you print duplicate elements from an array in Java? (solution)
102) How to swap two integers without using temp variable? (solution)
103) What is the interface? Why you use it if you cannot write anything concrete on
it?
The interface is used to define API. It tells about the contract your classes will
follow. It also supports abstraction because a client can use interface method to
leverage multiple implementations e.g. by using List interface you can take
advantage of random access of ArrayList as well as flexible insertion and deletion
of LinkedList. The interface doesn't allow you to write code to keep things
abstract but from Java 8 you can declare static and default methods inside
interface which are concrete.
104) The difference between abstract class and interface in Java? (answer)
There are multiple differences between abstract class and interface in Java, but
the most important one is Java's restriction on allowing a class to extend just one
class but allows it to implement multiple interfaces. An abstract class is good to
define default behavior for a family of class, but the interface is good to define
Type which is later used to leverage Polymorphism. Please check the answer for a
more thorough discussion of this question.
105) Which design pattern have you used in your production code? apart from
Singleton?
This is something you can answer from your experience. You can generally say about
dependency injection, factory pattern, decorator pattern or observer pattern,
whichever you have used. Though be prepared to answer follow-up question based upon
the pattern you choose.
109) What is "dependency injection" and "inversion of control"? Why would someone
use it? (answer)
110) What is an abstract class? How is it different from an interface? Why would
you use it? (answer)
One more classic question from Programming Job interviews, it is as old as chuck
Norris. An abstract class is a class which can have state, code and implementation,
but an interface is a contract which is totally abstract. Since I have answered it
many times, I am only giving you the gist here but you should read the article
linked to answer to learn this useful concept in much more detail.
112) What is difference between dependency injection and factory design pattern?
(answer)
Though both patterns help to take out object creation part from application logic,
use of dependency injection results in cleaner code than factory pattern. By using
dependency injection, your classes are nothing but POJO which only knows about
dependency but doesn't care how they are acquired. In the case of factory pattern,
the class also needs to know about factory to acquire dependency. hence, DI results
in more testable classes than factory pattern. Please see the answer for a more
detailed discussion on this topic.
120) The difference between nested public static class and a top level class in
Java? (answer)
You can have more than one nested public static class inside one class, but you can
only have one top-level public class in a Java source file and its name must be
same as the name of Java source file.
122) Give me an example of design pattern which is based upon open closed
principle? (answer)
This is one of the practical questions I ask experienced Java programmer. I expect
them to know about OOP design principles as well as patterns. Open closed design
principle asserts that your code should be open for extension but closed for
modification. Which means if you want to add new functionality, you can add it
easily using the new code but without touching already tried and tested code.
There are several design patterns which are based upon open closed design principle
e.g. Strategy pattern if you need a new strategy, just implement the interface and
configure, no need to modify core logic. One working example is Collections.sort()
method which is based on Strategy pattern and follows the open-closed principle,
you don't modify sort() method to sort a new object, what you do is just implement
Comparator in your own way.
123) Difference between Abstract factory and Prototype design pattern? (answer)
This is the practice question for you, If you are feeling bored just reading and
itching to write something, why not write the answer to this question. I would love
to see an example the, which should answer where you should use the Abstract
factory pattern and where is the Prototype pattern is more suitable.
125) The difference between nested static class and top level class? (answer)
One of the fundamental questions from Java basics. I ask this question only to
junior Java developers of 1 to 2 years of experience as it's too easy for an
experience Java programmers. The answer is simple, a public top level class must
have the same name as the name of the source file, there is no such requirement for
nested static class. A nested class is always inside a top level class and you need
to use the name of the top-level class to refer nested static class e.g.
HashMap.Entry is a nested static class, where HashMap is a top level class and
Entry is nested static class.
126) Can you write a regular expression to check if String is a number? (solution)
If you are taking Java interviews then you should ask at least one question on the
regular expression. This clearly differentiates an average programmer with a good
programmer. Since one of the traits of a good developer is to know tools, regex is
the best tool for searching something in the log file, preparing reports etc.
Anyway, answer to this question is, a numeric String can only contain digits i.e. 0
to 9 and + and - sign that too at start of the String, by using this information
you can write following regular expression to check if given String is number or
not
127) The difference between checked and unchecked Exception in Java? (answer)
checked exception is checked by the compiler at compile time. It's mandatory for a
method to either handle the checked exception or declare them in their throws
clause. These are the ones which are a sub class of Exception but doesn't descend
from RuntimeException. The unchecked exception is the descendant of
RuntimeException and not checked by the compiler at compile time. This question is
now becoming less popular and you would only find this with interviews with small
companies, both investment banks and startups are moved on from this question.
On the other hand, throws is used as part of method declaration and signals which
kind of exceptions are thrown by this method so that its caller can handle them.
It's mandatory to declare any unhandled checked exception in throws clause in Java.
Like the previous question, this is another frequently asked Java interview
question from errors and exception topic but too easy to answer.
130) The difference between DOM and SAX parser in Java? (answer)
Another common Java question but from XML parsing topic. It's rather simple to
answer and that's why many interviewers prefers to ask this question on the
telephonic round. DOM parser loads the whole XML into memory to create a tree based
DOM model which helps it quickly locate nodes and make a change in the structure of
XML while SAX parser is an event based parser and doesn't load the whole XML into
memory. Due to this reason DOM is faster than SAX but require more memory and not
suitable to parse large XML files.
133) What is the difference between Maven and ANT in Java? (answer)
Another great question to check the all round knowledge of Java developers. It's
easy to answer questions from core Java but when you ask about setting things up,
building Java artifacts, many Java software engineer struggles. Coming back to the
answer of this question, Though both are build tool and used to create Java
application build, Maven is much more than that. It provides standard structure for
Java project based upon "convention over configuration" concept and automatically
manage dependencies (JAR files on which your application is dependent) for Java
application. Please see the answer for more differences between Maven and ANT tool.
19. Have you worked on Serialization? Can you tell difference between Serializable
and Externalizable?
You can find detailed answer over here
Interview Question 3:
What is Singleton Pattern and Do you know how to make it Thread-Safe and Fast?
The singleton pattern is a design pattern that restricts the instantiation of a
class to one object. This is useful when exactly one object is needed to coordinate
actions across the system.
Interview Question 4:
What is JVM? Are you aware of Heapsize, Stacksize & Garbage Collection? Please
share some more light.
Java-JVM-HeapSize-Crunchify-Tips
When a Java program starts, Java Virtual Machine gets some memory from Operating
System. Java Virtual Machine or JVM uses this memory for all its need and part of
this memory is call java heap memory.
Interview Question 5:
Write a program in Java which Counts total number of Characters, Words and Lines
This one is the more frequently asked question. Please visit complete tutorial for
more info: https://crunchify.com/how-to-read-file-in-java-and-count-total-number-
of-characters-words-and-lines/
Interview Question 6:
What is JSON and How to read JSON object from file?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is
easy for humans to read and write. It is easy for machines to parse and generate.
It is based on a subset of the JavaScript Programming Language.
Follow these tutorials for how to READ JSON and WRITE JSON object in java.
Interview Question 7:
What is Semaphore and Mutex in Java. Provide detailed explanation related to
MultiThreading
Semaphore and Mutex in Java
Java Concurrency is a very wide topic. There are hundreds of tutorials and examples
available for use to use. Some time back I’ve written few tutorials on Run Multiple
Threads Concurrently in Java and different types of Synchronized Blocks.
Interview Question 8:
Are you aware of HashMap, ConcurrentHashMap, SynchronizedMap? Which one is faster?
HashMap is a very powerful data structure in Java. We use it everyday and almost in
all applications. I would suggest you to visit tutorial for more details:
https://crunchify.com/hashmap-vs-concurrenthashmap-vs-synchronizedmap-how-a-
hashmap-can-be-synchronized-in-java/
Interview Question 9:
What is Abstract Class and Interface in Java?
This one is also very popular Java interview questions. This is very big topic and
we do have complete tutorial with all details here.
9) What happens if you don't call wait and notify from synchronized block?
Another common Java interview question from multi-threding and inter thread
communication. As I said earlier you must know concept of wait and notify in Java
if you have worked for 2 to 3 years in Java. Check why wait and notify needs to
call from synchronized block for exact reason to answer this Java question.