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.