Friday, May 24, 2013

Advantages/Disadvantages of EJB

EJB Advantages
  • To access EJB free security is provided.
  • Declarative transactions are provided.
  • EJBs are cached & pooled. Containers manage the EJB life cycles.
  • Remote access capabilities are present & are clustered for sake of scalability.
  • OO concepts are supported for example inheritance.
  • Usage of attributes or annotation based programming is possible.
  • Free usage & access of complex resources


EJB Disadvantages
  • Complicated and large specification
  • Increased time of development
  • Complexities are added in comparison with straight Java classes
  • Potential to create a more essential, costly & complex solution
  • Continual revisions of the specifications
  • Lots of resources are used & have also lots of artifacts.
  • Requires understanding of certain intricacies. For example, granularity and rolling back a transaction, infrastructures like business delegates, value objects, session facades & strategies like dirty marker and lazy loading etc.

Tuesday, May 21, 2013

What is application context?

In context of the application... as in the domain of the application. Most of the time you will see people refer to settings being placed in an application context or a "global" scope of a program. A few people use the term loosely as "a place to put global data relevant to the application".

Hope this answers your question.

http://answers.yahoo.com/question/index?qid=20070212004858AA3TV2x

Saturday, May 18, 2013

What are JPA entities?


An Entity is roughly the same thing as an instance of a class when you are thinking from a code perspective or a row in a table (basically) when you are thinking from a database perspective.
So, it's essentially a persisted / persistable instance of a class. Changing values on it works just like changing values on any other class instance. The difference is that you can persist those changes and, in general, the current state of the class instance (entity) will overwrite the values the row for that instance (entity) had in the database, based on the primary key in the database matching the "id" or similar field in the class instance (entity).
There are exceptions to this behavior, of course, but this is true in general.

Friday, May 17, 2013

Why use Spring Framework ?

For a job interview, the info found in the Wikipedia should suffice:
http://en.wikipedia.org/wiki/Spring_framework

Look at the the "Dependency Injection" section.
Follow this logic:
  1. Eorget about Spring for a moment.
  2. Think about an application with many classes, where -as usual- each class depend on many others.
  3. Think about how you would instantiate those classes.
  4. Soon you realize that the way they are coupled together, makes it a nightmare to instantiate them.
  5. Moreover, if you are unit testing, you want to make it flexible enough so that you can change those dependencies with mock objects.
  6. You realize that factories are a good way of abstracting and centralizing those object creations.
  7. You think about centralizing all this, so that you only worry about the functionality of the classes, and let "something else" worry about all that creation boilerplate.
  8. That's when Spring comes. It's a centralized container for those objects. Those objects are just POJOs (or beans). Pretty simple.
  9. Spring is much more than a container, but that's for the dependency injection related stuff.


Cheers.

http://forum.springsource.org/showthread.php?113923-Why-use-Spring-Framework

Tuesday, May 14, 2013

What is dependency injection?


Basically, instead of having your objects creating a dependency or asking a factory object to make one for them, you pass the needed dependencies in to the constructor, and you make it somebody else's problem (an object further up the dependency graph, or a dependency injector that builds the dependency graph). A dependency as I'm using it here is any other object the current object needs to hold a reference to.
One of the major advantages of dependency injection is that it can make testing lots easier. Suppose you have an object which in its constructor does something like:
public SomeClass() {
    myObject = Factory.getObject();
}
This can be troublesome when all you want to do is run some unit tests on SomeClass, especially if myObject is something that does complex disk or network access. So now you're looking at mocking myObject but also somehow intercepting the factory call. Hard. Instead, pass the object in as an argument to the constructor. Now you've moved the problem elsewhere, but testing can become lots easier. Just make a dummy myObject and pass that in. The constructor would now look a bit like:
public SomeClass (MyClass myObject) {
    this.myObject = myObject;
}
Most people can probably work out the other problems that might arise when not using dependency injection while testing (like classes that do too much work in their constructors etc.) Most of this is stuff I picked up on the Google Testing Blog, to be perfectly honest...

Sunday, May 12, 2013

Stored Procedures vs Parameterized Queries [closed]


From the .NET tag (and only from the tag) I'm going assume SQL Server here. Parametrized queries are excellent for projects that have a single application and modest security requirements. The require less effort to set up, and many ORM systems are going to use them if you like it or not.
On the other hand, if your database is handled by multiple applications and you need to enforce consistency of access, or if you need complex security (partial access to tables, either by column or by row or both) you should be using stored procedures. They allow you to enforce your security requirements and provide a consistent interface so applications don't violate your data rules.
As far as performance goes, I haven't noticed enough difference between the two to care these days: parametrized queries plan caching seems to work well enough.

The difference between ++Var and Var++ [duplicate]


When ++var or var++ form a complete statement (as in your examples) there is no difference between the two. For example the following
int x = 6;
++x;
assert x == 7;
is identical to
int x = 6;
x++;
assert x == 7;
However, when ++var or var++ are used as part of a larger statement, the two may not be equivalent. For example, the following assertion passes
int x = 6;
assert ++x == 7;
whereas this one fails
int x = 6;
assert x++ == 7;
Although both var++ and ++var increment the variable they are applied to, the result returned byvar++ is the value of the variable before incrementing, whereas the result returned by ++var is the value of the variable after the increment is applied.
When used in a for loop, there is no difference between the two because the incrementation of the variable does not form part of a larger statement. It may not appear this way, because there is other code on the same line of the source file. But if you look closely, you'll see there is a ; immediately before the increment and nothing afterwards, so the increment operator does not form part of a larger statement.

How to convert a char to a string in Java?


Note that this method simply returns a call to String.valueOf(char), which also works.
As others have noted, string concatenation works as a shortcut as well:
String s = "" + 's';
http://stackoverflow.com/questions/8172420/how-to-convert-a-char-to-a-string-in-java

Spring Framework


Hibernate is an Object Relational Mapping tool, an alternative to Sun's Entity Beans 2.0. Hibernate has become over the years a "de facto standard" for object persistence in Java and today's JPA API is highly inspired by Hibernate (which can be used as JPA implementation).
Spring is a dependency injection framework which allows you to wire components and to benefits from additional services like declarative transaction management, declarative security, integration with many other frameworks, abstraction layers etc. Spring has been created to ease Enterprise Java applications development and to make it possible without EJBs and a "heavyweight" container. With Spring and Hibernate and e.g. Tomcat, you get a nice Enterprise stack. Spring is a "lightweight" container.
Spring and Hibernate have heavily influenced the way we build Java application and their adoption are the proof of the need for simplification. Despite, I see JEE 5 as Sun's answer to these "non standard" solutions to simplify Java Enterprise development.
So yes, Spring Hibernate are widely used together and Spring offers Hibernate (and JPA) integration but Spring and Hibernate are two different projects with separated board and governance. They have mutual interests but IMO the Hibernate Team manages Hibernate, the Spring Team manages Spring.

Plain English explanation of Big O


Quick note, this is almost certainly confusing Big O notation (which is an upper bound) with Theta notation (which is a two-side bound). In my experience this is actually typical of discussions in non-academic settings. Apologies for any confusion caused.

The simplest definition I can give for Big-O notation is this:
Big-O notation is a relative representation of the complexity of an algorithm.
There are some important and deliberately chosen words in that sentence:
  • relative: you can only compare apples to apples. You can't compare an algorithm to do arithmetic multiplication to an algorithm that sorts a list of integers. But two algorithms that do arithmetic operations (one multiplication, one addition) will tell you something meaningful;
  • representation: Big-O (in its simplest form) reduces the comparison between algorithms to a single variable. That variable is chosen based on observations or assumptions. For example, sorting algorithms are typically compared based on comparison operations (comparing two nodes to determine their relative ordering). This assumes that comparison is expensive. But what if comparison is cheap but swapping is expensive? It changes the comparison; and
  • complexity: if it takes me one second to sort 10,000 elements how long will it take me to sort one million? Complexity in this instance is a relative measure to something else.
Come back and reread the above when you've read the rest.
The best example of Big-O I can think of is doing arithmetic. Take two numbers (123456 and 789012). The basic arithmetic operations we learnt in school were:
  • addition;
  • subtraction;
  • multiplication; and
  • division.
Each of these is an operation or a problem. A method of solving these is called an algorithm.
Addition is the simplest. You line the numbers up (to the right) and add the digits in a column writing the last number of that addition in the result. The 'tens' part of that number is carried over to the next column.
Let's assume that the addition of these numbers is the most expensive operation in this algorithm. It stands to reason that to add these two numbers together we have to add together 6 digits (and possibly carry a 7th). If we add two 100 digit numbers together we have to do 100 additions. If we add two 10,000 digit numbers we have to do 10,000 additions.
See the pattern? The complexity (being the number of operations) is directly proportional to the number of digits n in the larger number. We call this O(n) or linear complexity.
Subtraction is similar (except you may need to borrow instead of carry).
Multiplication is different. You line the numbers up, take the first digit in the bottom number and multiply it in turn against each digit in the top number and so on through each digit. So to multiply our two 6 digit numbers we must do 36 multiplications. We may need to do as many as 10 or 11 column adds to get the end result too.
If we have two 100-digit numbers we need to do 10,000 multiplications and 200 adds. For two one million digit numbers we need to do one trillion (1012) multiplications and two million adds.
As the algorithm scales with n-squared, this is O(n2) or quadratic complexity. This is a good time to introduce another important concept:
We only care about the most significant portion of complexity.
The astute may have realized that we could express the number of operations as: n2 + 2n. But as you saw from our example with two numbers of a million digits apiece, the second term (2n) becomes insignificant (accounting for 0.0002% of the total operations by that stage).
The Telephone Book
The next best example I can think of is the telephone book, normally called the White Pages or similar but it'll vary from country to country. But I'm talking about the one that lists people by surname and then initials or first name, possibly address and then telephone numbers.
Now if you were instructing a computer to look up the phone number for "John Smith" in a telephone book that contains 1,000,000 names, what would you do? Ignoring the fact that you could guess how far in the S's started (let's assume you can't), what would you do?
A typical implementation might be to open up to the middle, take the 500,000th and compare it to "Smith". If it happens to be "Smith, John", we just got real lucky. Far more likely is that "John Smith" will be before or after that name. If it's after we then divide the last half of the phone book in half and repeat. If it's before then we divide the first half of the phone book in half and repeat. And so on.
This is called a binary search and is used every day in programming whether you realize it or not.
So if you want to find a name in a phone book of a million names you can actually find any name by doing this at most 20 times. In comparing search algorithms we decide that this comparison is our 'n'.
For a phone book of 3 names it takes 2 comparisons (at most).
For 7 it takes at most 3.
For 15 it takes 4.
...
For 1,000,000 it takes 20.
That is staggeringly good isn't it?
In Big-O terms this is O(log n) or logarithmic complexity. Now the logarithm in question could be ln (base e), log10, log2 or some other base. It doesn't matter it's still O(log n) just like O(2n2) and O(100n2) are still both O(n2).
It's worthwhile at this point to explain that Big O can be used to determine three cases with an algorithm:
  • Best Case: In the telephone book search, the best case is that we find the name in one comparison. This is O(1) or constant complexity;
  • Expected Case: As discussed above this is O(log n); and
  • Worst Case: This is also O(log n).
Normally we don't care about the best case. We're interested in the expected and worst case. Sometimes one or the other of these will be more important.
Back to the telephone book.
What if you have a phone number and want to find a name? The police have a reverse phone book but such lookups are denied to the general public. Or are they? Technically you can reverse lookup a number in an ordinary phone book. How?
You start at the first name and compare the number. If it's a match, great, if not, you move on to the next. You have to do it this way because the phone book is unordered (by phone number anyway).
So to find a name:
  • Best Case: O(1);
  • Expected Case: O(n) (for 500,000); and
  • Worst Case: O(n) (for 1,000,000).
The Travelling Salesman
This is quite a famous problem in computer science and deserves a mention. In this problem you have N towns. Each of those towns is linked to 1 or more other towns by a road of a certain distance. The Travelling Salesman problem is to find the shortest tour that visits every town.
Sounds simple? Think again.
If you have 3 towns A, B and C with roads between all pairs then you could go:
A -> B -> C
A -> C -> B
B -> C -> A
B -> A -> C
C -> A -> B
C -> B -> A
Well actually there's less than that because some of these are equivalent (A -> B -> C and C -> B -> A are equivalent, for example, because they use the same roads, just in reverse).
In actuality there are 3 possibilities.
Take this to 4 towns and you have (iirc) 12 possibilities. With 5 it's 60. 6 becomes 360.
This is a function of a mathematical operation called a factorial. Basically:
5! = 5 * 4 * 3 * 2 * 1 = 120
6! = 6 * 5 * 4 * 3 * 2 * 1 = 720
7! = 7 * 6 * 5 * 4 * 3 * 2 * 1 = 5040
...
25! = 25 * 24 * ... * 2 * 1 = 15,511,210,043,330,985,984,000,000
...
50! = 50 * 49 * ... * 2 * 1 = 3.04140932... × 10^64 
So the Big-O of the Travelling Salesman problem is O(n!) or factorial or combinatorial complexity.
By the time you get to 200 towns there isn't enough time left in the universe to solve the problem with traditional computers.
Something to think about.
Polynomial Time
Another point I wanted to make quick mention of is that any algorithm that has a complexity of O(na) is said to have polynomial complexity or is solvable in polynomial time.
Traditional computers can solve polynomial-time problems. Certain things are used in the world because of this. Public Key Cryptography is a prime example. It is computationally hard to find two prime factors of a very large number. If it wasn't, we couldn't use the public key systems we use.
Anyway, that's it for my (hopefully plain English) explanation of Big O (revised).

Saturday, May 11, 2013

Why should i use EJB? [closed]


In the commercial world, EJBs have almost totally been supplanted by Spring. The advantage of Spring is that it can be run inside a simple Web container like Jetty or Tomcat whereas EJBs (pre-3.1) require a J2EE application server (eg Websphere, Weblogic, JBoss, Glassfish), which has a larger footprint.
EJBs do a couple of things well, most especially stateless session beans, which can be an efficient avenue for distributed transactions.
EJB since 3.0 has been split into two parts: the EJB spec and the JPA spec. JPA (Java Persistence API) is as the name suggests the persistence part of the API. This is really commonly used in libraries like EclipseLink, Hibernate and Toplink. Hibernate is the most popular and predates JPA but the differences aren't so large.
JPA is a form of ORM (object-relational mapper) of projecting an object model onto a relational database.
JPA is, in my experience, used much more commonly than EJB.

Thursday, May 9, 2013

In Java, what purpose do the keywords `final`, `finally` and `finalize` fulfil?


final

final can be used to mark a variable "unchangeable"
private final String name = "foo";  //the reference name can never change
final can also make a method not "overrideable"
public final String toString() {  return "NULL"; }
final can also make a class not "inheritable". i.e. the class can not be subclasses.
public final class finalClass {...}
public class classNotAllowed extends finalClass {...} // Not allowed

finally

finally is used in a try/catch statement to execute code "always"
lock.lock();
try {
  //do stuff
} catch (SomeException se) {
  //handle se
} finally {
  lock.unlock(); //always executed, even if Exception or Error or se
}
Java 7 has a new try with resources statement that you can use to automatically close resources that explicitly or implicitly implement java.io.Closeable or java.lang.AutoCloseable

finalize

finalize is called when an object is garbage collected. You rarely need to override it. An example:
public void finalize() {
  //free resources (e.g. unallocate memory)
  super.finalize();
}
http://stackoverflow.com/questions/7814688/in-java-what-purpose-do-the-keywords-final-finally-and-finalize-fulfil

What exactly we mean by Precompiled SQL Statement

If a statement is used multiple times in a session, precompiling it provides better performance than sending it to the database and compiling it for each use. The more complex the statement, the greater the performance benefit.
If a statement is likely to be used only a few times, precompiling it may be inefficient because of the overhead involved in precompiling, saving, and later deallocating it in the database.
Precompiling a dynamic SQL statement for execution and saving it in memory uses time and resources. If a statement is not likely to be used multiple times during a session, the costs of doing a database prepare may outweigh its benefits. Another consideration is that once a dynamic SQL statement is prepared in the database, it is very similar to a stored procedure. In some cases, it may be preferable to create stored procedures and have them reside on the server, rather than defining prepared statements in the application.

http://www.coderanch.com/t/299852/JDBC/databases/Precompiled-SQL-Statement

Compile time polymorphism

Hi Rajan,
Thats perfectly right. You need to *understand* the polymorphism concepts first.

Poly - many, morphism - faces.

The ability to have more than one version of the executable piece of code in the same name to invoke is called POLYMORPHISM.

view plaincopy to clipboardprint?
  1. Actually speaking the compiler would create a binding between the place of calling and the method definition.  


The ability to take a decision and thereby creating the binding is what gives you the name. 

The Compile time polymorphism comes in such a way that the compiler is able to differentiate the exact version of code to invoke during the compile time itself. Rather, the compiler *can take a decision of which exact method to invoke* during the compile time itself. 

Whereas in Runtime Polymorphism, the compiler is unable to take such a decision during compilation. Moreover, compiler-is-left-free-for-that-sake until runtime with which it can decide and invoke the appropriate version of the method.

Only when Inheritance is in picture, you can very well play around with the Polymorphism as you are given the rights to assign the child class objects to any of its parent/super class references. 

I hope this clears your doubt!