Main Content RSS FeedRecent Articles

Good SQL Interview Questions »

How would you find out the total number of rows in a table?

Use SELECT COUNT(*) … in query

How do you eliminate duplicate values in SELECT?

Use SELECT DISTINCT … in SQL query

How you insert records into a table

Using SQL INSERT statement

How do you delete record from a table?

Using DELETE statement
Example : DELETE FROM EMP

How do you select a row using indexes?

Specify the indexed columns in the WHERE clause of query.

How do you find the maximum value in a column?

Use SELECT MAX(…) .. in query

How do you retrieve the first 5 characters of FIRSTNAME column of table EMP ?

SELECT SUBSTR(FIRSTNAME,1,5) FROM EMP

My SQL statement SELECT AVG(SALARY) FROM EMP yields inaccurate results. Why?

Because SALARY is not declared to have NULLs and the employees for whom the salary is not known are also counted.

How do you concatenate the FIRSTNAME and LASTNAME from EMP table to give a complete name?

SELECT FIRSTNAME || ‘ ‘ || LASTNAME FROM EMP

What is UNION,UNION ALL in SQL?

UNION : eliminates duplicates
UNION ALL: retains duplicates
Both these are used to combine the results of different SELECT statements.

Suppose I have five SQL SELECT statements connected by UNION/UNION ALL, how many times should I specify UNION to eliminate the duplicate rows?

Once.

In the WHERE clause what is BETWEEN and IN?

BETWEEN supplies a range of values while IN supplies a list of values.

Is BETWEEN inclusive of the range values specified?

Yes.

What is ‘LIKE’ used for in WHERE clause? What are the wildcard characters?

LIKE is used for partial string matches. ‘%’ ( for a string of any character ) and ‘_’ (for any single character ) are the two wild card characters.

When do you use a LIKE statement?

To do partial search e.g. to search employee by name, you need not specify the complete name; using LIKE, you can search for partial string matches.

Example SQL : SELECT EMPNO FROM EMP
WHERE EMPNAME LIKE ‘RAMESH%’

% is used to represent remaining all characters in the name.
This query fetches all records contains RAMESH in six characters.

What do you accomplish by GROUP BY … HAVING clause?

GROUP BY partitions the selected rows on the distinct values of the column on which you group by. HAVING selects GROUPs which match the criteria specified

Consider the employee table with column PROJECT nullable. How can you get a list of employees who are not assigned to any project?

SQL : SELECT EMPNO
FROM EMP
WHERE PROJECT IS null;

What are the large objects supported by oracle and db2?

Blob , Clob ( Binary Large Objects, Character Large Objects)

What’s the difference between a primary key and a unique key?

Primary key wont allow nulls, unique key allow nulls. Both Primary key and Unique key enforce the uniqueness of the column on which they are defined.

What is a join and explain different types of joins?

INNER JOIN
OUTER JOIN
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN
INNER JOIN

What is a self join?

Joining two instances of a same table.
Sample SQL : SELECT A.EMPNAME , B.EMPNAME
FROM EMP A, EMP B
WHERE A.MGRID = B.EMPID

What is a transaction and ACID?

Transaction - A transaction is a logical unit of work. All steps must be committed or rolled back.
ACID - Atomicity, Consistency, Isolation and Durability, these are properties of a transaction.

Materialized Query Tables in db2 ( This feature might not be available in oracle)?

Materialized Query Tables or MQTs are also known as automatic summary tables. A materialized query table (MQT) is a table whose definition is based upon the result of a query. The data that is contained in an MQT is derived from one or more tables on which the materialized query table definition is based. MQT improve the query performance.

Sample SQL to creat MQT.

CREATE TABLE CUSTOMER_ORDER AS
(SELECT SUM(AMOUNT) AS TOTAL_SUM,
TRANS_DT,
STATUS
FROM DB2INST2.CUSTOMER_ORDER
WHERE TRANS_DT BETWEEN ‘1/1/2001′ AND ‘12/31/2001′
GROUP BY TRANS_DT,
STATUS)
DATA INITIALLY DEFERRED REFRESH DEFERRED;

Best Servlet Interview Questions »

What is the servlet?

Servlet is a script, which resides and executes on server side, to create dynamic HTML. In servlet programming we will use java language. A servlet can handle multiple requests concurrently

What is the architechture of servlet package?

Servlet Interface is the central abstraction. All servlets implements this Servlet Interface either directly or indirectly (may implement or extend Servlet Interfaces sub classes or sub interfaces)

Servlet
|
Generic Servlet
|
HttpServlet ( Class ) — we will extend this class to handle GET / PUT HTTP requests
|
MyServlet

What is the difference between HttpServlet and GenericServlet?
A GenericServlet has a service() method to handle requests.HttpServlet extends GenericServlet added new methods
doGet()
doPost()
doHead()
doPut()
doOptions()
doDelete()
doTrace() methods
Both these classes are abstract.

What’s the difference between servlets and applets?

Servlets executes on Servers. Applets executes on browser. Unlike applets, however, servlets have no graphical user interface.

What are the uses of Servlets?

A servlet can handle multiple requests concurrently, and can synchronize requests. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers.

When doGET() method will going to execute?

When we specified method=’GET’ in HTML
Example : < form name='SSS' method='GET'>

When doPOST() method will going to execute?

When we specified method=’POST’ in HTML
< form name='SSS' method='POST' >

What is the difference between Difference between doGet() and doPost()?

GET Method : Using get method we can able to pass 2K data from HTML
All data we are passing to Server will be displayed in URL (request string).

POST Method : In this method we does not have any size limitation.
All data passed to server will be hidden, User cannot able to see this info
on the browser.

What is the servlet life cycle?

When first request came in for the servlet , Server will invoke init() method of the servlet. There after if any user request the servlet program, Server will directly executes the service() method. When Server want to remove the servlet from pool, then it will execute the destroy() method

Which code line must be set before any of the lines that use the PrintWriter?

setContentType() method must be set.

Which protocol will be used by browser and servlet to communicate?

HTTP

In how many ways we can track the sessions?

Method 1) By URL rewriting
Method 2) Using Session object

Getting Session form HttpServletRequest object
HttpSession session = request.getSession(true);

Get a Value from the session
session.getValue(session.getId());

Adding values to session
cart = new Cart();
session.putValue(session.getId(), cart);

At the end of the session, we can inactivate the session by using the following command
session.invalidate();

Method 3) Using cookies

Method 4) Using hidden fields

How Can You invoke other web resources (or other servelt / jsp ) ?

Servelt can invoke other Web resources in two ways: indirect and direct.

Indirect Way : Servlet will return the resultant HTML to the browser which will point to another Servlet (Web resource)

Direct Way : We can call another Web resource (Servelt / Jsp) from Servelt program itself, by using RequestDispatcher object.

You can get this object using getRequestDispatcher(”URL”) method. You can get this object from either a request or a Context.

Example :
RequestDispatcher dispatcher = request.getRequestDispatcher(”/jspsample.jsp”);
if (dispatcher != null)
dispatcher.forward(request, response);
}

How Can you include other Resources in the Response?

Using include method of a RequestDispatcher object.

Included WebComponent (Servlet / Jsp) cannot set headers or call any method (for example, setCookie) that affects the headers of the response.

Example : RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(”/banner”);
&nbspif (dispatcher != null)
&nbspdispatcher.include(request, response);
}

What is the difference between the getRequestDispatcher(String path) ServletRequest interface and ServletContext interface?

The getRequestDispatcher(String path) method of ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a “/” it is interpreted as relative to the current context root.

The getRequestDispatcher(String path) method of ServletContext interface cannot accepts relative paths. All path must sart with a “/” and are interpreted as relative to curent context root. If the resource is not available, or if the server has not implemented a RequestDispatcher object for that type of resource, getRequestDispatcher will return null. Your servlet should be prepared to deal with this condition.

What is the use of ServletContext?

Using ServletContext, We can access data from its environment. Servlet context is common to all Servlets so all Servlets share the information through ServeltContext.

Is there any way to generate PDF’S dynamically in servlets?

We need to use iText. A open source library for java. Please refer sourceforge site for sample servlet examples.

What is the difference between using getSession(true) and getSession(false) methods?

getSession(true) - This method will check whether already a session is existing for the user. If a session is existing, it will return that session object, Otherwise it will create new session object and return taht object.

getSession(false) - This method will check existence of session. If session exists, then it returns the reference of that session object, if not, this methods will return null.

Typical EJB Interview Questions »

What is the need of Remote and Home interface. Why cant it be in one?

The main reason is because there is a clear division of roles and responsibilities between the two interfaces. The home interface is your way to communicate with the container, that is who is responsible of creating, locating even removing one or more beans. The remote interface is your link to the bean, that will allow you to remotely access to all its methods and members. As you can see there are two distinct elements (the container and the beans) and you need two different interfaces for accessing to both of them.

Can I develop an Entity Bean without implementing the create() method in the home interface?

As per the specifications, there can be ‘ZERO’ or ‘MORE’ create() methods defined in an Entity Bean. In cases where create() method is not provided, the only way to access the bean is by knowing its primary key, and by acquiring a handle to it by using its corresponding finder method. In those cases, you can create an instance of a bean based on the data present in the table. All one needs to know is the primary key of that table. i.e. a set a columns that uniquely identify a single row in that table. Once this is known, one can use the ‘getPrimaryKey()’ to get a remote reference to that bean, which can further be used to invoke business methods.

What is the difference between Context, InitialContext and Session Context? How they are used?

javax.naming.Context is an interface that provides methods for binding a name to an object. It’s much like the RMI Naming.bind() method.

javax.naming.InitialContext is a Context and provides implementation for methods available in the Context interface.

Where as SessionContext is an EJBContext object that is provided by the EJB container to a SessionBean in order for the SessionBean to access the information and/or services or the container.

There is EntityContext too which is also and EJBContext object that’ll be provided to an EntityBean for the purpose of the EntityBean accessing the container details. In general, the EJBContext (SessionContext and EntityContext), AppletContext and ServletContext help the corresponding Java objects in knowing about its ‘context’ [environment in which they run], and to access particular information and/or service. Whereas, the javax.naming.Context is for the purpose of ‘NAMING’ [by the way of referring to] an object.

Why an onMessage call in Message-driven bean is always a separate transaction?

EJB 2.0 specification: “An onMessage call is always a separate transaction, because there is never a transaction in progress when the method is called.”

When a message arrives, it is passed to the Message Driven Bean through the onMessage() method, that is where the business logic goes.

Since there is no guarantee when the method is called and when the message will be processed, is the container that is responsible of managing the environment, including transactions.

Why are ejbActivate() and ejbPassivate() included for stateless session bean even though they are never required as it is a nonconversational bean?

To have a consistent interface, so that there is no different interface that you need to implement for Stateful Session Bean and Stateless Session Bean.

Both Stateless and Stateful Session Bean implement javax.ejb.SessionBean and this would not be possible if stateless session bean is to remove ejbActivate and ejbPassivate from the interface.

Static variables in EJB should not be relied upon as they may break in clusters.Why?

Static variables are only ok if they are final. If they are not final, they will break the cluster. What that means is that if you cluster your application server (spread it across several machines) each part of the cluster will run in its own JVM.

Say a method on the EJB is invoked on cluster 1 (we will have two clusters - 1 and 2) that causes value of the static variable to be increased to 101. On the subsequent call to the same EJB from the same client, a cluster 2 may be invoked to handle the request. A value of the static variable in cluster 2 is still 100 because it was not increased yet and therefore your application ceases to be consistent. Therefore, static non-final variables are strongly discouraged in EJBs.

If I throw a custom ApplicationException from a business method in Entity bean which is participating in a transaction, would the transaction be rolled back by container?

EJB Transaction is automatically rolled back only when a SystemException (or a subtype of it) is thrown.

Your ApplicationExceptions can extend from javax.ejb.EJBException, which is a sub class of RuntimeException. When a EJBException is encountered the container rolls back the transaction. EJB Specification does not mention anything about Application exceptions being sub-classes of EJBException.

You can tell container to rollback the transaction, by using setRollBackOnly on SessionContext/EJBContext object as per type of bean you are using.

Does Stateful Session bean support instance pooling?

Stateful Session Bean conceptually doesn’t have instance pooling.

Can I map more than one table in a CMP?

no, you cannot map more than one table to a single CMP Entity Bean. CMP has been, in fact, designed to map a single table.

Can I invoke Runtime.gc() in an EJB?

You shouldn’t. What will happen depends on the implementation, but the call will most likely be ignored.

Can a Session Bean be defined without ejbCreate() method?

The ejbCreate() methods is part of the bean’s lifecycle, so, the compiler will not return an error because there is no ejbCreate() method.

However, the J2EE spec is explicit:

the home interface of a Stateless Session Bean must have a single create() method with no arguments,
while the session bean class must contain exactly one ejbCreate() method, also without arguments.

· Stateful Session Beans can have arguments (more than one create method)

How to implement an entity bean which the PrimaryKey is an autonumeric field

The EJB 2 Spec (10.8.3 - Special case: Unknown primary key class) says that in cases where the PrimaryKeys are generated automatically by the underlying database, the bean provider must declare the findByPrimaryKey method to return java.lang.Object and specify the Primary Key Class as java.lang.Object in the Deployment Descriptor.

When defining the Primary Key for the Enterprise Bean, the Deployer using the Container Provider’s tools will typically add additional container-managed fields to the concrete subclass of the entity bean class.

In this case, the Container must generate the Primary Key value when the entity bean instance is created (and before ejbPostCreate is invoked on the instance.)

What is clustering?

Clustering is grouping machines together to transparantly provide enterprise services. Clustering is an essential piece to solving the needs for today’s large websites.

The client does not know the difference between approaching one server or approaching a cluster of servers.

Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB?

You can pass the HttpSession as parameter to an EJB method,only if all objects in session are serializable. This has to be consider as “passed-by-value”, that means that it’s read-only in the EJB. If anything is altered from inside the EJB, it won’t be reflected back to the HttpSession of the Servlet Container.

If my session bean with single method insert record into 2 entity beans, how can know that the process is done in same transaction (the attributes for these beans are Required)?

If your session bean is using bean-managed transactions, you can ensure that the calls are handled in the same transaction by :

javax.transaction.UserTransaction tran= null;
try{
tran=ctx.getUserTransaction();
tran.begin();
myBeanHome1.create(….);
myBeanHome2.create(…);
tran.commit();
}catch(…){}
You may want to check if you’re already running in a transaction by calling tran.getStatus().

When should I adopt BMP and when I should use CMP?

You can use CMP and BMP beans in the same application… obviously, a bean can be BMP or CMP, not both at the same time (they are mutually exclusive).

There is a common approach that is normally used and considered a good one. You should start developing CMP beans, unless you require some kind of special bean, like multi-tables, that cannot be completely realized with a single bean. Then, when you realize that you need something more or that you would prefer handling the persistence (performance issue are the most common reason), you can change the bean from a CMP to a BMP.

Java Interview Questions4 »

What methods java providing for Thread communications?

Java provides three methods that threads can use to communicate with each other: wait, notify, and notifyAll. These methods are defined for all Objects (not just Threads). The idea is that a method called by a thread may need to wait for some condition to be satisfied by another thread; in that case, it can call the wait method, which causes its thread to wait until another thread calls notify or notifyAll.

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 notify (so it is often better to use notifyAll than notify).

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. To understand synchronization we need to look into thread execution manner.

Threads may execute in a manner where their paths of execution are completely independent of each other. Neither thread depends upon the other for assistance. For example, one thread might execute a print job, while a second thread repaints a window. And then there are threads that require synchronization, the act of serializing access to critical sections of code, at various moments during their executions. For example, say that two threads need to send data packets over a single network connection. Each thread must be able to send its entire data packet before the other thread starts sending its data packet; otherwise, the data is scrambled. This scenario requires each thread to synchronize its access to the code that does the actual data-packet sending.

If you feel a method is very critical for business that needs to be executed by only one thread at a time (to prevent data loss or corruption), then we need to use synchronized keyword.

EXAMPLE

Some real-world tasks are better modeled by a program that uses threads than by a normal, sequential program. For example, consider a bank whose accounts can be accessed and updated by any of a number of automatic teller machines (ATMs). Each ATM could be a separate thread, responding to deposit and withdrawal requests from different users simultaneously. Of course, it would be important to make sure that two users did not access the same account simultaneously. This is done in Java using synchronization, which can be applied to individual methods, or to sequences of statements.

One or more methods of a class can be declared to be synchronized. When a thread calls an object’s synchronized method, the whole object is locked. This means that if another thread tries to call any synchronized method of the same object, the call will block until the lock is released (which happens when the original call finishes). In general, if the value of a field of an object can be changed, then all methods that read or write that field should be synchronized to prevent two threads from trying to write the field at the same time, and to prevent one thread from reading the field while another thread is in the process of writing it.

Here is an example of a BankAccount class that uses synchronized methods to ensure that deposits and withdrawals cannot be performed simultaneously, and to ensure that the account balance cannot be read while either a deposit or a withdrawal is in progress. (To keep the example simple, no check is done to ensure that a withdrawal does not lead to a negative balance.)

public class BankAccount {
private double balance;
// constructor: set balance to given amount
public BankAccount( double initialDeposit ) {
balance = initialDeposit;
}
public synchronized double Balance( ) {
return balance;
}
public synchronized void Deposit( double deposit ) {
balance += deposit;
}
public synchronized void Withdraw( double withdrawal ) {
balance -= withdrawal;
}
}
Note: that the BankAccount’s constructor is not declared to be synchronized. That is because it can only be executed when the object is being created, and no other method can be called until that creation is finished.

There are cases where we need to synchronize a group of statements; we can do that using synchronized statement.

Java Code Example

synchronized ( B ) {
if ( D > B.Balance() ) {
ReportInsuffucientFunds();
}
else {
B.Withdraw( D );
}
}

What is serialization?

Serialization is the process of writing complete state of java object into output stream, that stream can be file or byte array or stream associated with TCP/IP socket.

What does the sertilizable interface do?

Serializable is a tagging interface; it prescribes no methods. It serves to assign the Serializable data type to the tagged class and to identify the class as one which the developer has designed for persistence. ObjectOutputStream serializes only those objects which implement this interface.

How do I serialize an object to a file?

To serialize an object into a stream perform the following actions:

- Open one of the output streams, for exaample FileOutputStream
- Chain it with the ObjectOutputStream - Call the method writeObject() providingg the instance of a Serializable object as an argument.
- Close the streams

Java Code
———

try{
fOut= new FileOutputStream(”c:\\emp.ser”);
out = new ObjectOutputStream(fOut);
out.writeObject(employee); //serializing
System.out.println(”An employee is serialized into c:\\emp.ser”);

} catch(IOException e){
e.printStackTrace();
}

How do I deserilaize an Object?

To deserialize an object, perform the following steps:

- Open an input stream
- Chain it with the ObjectInputStream - Call the method readObject() and cast tthe returned object to the class that is being deserialized.
- Close the streams

Java Code

try{
fIn= new FileInputStream(”c:\\emp.ser”);
in = new ObjectInputStream(fIn);

//de-serializing employee
Employee emp = (Employee) in.readObject();

System.out.println(”Deserialized ” + emp.fName + ” ”
+ emp.lName + ” from emp.ser “);
}catch(IOException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace(); }

What is Externalizable Interface?

Externalizable interface is a subclass of Serializable. Java provides Externalizable interface that gives you more control over what is being serialized and it can produce smaller object footprint. (You can serialize whatever field values you want to serialize)

This interface defines 2 methods: readExternal() and writeExternal() and you have to implement these methods in the class that will be serialized. In these methods you’ll have to write code that reads/writes only the values of the attributes you are interested in. Programs that perform serialization and deserialization have to write and read these attributes in the same sequence.

Java Interview Questions3 »

What is a collection?

Collection is a group of objects. java.util package provides important types of collections. There are two fundamental types of collections they are Collection and Map. Collection types hold a group of objects, Eg. Lists and Sets where as Map types hold group of objects as key, value pairs Eg. HashMap and Hashtable.

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

StringBuffer is faster than String for concatenation.

What is Runnable interface? Are there any other ways to make a java program as multithread java program?

There are two ways to create new kinds of 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.
- An advantage of the second approach is that the new class can be a subclass of any class, not just of the Thread class.
Here is a very simple example just to illustrate how to use the second approach to creating threads:

class myThread implements Runnable {
public void run() {
System.out.println(”I’m running!”);
}

} public class tstRunnable {
public static void main(String[] args) {
myThread my1 = new myThread();
myThread my2 = new myThread();
new Thread(my1).start();
new Thread(my2).start();
}

<!– /* Font Definitions */ @font-face {font-family:Verdana; panose-1:2 11 6 4 3 5 4 4 2 4; mso-font-charset:0; mso-generic-font-family:swiss; mso-font-pitch:variable; mso-font-signature:536871559 0 0 0 415 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:”"; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:”Times New Roman”; mso-fareast-font-family:”Times New Roman”;} @page Section1 {size:8.5in 11.0in; margin:1.0in 1.25in 1.0in 1.25in; mso-header-margin:.5in; mso-footer-margin:.5in; mso-paper-source:0;} div.Section1 {page:Section1;} –>

The Runnable interface has only one method:
public void run();
Thus, every class (thread) implements the Runnable interface, has to provide logic for run() method

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

<!– /* Font Definitions */ @font-face {font-family:Verdana; panose-1:2 11 6 4 3 5 4 4 2 4; mso-font-charset:0; mso-generic-font-family:swiss; mso-font-pitch:variable; mso-font-signature:536871559 0 0 0 415 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:”"; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:”Times New Roman”; mso-fareast-font-family:”Times New Roman”;} span.klink {mso-style-name:klink;} @page Section1 {size:8.5in 11.0in; margin:1.0in 1.25in 1.0in 1.25in; mso-header-margin:.5in; mso-footer-margin:.5in; mso-paper-source:0;} div.Section1 {page:Section1;} –>

NEW

A Fresh thread that has not yet started to execute.

RUNNABLE

A thread that is executing in the Java virtual machine.

BLOCKED

A thread that is blocked waiting for a monitor lock.

WAITING

A thread that is waiting to be notified by another thread.

TIMED_WAITING

A thread that is waiting to be notified by another thread for a specific amount of time

TERMINATED

A thread who’s run method has ended.

The folowing code prints out all thread states.

public class ThreadStates{
public static void main(String[] args){
Thread t = new Thread();
Thread.State e = t.getState();
Thread.State[] ts = e.values();
for(int i = 0; i < ts.length; i++){
System.out.println(ts[i]);
}
}
}

Java Interview Questions2 »

Describe the wrapper classes in Java?

Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.

Following table lists the primitive types and the corresponding wrapper classes:

<!– /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:”"; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:”Times New Roman”; mso-fareast-font-family:”Times New Roman”;} @page Section1 {size:8.5in 11.0in; margin:1.0in 1.25in 1.0in 1.25in; mso-header-margin:.5in; mso-footer-margin:.5in; mso-paper-source:0;} div.Section1 {page:Section1;} –>

Primitive

Wrapper

boolean

java.lang.Boolean

byte

java.lang.Byte

char

java.lang.Character

double

java.lang.Double

float

java.lang.Float

int

java.lang.Integer

long

java.lang.Long

short

java.lang.Short

void

java.lang.Void

What are different types of inner classes?

Inner classes nest within other classes. A normal class is a direct member of a package. Inner classes, which became available with Java 1.1, are four types
• Static member classes
• Member classes
• Local classes
• Anonymous classes
Static member classes - a static member class is a static member of a class. Like any other static method, a static member class has access to all static methods of the parent, or top-level, class.

Member Classes - a member class is also defined as a member of a class. Unlike the static variety, the member class is instance specific and has access to any and all methods and members; even the parent’s this reference.

Local Classes - Local Classes declared within a block of code and these classes are visible only within the block.

Anonymous Classes - These type of classes does not have any name and its like a local class

Java Anonymous Class Example

Public class SomeGUI extends JFrame
{
… Button member declarations…

Protected void buildGUI()
{
button1 = new JButton();
button2 = new JButton();

button1.addActionListener(
new java.awt.event.ActionListener() <------ Anonymous Class
{
public void actionPerformed(java.awt.event.ActionEvent e)
{
// do something
}
}
);

What are the uses of Serialization?

In some types of applications you have to write the code to serialize objects, but in many cases serialization is performed behind the scenes by various server-side containers.

These are some of the typical uses of serialization:
• To persist data for future use.
• To send data to a remote computer using such client/server Java technologies as RMI or socket programming.
• To “flatten” an object into array of bytes in memory.
• To exchange data between applets and servlets.
• To store user session in Web applications.
• To activate/passivity enterprise java beans.
• To send objects between the servers in a cluster.

Java Interview Questions1 »

Explain garbage collection?

Garbage collection is an important part of Java’s security strategy. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects from the memory. The name “garbage collection” implies that objects that are no longer needed by the program are “garbage” and can be thrown away. A more accurate and up-to-date metaphor might be “memory recycling.” When an object is no longer referenced by the program, the heap space it occupies must be recycled so that the space is available for subsequent new objects. The garbage collector must somehow determine which objects are no longer referenced by the program and make available the heap space occupied by such unreferenced objects. In the process of freeing unreferenced objects, the garbage collector must run any finalizes of objects being freed.

How you can force the garbage collection?

Garbage collection automatic process and can’t be forced. We can call garbage collector in Java by calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.

What are the field/method access levels (specifies) and class access levels?

Each field and method has an access level:
• private: accessible only in this class
• (package): accessible only in this package
• protected: accessible only in this package and in all subclasses of this class
• public: accessible everywhere this class is available
Similarly, each class has one of two possible access levels:
• (package): class objects can only be declared and manipulated by code in this package
• public: class objects can be declared and manipulated by code in any package

<!– /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:”"; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:”Times New Roman”; mso-fareast-font-family:”Times New Roman”;} @page Section1 {size:8.5in 11.0in; margin:1.0in 1.25in 1.0in 1.25in; mso-header-margin:.5in; mso-footer-margin:.5in; mso-paper-source:0;} div.Section1 {page:Section1;} –>

For both fields and classes, package access is the default, and is used when no access is specified

What are the static fields & static Methods?

If a field or method defined as a static, there is only one copy for entire class, rather than one copy for each instance of class. Static method cannot access non-static field or call non-static method

Example Java Code

static int counter = 0;

A public static field or method can be accessed from outside the class using either the usual notation:

Java-class-object. Field-or-method-name

or using the class name instead of the name of the class object:

Java- class-name. field-or-method-name

What are the Final fields & Final Methods?

Fields and methods can also be declared final. A final method cannot be overridden in a subclass. A final field is like a constant: once it has been given a value, it cannot be assigned to again.

Java Code

private static final int MAXATTEMPTS = 10;

Java Interview Questions »

When you declare a method as abstract method?

When I want child class to implement the behavior of the method.

Can I call an abstract method from a non abstract method?

Yes, We can call a abstract method from a Non abstract method in a Java abstract class

What is the difference between an Abstract class and Interface in Java? Or can you explain when you use Abstract classes?

Abstract classes let you define some behaviors; they force your subclasses to provide others. These abstract classes will provide the basic functionality of your application, child class which inherited this class will provide the functionality of the abstract methods in abstract class. When base class calls this method, Java calls the method defined by the child class.
• An Interface can only declare constants and instance methods, but cannot implement default behavior.
• Interfaces provide a form of multiple inheritances. A class can extend only one other class.
• Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
• A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
• Interfaces are slow as it requires extra indirection to find corresponding method in the actual class. Abstract classes are fast.

What is user-defined exception in java?

User-defined exceptions are the exceptions defined by the application developer which are errors related to specific application. Application Developer can define the user defined exception by inherit the Exception class as shown below. Using this class we can throw new exceptions.

Java Example:

Public class noFundException extends Exception {
}
Throw an exception using a throw statement:

Public class Fund {

Public Object getFunds () throws noFundException {
if (Empty()) throw new noFundException();

}
}

User-defined exceptions should usually be checked.

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

All predefined exceptions in Java are either a checked exception or an unchecked exception. Checked exceptions must be caught using try… Catch () block or we should throw the exception using throws clause. If you don’t, compilation of program will fail.

Java Exception Hierarchy

+——–+
| Object |
+——–+
|
|
+———–+
| Throwable |
+———–+
/ \
/ \
+——-+ +———–+
| Error | | Exception |
+——-+ +———–+
/ | \ / | \
\________/ \______/ \
+——————+
Unchecked checked | Runtime Exception |
+——————+
/ | | \
\_________________/

Unchecked

30 Best Solaris Interview Questions »

1. List the files in current directory sorted by size?

- ls -l | grep ^- | sort -nr

2. List the hidden files in current directory?

- ls -a1 | grep “^\.”

3. Delete blank lines in a file?

- cat sample.txt | grep -v ‘^$’ > new_sample.txt

4. Search for a sample string in particular files ?

- grep .Debug. *.confHere grep uses the string .Debug. to search in all files with extension..conf. under current directory.

5. Display the last newly appending lines of a file during appendingdata to the same file by some processes ?

- tail .f Debug.logHere tail shows the newly appended data into Debug.log by some processes/user.

6. Display the Disk Usage of file sizes under each directory in current Directory ?

- du -k * | sort .nr (or) du .k . | sort -nr

7. Change to a directory, which is having very long name ?

- cd CDMA_3X_GEN*Here original directory name is . .CDMA_3X_GENERATION_DATA..

8. Display the all files recursively with path under current directory ?

- find . -depth -print

9. Set the Display automatically for the current new user ?

- export DISPLAY=`eval ‘who am i | cut -d”(” -f2 | cut -d”)” -f1′`Here in above command, see single quote, double quote, grave ascent is used. Observe carefully.

10. Display the processes, which are running under your username ?

- ps .aef | grep MaheshvjHere, Maheshvj is the username.

11. List some Hot Keys for bash shell ?

- Ctrl+l . Clears the Screen. Ctrl+r . Does a search in previously given commands in shell. Ctrl+u - Clears the typing before the hotkey. Ctrl+a . Places cursor at the beginning of the command at shell. Ctrl+e . Places cursor at the end of the command at shell. Ctrl+d . Kills the shell. Ctrl+z . Places the currently running process into background.

12. Display the files in the directory by file size ?

- ls .ltr | sort .nr .k 5

13. How to save man pages to a file ?

- man | col .b > Example : man top | col .b > top_help.txt

14. How to know the date & time for . when script is executed ?

- Add the following script line in shell script.eval echo “Script is executed at `date`” >> timeinfo.infHere, .timeinfo.inf. contains date & time details ie., when script is executed and history related to execution.

15. How do you find out drive statistics ?

- iostat -E

16. Display disk usage in Kilobytes ?

- du -k

17. Display top ten largest files/directories ?

- du -sk * | sort -nr | head

18. How much space is used for users in kilobytes ?

- quot -af

19. How to create null file ?

- cat /dev/null > filename1

20. Access common commands quicker ?

- ps -ef | grep -i $@

21. Display the page size of memory ?

- pagesize -a

22. Display Ethernet Address arp table ?

- arp -a

23. Display the no.of active established connections to localhost ?

- netstat -a | grep EST

24. Display the state of interfaces used for TCP/IP traffic ?

- netstat -i

25. Display the parent/child tree of a process ?

- ptree Example: ptree 1267

26. Show the working directory of a process ?

- pwdx Example: pwdx 1267

27. Display the processes current open files ?

- pfiles Example: pfiles 1267

28. Display the inter-process communication facility status ?

- ipcs

29. Display the top most process utilizing most CPU ?

- top .b 1

30. Alternative for top command ?

- prstat -a

General UNIX Interview Questions »

1. What are the main differences between Apache 1.x and 2.x?

2. What does the “route” command do?

Typical usage of route:

/sbin/route -n:

DISPLAY KERNEL ROUTING TABLES.

Or

To manipulate the routing table.

3. What are the read/write/execute bits on a directory mean?

Access rights (read/write/execute) on a directory means:
->read indicates that it is possible to list files in the directory.
->write indicates that it is possible to delete or move files in the directory.
->execute indicates that it is possible to read files in the directory provided we must have read permission on individual files of that directory.

or

Access rights (read/write/execute) on a directory means:

execute permission allows a user to enter the directory and perform read/write/execute files according to the permissions of the file. But you cannot ‘ls’ the directory until you have a read permission.
It means you should know the filename.
eg:

[amar@darkstar ~]$ ls -l | grep Book
d–x—— 6 amar amar 4096 Sep 5 11:27 BookScripting # directory only has
execute permission

[amar@darkstar ~]$ ls -l BookScripting/ # no read permission
ls: BookScripting/: Permission denied # so ‘ls -l’ denied

[amar@darkstar ~]$ ls -l BookScripting/test.sh
-r-x—— 1 amar amar 37 Sep 5 11:27 BookScripting/test.sh

[amar@darkstar ~]$ BookScripting/test.sh
you can execute

[amar@darkstar ~]$

4. What does iostat do?

iostat Will show the status of INPUT & OUTPUT.

5. what does vmstat do?

vmstat–To know the memory related status

6. What does netstat do?

netstat–To know the network status.

7. What is the most graceful way to bring a system into single user mode?

The most graceful way is to use the command init s.
If you want to shut everything down before going to single user mode then do init 0 first and from the ok prompt do a boot -s.

8. How do you determine disk usage?

The disk usage can be determined by using the command, du.This command outputs the number of kilobytes used by each sub-directory.

9. What is AWK?

AWK is a complete pattern scanning and processing language, it is most commonly used as a Unix command-line filter to reformat the output of other commands.

For example, to print only the second and sixth fields of the date command (the month and year) with a space separating them, at the Unix prompt, you would enter:
date | awk ‘{print $2 ” ” $6}’

10. What is SED?

SED (which stands for Stream EDitor) is a simple but powerful computer program used to apply various pre-specified textual transformations to a sequential stream of text data.

It reads input files line by line, edits each line according to rules specified in its simple language (the sed script), and then outputs the line.

11. What is the difference between binaries in /bin, and /usr/bin?

/bin - would contains the binaries frequently used by the normal user (as well as system administrator)
/usr/bin - would contains the binaries rarely used by the normal user (as wel as system administrator)

Or

Under Solaris, there is no difference. /bin is a symbolic link pointing to /usr/bin. Under Linux (RHAS3) /bin is seemingly for standard unix programs like vi, cp, mv, rm which you’d need in a single user environment where as /usr/bin contains programs you’d want for a multiuser environment. Keep in mind that sometimes /usr is a different disk partition and when you start up in single user mode you only have / mounted.

The /sbin directories are *supposed to* contain statically linked programs. This mas morphed into the idea of bin for user programs, sbin for admin programs.

12. What is a dynamically linked file?

A dynamically linked program is one that, when executed, loads shared libraries from /lib or /usr/lib in order to execute. The idea is that most programs use many of the same functions, so include a copy of a common function in *every* program on the file system. Instead, the function is placed in a shared library and when the program starts executing, the library is loaded which provides the program access to the function.

13. What is a statically linked file?

A statically linked program is one that contains all the information (libraries) it needs to run. It does not need to load additional libaries in order to execute.

14. What is MUTEX?

Short for mutual exclusion object. In computer programming, a mutex is a program object that allows multiple program threads to share the same resource, such as file access, but not simultaneously. When a program is started, a mutex is created with a unique name. After this stage, any thread that needs the resource must lock the mutex from other threads while it is using the resource. The mutex is set to unlock when the data is no longer needed or the routine is finished.

15. What is INODE?

A unique number associated with each filename. This number is used to look up an entry in the inode table which gives information on the type, size, and location of the file and the userid of the owner of the file.

16. Where INODE will be stored?

Inode is stored in File Management system ie in the Secondary Memory where os is stored