Wednesday, January 25, 2012

Core Java Interview Questions - Exception Handling

The following are some questions you might encounter with respect to Java Exception Handling in any Interview. Exception Handling is an important part of any Java Application because, this determines how gracefully you capture and handle unexpected situations. 

Apart from the questions below, there are a few articles that I have put up (as part of the SCJP Certification series) on Exception Handling that you might find useful. You can use them to revise/review your understanding of Exception Handling. 

They are: 

Exception Handling 
Common Exceptions & Errors 


1. How could Java classes direct messages to a file instead of the Console? 

The System class has a variable "out" that represents the standard output, and the variable "err" that represents the standard error device. By default, they both point at the system console. 

The standard output could be re-directed to a file as follows: 

Stream st = new Stream(new FileOutputStream("output.txt")); 

2. Does it matter in what order catch statements for FileNotFoundException and IOException are written? 

Yes, it does. The child exceptions classes must always be caught first and the "Exception" class should be caught last. 

3. What is user-defined exception in java ? 

User-defined expections are the exceptions defined by the application developer which are errors related to specific application. Application Developer can define the user defined exception by inheriting the Exception class. Using this class we can create & throw new exceptions. 

4. What is the difference between checked and Unchecked Exceptions in Java ? 

Checked exceptions must be caught using try-catch() block or thrown using throws clause. If you dont, compilation of program will fail. whereas we need not catch or throw Unchecked exceptions. 

5. What is the catch or declare rule for method declarations? 

If a checked exception may be thrown within the body of a method, the method must either catch that exception or declare it in its throws clause. This is done to ensure that there are no orphan exceptions that are not handled by any method. 

6. What is the purpose of the finally clause of a try-catch-finally statement? 

The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. It is usually used in places where we are connecting to a database so that, we can close the connection or perform any cleanup even if the query execution in the try block caused an exception. 

7. What classes of exceptions may be caught by a catch clause? 

A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. 

8. Can an exception be rethrown? 

Yes, an exception can be rethrown any number of times. 

9. When is the finally clause of a try-catch-finally statement executed? 

The finally clause of the try-catch-finally statement is always executed after the catch block is executed, unless the thread of execution terminates or an exception occurs within the execution of the finally clause. 

10. What classes of exceptions may be thrown by a throw statement? 

A throw statement may throw any expression that may be assigned to the Throwable type. 

11. What happens if an exception is not caught? 

An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown. 

12. What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?

The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination. 

13. Can try statements be nested? 

Try statements can be tested. It is possible to nest them to any level, but it is preferable to keep the nesting to 2 or 3 levels at max. 

14. How does a try statement determine which catch clause should be used to handle an exception?

When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception that was thrown, is executed. The remaining catch clauses are ignored. 

15. What is difference between error and exception 

Error occurs at runtime and cannot be recovered, Outofmemory is one such example. Exceptions on the other hand are due conditions which the application encounters, that can be recovered such as FileNotFound exception or IO exceptions 

16. What is the base class from which all exceptions are subclasses 

All exceptions are subclasses of a class called java.lang.Throwable 

17. How do you intercept and control exceptions 

We can intercept and control exceptions by using try/catch/finally blocks. 

You place the normal processing code in try block 
You put the code to deal with exceptions that might arise in try block in catch block 
Code that must be executed no matter what happens must be place in finally block 

18. When do we say an exception is handled 

When an exception is thrown in a try block and is caught by a matching catch block, the exception is considered to have been handled. Or when an exception thrown by a method is caught by the calling method and handled, an exception can be considered handled. 

19. When do we say an exception is not handled 

There is no catch block that names either the class of exception that has been thrown or a class of exception that is a parent class of the one that has been thrown, then the exception is considered to be unhandled, in such condition the execution leaves the method directly as if no try has been executed 

20. In what sequence does the finally block gets executed 

If you put finally after a try block without a matching catch block then it will be executed after the try block 
If it is placed after the catch block and there is no exception then also it will be executed after the try block 
If there is an exception and it is handled by the catch block then it will be executed after the catch block 

21. What can prevent the execution of the code in finally block 

Theoretically, the finally block will execute no matter what. But practically, the following scenarios can prevent the execution of the finally block. 

* The death of thread 
* Use of system.exit() 
* Turning off the power to CPU 
* An exception arising in the finally block itself 

22. What are the rules for catching multiple exceptions? 

A more specific catch block must precede a more general one in the source, else it gives compilation error about unreachable code blocks. 

23. What does throws statement declaration in a method indicate? 

This indicates that the method throws some exception and the caller method should take care of handling it. If a method invokes another method that throws some exception, the compiler will complain until the method itself throws it or surrounds the method invocation with a try-catch block. 

24. What are checked exceptions? 

Checked exceptions are exceptions that arise in a correct program, typically due to user mistakes like entering wrong data or I/O problems. Checked Exceptions can be caught and handled by the programmer to avoid random error messages on screen. 

25. What are runtime exceptions 

Runtime exceptions are due to programming bugs like out of bound arrays or null pointer exceptions. 

26. What is difference between Exception and errors 

Errors are situations that cannot be recovered and the system will just crash or end. Whereas, Exceptions are just unexpected situations that can be handled and the system can recover from it. We usually catch & handle exceptions while we dont handle Errors. 

27. How will you handle the checked exceptions 

You can provide a try/catch block to handle it or throw the exception from the method and have the calling method handle it. 

28. When you extend a class and override a method, can this new method throw exceptions other than those that were declared by the original method? 

No it cannot throw, except for the subclasses of the exceptions thrown by the parent class's method. 

29. Is it legal for the extending class which overrides a method which throws an exception, not to throw in the overridden class? 

Yes, it is perfectly legal.

If you have any questions that you want answer for, please leave a comment on this page OR drop a note to Snehal[at]TechProceed[dot]com and I will answer them.

Happy Learning!

Friday, January 20, 2012

Java Database Connectivity JDBC Interview Questions

Well, here we go. The following are some questions that you may encounter on JDBC concepts during your interviews. Remember that if you are a junior level developer (with less than 3 years working experience) many of these questions may seem too complicated for you and frankly you won’t be expected to know them either. 

You cannot think of an Enterprise Java Application that does not connect to a database. So, a strong understanding of JDBC concepts is crucial to your success as a potential candidate during an interview. 

Questions – Part 1: 

1. What is the JDBC? 

Java Database Connectivity (JDBC) is a standard Java API that is used to interact with relational databases from within a Java application. JDBC has set of classes and interfaces which can use from our Java application and interact with the database.

2. What are the Basic Steps in writing a Java program to connect to a database using JDBC? 

The basic steps in connecting to a database using JDBC are: 

1. Load the RDBMS specific JDBC driver because this driver actually communicates with the database (Incase of JDBC 4.0 this is automatically loaded). 
2. Open the connection to database which is then used to send SQL statements and get results back. 
3. Create JDBC Statement object. This object contains SQL query. 
4. Execute statement which returns resultset(s). ResultSet contains the tuples of database table as a result of SQL query. 
5. Process the result set. 
6. Close the connection. 

3. What are the main components of JDBC ? 

The five main components of JDBC are:

1. Driver Manager
2. Driver
3. Connection
4. Statement &
5. ResultSet 

4. How does a JDBC application work? 

A JDBC application can be logically divided into two layers: 
1. Driver layer 
2. Application layer 

First the Driver layer consists of DriverManager class and the available JDBC drivers. The application begins with requesting the DriverManager for the connection. An appropriate driver is choosen and is used for establishing the connection. This connection is given to the application which falls under the application layer. The application uses this connection to create Statement kind of objects, through which SQL commands are sent to backend and obtain the results. 

5. How do I load a database driver with JDBC 4.0 / Java 6? 

Provided the JAR file containing the driver is properly configured, just place the JAR file in the classpath. Java developers NO longer need to explicitly load JDBC drivers using code like Class.forName() to register a JDBC driver.The DriverManager class takes care of this by automatically locating a suitable driver when the DriverManager.getConnection() method is called. This feature is backward-compatible, so no changes are needed to the existing JDBC code.

Remember - if the correct JAR Files are missing in the classpath, this auto feature will not work 

6. What is JDBC Driver interface? 

The JDBC Driver interface provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each vendor driver must provide implementations of the java.sql.Connection, Statement, PreparedStatement, CallableStatement, ResultSet and Driver so that the Java classes that connect to the database can use them. 

7. What does the connection object represents? 

The connection object represents a literal connection or a communication context through which our Java code can interact with a database. i.e., all communication with database is through connection object only.

8. What is a Statement? 

The Statement acts like a vehicle through which SQL commands can be sent. You can create a Statement as follows: 

Statement stmt = conn.createStatement();

This method returns an object which implements statement interface which can be executed. 

9. What is a PreparedStatement? 

A prepared statement is an SQL statement that is precompiled by the database. It is a sub-set of the Statement. Through precompilation, prepared statements improve the performance of SQL commands that are executed multiple times (given that the database supports prepared statements). Once compiled, prepared statements can be customized prior to each execution by altering predefined SQL parameters. 

You can create a prepared statement as follows: 

PreparedStatement pstmt = conn.prepareStatement("UPDATE Emp_Salary SET Salary = ? WHERE Emp_Id = ?");
pstmt.setBigDecimal(1, 75000.00);
pstmt.setInt(2, 12345);

Note that conn is an instance of the collection class and the "?" represent the parameters that are to be passed to the query/prepared statement before it can be executed. 

10. What are callable statements? 

Callable statements are used from JDBC application to invoke stored procedures and functions objects of a database.

11. Can you call a stored procedure using JDBC? If so, how? 

Yes, you can call Stored Procedures using JDBC. we have to use the CallableStatement to do so. 


CallableStatement stproc_stmt = conn.prepareCall("{call procname(?,?,?)}");

Here conn is an instance of the Connection class.

12. How many types of JDBC drivers are there and What are they? 

There are four types of drivers defined by JDBC as follows: 
1. Type 1 – JDBC-ODBC Bridge 
2. Type 2 – Native API (Partly Java) Driver
3. Type 3 – Net-Protocol Fully Java Driver
4. Type 4 – Pure Java Driver

Type 4 JDBC driver is most preferred kind of approach in JDBC.

13. Which type of JDBC driver is the fastest one? 

JDBC Net pure Java driver(Type IV) is the fastest driver because it converts the JDBC calls into vendor specific protocol calls and it directly interacts with the database. 

14. Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection? 

No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.

15. What are the standard transaction isolation levels defined by JDBC? 

The values are defined in the class java.sql.Connection and are: 


You need to double check that the database you are connecting to, supports these isolation levelts. 

16. What is a ResultSet? 

The ResultSet represents set of rows retrieved due to query execution. You get a result set object as the output when you execute a query using the Statement or the PreparedStatement objects. 

ResultSet rs = stmt.executeQuery(sqlQuery);

17. What are the types of resultsets? 

JDBC supports 3 types of ResultSets. They are: 


18. What are the types of statements in JDBC?

The JDBC API has 3 types of Statement Interfaces. They are:

1. Statement
2. PreparedStatement
3. CallableStatement

19. What are the differences/key features between the 3 different types of Statements in JDBC? 

* This interface is used for executing a static SQL statement and returning the results it produces. 
* The object of Statement class can be created using Connection.createStatement() method. 

* A SQL statement is pre-compiled and stored in a PreparedStatement object.
* This object can then be used to efficiently execute this statement multiple times.
* The object of PreparedStatement class can be created using Connection.prepareStatement() method. This extends Statement interface. 

* This interface is used to execute SQL stored procedures.
* This extends PreparedStatement interface.
* The object of CallableStatement class can be created using Connection.prepareCall() method.

20. What is Connection pooling? What are the advantages of using a connection pool?

Connection Pooling is a technique used for sharing the server resources among requested clients. It was pioneered by database vendors to allow multiple clients to share a cached set of connection objects that provides access to a database. Getting connection and disconnecting are costly operation, which affects the application performance, so we should avoid creating multiple connection during multiple database interactions. A pool contains set of Database connections which are already connected, and any client who wants to use it can take it from pool and when done with using it can be returned back to the pool. Apart from performance this also saves you resources as there may be limited database connections available for your application. 

21. What does the Class.forName() method do? 

Method forName() is a static method of java.lang.Class. This can be used to dynamically load a class at run-time. Class.forName() loads the class if its not already loaded. It also executes the static block of loaded class. Then this method returns an instance of the loaded class. So a call to Class.forName('MyClass') is going to do following 
- Load the class MyClass.
- Execute any static block code of MyClass.
- Return an instance of MyClass.

JDBC Driver loading using Class.forName is a good example of best use of this method. The driver loading is done like this 


All JDBC Drivers have a static block that registers itself with DriverManager and DriverManager has static initializer method registerDriver() which can be called in a static blocks of Driver class. A MySQL JDBC Driver has a static initializer which looks like this: 

static { 
try { 
java.sql.DriverManager.registerDriver(new Driver()); 
} catch (SQLException E) { 
throw new RuntimeException("Can't register driver!"); 

Class.forName() loads driver class and executes the static block and the Driver registers itself with the DriverManager. 

22. When to use a PreparedStatement and when to use a Statement?

Statement is a object used for executing a static SQL statement and returning the results it produces. PreparedStatement is a SQL statement which is precompiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times. 

There are few advantages of using PreparedStatements over Statements 
* Since its pre-compiled, Executing the same query multiple times in loop, binding different parameter values each time is faster. 
* In PreparedStatement the setDate()/setString() methods can be used to escape dates and strings properly, in a database-independent way.
* SQL injection attacks on a system are virtually impossible while using PreparedStatements.

23. What do you mean by the term pre-compiled from a PreparedStatemnet perspective? 

The prepared statement(pre-compiled) concept is not specific to Java, it is a database concept. Statement precompiling means: when you execute a SQL query, database server will prepare a execution plan before executing the actual query, this execution plan will be cached at database server for further execution which makes it much faster than executing a fresh query that has to be compiled before execution. 

24. What does setAutoCommit(false) do?

A JDBC connection is created in auto-commit mode by default. This means that each individual SQL statement is treated as a transaction and will be automatically committed as soon as it is executed. If you require two or more statements to be grouped into a transaction then you need to disable auto-commit mode manually as follows: 


Once auto-commit mode is disabled, no SQL statements will be committed until you explicitly call the commit method as follows:


Alternately, if you want to ensure that all further transactions/queries are auto-committed then you can enable auto-commit as follows:


25. What are database warnings and How can I get them?

Warnings are issued by database to notify user of a problem which may not be very severe. Database warnings do not stop the execution of SQL statements. In JDBC SQLWarning is an exception that provides information on database access warnings. Warnings are silently chained to the object whose method caused it to be reported. Warnings may be retrieved from Connection, Statement, and ResultSet objects. 

The call to the getWarnings() method of either of these objects retrieves the first warning reported by calls on this object. If there is more than one warning, subsequent warnings will be chained to the first one and can be retrieved by calling the method SQLWarning.getNextWarning on the warning that was retrieved previously. 

Questions – Part 2: 

1. How will you retreive database warnings from a Connection object in JDBC? 

//Retrieving warning from connection object 
SQLWarning warning = conn.getWarnings(); 

//Retrieving next warning from warning object itself 
SQLWarning nextWarning = warning.getNextWarning(); 

2. How will you retreive database warnings from a Statement object in JDBC? 

//Retrieving warning from statement object 

//Retrieving next warning from warning object itself 
SQLWarning nextWarning = warning.getNextWarning(); 

3. How will you retreive database warnings from a ResultSet object in JDBC? 

//Retrieving warning from resultset object 

//Retrieving next warning from warning object itself 
SQLWarning nextWarning = warning.getNextWarning(); 

4. What does the clearWarnings() method do? 

A call to clearWarnings() method clears all warnings reported for this object. After a call to this method, the method getWarnings returns null until a new warning is reported for this object. 

5. What happens when I try to call the getWarning() method on a connection/statement/resultset after it has been closed? 

Trying to call the getWarning() method on either of these 3 objects after they are closed will cause an SQLException to be thrown. 

6. Let us say that I just closed my Statement object so, I cannot access the getWarning() on my statement. Can I still access the getWarning() on my ResultSet? 

No. Closing a Statement automatically closes the ResultSet connected to it. So, you will get the same SQLException if you try to do so. 

7. What is DatabaseMetaData? 

JDBC API has 2 Metadata interfaces DatabaseMetaData & ResultSetMetaData. The DatabaseMetaData provides Comprehensive information about the database as a whole. This interface is implemented by driver vendors to let users know the capabilities of a Database Management System (DBMS) in combination with the driver based on JDBC technology ("JDBC driver") that is used with it. Use DatabaseMetaData to find information about your database, such as its capabilities and structure.

8. How will you use the DatabaseMetaData? Can you write a sample example code? 

DatabaseMetaData md = conn.getMetaData(); 
System.out.println("Database Name: " + md.getDatabaseProductName()); 
System.out.println("Database Version: " + md.getDatabaseProductVersion()); 
System.out.println("Driver Name: " + md.getDriverName()); 
System.out.println("Driver Version: " + md.getDriverVersion()); 

9. What is ResultSetMetaData? 

JDBC API has 2 Metadata interfaces DatabaseMetaData & ResultSetMetaData. The ResultSetMetaData is an object that can be used to get information about the types and properties of the columns in a ResultSet object. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns. 

10. How will you use the ResultSetMetaData? Can you write a sample example code? 

ResultSet rs = stmt.executeQuery("SELECT * FROM TABLE_NAME"); 
ResultSetMetaData rsmd = rs.getMetaData(); 
int numberOfColumns = rsmd.getColumnCount(); 
boolean b = rsmd.isSearchable(1); 

11. What is rowset? 

A RowSet is an object that encapsulates a set of rows from either Java Database Connectivity (JDBC) result sets or tabular data sources like a file or spreadsheet. 

12. Why do we need a RowSet?

RowSet is a interface that adds support to the JDBC API for the JavaBeans component model. A rowset, which can be used as a JavaBeans component in a visual Bean development environment, can be created and configured at design time and executed at run time. The RowSet interface provides a set of JavaBeans properties that allow a RowSet instance to be configured to connect to a JDBC data source and read some data from the data source. A group of setter methods (setInt, setBytes, setString, and so on) provide a way to pass input parameters to a rowset's command property. This command is the SQL query the rowset uses when it gets its data from a relational database, which is generally the case. Rowsets are easy to use since the RowSet interface extends the standard java.sql.ResultSet interface so it has all the methods of ResultSet

13. What are the advantages of using RowSet over ResultSet?

There are two clear advantages of using RowSet over ResultSet: 

* RowSet makes it possible to use the ResultSet object as a JavaBeans component. 
* RowSet be used to make a ResultSet object scrollable and updatable. All RowSet objects are by default scrollable and updatable. If the driver and database being used do not support scrolling and/or updating of result sets, an application can populate a RowSet object implementation (e.g. JdbcRowSet) with the data of a ResultSet object and then operate on the RowSet object as if it were the ResultSet object.

14. What are the different types of RowSet ? 
There are two types of RowSet are there. They are: 
* Connected - A connected RowSet object connects to the database once and remains connected until the application terminates. 
* Disconnected - A disconnected RowSet object connects to the database, executes a query to retrieve the data from the database and then closes the connection. A program may change the data in a disconnected RowSet while it is disconnected. Modified data can be updated in the database after a disconnected RowSet reestablishes the connection with the database.

15. Can you give an example of Connected RowSet? 

A JdbcRowSet object is a example of connected RowSet, which means it continually maintains its connection to a database using a JDBC technology-enabled driver. 

16. Can you give an example of Disconnected RowSet?

A CachedRowSet object is a example of disconnected rowset, which means that it makes use of a connection to its data source only briefly. It connects to its data source while it is reading data to populate itself with rows and again while it is propagating changes back to its underlying data source. The rest of the time, a CachedRowSet object is disconnected, including while its data is being modified. Being disconnected makes a RowSet object much leaner and therefore much easier to pass to another component. For example, a disconnected RowSet object can be serialized and passed over the wire to a thin client such as a personal digital assistant (PDA). 

17. What are the benefits of having JdbcRowSet implementation? 

The JdbcRowSet implementation is a wrapper around a ResultSet object that has following advantages over ResultSet 
* This implementation makes it possible to use the ResultSet object as a JavaBeans component. A JdbcRowSet can be used as a JavaBeans component in a visual Bean development environment, can be created and configured at design time and executed at run time. 
* It can be used to make a ResultSet object scrollable and updatable. All RowSet objects are by default scrollable and updatable. If the driver and database being used do not support scrolling and/or updating of result sets, an application can populate a JdbcRowSet object with the data of a ResultSet object and then operate on the JdbcRowSet object as if it were the ResultSet object. 

18. What is the need of BatchUpdates feature in JDBC? 

The BatchUpdates feature allows us to group SQL statements together and send to database server in one single shot instead of multiple calls.

19. What is a DataSource? 

A DataSource object is the representation of a source of data in the Java programming language. 

In basic terms: 
* A DataSource is a facility for storing data. 
* DataSource can be referenced by JNDI. 
* Data Source may point to RDBMS, file System , any DBMS etc..

Typically in enterprise application perspective, the term DataSource can be used interchangeably with a RDBMS database because in almost all cases, our DataSource will be pointing to an RDBMS database. 

20. What are the advantages of DataSource? 

The few advantages of using data source are : 
* An application does not need to hardcode driver information, as it does with the DriverManager. 
* The DataSource implementations can easily change the properties of data sources. For example: There is no need to modify the application code when making changes to the database details. 
* The DataSource facility allows developers to implement a DataSource class to take advantage of features like connection pooling and distributed transactions. 

21. What is the difference between a Statement and a PreparedStatement? 

Some of the main differences between a statement & PreparedStatement are: 

A standard Statement is used to create a Java representation of a literal SQL statement and execute it on the database. A PreparedStatement is a precompiled statement. This means that when the PreparedStatement is executed, the RDBMS can just run the PreparedStatement SQL statement without having to compile it first.
Statement has to verify its metadata against the database every time. A prepared statement has to verify its metadata against the database only once.
If you want to execute the SQL statement once go for STATEMENT If you want to execute a single SQL statement multiple number of times, then go for PREPAREDSTATEMENT. PreparedStatement objects can be reused with passing different values to the queries.

22. What’s the difference between TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE in ResultSets? 

An insensitive resultset is like the snapshot of the data in the database when query was executed. A sensitive resultset does NOT represent a snapshot of data, rather it contains points to those rows which satisfy the query condition.
After we get the resultset the changes made to data are not visible through the resultset, and hence they are known as insensitive. After we obtain the resultset if the data is modified then such modifications are visible through resultset.
Performance not effected with insensitive. Since a trip is made for every ‘get’ operation, the performance drastically get affected.

If you have any questions that you want answer for, please leave a comment on this page OR drop a note to Snehal[at]TechProceed[dot]com and I will answer them.

Happy Learning!

Tuesday, January 10, 2012

Java Strings Interview Questions

The following are some questions you might encounter with respect to Strings in any Java Interview. Strings are very powerful and frankly speaking, there can be no Java based application that does not use Strings. 

Apart from the questions below, there are a few articles that I have put up (as part of the SCJP Certification series) on Strings that you might find useful. You can use them to revise/review your understanding of Strings. 

They are: 

Java String Class
StringBuffer & StringBuilder


1. What would you use to compare two String variables - the operator == or the equals() method? 

I would personally prefer/use the equals() method to compare two Strings if I want to check the value of the Strings and the == operator if I want to check if the two variables point to the same instance of the String object. 

2. For concatenation of strings, which method is good, StringBuffer or String ? 

StringBuffer is faster than String for concatenation. Also, it is less memory/resource intensive when compared to Strings. 

3. As a continuation to the previous question - Why would you say StringBuffers are less resource intensive than Strings during Concatenation? 

As you might already know, Strings are immutable. So, when you concatenate some value to a String, you are actually creating a fresh String object that is going to hold some more data. This way you have created a new object while the old String object is still alive. As you keep concatenating values to the String, newer objects are going to get created which are going to use up the virtual memory. Whereas, if you use a StringBuffer, you are just editing the objects value rather than creating new objects. 

4. To what value is a variable of the String type automatically initialized? 

The default value of String variable is null. 

5. What is the difference between the String and StringBuffer classes? 

String objects are constants or in other words immutable while StringBuffer objects are not. 

6. What happens when you add a double value to a String? 

The result is a String object. For that matter, if you add anything to a String, you will end up with a String. 

7. What will be the result if you compare StringBuffer with String if both have same values? 

It will return false as you cannot compare String with StringBuffer directly. If you really want to compare the contents of the String & the StringBuffer you would have to invoke the equals method with the String and the toString() output of the StringBuffer. 

8. What is difference between String, StringBuffer and StringBuilder? When to use them?

For all practical understanding purposes, all these 3 classes are used to handle/manipulate Strings. The main difference between these 3 classes is:

* Strings are immutable while StringBuffer & StringBuilder objects are mutable (can be modified)
* StringBuffer is synchronized (thread safe) while StringBuilder is not. 

9. When to use Strings or StringBuffer or StringBuilder? What will drive this decision? 

The type of objects you need to create and how they will be used will drive this decision. So, 

* If the object value is not going to change, use the String class
* If the object value will be changed frequently we must choose either the StringBuffer or the StringBuilder. 
* Here, if your object will be accessed only by a single thread use StringBuilder because it is faster 
* If your object may be accessed my multiple threads use the StringBuffer because it is thread safe 

Note: Thread safety is not free and comes at the expense of performance. So, if your system is not multi-threaded then use the StringBuilder which will be much faster than the StringBuffer. 

10. Why String class is final or immutable?

The reason "Why" the string class is final is because - The developers of the Java language did not want programmers to mess with the basic functionality of the String Class. Almost all the basic or core functionality related classes in Java are final for the same reason. 

If String were not final, you could create a subclass and have two strings that look alike when you see the value in the string, but that are actually different. 

Ex: See the two string objects below, MyString and YourString are two classes that are sub-classes of the "String" class and contain the same value but their equality check might fail which does not look right. Doesnt it? 

MyString str1 = "Rocky";
YourString str2 = "Rocky";

This is why String class is final. 

If you have any questions that you want answer for, please leave a comment on this page OR drop a note to Snehal[at]TechProceed[dot]com and I will answer them.

Happy Learning!

Java Threads & Multi-threading Interview Questions

The following are some questions you might encounter with respect to Java Multi-threading in any Interview. Multi-threading is a powerful and rather a complicated feature of Java. Expertise in multithreading is an added advantage to any and every core java programmer. 

Apart from the questions below, there are a few articles that I have put up (as part of the SCJP Certification series) on Java Multi-threading that you might find useful. You can use them to revise/review your understanding of Servlets. 

They are: 

Introduction to Threads and Multithreading 
Thread States and Transitions 
Preventing Thread Execution 
Thread Priorities 
Thread Synchronization 
Thread Interactions 


1. Why would you use a synchronized block vs. synchronized method? 

Synchronized blocks place locks for shorter periods than synchronized methods. 

2. What's the difference between the methods sleep() and wait() 

The code sleep(1000); puts thread to sleep (Or prevent the thread from executing) for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. 

The method wait() is defined in the class Object and the method sleep() is defined in the class Thread. 

3. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it? 

If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface. 

4. What is Runnable interface ? Are there any other ways to make a multithreaded java program? 

There are two ways to create new threads: 

- Define a new class that extends the Thread class 
- Define a new class that implements the Runnable interface, and pass an object of that class to a Thread's constructor. 

The advantage of the second approach is that the new class can be a subclass of any class, not just of the Thread class. 

5. How can I tell what state a thread is in ? 

Prior to Java 5, isAlive() was commonly used to test a threads state. If isAlive() returned false the thread was either new or terminated but there was simply no way to differentiate between the two. 

Starting with the release of Java Tiger (Java 5) you can now get what state a thread is in by using the getState() method which returns an Enum of Thread.States. A thread can only be in one of the following states at a given point in time. 

New, Runnable, Blocked, Waiting, Timed_waiting and Terminated 

6. What is the difference between notify and notify All methods ? 

A call to notify causes at most one thread waiting on the same object to be notified (i.e., the object that calls notify must be the same as the object that called wait). A call to notifyAll causes all threads waiting on the same object to be notified. If more than one thread is waiting on that object, there is no way to control which of them is notified by a call to notifyAll 

so, sometimes it is better to use notify than notifyAll. 

7. What is synchronized keyword? In what situations you will Use it? 

Synchronization is the act of serializing access to critical sections of code. We will use this keyword when we expect multiple threads to access/modify the same data. It helps prevent dirty read/write and helps keep thread execution clean and seperate. For more details on why we need Synchronization and how to use it, you can visit the article on Thread Synchronization as it is a large topic to be covered as an answer to a single question. 

8. Why do threads block on I/O?

Threads block on i/o (i.e., Thread enters the waiting state) so that other threads may execute while the i/o Operation is performed. This is done to ensure that one thread does not hold on to resources while it is waiting for some user input - like entering a password. 

9. What is synchronization and why is it important?

With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors. For more details on why we need Synchronization and how to use it, you can visit the article on Thread Synchronization as it is a large topic to be covered as an answer to a single question. 

10. Can a lock be acquired on a class?

Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object. 

11. What's new with the stop(), suspend() and resume() methods in JDK 1.2?

Actually there is nothing new about these methods. The stop(), suspend() and resume() methods have been deprecated as of JDK 1.2. 

12. What state does a thread enter when it terminates its processing? 

When a thread terminates its processing, it enters the dead state. 

13. How do you make threads to wait for one another to complete execution as a group? 

We can use the join() method to make threads wait for one another

14. What is the difference between yielding and sleeping? 

When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state. 

15. What is the difference between preemptive scheduling and time slicing?

Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and many other factors. You can refer to articles on Operating Systems and processor scheduling for more details on the same. 

16. When a thread blocks on I/O, what state does it enter? 

A thread enters the waiting state when it blocks on I/O. 

17. What is a task's priority and how is it used in scheduling? 

A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks. 

18. When a thread is created and started, what is its initial state? 

A thread is in the ready state after it has been created and started. 

19. What invokes a thread's run() method? 

After a thread is started, via its start() method, the JVM invokes the thread's run() method when the thread needs to be executed. 

20. What method is invoked to cause an object to begin executing as a separate thread? 

The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread. 

21. What is the purpose of the wait(), notify(), and notifyAll() methods? 

The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods. 

22. What are the high-level thread states? 

The high-level thread states are ready, running, waiting, and dead. 

23. What is an object's lock and which object's have locks? 

An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object. 

24. What happens when a thread cannot acquire a lock on an object?

If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available. 

25. How does multithreading take place on a computer with a single CPU? 

The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially. 

26. What happens when you invoke a thread's interrupt method while it is sleeping or waiting?

When a task's interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown. 

27. How can a dead thread be restarted? 

A dead thread cannot be restarted. Once a thread is dead, it stays dead and there is no way to revive it. 

28. What are three ways in which a thread can enter the waiting state? 

A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method. 

29. What method must be implemented by all threads? 

All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface. Without a run() method, a thread cannot execute. 

30. What are synchronized methods and synchronized statements? 

Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. 

A synchronized statement can be inside a regular method and vice versa. 

31. What are volatile variables 

It indicates that these variables can be modified asynchronously. i.e., there is no need for synchronzing these variables in a multi-threaded environment. 

32. Where does java thread support reside 

It resides in three distinct places 

The java.lang.Thread class (Most of the support resides here) 
The java.lang.Object class 
The java language and virtual machine 

33. What is the difference between Thread and a Process 

Threads run inside process and they share data. 

One process can have multiple threads, if the process is killed all the threads inside it are killed

34. What happens when you call the start() method of the thread 

This registers the thread with a piece of system code called thread scheduler. The schedulers is the entity that determines which thread is actually running. When the start() method is invoked, the thread becomes ready for running and will be executed when the processor allots CPU time to execute it. 

35. Does calling start () method of the thread causes it to run 

No it just makes the thread eligible to run. The thread still has to wait for the CPU time along with the other threads, then at some time in future, the scheduler will permit the thread to run 

36. When the thread gets to execute, what does it execute 

It executes all the code that is placed inside the run() method. 

37. How many methods are declared in the interface runnable 

The runnable method declares only one method : public void run(); 

38. Which way would you prefer to implement threading - by extending Thread class or implementing Runnable interface 

The preferred way will be to use Interface Runnable, because by subclassing the Thread class you have single inheritance i.e you wont be able to extend any other class in Java. 

39. What happens when the run() method returns 

When the run() method returns, the thread has finished its task and is considered dead. You can't restart a dead thread. 

40. What are the different states of the thread 

The different states of Threads are: 

New: Just created Thraed
Running: The state that all threads want to be 
Various waiting states : Waiting, Sleeping, Suspended and Blocked 
Ready : Waiting only for the CPU 
Dead : Story Over

41. What is Thread priority 

Every thread has a priority, the higher priority thread gets preference over the lower priority thread by the thread scheduler 

42. What is the range of priority integer that can be set for Threads? 

It is from 1 to 10. 10 beings the highest priority and 1 being the lowest 

43. What is the default priority of the thread 

The default priority is 5. It is also called the Normal Priority. 

44. What happens when you call Thread.yield() 

It causes the currently executing thread to move to the ready state if the scheduler is willing to run any other thread in place of the yielding thread. Yield is a static method of class Thread 

45. What is the advantage of yielding 

It allows a time consuming thread to permit other threads to execute

46. What happens when you call Thread.sleep() 

It causes the thread to while away time without doing anything and without using the CPU. A call to sleep method requests the currently executing thread to cease executing for a specified amount of time as mentioned in the argument to the sleep method. 

47. Does the thread method start executing as soon as the sleep time is over 

No, after the specified time is over the thread enters into ready state and will only execute when the scheduler allows it to do so. There is no guarantee that the thread will start running as soon as its sleep time is over. 

48. What do you mean by thread blocking 

If a method needs to wait an indeterminable amount of time until some I/O occurrence takes place, then a thread executing that method should graciously step out of the Running state. All java I/O methods behave this way. A thread that has graciously stepped out in this way is said to be blocked. 

49. What threading related methods are there in object class 

wait(), notify() and notifyAll() are all part of Object class and they have to be called from synchronized code only 

50. What is preemptive scheduling 

Preemptive scheduing is a scheduling mechanism wherein, the scheduler puts a lower priority thread on hold when a higher priority thread comes into the waiting queue. The arrival of a higher priority thread always preempts the execution of the lower priority threads. The problem with this system is - a low priority thread might remain waiting for ever. 

51. What is non-preemptive or Time sliced or round robin scheduling 

With time slicing the thread is allowd to execute for a limited amount of time. It is then moved to ready state, where it must wait along with all the other ready threads. This method ensures that all threads get some CPU time to execute. 

52. What are the two ways of synchronizing the code 

Synchronizing an entire method by putting the synchronized modifier in the methods declaration. To execute the method, a thread must acquire the lock of the object that owns the method. 

Synchronize a subset of a method by surrounding the desired lines of code with curly brackets and inserting the synchronized expression before the opening curly. This allows you to synchronize the block on the lock of any object at all, not necessarily the object that owns the code 

53. What happens when the wait() method is called 

The following things happen: 

The calling thread gives up CPU 
The calling thread gives up the lock 
The calling thread goes into the monitor's waiting pool 

54. What happens when the notify() method is called 

One thread gets moved out of monitors waiting pool and into the ready state and The thread that was notified must reacquire the monitors lock before it can proceed execution

55. Using notify () method how you can specify which thread should be notified 

You cannot specify which thread is to be notified, hence it is always better to call notifyAll() method 

Questions Contributed by our Blog Readers: 

Contributed by Sweta Pawar:

Which statement at line 17 will ensure that j=10 at line 18

1 class A implements runaible (
2 int i;
3 public void run () (
4 try (
5 thread.sleep(5000);
6 i= 10;
7 ) catch(InterruptedException e) {}
8 )
9 )
11 public class Test {
12 public static void main (string args[]) (
13 try (
14 A a = new A ();
15 Thread t = new Thread (a);
16 t.start(); 
17 ** HERE** 
18 int j= a.i;
20 ) catch (Exception e) {}
21 )
22 )

Answer: t.join();

If you have any questions that you want answer for, please leave a comment on this page OR drop a note to Snehal[at]TechProceed[dot]com and I will answer them.

Happy Learning!

Thursday, January 5, 2012

Inheriting Java: Java Collections Interview Questions - Part 2

As a continuation from the part 1 of questions on the Java Collections topic, this article is going to contain some more questions on the Java Collections area. If you want to visit the part 1 questions click here

Apart from the questions in the Part 1 and below, there are a few articles that I have put up (as part of the SCJP Certification series) on Collections that you might find useful. You can use them to revise/review your understanding of Java collections. 

They are: 

  1. Introduction to Collections 
  2. ArrayList Basics 
  3. Sorting Collections 
  4. Searching Collections 
  5. Collections Summary


1. What is the difference between java.util.Iterator and java.util.ListIterator? 

Iterator - Enables you to traverse through a collection in the forward direction only, for obtaining or removing elements 
ListIterator - extends Iterator, and allows bidirectional traversal of list and also allows the modification of elements. 

2. What is the difference between the HashMap and a Map? 

Map is an Interface which is part of Java collections framework. It stores data as key-value pairs. 
Hashmap is class that implements that using hashing technique. 

3. What does synchronized means in Hashtable context? 

Synchronized means only one thread can modify a hash table at one point of time. Any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released. 
This adds an overhead which makes the Hashtable slower when compared to the Hashmap. You must choose a Hashmap when you want faster performance and choose the Hashtable when you want thread safety

4. Can we make a Hashmap thread safe? If so, how? 

HashMap can be made thread safe by synchronizing it. Example: 
Map m = Collections.synchronizedMap(hashMap); 

5. Why should I always use ArrayList over Vector? 
You should choose an ArrayList over a Vector because – not all systems are multi-threaded and thread safety is not a mandatory requirement. In such cases, using a Vector is not only overkill but also adds a lot of overhead which might slow down system performance. Even if you are just iterating through a vector to display its contents, the lock on it still needs to be obtained which makes it much slower. So, choose the ArrayList over a Vector unless your system is multi-threaded. 

6. 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. 

7. What is the difference between Enumeration and Iterator? 

The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, whereas using Iterator we can manipulate the objects also like adding and removing the objects. So Enumeration is used whenever we want to make Collection objects as Read-only. 

8. What is the difference between Sorting performance of Arrays.sort() vs Collections.sort()? Which one is faster? Which one to use and when?

Actually speaking, the underlying sorting algorithm & mechanism is the same in both cases. The only difference is type of input passed to them. Collections.sort() has a input as List so it does a conversion of the List to an array and vice versa which is an additional step while sorting. So this should be used when you are trying to sort a list. Arrays.sort is for arrays so the sorting is done directly on the array. So clearly it should be used when you have an array available with you and you want to sort it. 

9. What is java.util.concurrent BlockingQueue? How it can be used?

The BlockingQueue is available since Java 1.5. Blocking Queue interface extends collection interface, which provides you the power of collections inside a queue. Blocking Queue is a type of Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element. A typical usage example would be based on a producer-consumer scenario. Note that a BlockingQueue can safely be used with multiple producers and multiple consumers. 

10. What is the ArrayBlockingQueue? 

An ArrayBlockingQueue is a implementation of blocking queue with an array used to store the queued objects. The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. ArrayBlockingQueue requires you to specify the capacity of queue at the object construction time itself. Once created, the capacity cannot be increased. This is a classic "bounded buffer" (fixed size buffer), in which a fixed-sized array holds elements inserted by producers and extracted by consumers. Attempts to put an element to a full queue will result in the put operation blocking; attempts to retrieve an element from an empty queue will be blocked. 

11. Why doesn't Map interface extend Collection?

Though the Map interface is part of collections framework, it does not extend collection interface. This was done as a design decision by Sun when the Collection framework was created. Think of it this way – A Map contains key-value pair data while a general collection contains only a bunch of values. If the map were to extend the collection class, what will we do with the keys and how will we link the values to their corresponding keys? Alternately, if the collection were to extend the Map, then, where will we go to get the key information for all the values that are already in the Collection?

Get the idea? For all practically purposes a Map is considered a collection because it contains a bunch of data in key-value pairs but it does not explicitly extend the collection interface. 

12. Which implementation of the List interface (ArrayList or LinkedList) provides for the fastest insertion of a new element into the list? 


If you are surprised about the answer you see above, read the question again “Fastest Insertion of a new element into the list”. The question is about inserts and not reading data. So, the linkedlist is faster. Because, when an element is inserted into the middle of the list in an ArrayList, the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions. 

13. Which implementation of the List Interface (ArrayList or LinkedList) provides for faster reads during random access of data? 

ArrayList implements the RandomAccess interface, and LinkedList does not. The commonly used ArrayList implementation uses primitive Object array for internal storage. Therefore an ArrayList is much faster than a LinkedList for random access, that is, when accessing arbitrary list elements using the get method. Note that the get method is implemented for LinkedLists, but it requires a sequential scan from the front or back of the list. This scan is very slow. For a LinkedList, there's no fast way to access the Nth element of the list.

14. Which implementation of the List Interface (ArrayList or LinkedList) uses more memory space for the same amount (number) of data? 

Each element of a linked list (especially a doubly linked list) uses a bit more memory than its equivalent in array list, due to the need for next and previous pointers. So, the LinkedList uses more memory space when compared to an ArrayList of the same size

15. Where will you use ArrayList and Where will you use LinkedList? 

If you frequently add elements to the beginning of the List or iterate over the List to delete elements from its interior, you should consider using LinkedList. These operations require constant-time in a LinkedList and linear-time (depending on the location of the object being added/removed) in an ArrayList. 

If the purpose of your collection is to populate it once and read it multiple times from random locations in the list, then the ArrayList would be faster and a better choice because Positional access requires linear-time (depending on the location of the object being accessed) in a LinkedList and constant-time in an ArrayList. 

In short - If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList offers the optimal collection. If, however, you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList offers the better implementation.

16.Why insertion and deletion in ArrayList is slow compared to LinkedList? 

ArrayList internally uses and array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of old array is copied to new array. 

During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion. In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node an updating the next pointer on the last node and the previous pointer on the new node. Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node. 

17.How do you traverse through a collection using its Iterator? 

To use an iterator to traverse through the contents of a collection, follow these steps: 
1. Obtain an iterator to the start of the collection by calling the collection’s iterator() method. 
2. Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true. 
3. Within the loop, obtain each element by calling next(). 

18.How do you remove elements during Iteration? 

Iterator also has a method remove() when remove is called, the current element in the iteration is deleted.

19.What are the main implementations of the List interface? 

The main implementations of the List interface are as follows : 
ArrayList : Resizable-array implementation of the List interface. The best all-around implementation of the List interface. 
Vector : Synchronized resizable-array implementation of the List interface with additional "legacy methods." 
LinkedList : Doubly-linked list implementation of the List interface. May provide better performance than the ArrayList implementation if elements are frequently inserted or deleted within the list. Useful for queues and double-ended queues (deques). 

20.What are the advantages of ArrayList over arrays? 

Some of the advantages ArrayList has over arrays are: 
It can grow dynamically 
It provides more powerful insertion and search mechanisms than arrays. 

21.How to obtain Array from an ArrayList?

Array can be obtained from an ArrayList using toArray() method on ArrayList.
List arrayList = new ArrayList();
Object a[] = arrayList.toArray();

22.Why are Iterators returned by ArrayList called Fail Fast? 

Because, if list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. So, it is considered fail fast. 

23.How do you sort an ArrayList (or any list) of user-defined objects? 

Create an implementation of the java.lang.Comparable interface that knows how to order your objects and pass it to java.util.Collections.sort(List, Comparator).

24.What is the Comparable interface?

The Comparable interface is used to sort collections and arrays of objects using the Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class implementing the Comparable interface can be ordered.
The Comparable interface in the generic form is written as follows: 
interface Comparable
where T is the name of the type parameter.

All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:

int i = object1.compareTo(object2)

If object1 < object2: The value of i returned will be negative. 

If object1 > object2: The value of i returned will be positive. 

If object1 = object2: The value of i returned will be zero. 

25.What are the differences between the Comparable and Comparator interfaces? 

The Comparable uses the compareTo() method while the Comparator uses the compare() method
You need to modify the class whose instance is going to be sorted and add code corresponding to the Comparable implementation. Whereas, for the Comparator, you can have a separate class that has the sort logic/code. 

In case of Comparable, Only one sort sequence can be created while Comparator can have multiple sort sequences.

If you have any questions that you want answer for, please leave a comment on this page OR drop a note to Snehal[at]TechProceed[dot]com and I will answer them.