TOP Java QA PDF
TOP Java QA PDF
volatile variables provide the guarantee about ordering and visibility e.g. volatile assignment
cannot be re-ordered with other statements but in the absence of any synchronization instruction
compiler, JVM or JIT are free to reorder statements for better performance. volatile also provides
the happens-before guarantee which ensure changes made in one thread is visible to others. In
some cases volatile also provide atomicity e.g. reading 64-bit data types like long and double are
not atomic but read of volatile double or long is atomic.
5) Which one would be easy to write? synchronization code for 10 threads or 2 threads?
In terms of writing code, both will be of same complexity because synchronization code is
independent of a number of threads. Choice of synchronization though depends upon a number
of threads because the number of thread present more contention, so you go for advanced
synchronization technique e.g. lock stripping, which requires more complex code and expertise.
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.
No, Swing is not thread-safe. You cannot update Swing components e.g. JTable, JList or JPanel
from any thread, in fact, they must be updated from GUI or AWT thread. That's why swings
provide invokeAndWait() and invokeLater() method to request GUI update from any
other threads. This methods put update request in AWT threads queue and can wait till update or
return immediately for an asynchronous update. You can also check the detailed answer to learn
more.
11) What is a thread local variable in Java?
Thread-local variables are variables confined to a thread, its like thread's own copy which is not
shared between multiple threads. Java provides a ThreadLocal class to support thread-local
variables. It's one of the many ways to achieve thread-safety. Though be careful while using
thread local variable in manged environment e.g. with web servers where worker thread out lives
any application variable. Any thread local variable which is not removed once its work is done
can potentially cause a memory leak in Java application.
15) What is an immutable object? How do you create an Immutable object in Java?
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.
21) There are two classes B extends A and C extends B, Can we cast B into C e.g. C = (C)
B;
result. When you add two integral variable e.g. variable of type byte, short, or int then they are
first promoted to int and them addition happens. If result of addition is more than maximum
value of a then a + b will give compile time error but a += b will be ok as shown below
byte a = 127;
byte b = 127;
b = a + b; // error : cannot convert from int to byte
b += a; // ok
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.
37) How do you find if JVM is 32-bit or 64-bit from Java Program?
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?
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?
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.
equals() method. According to Java specification, two objects which are equal to each other
using equals() method must have same hash code.
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.
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.
77) Tell me few best practices you apply while using Collections in Java?
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?
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.
80) Name 5 JDBC best practices your follow? Another good Java best practices for
experienced Java developer of 7 to 8 years experience. Why it's important? because they are the
ones which set the trend in the code and educate junior developers. There are many best practices
and you can name as per your confort and conviniece. Here are some of the more common ones:
a) use batch statement for inserting and updating data.
b) use PreparedStatement to avoid SQL exception and better performance.
c) use database connection pool
d) access resultset using column name instead of column indexes.
e) Don't generate dynamic SQL by concatenating String with user input.
81) Name couple of method overloading best practices in Java? Here are some best practices
you can follow while overloading a method in Java to avoid confusion with auto-boxing:
a) Don't overload method where one accepts int and other accepts Integer.
b) Don't overload method where number of argument is same and only order of argument is
different.
c) Use varargs after overloaded methods has more than 5 arguments.
83) How do you format a date in Java? e.g. in the ddMMyyyy format?
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.