Feb 28, 2011

Java Application Development Blame Game

A Case of Blame Game


Recently, a colleague was given an assignment to prepare the Low Level Design (LLD) document for an enhancement request from the customer. The guy is very experienced (8+ years) and had been frequently working on design and coding assignments.


He prepares the document and passes to the design document reviewer. The reviewer cross checks the requirements with High Level Document (HLD) and approves the LLD with some suggestions. The LLD document is given to the developer. 


In the meantime, the architect who is responsible for high level design changes his mind and provides a new version of the High Level Design (HLD) document. Now the guy preparing LLD gets confused about the complex logic that was present earlier and the new thinking from the architect.


Not to delay the preparation of LLD and pressure from the manager, he quickly makes changes to his earlier version of LLD by looking at the newer version of HLD and passes to the reviewer. (This time they have an informal discussion about the changes while having evening tea)
The reviewer having so much to review has a look at the logic and approves with cosmetic changes. (May be just to show off). The developer completes the code on time and everyone is happy.


The System Tester uses HLD for cross checking the logic on which various requests are generated depending upon the selections being made for the various fields on the current page. Boom! There is a flaw in the logic being developed and the bug gets escalated.


Bug review meeting is held between the project lead, team leads and testing manager. The manager responsible for the delivery of the module is asked about the quality of work being done. He is told that his team is not paying attention to the requirements.


The team lead comes back and has a meeting with LLD Designer, LLD Reviewer, Code Developer and Code Reviewer (same as LLD Reviewer).


LLD Designer:  I had done the changes as per the HLD. But the logic was not clear and the HLD designer sitting at the remote location didn't reply to my queries in a timely manner.
LLD Reviewer: I had reviewed whatever was given to me in order to check that the LLD is understood by the developer easily. I was told by LLD designer that the logic is correct. Even we had an informal discussion on this
Code Developer: I have written my code according to the LLD. How can I be responsible for some mistake in LLD?
Code Reviewer: I had reviewed the code according to LLD and since they were in sync, I approved it.


The manager is most furious with the Reviewer because he is involved in LLD Review and Code Review. The manager argues that there are bound to be mistake in LLD or Code and his job was to review. If he has not caught the fallacy in LLD then what is the purpose of reviews.

Who do you think is responsible for poor feedback from the customer?


Feb 27, 2011

How to Initialize String Array in Java

How to Initialize String Array in Java
An array of Strings is just like any other array but has String objects as its elements. As with other kind of arrays, the String array can be initialized is declared as:
String[] strArray;

Here we are declaring strArray as a reference variable. At this point, no memory has been allocated to any String object.

To initialize a String array, we need to use the new operator as shown below:
String[] strArray = new String[10];


We need to specify the size of array at compile time (while writing the program). We could also use constants in order to specify the size of the array being created. The constants can be created by using the final variable.

After using the above statement, 10 String objects are created and are initialized to null.

To provide values to each of the String object, use the index of the array as shown below:
strArray[0] = "Str1";
strArray[1] = "Str2";

...........................
strArray[9] = "Str10"

 Other way to initialize string objects in a string array, the following piece of code can be used:
String[] strArray = new String {"str1",>"str2","str3",str4","str5","str6","str7","str8",>"str9","str10",};


Here we are defining a String array object and providing values to individual String objects as well.

Feb 26, 2011

SOLID - OOPS/OOAD Principle

SOLID - OOPS/OOAD Principle

The Object Oriented concepts in all OOPS language follow some common principles. These principles are guidelines for developers and architects which they need to understand as they grow their understanding of the language.

The SOLID principles are the most talked about in the Enterprise Java world. These principles deal with cohesion, coupling, inheritance, abstract types in the Object Oriented Analysis and Design (OOAD)

The five principles are also asked about in Java or JEE interview. SOLID is an acronym for 5 principles of the Java language which are listed here:

1) S - Single Responsibility Principle: This principle is very closely related to the highly cohesive design methodology. This principle says that each class, method and variable should have single responsibility to perform. If there are multiple responsibilities assigned to a class then it becomes very difficult to maintain as the Java application scales. So sufficient time should be given to think what responsibility will be assigned to which class, method or variable.

2) O - Open Closed Principle: This principle says that when a class is inherited by other class then the superclass should not be a candidate for change just because it is going to be inherited by some other class. Thus it can be said that a class may be open for inheritance but closed for change because of inheritance.

3) L - Liskov Substitution Principle: This principle says that when multiple classes inherit or implement a class/interface and we have reference of super type which references to an object of one of the sub type then changing the subtype object from one class to another should not make any change.
Vehicle v = new Suzuki();
v = new Benz();
The change of object in the above Java sample code should not make any change to the various methods being invoked other than the fact that the methods will now be invoked on Benz object instead of the Suzuki object.

4) I - Interface Segregation Principle: This principle says that instead of having a big fat interface or class, split the functionality into multiple parts.This is different from the Single Responsibility Principle because even if a class has a single responsibility, it can be split into multiple parts for better understanding and maintainability. One common method to split a fat class is to make it implement/inherit other thin interface/class.

5) D - Dependency Inversion Principle: This principle is very much similar to the Open Closed Principle it states that the super type should not be dependent on the sub type but the sub type should be dependent on the super type. The above is possible if abstract entities are super types and concrete types as sub types. The sub types can anytime changed without affecting the super types.

Here is the analysis for the above discussion:

S and I are similar but with the difference that I can be used when S makes a single class grow fat. I have seen some classes having 2000 lines of code and 10-15 methods. It really makes life Hell

O, L and D are similar but O to not changing the super type just because of inheritance relationship, L asks us to make sure that multiple sub type objects are substitutable for a reference of super type and D emphases on coding to interfaces or abstract classes

Feb 25, 2011

Java Language Basics Exercise

 Java Language Basics Exercise

In continuation to the first part of the exercises for Java Beginners who want some exercise to make them write code, here is the second part of the exercise which introduces interfaces, classes, methods and flow control in Java.

One can use this exercise after going through a good Java book. Head First Java and Effective Java are recommended.

Note: The solution and extension of this exercise for further Java concepts is coming soon...

The second part of the exercise follows:


1)    See if you can provide any name for the .java files corresponding to classes GenericBank, HdfcBank and Test. Can you use Industry.java as file name for the public class HdfcBank. What if you make the class HdfcBank  as default
2)    Can the interface WithdrawContract inherit DepositContract?
3)    Try using final, private modifiers with the WithdrawContract interface declaration. After that revert back to public access specifier.
4)    Try using the following syntax for the main method in the Test.java class and see which are valid what is not:
static public void main (String  []args)
static public void main (String[]  s)
static public int main (String[] args)
private static void main (String[] args)
public void main (String[] args)
5)    You may have guessed that a customer will not come to GenericBank. Mark that class as abstract. Now no one will be able to create instance of GenericBank class. Have you got a compiler error in the Test class corresponding to the hb1 instance variable?
6)    Mark the method checkbalance as abstract in the GenericBank class? How will you resolve these new compiler errors?
7)    Now the HDFC Bank has decided to add some extra checks while depositing and withdrawing money and they intend to provide their own version of withdraw and deposit methods. What should they do? They do not want to stop inheriting the GenericBank class as it will provide them extra services in the future.  They want to use the same method name as in GenericBank class. Have you heard of overloading? Add those methods in HdfcBank class and don’t remove them from the GenericBank class.
8)    What is the name given to the kind of methods added in HdfcBank class in step 7 above?
9)    Add a method public void maximumwithdraw() in WithdrawContract interface and public void maximumdeposit in DepositContract. These methods will be called before withdraw and deposit of funds into an account. Make the HdfcBank class to implement these interfaces. The HdfcBank class will have to provide an implementation of these methods. For this exercise, you can assume a maximum limit of Rs 50000 for withdraw as well as deposit. If the limit crosses the maximum allowable amount. Throw a RuntimeException.
10)  The contract methods maximumwithdraw and maximumdeposit could have been written in an abstract class also. The HdfcBank class could have inherited that class then why interfaces have been choose. Recall the difference between abstract class and interfaces, multiple inheritance and diamond problem here.
11)  Try to play with the methods declared in Withdraw_Contract and Deposit_Contract interfaces. Can you declare them private or final or protected or static? Think of the reason in every scenario.


Exercise for Object-Oriented Programming Concepts

Exercise for Object-Oriented Programming Concepts

For all those programmers who are new to Java and have read some book but need some Java exercise or Java Tutorial can use this first write up to begin writing Java programs. You can read the steps and accordingly write your code. There will be some steps which I have not mentioned (like the name of your Java project if using a Java IDE). You can either use what you feel comfortable or leave query in the comments. The solution can be found at Object Oriented Exercise Solution

Basically, I am covering Inheritance, Abstraction, Data Hiding and Polymorphism in this Java OOPS exercise.


1) Write a program where public class HdfcBank inherits another public class GenericBank. Create one more public class Test.java which has the main method which is used for creating reference variables and calling member methods on the instance variables. See if you can declare a reference variable of super class which references to the subclass object (something like GenericBank hb = new HdfcBank())
Also declare one more instance variable as GenericBank hb1 = new GenericBank()
2) Add a method public void welcome (which prints Welcome) in the GenericBank class.  Are you able to call the super class method using the hb and hb1 reference variables? What happens at runtime?
3) Add the method public void welcome (prints Welcome to HDFC Bank) in the HdfcBank class. Call the method Welcome using the hb and hb1 instance variables. Have you now got an idea of how runtime polymorphism works?
4) Create one more class SocialBank, try to inherit the HdfcBank class from GenericBank and SocialBank classes. Why that is not allowed. Is it the diamond problem?
5) Add two interfaces WithdrawContract and DepositContract. Are you able to implement these interfaces from HdfcBank class?
6) Add an instance variable bankbalance to the GenericBank class. Will you make that variable private, protected, default or public?
7) Add a method public void deposit (int amount) in the GenericBank class. Call this method using the hb instance variable.
8) Add a method public void withdraw (int amount) in the GenericBank class. Call this method using the hb instance variable.
9) Add a method public void checkbalance (int amount) in the GenericBank class. Call this method using the hb instance variable.
10) Add more versions of these methods as listed below as the amount can be in float numbers also:
public void deposit (double amount)
public void withdraw (double amount)
public void checkbalance (double amount)
Is it also a form of polymorphism? What is the name given to such methods?
11) Can you guess the benefit of adding the methods deposit, withdraw and checkbalance? You could also have made the bankbalance instance variable as public and performed various arithmetic operations by accessing that variable from anywhere? Is this data hiding?
12) The Test class simulates the customer of the bank. Can you think of a situation where the customers have to manage the workflow of the bank? Is the use of HdfcBank class for maintaining balance and providing operations on the account provides an abstraction for the customer? (The code in HdfcBank could also have been written in the Test class itself)

My List of Top 20 Java Related Books

My List of Top 20 Java Related Books

We come across many Java books (Be it Enterprise Java, Java Frameworks or Software Engineering) frequently. Every Programming/Technology author and publisher tries to format the book in a way which makes it unique and doesn't repeat what already is available in the market for Java developers.

Here is my list of top 20 books on Java related technologies:



Core Java:
1) Core Java Fundamentals (Volume 1 and Volume 2)
Core Java, Vol. 2: Advanced Features, 8th Edition

2) The Complete Reference : Java
Java The Complete Reference, Seventh Edition (Osborne Complete Reference Series)

3) A Programmer's Guide to Java Certification : Khalid Mughal
 A Programmer's Guide to Java SCJP Certification: A Comprehensive Primer (3rd Edition)
4) OCPJCP for Java Study Guide : Kathy Sierra and Bert Bates
SCJP Sun Certified Programmer for Java 5 Study Guide (Exam 310-055)
5) Java Pitfalls and More Java Pitfalls
More Java Pitfalls: 50 New Time-Saving Solutions and Workarounds
6) Taming Java Threads
Taming Java Threads
Enterprise Java and Frameworks

7) Head First Servlets and JSP
Head First Servlets and JSP: Passing the Sun Certified Web Component Developer Exam
8) EJB 3 in Action
EJB 3 in Action
9) Struts in Action
Struts 2 in Action

 10) Spring in Action
Spring in Action
11) Web Services Essentials - SOAP, UDDI and WSDL
Web Services Essentials (O'Reilly XML)

12) XML Bible
XML 1.1 Bible
13) Teach Yourself EJB in 21 Days
Sams Teach Yourself EJB in 21 Days
Design Patterns and Methodologies
14) Head First Design Patterns
Head First Design Patterns
15) Agile in a Flash
Agile in a Flash: Speed-Learning Agile Software Development (Pragmatic Programmers)

16) Teach Yourself UML in 24 Hours
Sams Teach Yourself UML in 24 Hours, Complete Starter Kit (3rd Edition)
17) Object Oriented Software Construction
Object-Oriented Software Construction (Book/CD-ROM) (2nd Edition)
Servers
18) JBoss : A Developer's Notebook
JBoss: A Developer's Notebook
19) Tomcat : The Definitive Guide
Tomcat: The Definitive Guide
Tools and Utilities
20) ANT in Action
Ant in Action: Covers Ant 1.7 (Manning)

Feb 23, 2011

Force Subclass to Override Method From Concrete Class

How will you force the subclasses of a concrete class to override a method?

There is no such real world scenario where a concrete entity will want to force a more specific entity to override its method. If it is to be overridden then why not make the super class as abstract.

Anyways, the logic behind the interview questions being asked now a days is something which requires best talent from the psychology field.

Solution: The solution which I have come up with for the above Java Interview question is to use the instanceof operator in the super class and throw an exception if the instance on which method is being invoked is found to be of the sub class. The sample program showing this scenario follows:

Though still its not like generating compile time error but gives exception at runtime.  Do suggest if you have a better solution.

public class Test{

   void test() {
    if ((this instanceof Test1)) {
     throw new RuntimeException();
    }
    System.out.println("passed");
   }
   
   public static void main(String[] args) {
    Test t1 = new Test();
    Test1 t2 = new Test1();
    
    t1.test();
    t2.test();
   }
 
}
class Test1 extends Test {

}

The output of above program is:

passed
Exception in thread "main" java.lang.RuntimeException
 at Test.test(Test.java:5)
 at Test.main(Test.java:15)

Feb 22, 2011

How Many Programming/Technology Hells Have You Seen

How Many Programming/Technology Hells Have You Seen

Every approach has its pros and cons but when something becomes too difficult to handle and that to frequently, it becomes a hell for us.

So a hell is nothing but a problem that comes back to you without any fault from writing the code but because of using some methodology or standard.

The problems with various approaches become more painful when the application scales.

Here are some common hells. Probably you may like to add more to the list.


1) DLL Hell:
A kind of dependency hell where Windows can't locate a DLL when you start or use an application


2) XML Hell:
You keep on adding XML's and at a later stage find it very difficult to maintain (Reason why annotations in EJB3 came up)


3) Jar Hell:
After all the classloader have run, the required dependent class in a particular jar has not been loaded.
Or
There are so many versions of Jar files released which confuses you about the right version of jar to use.


4) Meta Data Hell:
All those who have used annotations for hard coding various kind of stuff have felt this hell.


5) Redirect Hell:
This relates to extra processing by various websites before  being actually shown the page being sought. Google, Yahoo, MSFT, Facebook, Twitter- all do such things and sometimes frustrate us.


6) Dependency Hell:
Have you ever installed a game and found that the version of DirectX you have is not compatible with the game. You need to download and install the proper version.


Absurd Java Interview Question - Inner Classes

Inner Class Nested Levels In Java

Can we have inner classes within other inner classes in Java?

As always, interviewers don't ask about actual work to be done but rather some absurd questions.:(

How frequently does one see inner classes being used in an application leave aside inner classes at nested levels.


Yes one can have as many nested level of inner classes . The code below proves it.
However, the usability of this code is debatable. 

public class Test{

    class a1{
        class a2{
            class a3{
                class a4{
                }
            }
        }
    }

    public static void main(String[] args) {
Test.a1.a2.a3.a4 abc = new Test().new a1().new a3().new a4().new a6();
    }
}

Feb 21, 2011

Abstract Classes Have Constructors

Abstract Classes Have Constructors 


1) In Java , we have default constructors provided for classes by the compiler (in case one is not declared).

2) The abstract classes can't be instantiated by using the new operator because they don't provide full implementation of all the methods.

Then does it make sense to have constructors inside abstract classes. Let us find it using a sample abstract class:
public abstract class Test{
   public abstract void doSomething();
}
The decompiled code for this class will show the truth about constructors in abstract classes in Java
public abstract class Test
{
    public Test()
    {
    }
    public abstract void doSomething();
}
Woha!! that constructor was provided by Java. Why?

The reason is that when a class extends any other class and an instance of the subclass is created then the constructor calls are chained and the super class constructors are invoked. This rule is no exception for abstract class

Moreover, having constructors in a class doesn't necessarily mean that instance of that class will be created using the new operator, but the constructors are intended for writing any initializing code.

Feb 19, 2011

When (not) to Use the Java Enterprise Frameworks

When  (not) to Use the Java Enterprise Frameworks

The first advice is that one should not add Spring, EJB, Struts, Rule Manager or any other framework until convinced. Every Java/JEE project has its own needs. By adding the latest framework or third party tool one may be able to boast of using the latest technology in the project but the results may not  be what the customer expected.

Moreover, the time and budget constraints play a crucial role in deciding what framework to use. If you have ample time then you can keep on looking for tools which can perform your task much easier but even then performance should be taken into consideration.

Spring is the latest buzz word in the Java enterprise applications. Almost every requirement that we see posted on job portals requires experience in Spring. Of course, Spring can make an application easier to code and also bring in more maintainability but it will affect the performance.

If I have say a log analyser application wherein I need to parse the log file and display where piece of information in the graphical format. This kind of application does not have any enterprise requirements like Transaction management, Security, Multi-threading or life-cycle management. So it does not make sense to include the Spring or EJB in this kind of application.

Though it is true that Spring brings in loose coupling between the classes which is required for maintaining the application. But coupling between classes can be handled without any framework to some level. It’s when the application grows to a level that there are 100 classes, the need for framework arises.

So it is always advised by the Java Gurus to judge the requirement before going in to choose a particular framework. Pick the framework which suits your application requirements and not just the latest in the market.

An application which will generate DAO and DTO for another application is not a good candidate for enterprise frameworks like Spring and EJB. But an application which manages the identities of users on applications like Lotus Notes, PeopleSoft or SAP is a good candidate for the enterprise frameworks. 

A good example will be if the application requires good performance, security but doesn't require services like thread management or lifecycle management then one can consider using PL/SQL procedures and LDAP for its requirements instead of not using the extra services which will be overhead when an framework is used.

The common factors to be considered before deciding the framework for an application are:
1) Do you want to have transaction to be managed? This is meaningful in case you have lot of database READ and UPDATE operations
2) Do your users invoke the application at same time?
3) Do you see the number of users increasing in the future?
4) What is the number of classes in your application?
5) Is your application more of a utility application than an enterprise application?

Feb 18, 2011

25 Interview Questions for Java Developers

25 Interview Questions for Java Developers

Core Java
1) Tell me about your technical experience. Tell more about the technologies and projects that you have worked on?
2) What is the difference between HashMap and Linked HashMap
3) What is the difference between comparable and comparator interfacs?
4) What is hashcode and equals contract?
5) What are sorted collections in Java
6) What is the application server you have used? (They are working on weblogic server)
7) Have you worked on web services?

Web Services
Since I had worked on Rest web services
8) What is the difference between PUT and POST request
9) What is the difference between SOA and REST web services
10) Have you worked on any other framework than RESTLET.

EJB
11) What are the benefits of EJB 3
12) Why will you use EJB in an application.
13) Can I have an application where I have session beans and not entity beans? What purpose will session beans serve to me?
14) If I have a reporting application, will it be a good decision to choose EJB's for this application. There are going to be more read operations in this application?
15) What is the difference between writing database logic using DAO, DTO design patterns using JDBC than EJB?
16) What are interceptors in EJB

Servlets
17) What are filters in servlets
18) What are listeners in servlets

Optional
19) What is AJAX? (They use AJAX in the web pages...good to have)
20) Have you worked on Javascript?

Database
21) What is an outer join?
22) What are the various normalization forms and which level of normalization in what case?
23) Have you worked on SQL and PL/SQL?

Analytical
24) I have 50 consecutive numbers starting from 1 to 50 and one number is missing. How will you find the missing number?
25) What if I have 2 numbers missing, then how will you find both of them?

Feb 17, 2011

What is The Difference Between EJB 3.0 and EJB 2.0

1) In EJB3, one can move most of the deployment descriptors of EJB2 in the code itself by using Annotations.
2) One can also avoid writing the common code like Home/Remote interfaces and can use annotations for the same.
3) The container takes care of life cycle methods because in EJB2 we need to declare the life cycle methods like ejbActivate, ejbPassivate, ejbCreate etc. Any method can be made life cycle method by using the proper annotation.
4) Entity Beans in EJB3.0 are POJO and being referred to as JPA entities which makes Entity beans lightweight.
5) The EJB's in EJB 3.0 can extend other EJB's but that is not the case with EJB 2.0
6) EJB 3.0 integrates with ORM tools seamlessly but EJB 2.0 did not provide any support to integrate with ORM tools.
7) EJB 3.0 provides DI for clients invoking the EJB's
8) EJB3.0 provides timer service, interceptors which were not present in EJB 2.0

Feb 15, 2011

Prepared Statement Misconceptions

Using JDBC Prepared Statements in Java

I will start with the basics. For those who are not aware of bind variables in databases, let me clarify that bind variables mean that the SQL query is compiled and ready for execution from second time onwards. One just needs to provide the values for the placeholder variables in the query. Every time an SQL query is run, the database engine will not parse and compile the query. Instead it can use the pre-compiled query stored in the database.

The best thing about using bind variables is that it does not matter from where the query was sent to the database for the first time. This means that if the query was fired by a Java application, the same query with bind variables can be used by.net application. This is because the database engine does not differentiate between the applications which are using the data from the database.



Digxa shopping comparison site. Dig for the best price on products worldwide.

Get This Widget

If you're using any database and running a Java application, which makes use of JDBC calls to retrieve or update records then you may be aware that the PreparedStatement allows one to send the query only once and then different values can be used in place of the place holders in the query.

But a common misconception in Java Developer’s is that the PreparedStatement always means the use of bind variables and it always results in increasing performance.

Let us take the first point: One can pass values in the SQL query used to with the instance for PreparedStatement. This means that PreparedStatement will act just like a Statement object. Thus the PreparedStatement does not always mean the use of bind variables.

Now coming to the second point, the use of bind variables in PreparedStatement results in increased the performance only when the SQL query passed to the PreparedStatement object is run in a batch of is run a number of times. If the query is to be run only a few numbers of times then it's better to use a statement of object. This is because the use of PreparedStatement results in extra processing by the database which can hamper the performance in case the query is to be run a number of times. The benefits of PreparedStatement become visible only when a batch is run.

So we have the following to take away from this article:
1) The use of PreparedStatement does not always mean the use of bind variables
2) The user PreparedStatement does not alway`s mean an increase in performance.
3) The use of bind variables results in an increase of performance because of the composition of SQL queries

Feb 13, 2011

Why Have You Changed So Many Employers

While it's true that, frequently changing your employer leaves a negative impression on your future employer. But sometimes situation is like that only. I have seen software engineers changing their employers every year. It may not create a problem in case of part-time employees but it definitely raises a question in case of full-time employees.

I mean that every interviewer is going to ask for the reason to change the employer, even for the sake of asking. And if he notices too many companies in your resume, you are going to be hammered. If you have changed employers frequently then it's better to be prepared with an answer.



Digxa shopping comparison site. Dig for the best price on products worldwide.


Get This Widget

The only thing to remember while answering this question should be that it should not give an impression that you changed the company only for the sake of changing. This is because whatever reason you give the interviewer is not going to reject you unless there is no logic behind changing the organisation or employer.

I have seen Java developers with three different employers in three years and still looking for the fourth one in the fourth year. So do not worry if you have the technical expertise required for the job.

The common reasons for changing the employer are:
  • Relocation
  • Interest mismatch
  • Not getting the expected exposure
  • Looking for a better role
If the discussion gets too long and you are feeling out of replies then you can end the discussion by saying that the company does so many things to grow and as an individual I also have the right to grow.
 To mention the salary should also be avoided as it can be negotiated with the HR.

The final advice will be not to change employers every year. It can be that you changed your employers for the first time after two years and then one year and then two years and like that.

Best is to be working from home for various clients and be bound by any contract.

Feb 11, 2011

Big O Notation for Java Developers

Big O notation

As a Java or JEE developer we are most of times concerned with web technologies like Struts, Spring, Hibernate to design that best performing application. There is nothing wrong with it. But when it comes to write the business logic or some utility code then performance needs to be measured. Big O is by far the most used notation for comparing various algorithms and approaches. The downside is that most developers just recognize it with some notation and only know the complexity of some popular algorithms like Binary Search, Hashing algorithms and Quick Sort etc.

The questions listed below can save you from being hammered by the interviewer in an interview or by your professor in the college.

Q:What is Big O?
Ans:It tells how the program scales and not the actual performance of an algorithm or code. Its like telling of the order of.

Q:How?
 

Ans: O(n) doesn't tell exactly how much time it will take for a loop with limiting value of n to complete or the amount of memory required by a Java application. But it tells me the order of time unit or memory unit that it will take.

Q:So you mean Big O is used for worst case complexity?
Ans: No it can be used for best,average and worst case complexity scenarios. Big O tells me the maximum time/memory units to expect with increasing/decreasing input data size.

Q:If I have 4 statements inside a for loop thus they will be iterated 4n times at the maximum so I should say O(4n) right?
Ans: No, the Big O gives us the estimate and not exact time complexity. Moreover, n and 4n don't make much difference if n is 100000000. But n and n^2 do make a lot of difference at that value of n. Hence I will say the complexity to be O(n) for a loop even if it has 5 or 10 statements

Q: How will you represent Big O mathematically?
Ans: The mathematical definition of Big O is:
    f(x) = O(g(x)) if and only if  |f(x)|
  k*|g(x)| for all k>c

Q: What does that expression mean?
Ans: It means that Big O defines the limiting behavior for an algorithm or a piece of code to complete its execution or consume memory.
The expression means that when I multiply some constant value with the function (whose complexity I am defining using the Big O notation), the resulting value becomes greater than the Big O notation function. This is because Big O is the maximum value for time/memory complexity for the function g(x)

Q:What will be the Big O notation for the function 100*x^8 + 20*x^2 + 12?
Ans: The complexity will be O(x^8)

Q: How did you arrive at that value?
Ans: Rule 1: Ignore all terms except the one with largest exponent of the variable in addition or subtraction operations.
This gives me O(100*x^8)
Rule 2: Ignore the constant terms or any other terms which are not dependent on the variable
This gives me O(x^8)

Q: OK what about 1000000000*n + 10n^2. Will it still be n^2?
Ans: Yes because the constants matter only till some input size and Big O is for measuring scaling to large input size. The constant with n in the question will be meager term in front of 100000000000000000000. SO I can ignore that constant in my Big O notation and mark it as O(n^2)

Q:But I have a function 12*m^10*n^2 + 20*m^8*n^15. What will be Big O for this?
Ans: Big O is defined for single variable only. Probably it needs to be extended to be applied to multiple variables.

Feb 10, 2011

25 Servlet Interview Questions

Most of the interviews include questions from core Java,servlets, JSP and EJB et cetera. Here in this article I am listing the 25 most asked questions on servlets. Servlet is not a vast topic so you can expect 7 to 10 questions from servlets in an interview. I am not providing the answers for these questions as you can simply search for the answers on the Internet.

If you are looking for code Java interview questions than I have already written a blog post for the same here
  1. How will you create a servlet?
  2. Is a servlet thread safe?
  3. Can a servlet only be created for HTTP protocol or can I write a servlet for the FTP protocol also?
  4. What are the minimum methods to be added in order to create a servlet?
  5. What are the various scopes available to a servlet?
  6. How to maintain concurrency in a servlet-based web application for the attributes and parameters?
  7. How will you end a session programmatically. What are the ways to specify the session timeout?
  8. What are the ways or session tracking in a servlet-based web application?
  9. How to specify the mapping for the URL of the servlet?
  10. What are the various parts of the URL of a servlet?
  11. What is the difference between servlet config and servlet context objects?
  12. What is the difference between GET and POST request?
  13. What is a filter with respect to servlet API and how can one chain the filters ?
  14. What is the difference between SendRedirect and Forward ?
  15. How will you write a HTML form which submits to a servlet?
  16. How will you pass initialization parameter to a servlet?
  17. How is a servlet file is stored in the web application server?
  18. What is the effect of making the service method synchronised?
  19. Are HTTPServl andetRequest and HTTPServletResponse classes or interfaces?
  20. What is the rule to specify the URL to forward/sendredirect methods?
  21. Why is there a call to service method of superclass in the servlet's service method?
  22. What is the life cycle of a servlet?
  23. What is meant by load on start-up that in web.xml?
  24. What will happen if two or more servlets are mapped to the same URL pattern in the web.xml file?
  25. Why there is no constructor defined in a servlet?
Do suggest If I have missed any important servlet interview question...