Showing posts with label online resource. Show all posts
Showing posts with label online resource. Show all posts

Saturday, June 27, 2015

Uncaught Exception in Java: Yet Program Exits with Success?

In Java, you would have noticed that if we get an uncaught exception JVM exits with success (exit code is zero). While in C++ if there is an exception which is not handled, program returns with non-zero Exit Code. Only in case of explicit System.exit(), do we a non-zero Exit code, which reflects Failure. 

Some consider this a design issue, some consider this s defect. When such a code is called from within a script, coders tend to rely on exit status. They get confused often in Java as Success does not mean every time a successful exit.

What should we do in Java?
Write a top level try-catch in main. If any Exception is there, catch it and throw System.exit(1) explicitly. In an already written code that you are using, don't rely on exit codes.

Friday, June 26, 2015

Can you suggest improvements in Java?

This is one of those abstract questions that often comes across in Java interview questions. More of than not, candidates are not able to give coherent answers to this question. The point to remember is that interviewer is also just fishing. He want to see if you can think through and is suitable for a senior level position.

There is no exact answer to this. At the same time answer to his question might end up impressing the interviewer and give up an upper hand while bargaining the salary.

Here's few things that can be improved in Java. A lot of improvements have come across in Java 1.7 and 1.8. More coming in Java 9 in 2016.

1. Java is slow: One major criticism of Java as compared to C++ is slowness. There has been a lot of discussion on this but nothing much has improved. Would like the JVM speed to be better.
With Java 8 a lot of bootstrapping has been made faster. But more needs to be done. 

2. Uncontrolled Garbage Collection: The Automated Garbage collection tends to make application unresponsive during full gc. My suggestion would be to relinquish some control of Garbage Collection to users. There can be custom gc for those who want control, but for advanced developers, this might aid end result.

3. Pattern Matching support for Switch: Switch now supports Strings, but there is an a need for Groovy/Scala type pattern matching.

4. Reflection: A security nightmare. More than the use, this has potential to be misused. I would do away with reflection API.

5. All is Object: With everything in Java orginating from Object class, I wonder if there any requirement of primitive types. I would do away with them.

6. Date Handling: Every time I want to handle Date in Java, it's pretty confusing. This should be made simpler and straight forward.

Major improvements in Java 7/8
1. Functional programming introduced in Java 8
2. Resources freed automatically, without need to do them in finally. This was improved in Java 7

Thursday, June 25, 2015

Arraylist v/s Vector

ArrayList v/s Vector


Expect this question in a junior level (0-2 yrs) interview. One of the most done to death and still kicking question. This questions lays the foundation of advanced level question.

Let's see the differences one by one.

S No.
Arraylist
Vector
1
Non Synchronized and hence not thread safe
Synchronized and Thread safe
2
Faster performance as non-synchronized
Slower performance as only one thread access at a time.
3
Array increase the size by 50% when full (Starting Size 10 by default)
Vector doubles the size when full.
4
Uses Iterator for iteration
Uses Enumerator for iteration

Wednesday, June 24, 2015

HashMap v/s ConcurrentHashMap

Concurrence


Going a step further interviewer now delves into the multi-threading regime. One of the first questions that is asked at mid-level (2-4 yrs) is difference between HashMap and ConcurrentHashMap. 

This is check of knowledge of basic usage of the Candidate, since if you have worked on any Java application, you would have come across HashMap/ConcurrentHashMap for sure.


S No.
HashMap
ConcurrentHashMap
1
Not Thread safe
Thread safe.
2
synchronized(map) makes HashMap synchronized
Already thread safe
3
synchronized(map) locks entire map. Reduces Performance
Takes lock only on a portion of the Map and not the whole Object. Faster Performance
4
One null key is allowed
Null key is not allowed
5
Better performance in Single threaded Environment
Not Got performance in Single threaded Environment

Monday, June 22, 2015

Iterator v/s Enumator

Iterator v/s Enumerator

Often asked during interviews from Collections. They are both used to iterate over a Collection of Data. Below is the difference in tabular format and sufficient for interviews.


Differences
S No.
Iterator
Enumerator
1
Methods
hasNext()
next()
remove()
Methods
hasMoreElement()
nextElement()
2
Secure as throws ConcurrentModificationException if other thread tries to modify the Collection object while one thread is iterating over it
Not secure as no concept of ConcurrentModificationException
3
remove() method makes it read/modify interface
remove() method is absent, hence it is Read-only interface




Similarities
S No.
Iterator
Enumerator
1
Interface
Interface
2
java.util package
java.util package
3
Used for iteration
Used for iteration

Sunday, June 21, 2015

Java HashMap v/s HashTable

Map v/s Table
HashMap always brings innumerable interview questions along with itself. One of the common interview questions is the difference and similarities between Java HashMap and HashTable. You might not get the direct question like this but something on similar lines. 

We have tried to list the difference and similarity. Have a go!

Differences
S No.
HashMap
HashTable
1
Not synchronized. Not thread safe
Synchronized. Thread safe
2
Allows one Null Key and multiple null values
Null keys and Null values not allowed
3
Iterated by using Iterator
Iterated by using Enumerator
4
Iterator in HashMap is fail-fast
Enumerator in HashTable is not fail fast
5
Faster and uses less memory as unsynchronized
Slower and uses more memory as synchronized


Similarities
S No.
HashMap
HashTable
1
Does not guarantee order of Map
Does not guarantee order of Map
2
Constant Time for put/get
Constant Time for put/get
3
Works on Hashing Principle
Works on Hashing Principle
4
Implements Map Interface
Implements Map Interface

Friday, June 19, 2015

Concurrency Utilities Fork/Join Framework

Forks Join!

With the advent of multiple processors, the code also need to evolve. We need to write code which can spawn Threads in such a manner so as to take complete use of multiple processors. The idea is to use all available processing power which leads to enhanced performance. No Thread should remain free.

Fork/Join framework is an implementation of ExecutorService. We have a ThreadPool. Tasks are allotted to the worker threads. The difference here is if some thread is free, it will steal the work from a busy thread, thereby maximizing performance.
ForkJoinPool is the implementation of ExecutorService which can run ForkJoinTasks. It is different from other ExecutorServices as the threads in the pool tries to steal the subtasks created by other Tasks (being processed by other threads). It’s like a workaholic employee who ends up doing other people’s work also. In effect it improves firms overall performance.
1
2
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(new SumArray(array, 0, array.length));
SumArray extends ForkJoinTask (RecursiveTask/RecursiveAction). See here the analogy with a simple ThreadPoolExecutor, which requires a Runnable/Callable task.
The SumArray needs to have function compute() (analogous to run()) which will be called post pool.invoke() (analogous to execute()). Also a function invokeAll() is available to the SumArray, which is just like invoke, but takes multiple ForkJoinTasks and assign them to the ForkJoinPool.
1
2
3
4
5
6
7
8
9
10
11
protected void compute() {
        if(length < 1000 ) { //No need to Split the Task
            sumDirectly();
            return;
        }
        //Need to split the Task
        invokeAll(new SumArray(array, 0, length/2),
                new SumArray(array, length/2, length));
}