Sunday, July 27, 2008

Strongly Coupled Vs Loosely Coupled Classes in Java

Flexibility Vs Readability in J2EE :

(‘Flexibility’ of the application is inversely proportional to ‘Simplicity’ or ‘Readability’)

It is a common problem in Java /J2EE, when the application is designed in a more flexible way. When designing an application as a generalized way, the code becomes more complicated to read and understand. But conversely, such a code is easy to extend the application’s additional functionality.

But then, when the application’s functionality is added distinctly for every functionality simply, the code completion is easy and gets completed soon as expected, but this brings-in some other overhead. Application code becomes very large and maintenance of such application becomes very high and it may need re-deployment for every minor changes. When the similar functionality is added, you may still need to devise a new mechanism and new coding efforts.


Loosely Coupled and Strongly Coupled Classes in Java / J2EE

Strongly Coupled classes:

Strongly coupled classes have very-high dependancy. For example, consider the following code:

public int findSize(ArrayList myList)
{
int s = myList.size();
}


The above code is simple to write but brings-in quite a few complications during the run-time, which may be very difficult. This is called strongly coupled class. Because this enforces a lot of conditions for example, myList should not be NULL or myList cannot be any other type other than ArrayList, etc.,


Loosely Coupled classes:

Loosely coupled classes are generic classes and they are used for many purposes and it is normally error-free. For example, consider the following code (only a sample scenario):

public int findSize(Object obj) throws Exception
{

if (obj == null) throw new Exception("The Object is NULL");
else if (obj instanceOf ArrayList) return ((ArrayList)obj).size();
else if (obj instanceOf Vector) return ((Vector)obj).size();
else if (obj instanceOf String) return ((String)obj).length();
else throw new Exception(“Incompatible Type”);
}


In the above method, the calling method can pass any type of parameters and this can be even more generalized to be useful for many types. Such classes are called loosely coupled classes.

Reflection Pattern:

Java’s reflection pattern is the most-beautiful example and you can even develop many frameworks based on this.

Hope this concept is useful. I would meet you tomorrow with yet another real-time scenario in the next blog. Till then, take care. Bye.

Regards,
Swathika.
Write to me your queries to swathikalakshmi@gmail.com

Thursday, July 24, 2008

Problems of Duplicate / Multiple Form Submissions - Solutions

How to avoid duplicate form submissions?

It is a common problem in many applications where the duplicate submission occurs. This would happen in the following circumstances:

1. When the user clicks the ‘Submit’ button quickly twice without patience.
2. When the user cliks on ‘Back’ button of the browser and clicks on ‘Submit’ again.
3. When the user refreshes the form page again which submits the form.

These problems can be avoided by the special feature provided by struts called token. Let us see clearly about token feature in struts.

What is the concept behind struts’s token feature?

Everytime the page with the form is shown to the user, internally there is a hidden form field with the property name ‘TOKEN’ which has very long random string value. Whenever the form page is displayed, the token is created with the new value. When we use ‘Back’ button, unfortunately, the TOKEN value is the one which has been already submitted and verified by Struts during the previuos action call. So during the duplicate submission, struts declares it as an invalid token and hence the warning or error is raised by throwing suitable exceptions.

How do we implement this token feature?

It is very simple and very little programming is required related to this. Struts provides three methods for this purpose, which can be used in Action classes. They are:

a. saveToken(request)
b. isTokenValid(request)
c. resetToken(request)


Step 1: Create a dummy action class prior to come to the specific form page which calls the method saveToken(request). This process initializes a new token in request. Forward this to the JSP page where the form is found (where the value is entered).

Step 2: Form is submitted and action class is called. (In this page, the hidden form field is automatically created).

Step 3. Inside your action, when you call INSERT or UPDATE call the method ‘isTokenValid’ which returns boolean value and you can hence decide if it is a valid submission or duplicate submission, such as if (!isTokenValid(request)) throw ….

Step 4: After the successful INSERT or UPDATE, we should not forget to reset the token value in session. The token can be reset by resetToken(request)

Hope this conept is useful to you. There are plenty of other real-time scenarios and problems that we come across day by day. We shall discuss all such design issues in blogs to come.

Till then, See you.

Regards,

Swathika.

For queries, write to me to swathikalakshmi@gmail.com

Monday, July 21, 2008

Correlated Vs Non-Correlated sub queries.

Difference between Correlated and Non-correlated sub-queries.

Which is an efficient one? Discussions.

1. What is a non-correlated sub-query?

Non-correlated sub-query is a sub-query where the inner query does not refer to any of the fields or columns specified in the outer query. Consider the following

SELECT * FROM EMPLOYEE EMP

WHERE EMP.CODE = (SELECT CODE FROM LOCATION WHERE NAME= ‘Chennai’ )

In the above query, the inner query is executed only once and the value is substituted for every row from the outer query. For example, if the EMP table contains 50 rows and the LOCATION table contains 10 rows, the read operations is done 60 times.


2. What is correlated sub-query?

The query with sub-query is a correlated sub-query when the inner query refers to any of the fields from the tables specified in the outer query.

Assume the following query:

SELECT * FROM EMPLOYEE EMP

WHERE EMP.CODE = (SELECT LOC.CODE FROM LOCATION LOC WHERE LOC.NAME= EMP.LOCATION )

This type of query is called as corrleated sub-query. Because the inner query refers to the field LOCATION from the outer query which degrades the performance of the application. This happens particularly when the number of rows are more in both tables.

In the above query, the inner query is executed for every row available in the table mentioned in the outer query. Assume that the EMP table contains 50 rows and the LOCATION table contains 10 rows, the read operation is done 50 + (50*10) which is 550 times.

3. How to decide, which query to use?

The answer is, ‘It depends’. But we should observe carefully which type of query needs to be used in our application. We need to use correlated sub-queries only when there is no other way to achieve that result. However it is essential for us to know the nature of the execution of SQL queries as a developer, so that we deliver the code as efficient as possible.


There are lot of other topics to come this week. Keep looking for it. Till then, Bye. Thanks for reading.


Regards,

Swathika.

swathikalakshmi@gmail.com

Saturday, July 19, 2008

Advanced J2EE Concepts - Implementing Internationalization in Struts

Advanced J2EE Concepts - Internationalization in Struts

How is ‘Internationalization’ implemented in struts?

Default Internationalization (Detected based on Browser's settings):

Internationalization is an important concept of making the application to be compatible with different geographical location and user-friendly with respect to their location by means of providing the information in their preferred language.

In struts, it can be done quite easily. The application resource file name can be extended with underscore followed by locale.

For example ,

When your application contains the file “ApplicationResource_en.properties”, it would mean that it supports english language. When another file “ApplicationResource_fr.properties” exists, it would mean the localization for ‘French’.

The selection of file and the content is done and decided automatically by struts. When the browser’s setting is found with French settings, then struts automatically retrieves the value for the specific key from the appropriate resource file. Similarly you can add multiple property files for various locale.

But please remember that you can have one property file name with different extensions like _en, _fr, _de, etc., If they differ, the internationalization will not work. Also that only one file (one time), is specified in struts-config.xml. Each property file must have the same key with different values as follows:

In ApplicationResources.properties_en, you specify mainpage.welcome=Hi, You are welcome..

In ApplicationResources.properties_fr, you specify mainpage.welcome=< message in French >

Programmatic implementation of Internationalization (By manual selection)

The localization can even be done programmatically by placing ‘Locale’ object in session.
session.setAttribute("org.apache.struts.action.LOCALE", new Locale("fr"));

For example, You can create links one for each country's localization in the main page. Each link leads to an action class with different query string such as

<A HREF="setCountry?lang=en" > English <A>

<A HREF = "setCountry?lang=de"> German <A>

<A HREF="setCountry?lang=fr"> French <A>

When clicked, the action is called. Inside the action class you retrieve the lang parameter as follows

String lang = request.getParamter("lang");

if (lang.equals("fr"))

session.setAttribute("org.apache.struts.action.LOCALE", new Locale("fr"));

if (lang.equals("de"))
session.setAttribute("org.apache.struts.action.LOCALE", new Locale("de"));

-------------------------------------------------------------

Hope this explains the concept of internationalization. For any queries, write to me to swathikalakshmi@gmail.com. I would come with lot more of advanced concepts in blogs to come.

Regards

Swathika.

Java Advanced Concepts Part 2 - Servlet Filters

1. What are filters? How are they useful in web-applications?

Filters are useful to restrict the user request and perform some processing based on the URL. This acts like a firewall between the user request and the application.

For example, there would be a filter which is defined to be invoked when the URL starts with admin (adminLogin.do, adminSalesReport.do, adminCreateUser.do etc.,). This indicates that the filter and it would get processed only when the URL starts with admin to check if the given user is admin user or not) when the URL starts with any other word, say, login.do, it would ignore the admin authorization. After writing Filter class, you need to configure the same in WEB.XML.

The typical Filter call looks like the code given below:

public final class AdminOptions implements Filter {
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, UserAccessError, ServletException
{ String userName = request.getParameter(“userName”);
String password = request.getParameter(“password”);

Vector accessRights;
accessRights = LoginService.getAccess(userName,password);
if (accessRights==null) throw new UserAccessError();
chain.doFilter(request,response);
}

How to activate and configure the above Filter into WEB.XML

<filter>
<filter-name>AdminOptions</filter-name>
<filter-class>com.siva.AdminOptions</filter-class>
</filter>

<filter-mapping>
<filter-name>AdminOptions</filter-name>
<url-pattern>/admin*.jsp</url-pattern>
</filter-mapping>

The above Filter would be called when invoking any JSP that starts with “admin”. Also Also remember that you can have many levels of Filters that are executed as a chain one after another as required.

2. What is validation framework? Can we use it in Struts? How?

Validation framework is the framework that contains the necessary components for validation purposes. The validation routine can be used just by specifying the necessary validation and you need not repeatedly write the code for any such validation.

The validation framework can be easily included by downloading the jar file and placing it into LIB folder. Also required are the two important XML files that configures the required validation in the application. They are validation.xml and validator-rules.xml. The validator-rules.xml file contains all the validations and their mapping. But validation.xml is used to define the validations that are required in our applications. You need to place the following configuration settings in struts-config.xml

<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,
/WEB-INF/validation.xml"/>
</plug-in>


3. List the configuration files used in Struts and their uses.

ApplicationResources.properties – This file defines the key – value pairs of the properties that are used in the application.
struts-config.xml – This xml file defines all the components that are used in struts application and how these components are interpreted. For example, when you define an action in JSP, struts-config file indicates the mapping of this action to the particular action class. It specifies whether the validation needs to be included or not, etc.,
These two files act like a bridge between controller layer and model layer.

4. What are the advantages of struts tag libraries? Why?

Struts provides plenty of tag libraries each is used for unique purpose. For example, bean tag library is used to create instance and set and retrieve the properties. logic tag library is useful to compare the bean for specific criteria.

These tag libraries are a bit faster when compared to scriptlets. Because the tag libraries are compiled components and no need to re-compile when JSP is executed. But scriplets need compilation which makes the process little slow.

5. What are the important components in Struts?
Action – Defines the busines part of the application.
ActionForm – Includes getter & setter methods and server-side validation routine.
ActionServlet – Controller that resolves all the requests from the user into required action.
ActionMapping – Defines which action class leads to which JSP.
Action Forward – Defines the destination JSPs.

Saturday, July 12, 2008

Tricky Questions in Struts / J2EE / SQL :

Tricky Questions in J2EE, Struts and SQL :

Sometimes, during the interview, when you answer almost all questions theoretically, the direction of the interview would change and the interviewer would start asking tricky questions. These types of questions have no definite answer in theory and it comes more of practical scenarios and real-time experiences. I am going to discuss such type of questions and hope this is useful to readers such as you.

During the J2EE or Java interview, you should be able to answer little bit of SQL also. So be prepared some basics or even tricky queries, so that you give the interviewer the feeling that you would manage any circumstances in your development team.

Obviously these types of questions cannot be answered from books. So I want to share these with you.

1. How can you find the nth smallest or greatest number using SQL?

SELECT A.NUMBER FROM EMP A
WHERE (SELECT COUNT(B.NUMBER) FROM EMP B WHERE B.NUMBERl > A.NUMBER) = 2;


The above query finds the 3rd greatest number. Substitute 5 in place of 2 if you want to find the 6th greatest number. Substitute < in place of > to get the nth smallest number.

Above query is a bit complex to understand by looking at it concept-wise. The query does a simple thing. It fetches the number from the table, such that there are 2 more bigger numbers than that. The outer query picks up a number and the sub-query finds the number of elements that are greater than the number picked by the outer query. Such number is the third highest number. (Consider numbers 3, 4, 23, 143, 15, 20; Here, there are 2 numbers greater than 20; they are 23 and 143. So the third greatest number is 20).

Since this is a correlated sub-query, it is executed distinctly for every row in the table. So number of times the sub-query is executed is dependent on the number of rows in the table. When the number of rows increases, obviously the performance of the query comes down.

2. How can you display multiple related rows as a single row?

For example assume the following rows in EMP table:

Name Value
---------------
John A
John B
John C

The above rows should be displayed as
John A B C

The solution to the above problem is query using self-join:

SELECT A.NAME, A.VALUE, B.VALUE, C.VALUE FROM EMP A, EMP B, EMP C
WHERE (A.VALUE <> B.VALUE) AND (B.VALUE <> C.VALUE)


3. How can you avoid a page from being cached in JSP?

When you feel that the JSP contains all dynamic content and the content should not be cached, particularly when clicking Back and Forward buttons in the browser. So when you prevent the page from being cached, the page always displays the contents interact dynamically whenever the URL is typed again or when Back is pressed.

This can be achieved by setting appropriate page headers in JSP.
<%
response.setHeader("Cache-Control","no-store"); Headers are set with appropriate values
response.setHeader("Pragma\","no-cache");
response.setDateHeader ("Expires", 0); // The page get expired immediately.
%>


4. How can you efficiently display huge amount of information in a single JSP (HTML) page?

First, classify the information that you want to display, as categories. Put each category under DIV tag with suitable id. Also make the ‘cursor:hand’ style property to the headings of these tags. This heading when clicked, runs a small javascript code that displays only one DIV, ie., displaying only one heading and hiding the rest of them. At any time, all the topic-headings are visible to the userm, only the contentes are either visible or hidden. When the user clicks on the second heading, the selected DIV tag is set visible and others are hidden. The visible and hidden properties are set with the help of suitable CSS style properties.

5. How can you import a JSP content into an Excel (.XLS) format?

The normal JSP content can be downloaded as an excel sheet by setting appropriate headers and document type with the document name. The simple example is given as follows:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@
page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<HTML>
<head>
<%response.setContentType("application/vnd.ms-excel"); %>
<%response.setHeader("Content-disposition","attachment;filename=Demo.xls");%>
<title>excelReport</title>
</head>
<body>
<table>
<tr>
<td> One </td>
<td> Two </td>
</tr>

</table>
</body>
</HTML>


In the above example, the content type is set to application that is ms-excel type. Also that the content is disposed in the browser in the form of an attachment in XLS type with the name provided under filename.

If you feel that the above article is helpful or if you have any queries, write to me to swathikalakshmi@gmail.com

I would come with some more tricky questions in the next week.

Bye.
Swathika.

Friday, July 11, 2008

How to design an 'Architecture of J2EE application'

Steps to Design ‘Architecture of the J2EE / Struts’ application

The term ‘Architecture’ of the application referes to the structure of the typical J2EE application. The term structure may refer to the following:

1. Folders structure
2. Tiers
3. Components
4. Communication between Components

These are discussed below.

Folder Structure:

The folders found in the typical J2EE application is just the arrangements of files that would be used while the user interacts to the application. For example, all the pictures can be stored under ‘image’ folder and all the documents can be stored in folders named as ‘pdfs’ or ‘docs’, etc.,

Tiers:

Tiers are the layers found in the applications. The various tiers are Interface tier, Business Tier, Persistence Tier, etc., This is decided based on the complexity of the application, number of developers in the team, Timelines of the delivery, etc., For example, if the application is used for a short period of time, then there would not be more number of components, we can design just with JSPs. But large applications need business tier, to enhance the reusability.

Components:

The various components used in typical j2ee application would be Forms, Business classes, Utility classes, DTOs, JDOs, Action classes, Custom Tag classes, etc. These components are not chosen arbitrarily, they are carefully observed, analysed and finalized based on the specific requirements of the applications.

Communication Between Components:

This is a bit complex for the system architect and the technical leads. This greatly influences the performance of the application. The decisions taken here would be like where the exceptions are handled how the components would interact between each other. How the data needs to be fetched and passed on to the business classes, and How the fetched data is going to be displayed to the user and by what means etc.,

Diagram to demo the Various Layers and Components :












We will discuss the architecuture details and lot more in the next blog. Keep Visiting. Thanks.

Regards,
Swathika.

Wednesday, July 9, 2008

Design Concept - Secrets of contains() method in Vector and ArrayList

How .contains() method works?

When you store strings into a Vector or ArrayList, you tend to use .contains() method to check if the given string is found in the list or not. If found the method returns true and false when not found.

But when you try the same when you store your own objects, say DTOs and other user-defined objects, it does not work. Why? This is a practical-sceanario many people struggle and get confused when the contents are same but the result is false. Let us analyse. Here we go...

The secret behind .contains() method is the .equals() method in Object class. Because, internally, the contains() method uses equals() method to check the equality. For String objects, it uses by default and checks if the contents are same or not. But for the user-defined objects, it checks if the equals() method is defined for the object or not. If there is no equals() method defined, it uses default equals method that checks if the references (address) of these objects are same or not. As a result, you find that always false is returned though the property values are same. So the solution is to override equals() method for the object you are trying to store into Vector and ArrayList.

Let us see an example:

public class User
{
String userName;
String password;

public void setUserName(String userName)
{
this.userName = userName;
}

public void setPassword(String password)
{
this.password = password;
}

public String getUserName()
{
return userName;
}

public String getPassword()
{
return password;
}

public boolean equals(Object obj)
{
if (! (obj instanceof User)) // If objects are of different type, return false
return false;
User user = (User) obj; // Cast the object to User type.
// Find if the userName and password are same in both objects.
return (this.userName.equals(user.userName) && this.password.equals(user.password) );
}

}


Demo of using the .contains method:

Vector users = new Vector();
User x = new User(); x.setUserName(“Swathika”); x.setPassword(“Swathika”);
User y = new User(); y.setUserName(“Swathika”); y.setPassword(“Swathika”);
User z = new User(); z.setUserName(“Swathika”); z.setPassword(“Swathika”);
users.add(x);
users.add(y);
System.out.println(“The equality :” + users.contains(z))

The result would be

The equality : true

So, take care when you use Vector and Arraylist to store user-defined objects. Let us see some more design concepts and lot more in articles to come. In the next blog, we will see how to use inheritance and how to use base class and super class effectively, in practical scenarios. Please keep visiting my blog.

Regards,
Swathika.

Sunday, July 6, 2008

Designing Abstract Classes and Interfaces in J2EE Applications

Advanced Design Concept - Abstract classes and Interfaces

Using abstract classes and interfaces are the very important design decisions to be made by the technical leads and application architects to make the application very effective. It not only makes the effective application design and it also helps the team to effectively develop codes during the design and coding phase.

When to use Abstract Classes? When to use Interface? What is the practical use?

Basically everyone knows the theory behind it. If you do not want to make the instance directly, you will use abstract classes. To define the structure of the classes you use interface.

But thats ok. What is the practice? In the interview, the questions are normally asked as 'Give the scenario where you use abstract classes and interface' or 'Why do we need abstract classes if you cannot create the instance?'.

Let us discuss it. Take the scenario of a typical J2EE logging-in module. The concept of logging in would effect only when the user exists. If the user exists and the password is right, you will allow the user to go ahead further. But the user is of different kind. He may be the simple user or administrator. So this is decided by authorization, where the user is listed out the pages or components which he can access. How do we do it? This magic is achieved by abstract class. Let us assume the following classes:

The abstract class is named as 'UserAuthorization'.
The normal class is named as 'UserDetails'.
The interface is User.

You cannot authenticate differently for different people. Authorization mechanism is one for each application. So we can design as follows:

Class UserDetails extends UserAuthorization implements User
{
.......
}

The above prototype explains the concept. The UserDetails contains the name, type, address and phone numbers. The UserAuthorization class uses these values supplied through parameters and performs the authorization. Since it is a super class, the UserDetails class can directly access those data and get the authorization details. The interface enforces the UserAuthorization and UserDetails classes to compulsority declare the necessary methods.

In this example, the abstract class has no need to get instantiated and used only by the derived classes. The need of interface is a beautiful concept. Once the architect designs the prototype of the methods, all the team members, wherever they are, must necessarily use exactly the same prototype to avoid errors. Obviously, they would have no rights to change the signature of the methods found in interface. They only have to adjust their classes to suit the needs of the application decided by the architect. This is how the common components are designed to minimize the application bugs and to enfore the common design principles and consistency.

Hope this explains the Abstract classes and Interface. If you feel this useful, write to me to swathikalakshmi@gmail.com.

I would come out with yet another beautiful concept in my blog. Keep visiting.

Thanks & Regards,
Swathika.

Friday, July 4, 2008

Advanced Exception Handling Techniques in Struts

How to handle Exceptions in Struts based J2EE Applications:

There are so many possible exceptions that could arise in our applications. Some practical scenarios are discussed here today. They are

1. Compile-time Exceptions
2. Run-time Exceptions

Compile-Time Vs Run-Time Exceptions:

Compile-time exceptions are the ones that are expected to occur by various situations. These exceptions are caught and distributed to various other pages with the proper messages or warnings.

For example, we can take the scenario of the user trying to login with the invalid user and password. How do we catch this in J2EE applications?

After retrieving the result set from the database table, Checking if the result set is not empty would mean that the user exists matching the entered name. If not, throw the exception that the user not available. This is checked-exception. This is not a bug in the application, because as a developer, you expect this case to occur while developing the code.

Other way, we directly retrieve the name of the user from the result set assuming that the row exists matching the user name. If this leads to NullPointerException while retrieving, then it would automatically mean that the user is not found. This is run-time exception. This is a bug in the application. As a developer, you must fore-cast the side-effects of reading the data from the empty result-set.

Exceptions in Struts based J2EE applications:

Usually there are two ways in which you can catch the exceptions. They are

1. Declarative Exceptions
2. Programmatic Exceptions

Declarative Exception Handling:

In this way, we can catch the exception from action classes by declaring the name of the exception and the path to go when the specified exception arises. The declarative exceptions can be placed as action-specific or global. In action specific, we define these exceptions and path inside the action tag. Otherwise, the exceptions are defined inside the global-exception tag. This would mean that, if this exception arises in any action class, it would automatically forwarded to the specified path known as error-page. The error-page then shows the exact warning message.


Entry in struts-config.xml for Declarative Exception:

<action path = "/login" type= "com.siva.LoginAction" parameter="name" input="/login.jsp" >
<exception key="error.invalidPassword" type="RuntimeException" path="/index.jsp" />
</action>


Entry in ApplicationResources.properties

error.invalidPassword = Invalid password entered. Please try agin.

Programmatic Exception Handling

In this way, we check lot of if inside the try-catch block. If the exception is caught in the try block, the control flows into catch block, where we add the errors into the messages and put it in the session. Then the control is forwarded manually to the error-page where the warning message is displayed. The drawback of this method, is the developer is fully responsible for the various flow of applications where the chance of misleading is high.

Sample Code to check the exception programmatically:


ArrayList matchedUser = (ArrayList) ReadFactory.getService().getUserNames();
UserDTO user = matchedUser.getUser();
String userName = null;
String userPassword = null;
try
{

if (user==null) throw new Exception();
userName = user.getName();
userPassword = user.getName();
}
catch( Exception ex)
{
ActionMessages errors = new ActionMessages();

errors.add("userName", new ActionMessage("error.userName.not.found"));

saveMessages(request, errors);
}

if (errors.size()==0) return mapping.findForward("success"); else mapping.findForward("failure");

Ok. Thats all for today. We will see some more design concepts in days to come. You expect lot more advanced concepts next week. Bye for now.

In the next post, we will see 'Advanced J2EE Design Concept - How to use Abstract Classes & Inheritance in J2EE applications effectively'.

Still to come posts : Servlet - Filter Concepts, Authorization, Authentication Techniques.

Cheers,

Swathika.

Thursday, July 3, 2008

Design Level Concepts in J2EE

Importance of Business Classes, Validations and Exception Handling:

Use rollback in Business Methods:

Perform the set of transactions together in the business component and rollback if any one of them fails. This method is called “Either All or None”.

Where to throw Exception:

It is a good idea to throw exception in business methods (in action classes in struts or in business components where the exception is caught into action class).

Where to make the validation:

The validation needs to be done always in business class. Because, there are plenty of crooked ways in poorly written application to get through validations. So one has to write the validation routines in business classes to ensure the valid database updates. For simple validations, you can prefer javascripts.

How to simplify the Exception Handling:

Use common exception defined in deployment descriptor (web.xml) or in struts-config.xml. Because all the applications are comprised of so many components where the same validations need to be performed again and again. So to bring in the simplicity and the consistency, it is better to have this common exception handling across the different components.

Where to place the queries:

It would be better to collect all the SQL named queries in a property file and to provide mechanisms to parse these and use.


Why does one need ‘Common Standards’ for specific application?

When 10 developers are involved in a team and assume there are 10 teams working for the company, then there would be easily 100 different coding styles and it would definitely lead to the complexities during the maintenance of the application. If this is not resolved early, it would lead to very expensive in future to handle. So it is always ideal to sit, discuss and frame the design standards before developers start their work.


What is the way in which the message/warning could be displayed?

Selecting the criteria and providing the results can happen in the same page, may be different layouts could be used. The search would either fail or pass and hence both success and warning message should be displayed in the page along with the result. The messages should be very precise and clear for the user to understand. For example,

The phone number of the user John has been changed to 98xxx9x80x;
The password has been changed successfully; etc.,

There are lot of design issues that may happen in the application. We will see all that and try to resolve it. Thanks for your visit and see you tomorrow. Until then Bye.

Best Regards,
Swathika.

Wednesday, July 2, 2008

Core Java Interview Questions (FAQs)

FAQs of Core Java:

1)What is OOPS?

Ans: Object oriented programming organizes a program around its data,i.e.,objects and a set of well defined interfaces to that data.An object-oriented program can be characterized as data controlling access to code.

2)what is the difference between Procedural and OOPs?
Ans: a) In procedural program, programming logic follows certain procedures and the instructions are executed
one after another. In OOPs program, unit of program is object, which is nothing but combination of data
and code.
b) In procedural program,data is exposed to the whole program whereas in OOPs program,it is accessible with in the object and which in turn assures the security of the code.

3)What are Encapsulation, Inheritance and Polymorphism?
Ans: Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse.

Inheritance is the process by which one object acquires the properties of another object.

Polymorphism is the feature that allows one interface to be used for general class actions.

4)What is the difference between Assignment and Initialization?
Ans: Assignment can be done as many times as desired whereas initialization can be done only once.

5)What are Class, Constructor and Primitive data types?
Ans: Class is a template for multiple objects with similar features and it is a blue print for objects. It defines a type of object according to the data the object can hold and the operations the object can perform.

Constructor is a special kind of method that determines how an object is initialized when created.

Primitive data types are 8 types and they are:
byte, short, int, long
float, double
boolean
char

6)What is an Object and how do you allocate memory to it?
Ans: Object is an instance of a class and it is a software unit that combines a structured set of data with a set of
operations for inspecting and manipulating that data. When an object is created using new operator, memory
is allocated to it.

7)What is the difference between constructor and method?
Ans: Constructor will be automatically invoked when an object is created whereas method has to be called explicitly.

8)What are methods and how are they defined?
Ans: Methods are functions that operate on instances of classes in which they are defined. Objects can
communicate with each other using methods and can call methods in other classes.
Method definition has four parts. They are name of the method, type of object or primitive type the method
returns, a list of parameters and the body of the method. A method's signature is a combination of the first
three parts mentioned above.

9)What is the use of bin and lib in JDK?
Ans: Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all packages.

10)What is casting?
Ans: Casting is used to convert the value of one type to another.

11)How many ways can an argument be passed to a subroutine and explain them?
Ans: An argument can be passed in two ways. They are passing by value and passing by reference.
Passing by value: This method copies the value of an argument into the formal parameter of the subroutine.
Passing by reference: In this method, a reference to an argument (not the value of the argument) is passed to
the parameter.

12)What is the difference between an argument and a parameter?
Ans: While defining method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.

13)What are different types of access modifiers?
Ans: public: Any thing declared as public can be accessed from anywhere.
private: Any thing declared as private can't be seen outside of its class.
protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages.
default modifier : Can be accessed only to classes in the same package.

14)What is final, finalize() and finally?
Ans: final : final keyword can be used for class, method and variables.
A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods.
A final method can' t be overridden
A final variable can't change from its initialized value.

finalize( ) : finalize( ) method is used just before an object is destroyed and can be called just prior to
garbage collection.
finally : finally, a key word used in exception handling, creates a block of code that will be executed after a
try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown.
For example, if a method opens a file upon exit, then you will not want the code that closes the file
to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this
contingency.

15)What is UNICODE?
Ans: Unicode is used for internal representation of characters and strings and it uses 16 bits to represent each other.

16)What is Garbage Collection and how to call it explicitly?
Ans: When an object is no longer referred to by any variable, java automatically reclaims memory used by that
object. This is known as garbage collection.
System.gc() method may be used to call it explicitly.

17)What is finalize() method ?
Ans: finalize () method is used just before an object is destroyed and can be called just prior to garbage collection.

18)What are Transient and Volatile Modifiers?
Ans: Transient: The transient modifier applies to variables only and it is not stored as part of its object's
Persistent state. Transient variables are not serialized.
Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by
volatile can be changed unexpectedly by other parts of the program.

19)What is method overloading and method overriding?
Ans: Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading.

Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding.

20)What is difference between overloading and overriding?
Ans: a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method.
b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass.
c) In overloading, separate methods share the same name whereas in overriding,subclass method replaces the superclass.
d) Overloading must have different method signatures whereas overriding must have same signature.

21) What is meant by Inheritance and what are its advantages?
Ans: Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses.

22)What is the difference between this() and super()?
Ans: this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a super class constructor.

23)What is the difference between superclass and subclass?
Ans: A super class is a class that is inherited whereas sub class is a class
that does the inheriting.

24) What modifiers may be used with top-level class?
Ans: public, abstract and final can be used for top-level class.

25)What are inner class and anonymous class?
Ans: Inner class : classes defined in other classes, including those defined in methods are called inner classes.
An inner class can have any accessibility including private.

Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.

Tuesday, June 24, 2008

Interview Questions that would reveal your psychology

Glimpses:

Some questions in the interview may reveal your inner qualities, your likely co-operation with team members, your general attitude, your technical and non-technical skills. Take a good care to answer this type of questions. I have tried to explain some of them. Good Luck.

Tips to answer such questions:

  • Be prepared thoroughly for these questions. Struggling gives clear hint.
  • Be honest to these questions. That is the best way of tackling any interview.
  • Never let down your previous employer.
  • Never let down your colleagues.
  • Strongly express what you can do and what you cannot do. Because commitment to unknown areas would backfire you.
  • Your technical skills take only 10% in the interview. Only soft-skills are what the interviewers are looking for.

Questions :

  • What do you know about our company?
  • Could you mention our competitors ?
  • Why have you applied for this particular position?
  • How did you learn of the vacancy?
  • What are your salary expectations?
  • What is your current salary or remuneration package?
  • Why do you want to leave your present job?
  • What do you think determines a person's progress within a company?
  • Why shoule we should hire you?
  • What are the blunders, you know, you have committed at work?
  • What are the things that irritate you the most in the workplace with colleagues?
  • Why do you think you might like to work for our company?
  • Do you prefer any particular geographic location? Why? Are you prepared to re-locate?
  • Would you be prepared to travel nationally/abroad? Are you prepared to go where the company sends you?
  • What are your strengths and weaknesses?
  • What would you like to be doing in 5 years time from now?
  • What are your most redeeming qualities?
  • What are your hobbies or interests?
  • What did you like/dislike about your previous employer and manager?
  • If we communicate to your previous employer, what would they tell us about you?
  • If you are given a task to do but didn't how to go about it, what would you do?
  • If you lack experience, what do you have to offer?
  • What characteristics do you think an employer looks for in an employee?
  • What sort of a company would you like to work?
  • Mention the five words that describe about you?
  • What sort of things frustrated you in your last job?
  • Do you work best on your own or in a team?
  • In your opinion, what are the most important factors in running a business?
  • What types of people seem to rub you the wrong way?
  • What types of books do you read?
  • Tell us about your home life?
  • Tell us in brief about your IT skills?
  • Can you tell me about your biggest failures and how you dealt with them?
  • Are you prepared to work at weekends?
  • What is the most significant impact you've made at your organisation in the last year?
  • How do you feel about working overtime?
  • Aren't you a bit over-qualified for this position?
  • How do you cope with your ideas not being implemented, especially when you know they would be worthwhile?
  • How do you take criticism?
  • Why have you changed jobs so many times in the past?
  • Why are you interested in a position with our company?
  • What steps have you taken to be more successful in your career?
  • Tell me about a time you became angry at work. If you had to dismiss 30 people, how would you decide whom to let go?

Monday, June 23, 2008

Struts / Java / J2EE Frequently-Asked Interview Questions

Are Struts's action classes Thread-safe?
Yes. Action classes are based on "one-instance and many-threads". This is to conserve resources and to provide the best possible throughput.

What are the various Struts Tag libraries?
There are various struts tags. But the most-repeated tags are:
struts-bean.tld
struts-html.tld
struts-logic.tld
struts-nested.tld

What is ActionMapping in struts?
Action mapping defines the flow of one request. The possible sequence is
User -> request -> Form -> Validation -> Business Code -> Forward -> JSP -> response -> User.
The components involved are Action classes, Forms and JSP.

What are the advantages of having multiple struts-config in the same application?
The implementation with many struts-config is to organize the development work, so that many people may be involved and it is some organized way of doing things. But this would result in some compromise in performance(speed). Technically there is no any difference between single and multiple struts-config files.

What are the ways in which resource file can be used in struts?
Defining message resources in struts-config file.
Programmatically using resource files in Java classes or in JSP files.

Explain the term 'architecture of the application'?
Architecture is the set of rules (or framework) to bring in some common way of assembling or using J2EE components in the application. This helps in bringing consistency between codes developed by various developers in the team.

Which is the architecture followed by struts?
Struts follows MVC architecture.

What are components corresponding o M, V and C in struts?

Model : The model represents the data of an application. Anything that an application will persist becomes a part of model. The model also defines the way of accessing this data ( the business logic of application) for manipulation. It knows nothing about the way the data will be displayed by the application. It just provides service to access the data and modify it. Here 'Form Bean' represents Model layer.

View : The view represents the presentation of the application. The view queries the model for its content and renders it. The way the model will be rendered is defined by the view. The view is not dependent on data or application logic changes and remains same even if the business logic undergoes modification. JSP represents View Layer.

Controller : All the user requests to the application go through the controller. The controller intercepts the requests from view and passes it to the model for appropriate action. Based on the result of the action on data, the controller directs the user to the subsequent view. Action classes (action servlets) represent Controller layer.

Differentiate between the terms 'Design Patterns', 'Framework' and 'Architecture'.
Design Pattern: The various solutions arrived at for the known problem. This helps to avoid re-inventing the wheel. The risk-free solution can be easily used by others. For example, singleton is the design pattern that you can use instantly to enfore one object per class. You do not need to think of this on your own.
Framework: A framework is a structure or set of rules, used to solve or address complex issues. It is basically a reusable designf for the J2EE applications. For example, Struts, JSF,etc., are the frameworks. You can use these frameworks based on the requirements of your application and each has its own set of advantages.

Architecture: It is a design that describes how the various components in the application fit together. For example, MVC is an architecture which is helpful to define how the components interact within the application.


What is the difference between ActionForm and DynaActionForm?
In action form, you need to define the form class that extends ActionForm explicitly, whereas you can define the form dynamically inside the struts-config file when using DynaActionForm.

How can you use Validator framework in struts?
Validator Frameworks are helpful when the application needs server-side validation such that the particular set of validations occur very frequently within the same application. This avoids writing complex code in validation() method in every form bean. Using validator framework, there are different pre-written validations in place. You can customize these validations in XML file.

What are client-side and server-side vaidations?
Client-side validations: These are the validations that id done using javascripts. There is always a danger involved that the user can get through (crack-through) these validations. But for some simple validations, like converting lower-case to upper-case or date validations can be done, you can use javascripts.
Server-side validations: These are the validations done in server-side using Java components (Form bean or in business logics) where the user has no chance to crookedly get through the system.

What are the advantages & differences between using validate() method in form over validations using validator framework.
Refer to the previous-answer.

Define the terms authentication and authorisation.
Authentication is the process/rule that validates if the user is allowed to access the system or not.
Authorization is the process/rule that validates if the user is allowed to access the particular part of the system or not. This occurs after user's successful authentication.

What are the components provided in J2EE to perform authentication and authorization?
Authentication – RequestProcessor and/or Filter.
Authorization - DTO, JDO or Java or Action classes.

Give the difference between between 'DispatchAction' and 'Action'.
A DispatchAction contains various different methods other than the standard execute() method in Action classes. These methods are executed based on some request parameter. For example, you can code in such a way that three buttons (namely Insert, Delete, Update) buttons correspond to different methods such as insert(), delete() and udpate(). The submit button in JSP would have the property that has the value which matches to any one of the methods defined in DispatchAction class.

What is pagination technique? How can you design them in struts?
Pagination is the technique where the bulk of results are split into different pages and only the information where the user can conveniently see are displayed in a page. (Like in Goooooogle). This can be achieved in many ways, but the simplest method is to have a query string (say http://www.testwebsite?pageNumber=2) would lead to information corresponding to resultset rows from 11 to 20. Assuming that you want to display 10 related rows of information, you can set the formula as follows:
Starting row = (pageNumber-1) * + 1 which is equal to 11.
Ending row = Starting row + which is equal to 20.

How can you populate the drop-down list using form properties?
There are many ways for this. But the best method is to use which defines collection that needs to be used to populate the drop-down list, the property to store the selected value and the collection that is used to display the labels (what we see in JSP page). For Example,

html:options collection="form-collection-property"
property="form-property"
labelProperty="form-another-collection-property"

What is the XML parser provided in struts? Can you use it for other purposes?
'Digester' framework. Yes we can use for our applications to store and parse our application-related data.

Difference between Struts 1.0 and 1.1
  • Perform() method was replaced by execute()
  • DynaActionForms are introduced.
  • Tiles Concept is introduced
  • We can write our own Controller by Inheriting RequestProcessor

Sunday, June 22, 2008

How to succeed in Java / J2EE interviews?

Why does one need 'Interview Skills' ?
Many a times, even an academically successful person could not easily turn into an IT professional. This is because, many are afraid of taking up an interview or they are not confident. So, one always needs to know that succeeding an interview is an art. Clearing the interview is a very easy task, but it is a process oriented one and anyone looking for a job should dedicate some time towards the preparation for an interview.

What happens in a normal interview?
Normally, the interview starts with the basic questions like 'Can you say about yourself',
'Why do you want a job in our company' and 'Say a few words about your family', etc. The first thing that happens in any interview is that the interviewer wants to know about you by you.

What do I prepare for an interview other than technical subject?
It always takes an hour or two to write down in a piece of paper about you, your skills, family background, academic background, etc. Though you know all these things already, it is always better to practice a little bit (like singing in a bathroom!) and say it to yourself loud about you and your good qualities. This definitely brings some confidence in you.


The Concept of any Java based interview:
The interview does not happen so randomly. It is a systemmatic process. At first, the interviewer just tests if you know the basics, for example the question is more likely as 'what is the difference between Vector and ArrayList', 'How do you handle a session' , etc. In this stage, you need to be very clear and short in your answer.

If you keep answering the questions, he/she gradually increases the depth of the questions and expect you to answer more technically/professionally than just mentioning answers. For example, the questions are more likely to test the concept behind it and not to test the answer. For example, the questions are more likely to be 'how can you implement a filter', 'why do we need to use hidden form fields', etc. In this stage, you need to come out of your shell, and narrate clearly the concepts the interviewer expects from you.

No interviewer would allow you to answer all the questions and appreciate you straightaway. So, in the next stage, the interviewer would try to trap you with questions such that you cannot answer. This is the phase wherein you prove yourself and not to try to fool the interviewer. You should never forget to be very friendly and kind to the interviewer while answering (from the heart).

I have tried to demonstrate some of the questions as given below for the professionals with various levels of experience.

Interview Questions (Samples) for "Java Developers" in Java/J2EE:

1. Which is the parser that is used in Struts to parse the struts-config.xml file?

2. Are struts action classes thread-safe?

3. Explain the life-cycle of Struts?

4. What is the difference between ArrayList & Vector?

5. Assume String x=”Chennai”, y=”Chennai”. Do x and y refer the same? Why?

6. How would you submit the struts's action automatically from the JSP page?

7. What is the difference between sendRedirect() and forward()?

Interview Questions (samples) for "Technical Leads" in Java/J2EE

1. What are the possible layers in Java? How would you decide number of layers?

2. How would you decide the number of developers required for the project?

3. What are the design issues that could occur in a J2EE application? How to solve them?

4. How would you design an exception handling techniques? What are the factors to consider?

5. What are the techniques behind displaying error or information to the user through JSP page?

6. What are custom tags? How would you create them?

Tips for being successful in interviews:

1. At first, be trained to talk about yourself and never let yourself down before the interviewer. Because, everybody wants to recruit people who are self-confident.

2. Collect your experiences in your projects and if possible, have info-base for yourself that clearly narrates the problems and solutions that you can refer later.

3. Collect the technical aspects of the projects in general, so that you can explain to the interviewer spontaneously rather than thinking at the wrong time.

4. As you grow, focus on design techniques of the projects rather than technicalities.

5. Explain with situations, examples, scenarios rather than giving the answer monotonously.

I would try to update this blog everyday with various interesting facts, scenarios and interview questions. Keep visiting this page regularly.....
Thanks and I wish all the readers all the best in the interviews.
Cheers.