Sunday, April 27, 2008

Java Fundamentals - Points to remember

Java Fundamentals

Quick reference points

1. Keywords are the special reserved words in java that cannot be used as identifiers for classes, methods or variables.

2. const and goto are reserved but unused keyword in Java. If you use them in as identifiers, the compiler will throw an error.

3. include, overload, virtual, friend, unsigned, main are not keywords in java.

4. null , true and false are reserved values , they cannot be used as identifiers.

5. Java primitives are – byte(1 byte), short(2 bytes) , int (4 bytes), long(8 bytes), float (4 bytes) and double (8 bytes). All are signed values.

6. char is an integer type that can be assigned any value between 0 and 65535.

7. All integers are defined as int by default.

8. All floating point literals are double by default.

9. If we assign a floating point literal to a variable of type float, the complier will throw an exception. We should use ‘f’ or ‘F’ as a suffix to assign a floating point literal to a variable of type float.

10. A boolean literal can only have values – ‘true’ or ‘false’ (Case insensitive).

11. The characters are 16 bit (2 byte) unsigned integer under the hood. If we are assigning an integer value to a variable of type char, we should type cast it, else the complier will throw exception
o char a = 100 ; // legal
o char b = -100 ; // illegal
o char c = (char)-100; // legal
o char d = ‘a’ ; // legal
o char e = ‘\u1000’ ; // legal

12. Arrays are objects in java which stores multiple variables of same type.

13. Arrays are always Objects.

14. Array declaration is done by specifying the type of the variable being stored and the empty square brackets.

15. An Array of type A can store an Array of type B if B can satisfy ‘is A’ relationship of type A.

16. It is illegal to specify the size of an array during array declaration.

17. We should specify the size of an array during construction of an array.

18. Multi dimensional arrays are nothing but an array of arrays.

19. The dimensions in a multidimensional array can have different lengths.

Java as Object Oriented Programming Language

Java as Object Oriented Programming Language

The most commonly asked questions on Java in interviews are the concepts of Object Oriented Programming.

The Object Oriented Programming Languages follow the principle of programming using the objects which represents real life objects of life such as Car, House, and Accounts etc.

The features of OOPL which forms the basic building block or pillar of OOPS are Polymorphism, Inheritance and Encapsulation. By short called as P-I-E of OOPS.

Polymorphism: The one line definition – “Same name different functionality”

Polymorphism is the ability of a single variable of a given type to reference objects of different types and automatically calls the method that is specific to the type of the object variable references to.

For example

If you have a class “Account”, “SavingsAccount” and “FixedDepositAccount”

class Account
{
public int calcInterest()
{
// calculates generic interest amount
}}

class SavingsAccount extends Account
{
public int calcInterest()
{
// calculates savings account interest
}
}

class FixedDepositAccount extends Account
{
// No implementation of calcInterest method
// same as generic interest
}

Now ,

Account savAcc = new SavingsAccount();

savAcc.calcInterest(); // This will call the method on SavingsAccount class

Account fixAcc = new FixedDepositAccount();

fixAcc.calcInterest() ; // This method will call the method on Account class as there is
// implementation for


The above example illustrated the power of polymorphism where, we can easily modify method implementations without actually breaking the code elsewhere.

So, whenever we call a method on an object, even though we don’t know that type it is, right thing happens at the runtime. This is called Polymorphism.

Inheritance : One line definition “inheriting the features of superclass to the subclass”

Inheritance is the inclusion of the behaviour of the bas class in the derived class so that the methods/members can be accessible in the derived classes. It helps in code reuse, reduced development time and increased maintainability of code.

There are two types of inheritance,

Implementation inheritance – where the subclass extends the functionality of the superclass. Here the derived class has an option to implement all or some of the features of the superclass based on its requirement.
Here you can only extend only one class.

Interface inheritance - This is also known as sub typing. Interfaces provide a mechanism for specifying a relationship between otherwise unrelated classes, typically by specifying a set of common methods each implementing class must contain. Interface inheritance promotes the design concept of program to interfaces not to implementations. This also reduces the coupling or implementation dependencies between systems. In Java, you can implement any number of interfaces. This is more flexible than implementation inheritance because it won’t lock you into specific implementations which make subclasses difficult to maintain. So care should be taken not to break the implementing classes by modifying the interfaces.


Encapsulation – Data Hiding or Hiding the implementation details

Encapsulation refers to keeping all related members (methods and variables) together in an object. Encapsulation results in modular code making them safe and preventing the misuse of the members.

Marking the instance variables of an Object as private and provide public methods for accessing the variables make a class (Object) tightly encapsulated. By this, we can restrict the access of instance variables and we can change the business logic for the variables without actually breaking the code.

For ex:

public class Bowling
{
private int noOfDeliveries;

public void setNoOfDeliveries(int balls)
{
// here we can write a logic to restrict the user to only set the
// value of instance variable between 0 and 6
// preventing the instance variable being corrupted with invalid values
}
}

Thursday, April 17, 2008

Interview Questions on Struts Framework

The Struts Framework is becoming popular day by day and it has become a hot selling expertise in IT field. Struts Framework has become an important skill to have for a Java Web Developer and the IT industry is looking out for more and more struts developers.

Even though we have lot of experience, we sometime fail to answer from basic questions on Struts Framework. So here is the collection of some frequently asked questions on struts framework for your quick reference during Job hunt.

Frequently asked questions on Struts


1. What is Struts? Explain in some few words

Struts framework is a popular framework for developing web applications using Java technology. It follows Model – View – Control (MVC) architecture.

The core of the Struts framework is a flexible control layer based on standard technologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various Jakarta Commons packages. Struts encourage application architectures based on the Model 2 approach, a variation of the classic Model-View-Controller (MVC) design paradigm.
Struts provide its own Controller component and integrate with other technologies to provide the Model and the View. For the Model, Struts can interact with standard data access technologies, like JDBC and EJB, as well as most any third-party packages, like Hibernate, iBATIS, or Object Relational Bridge. For the View, Struts works well with Java Server Pages (JSP), including JSTL and JSF, as well as Velocity Templates, XSLT, and other presentation systems.
The Struts framework provides the invisible underpinnings every professional web application needs to survive. Struts helps you create an extensible development environment for your application, based on published standards and proven design patterns.

2. What is Jakarta Struts Framework?

Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.

3. What is Action Servlet?

The class org.apache.struts.action.ActionServlet is called the ActionServlet. In the Jakarta Struts Framework this class plays the role of controller. All the requests to the server go through the controller. Controller is responsible for handling all the requests.

4. How you will make available any Message Resources Definitions file to the Struts Framework Environment?

The Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project.

Message Resources Definitions files can be added to the struts-config.xml file through tag.

Example:
.

5. What is Action Class?

The Action Class is part of the Model and is a wrapper around the business logic.

The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. In the Action Class all the database/business processing is done. It is advisable to perform all the database related stuffs in the Action Class.

The ActionServlet (commad) passes the parameterized class to Action Form using the execute () method. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.

6. What is ActionForm?

An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm.

ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.

7. What is Struts Validator Framework?

Struts Framework provides the functionality to validate the form data. It can be used to validate the data on the user’s browser as well as on the server side.

Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class.

The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.

8. Give the Details of XML files used in Validator Framework?
The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml to define the form specific validations. The validation.xml defines the validations applied to a form bean.

9. How you will display validation fail errors on jsp page?

Following tag displays all the errors:


10. How you will enable front-end validation based on the xml in validation.xml?

The tag to allow front-end validation based on the xml in validation.xml.

For example the code:


generates the client side java script for the form \"logonForm\" as defined in the validation.xml file.

The when added in the jsp file generates the client site validation script.

11. How to get data from the velocity page in a action class?

We can get the values in the action classes by using
data.getParameter(\"variable name defined in the velocity page\");


Will update some more questions soon.

Leave you comments and questions and will reply to it.
Checkout my other blogs
http://vinayknl.blogspot.com/

References
http://struts.apache.org/
- Vinay

Tuesday, April 15, 2008

Java interview discussions - 1

Java interview discussion

Interviewer : Do you know why Java is used by us for developing apps over other programming languages??

Candidate : Java is a fun language to work with. It is an Object Oriented language and has better portability than other languages.

Java has a built-in support for multi-threading, socket communication, and memory management (automatic garbage Collection).

It also supports Web based applications (Applet, Servlet, and JSP), distributed applications (sockets, RMI. EJB etc) and network protocols (HTTP, JRMP etc) with the help of extensive standardised APIs (Application Program
Interfaces).

Interviewer : What do you mean by "Java Platform"

Candidate : Java platform is a software-only platform, which runs on top of other hardware-based platforms like UNIX, NT etc.

The Java platform has 2 components:

1. Java Virtual Machine (JVM) – ‘JVM’ is software that can be ported onto various hardware platforms. Byte codes are the machine language of the JVM.
2. Java Application Programming Interface (Java API).

Wednesday, April 9, 2008

Java Collections – Part 1

Interview questions on Java Collections API

1. What is the Collections API?

The Collections API is a set of classes and interfaces that support operations on collections of objects.

2. What is the List interface?

The List interface provides support for ordered collections of objects.

3. What is the Vector class?

The Vector class provides the capability to implement a growable array of objects.

4. What is an Iterator interface?

The Iterator interface is used to step through the elements of a Collection.

5. Which java.util classes and interfaces support event handling?

The EventObject class and the EventListener interface support event processing.

6. What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars

7. What is the Locale class?

The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.

8. What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar.

9. What is the Map interface?

The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.

10. What is the highest-level event class of the event-delegation model?

The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy.

11. What is the Collection interface?

The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates.

12. What is the Set interface?

The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.

13. What is the typical use of Hashtable?

Whenever a program wants to store a key value pair, one can use Hashtable.

14. I am trying to store an object using a key in a Hashtable. And some other object already exists in that location, then what will happen? The existing object will be overwritten? Or the new object will be stored elsewhere?

The existing object will be overwritten and thus it will be lost.

15. What is the difference between the size and capacity of a Vector?

The size is the number of elements actually stored in the vector, while capacity is the maximum number of elements it can store at a given instance of time.

16. Can a vector contain heterogeneous objects?

Yes a Vector can contain heterogeneous objects. Because a Vector stores everything in terms of Object.

17. Can an ArrayList contain heterogeneous objects?

Yes a ArrayList can contain heterogeneous objects. Because an ArrayList stores everything in terms of Object.

18. What is an enumeration?

An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.

19. Considering the basic properties of Vector and ArrayList, where will you use Vector and where will you use ArrayList?

The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than the synchronized one.


- Vinay

Check out my other blogs

http://internetpatrol.blogspot.com
http://vinayknl.blogspot.com

Some useful links
Java Website

Thursday, April 3, 2008

DataBase interview questions - Part 1

Collection of questions on DB and SQL

1. What is SQL?

SQL stands for 'Structured Query Language'.

2. What is SELECT statement?

The SELECT statement lets you select a set of values from a table in a database. The values selected from the database table would depend on the various conditions that are specified in the SQL query.

3. How can you compare a part of the name rather than the entire name?

SELECT * FROM people WHERE empname LIKE '%ab%'
Would return a recordset with records consisting empname the sequence 'ab' in empname .

4. What is the INSERT statement?

The INSERT statement lets you insert information into a database.

5. How do you delete a record from a database?

Use the DELETE statement to remove records or any particular column values from a database.

6.How could I get distinct entries from a table?

The SELECT statement in conjunction with DISTINCT lets you select a set of distinct values from a table in a database. The values selected from the database table would of course depend on the various conditions that are specified in the SQL query. Example
SELECT DISTINCT empname FROM emptable

7.How to get the results of a Query sorted in any order?

A:You can sort the results and return the sorted results to your program by using ORDER BY keyword thus saving you the pain of carrying out the sorting yourself. The ORDER BY keyword is used for sorting.

SELECT empname, age, city FROM emptable ORDER BY empname

8. How can I find the total number of records in a table?

You could use the COUNT keyword , example

SELECT COUNT(*) FROM emp WHERE age>40


9. What is GROUP BY?

A:The GROUP BY keywords have been added to SQL because aggregate functions (like SUM) return the aggregate of all column values every time they are called. Without the GROUP BY functionality, finding the sum for each individual group of column values was not possible.


10.What is the difference among "dropping a table", "truncating a table" and "deleting all records" from a table.


Dropping : (Table structure + Data are deleted), Invalidates the dependent objects ,Drops the indexes
Truncating: (Data alone deleted), Performs an automatic commit, Faster than delete
Delete : (Data alone deleted), Doesn’t perform automatic commit


11. What are the Large object types suported by Oracle?

Blob and Clob.


12.Difference between a "where" clause and a "having" clause.

Having clause is used only with group functions whereas Where is not used with.

13. What's the difference between a primary key and a unique key?

Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only.


14. What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors?

Cursors allow row-by-row prcessing of the resultsets.
Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information.
Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip, where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors.
Most of the times, set based operations can be used instead of cursors.


15. What are triggers? How to invoke a trigger on demand?

Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or DELETE operation takes place on a table.
Triggers can't be invoked on demand. They get triggered only when an associated action (INSERT, UPDATE, DELETE) happens on the table on which they are defined.
Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers, as constraints are much faster.


16. What is a join and explain different types of joins.

Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table.
Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.


17. What is a self join?

Self join is just like any other join, except that two instances of the same table will be joined in the query.

Wednesday, April 2, 2008

JDBC interview questions - Part 1

Here is a compilation of some frequently asked JDBC questions in job interviews

1. What is JDBC?

Ans : JDBC stands for Java Database Connectivity. It is an API which provides easy connection to a wide range of databases. To connect to a database we need to load the appropriate driver and then request for a connection object.

The Class.forName(….) will load the driver and register it with the DriverManager

2. What is a Transaction?

Ans: A transaction is a set of operations that should be completed as a unit. If one operation fails then all the other operations fail as well.

3. What are the steps in the JDBC connection?

Ans : While making a JDBC connection we go through the following steps :

Step 1 : Register the database driver by using :
Class.forName(\" driver classs for that specific database\" );

Step 2 : Now create a database connection using :
Connection con = DriverManager.getConnection(url,username,password);

Step 3: Now Create a query using :
Statement stmt = Connection.Statement(\"select * from TABLE NAME\");

Step 4 : Exceute the query :
stmt.exceuteUpdate();


4. What is the difference between statements and prepared statements?

Ans : Prepared statements offer better performance, as they are pre-compiled. Prepared statements reuse the same execution plan for different arguments rather than creating a new execution plan every time. Prepared statements use bind arguments, which are sent to the database engine. This allows mapping different
requests with same prepared statement but different arguments to execute the same execution plan.

5. Which are te types of JDBC drivers ?

Ans: a. JDBC-ODBC Bridge Driver (Type-1 driver)
b. Native API Partly Java Driver (Type-2 driver)
c. Net protocol pure Java Driver (Type-3 driver)
d. Native protocol Pure Java Driver (Type-4 driver)

6.What are the types of resultsets in JDBC3.0? How you can retrieve information of resultset?

Ans: ScrollableResultSet and ResultSet. We can retrieve information of resultset by using java.sql.ResultSetMetaData interface. You can get the instance by calling the method getMetaData() on ResulSet object.

7. How can we store java objects in database ?

Ans: We can store java objects by using setObject(), setBlob() and setClob() methods in PreparedStatement.

8. What do you mean by isolation level?

Ans: Isolation means that the business logic can proceed without consideration for the other activities of the system.

9. List some exceptions thrown by JDBC

A. BatchUpdateException , DataTruncation , SQLException , SQLWarning

10. In which interface the methods commit() & rollback() are defined ?

Ans: java.sql.Connection interface

11. How to binary data is stored in the database ?

Ans: The binary data such as images are stored as binary streams
- getBinaryStream(), setBinaryStream()). It will not be visible in database, it is stored in form of bytes, to make it visible we have to use any one frontend tool.

12. How to check null value in JDBC?

A. By using the method wasNull() in ResultSet ,it returns boolean value. Returns whether the last column read had a value of SQL NULL. Note that you must first call one of the getXXX methods on a column to try to read its value and then call the method wasNull to see if the value read was SQL NULL.