Saturday, July 11, 2015

Java Interview Questions - from corejavainterviewquestions



http://www.corejavainterviewquestions.com/core-java-interview-questions-1/
What does “write once run anywhere” mean in relation to Java?
Java is a cross platform language; java compiles down to byte code which can be run on a Java Virtual Machine (JVM). JVMs are available on many platforms including the major operating systems. This means that any Java application can in theory run on any platform where a JVM is available, hence write once (for the JVM) and run anywhere (there is a JVM).


What does it mean when we say java does not support multiple inheritance? Is this a good thing?
Java cannot extend functionality from more than one concrete or abstract class.  If both parent classes had a jump() method, it would be unclear which functionality the caller would need to use.  We can implement multiple interfaces however as the the implementation occurs in our actual class so this problem does not occur.

http://www.corejavainterviewquestions.com/core-java-interview-questions-part-ii/
What is the contract between hashcode and equals?
Two objects which are equal must have the same hashcode.  Two objects with the same hashcode may or may not be equal.

What do we mean when we say java supports covariant return type
When implementing/overriding a method, we can return a class which is a subtype of the original return type.

What is the difference between HashMap and HashTable?
HashTable is syncronized and will not allow null values.  HashMap is not syncronized and will allow 1 null key and all null values.  HashTable is generally discouraged now, with Collections.synchronizedMap(Map) and ConcurrentHashMap as preferred alternatives.

What is the difference between Collections.synchronizedMap and ConcurrentHashMap?
ConcurrentHashMap is significantly more performant and allows parallel access for reads and writes from multiple threads.  However, it makes no guarantee that the iterator will or will not include updates made during the iteration.  There is therefore the potential for a Thread to have an out of date view.  Collections.synchronizedMap locks the entire map for reads and writes and is therefore unperformant but has guaranteed safety and data visibility.  ConcurrentHashMap also does not allow null keys or values.

http://www.corejavainterviewquestions.com/core-java-interview-questions-list-part-iii/
Can you overload the main method?
Absolutely.  However, the JVM will only use the standard main(String[] args) when launching.

What is a marker interface?
A Marker interface is an interface with no methods on it, used only as an indicator.  Serializable and Clonable are examples in the JDK.

Can a constructor be final?
Nope. there is no meaning, a constructor can't be overridden after all.

What does applying final actually do?
Applying final to a variable means the variable cannot be changed.
Applying final to method means they can be overridden.
Applying final to a class means the class cannot be overridden

What is casting in Java?
Casting is the act of turning one object into another.  We can refer to an Integer as an Integer, or upcast it to an Object.  It is an upcast as it is higher in the inheritance hierarchy. Alternatively, if we cast the other way from an Object to an Integer, we are downcasting.  We must be careful when casting as, if the object cast is invalid it will throw a ClassCastException.

Can we override an overloaded method?
Yes! Of course.  They are two orthogonal concepts.

What is a transient variable?
When a variable is marked transient it will not be serialized.

What is the difference between while and do while?
A while loop is not guaranteed to run; if the condition is false then the code in the loop will not be executed.  A do while is guaranteed to execute once.


http://www.corejavainterviewquestions.com/java-exception-interview-questions/
Exceptions are a way to programmatically convey system and programming errors. All exceptions inherit from Throwable.  When something goes wrong you can use the throw keyword to fire an exception.

There are 2 types of exception in Java, what are they and what’s the difference?
The two types of exception are checked and unchecked

A checked exception is one that forces you to catch it. It forms part of the API or contract. Anyone using code that throws a checked Exception can see that as it is declared on the method and they are forced to handle it using a try/catch block.  Unchecked on the other hand does not need to be caught and does not notify anyone using the code that it could be thrown.

All exceptions are checked exceptions except those that inherit from java.lang.RuntimeException.

When catching exceptions it is important to do so in order from most specific to least specific.  If your catch block catches Exception first and then IOException second, the first catch block will always catch any Exception coming through and the IOException will be rendered useless (and in fact it will cause a compiler error saying the Exception has already been caught)

C sharp does not have Checked Exceptions.  Can you tell me why this might be? Who do you think was right, Java or C sharp?

http://www.corejavainterviewquestions.com/java-threading-interview-questions-complete-guide/
What other options do we have for creating Thread safe code?
making a variable volatile is more performant and less complex.
The Atomic Classes
These are completely thread safe and do not involve locking, but instead use Compare and Swap (CAS) operations.  A CAS operation is an atomic one (as in, it happens as one single operation) where the field is checked that the value is what was expected (it hasn’t been modified by a thread) and if so it sets the value to the new amount.

Immutability
What do wait(), notify() and notifyAll() do?
Why must they be called from a synchronised block?
What alternatives are there to these?
wait(), notify() and notifyAll() are used as a means of inter-thread communication.  When acquiring a lock on an object it may not be in the required state; perhaps a resource isn’t set yet, a value isn’t correct.  We can use wait() to put the thread to sleep until something changes.  When that something does change, the awaiting clients can be notified by calling notify() or notifyAll() on the object that is being waited for.  If all of your waiting  threads could in theory take action with the new information then use notifyAll().

What is a deadlock?
How do we prevent deadlocks?

The easiest way to prevent deadlock is to ensure that the acquisition of locks is consistent.   If both Threads try to acquire Object 1 then Object 2 in that order then deadlock will not occur.  It is important to code defensively when acquiring locks.  Even better is to make synchronized blocks as small as possible and where possible avoid locking multiple objects.

http://www.corejavainterviewquestions.com/java-collections-data-structures-interview-questions/

http://www.corejavainterviewquestions.com/core-java-interview-questions-list-part-v/
Why do we care about autoboxing?
It can cause a performance hit.

When should I use a float or a double?
Generally it is better to prefer double unless there is a very specific reason not to. A float is half the size of a double and can be faster on some processors, however double can be faster on some modern processors.  There is a wonderful piece of advice on StackOverflow:

“Don’t use float. There is almost never a good reason to use it and hasn’t been for more than a decade. Just use double.”

A float is single (32 bit) precision whereas a double is (unsurprisingly) double (64 bit) precision.
There is rarely cause to use float instead of double in code targeting modern computers. The extra precision reduces (but does not eliminate) the chance of rounding errors or other imprecision causing problems.
What is a constructor? Why is it different from other methods?
A constructor is used to create an object.  It does not specify a return type (as the return type is implied; the constructor for MyObject will return a MyObject type). Constructor must be called via the new keyword, whereas regular methods will be called on an existing object (or static methods on a class). Constructors must have the same name as the class.  A default constructor is created by the JVM if one is not coded. If a class is a subclass then the first line must be to call super() to initialise the variables etc. inherited from the parent class.

Explain pass by reference and pass by value
In pass by reference, a reference to the object is passed around, not the actual object.
In pass by value, a copy of the actual object is passed around. This means it cannot be modified by the method it is passed to.

Is Java Pass by reference or pass by value?
Java is always pass by value. However, when passing an object to a method, the reference is passed by value.  This means the same object is referenced by both the method and the caller despite being pass by value.

Are Java variables initialised with default values?
Static and Instance variables are given default values (e.g. false, 0, and null for Objects.  Local variables are not, and attempting to access them before initialisation will result in a compiler error.

What access modifiers can I have on a class?
On a top level class, only public or default. Marking a class private or protected will result in a compiler error.  Inner classes can be private and static.

http://www.corejavainterviewquestions.com/multiple-interface-inheritance/
Can you inherit from an interface twice? 
public class BasketOfApplesAndOrange implements Basket<Apple>, Basket<Orange> // this will not compile
No! There’s not a chance this will compile.
To inherit from an interface twice is illegal in Java. It’s tempting to think that Generics will allow you to get away with it (and I confess I fell for this myself years ago when I was asked it in an interview). But generics are implemented terribly in Java, and one of the consequences is that they are erased away before runtime- better known as type erasure. So at compile time it may be implementing Basket<Orange>, Basket<Apple>, but at runtime this just becomes implements Basket, Basket, which is illegal syntax.

Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts