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

Tuesday, June 23, 2015

Better way to check if String is empty: length() vs equals()


Empty?

It's quite a common and necessary thing to check if the string is empty or not. Different people use different things. Interviewer tries to check by giving you two ways to do it and ask you which one is better and why?

Let's see the two ways below, In fact we have isEmpty() function also, but interviewer is not interested in that.



On the face of it, both seems fine. Aren't they? So why is 2nd one not preferred way?

Simple. Check the Java code for equals() and length(). length() is simple and less time and memory. equals() takes more time and resources. 

length() just returns the count of characters. (isEmpty() also does length() == 0 check)
equals() used while loops, temporary arrays, typecasting and reference checks, which makes it unnecessary for this use case.



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

Saturday, June 20, 2015

Story behind naming of JAVA

THE JAVA EFFECT!
Have you ever wondered what does JAVA stands for? What is the full form? Who named it? Well, time to quell the anxieties. As per James Gosling, the story goes something like.

Initially the working title was named 'Oak', randomly on a oak tree outside the office. When it came to legalities, Trademark Lawyers found it infeasible. The product was ready. But now they were left without a name to package it.

Without time or resources to spend on naming the product, a naming consultant locked a dozen of the team members into a room and start asking questions, "How does this product makes you feel like?". Obvious answer was excited!. Then the question, "What else makes you feel the same?" Coffee! Java! After a lot of questions and lots of answers, they prepared a list, which was send to the lawyers for vetting.

Initial names like 'Silk' was rejected. The fourth on the list, 'Java' was approved. The very next option and Gosling's favourite was 'Lyric'. How would you have liked to work on LYRIC?

As per Gosling, he can't be sure who shouted JAVA during the session, but his best guess is Mark Opperman.

Friday, June 19, 2015

AWS Lambda: Introduction

AWS Lambda (Amazon Web Services Lambda) is a service that manages compute resources and runs the code within milliseconds of trigger. Say if someone uploads an image from an app. Applications running using AWS are able to run the code almost real time.

We can also create back-end services and trigger compute resources automatically (w/o direct user input). 

One has to pay as per the compute time and requests served. This sounds a good thing for small entities looking to build applications without provisioning infrastructure. For web/mobile applications handling huge traffic, AWS claims to process within milliseconds. 

You can try it put for free. AWAS Lambda offers 1,000,000 requests and upto 3.2 millions seconds for free. 

With the trust of Amazon, this seems to be an interesting option.

Best is that there is no need to buy custom hardware and keep it (even when it is idle). If you are starting up your startup, best is to take advantage of AWS Lambda. This is real time (almost) and highly cost effective.

Write the code and upload the code. Everything else is taken care of. It has fault-tolerant with multiple redundancies of data built-in. You can write your code in Java. 

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));
}