Monday, October 27, 2008

Check memory usage by your java program

It is always helpul for us to know how much memory is our program consuming for its execution. It helps us to improve our program performance and optimize programs.
In Java, we have ways to do this programatically.
If you want to know programatically, you can use Runtime.totalMemory() to find out the total amount used by the JVM, and Runtime.freeMemory() to find out how much of that is still available (i.e. it's allocated to the JVM, but not allocated within the JVM - new objects can use this memory).
These are instance methods - use Runtime.getRuntime() to first get the singleton instance.

Sunday, October 19, 2008

Java best practices - Having multiple return statements.

Is having multiple return statement in a method a bad practice ?
We have seen or read in books saying we should have only one exit point for a method. But actually it depends on the case/scenario which we are dealing with. It is proposed to have a single exit point because it will be useful for logging or have some clean up code in one place.

It would be unwise deciding using multiple exit points in many cases, that we are better of returning from a method as soon as it is logically correct to do so.

for example :

public void DoStuff(Foo foo)
{ if (foo == null) return;
...
}

The above code is cleaner than
public void DoStuff(Foo foo)
{ if (foo != null)
{ ...
}
}

So, it is always fine to use multiple exit points where we need not do any logging/ clean up code and in places where it is absolutely logical to do so.

Tuesday, May 27, 2008

Java Interview Questions - 3

Here is the collection of some of frequently asked questions on Core Java interview.
These questions are collected from various sources such as forums, discussion rooms etc where people posted questions that were asked to them on java interviews.
P.S : If you need anymore info or think answers are incorrect please add comments on it and i will try to fix them

1)Can I get Session object from servlet or jsp to simple java class?
Yes. In your simple java class, have a instance variable of type Session/HttpSession and getter and setter method for it. From a servlet, set the HttpSession object for this class.

2)What is a singleton class?
Singleton classes are those which are designed such that we can create only one instanceof the object and provide a method to access this instance of the class. Creation of multiple instances is avoided by making all its constructors as private.

3)What happened if i clone a singleton object?
We cannot clone singleton class. Since the constructor is private, the clone methodof the object class is not visible.Further you can opt for overriding clone method in your singleton class and throw suitable exception by yourself ( CloneNotSupported exception)

4)What is the difference between sendRedirect and forward in servlet ?
sendRedirect is done at the server side without any knowledge of the calling client.There will be no change in the url or any changes for the clients point of view.
forward sends the new url to the client and the client goes to that url for further action.There will be visible change in the url in the browser

5)Can I call a static variable with object?
Yes, But not a good practice. Method call will be based on the type of the Objectnot on the instance of the object.

6)What are the collection framework hibernate supports?
Bag,Set,List,Map and Array

7) Explain System.out.println()
System.out.println()
System is a class in java.lang package.
out is a final static member of type PrintStream(java.io) in System class.(System class imports java.io.* for us so we need
not bother to import java.io package.)
and
println is the method provided by PrintStream class.

8) What is the difference between sleep(1000), suspend() and wait(1000) ?
Thread.sleep() sends the current thread into the "Not Runnable" state for some amount of time. The thread keeps the monitors it has aquired -- i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt() it will wake up the sleeping thread. Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the
sleep method). A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.

t.suspend() is deprecated. Using it is possible to halt a thread other than the current thread. A suspended thread keeps all its monitors and since this state is not interruptable it is deadlock prone.

object.wait() sends the current thread into the "Not Runnable" state, like sleep(), but with a twist. Wait is called on a object, not a thread; we call this object the "lock object." Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the "wait list" associated with the lock. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original,
waiting thread. Basically, wait()/notify() is like sleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object.

9) JVM and Platform Independence OR Java as Compiled and Interpreted
Java is called Platform independent language because a program which is written in Java can run on any machine independent of which platform it is running on ( Windows/Linux/Solaris..).
Here JVM (Java Virtual Machine) plays an important role in it.
All java files will be converted into .class files which contains byte code which is not platform dependent. Then comes the JVM which interprets the byte code into platform/machine dependent code. That is why java is also called compiled and interpreted language.
Even though the JVM is different for different platform, the key advantage here is, we do not need to compile the java application to make it run on different platform it was originally created.

10)How many objects are created in the below code
String s= new String("abc");
Assuming that there is no String "abc" inside String constant pool,
2 objects are created.
One in Heap memory and the other in the String Constant Pool.

Tuesday, May 20, 2008

Static variables and methods

‘static’ is a modifier in java which can be used for methods and instance variables and a block of code outside any methods inside a class.
We can use static as a modifier to a class or a method when the member’s behaviour doesn’t depend on the instance of the class so that there will be no need to create an instance of that class to access the static members.

Variables and members marked as static belong to a class rather than any particular instance of the class. So, if you modify a variable in one instance of the class, it will affect all future use of the variable in any other instance of the class (unless the class itself is reloaded).

Static methods can’t access non-static variables of a class.

Static methods cannot be overridden.

Static modifier can only be applied to methods, instance variables and top level inner classes.

Declaration and Access control – 2

Some Quick Reference points about Declaration and Access control for Java Job Interviews
1. A method marked as ‘private’ can’t be overridden. This does not mean that we cannot have a method with same name and signature in the subclass.

2. For a sub class outside the package, the protected member can be accessed only through inheritance. i.e the protected members cannot be accessed by its sub classed outside the package using the reference of a super class.

3. We cannot apply any access modifiers to local variables. The only modifier that can be applied to local variable is ‘final’.

4. ‘ synchronized’ modifier can only be applied to methods or a block of code inside a method.

5. ‘synchronized’ modifier indicates that the methods or block of code to make sure that only one thread accesses the code at a time.

6. ‘native’ modifier indicates that the method is implemented in a platform dependent language such as C.

7. ‘native’ can be applied only to methods.

8. ‘strictfp’ modifier can be applied to classes and methods.

9. ‘strcitfp’ modifier forces floating point literals to adhere to the IEE754 standars.

10. ‘transient’ and ‘volatile’ modifier can be applied only to instance variables.

11. ‘transient’ variables are ignored during serialization of the objects.

12. The volatile modifier tells the JVM that a thread accessing the variable must always reconcile its own private copy of the variable with the master copy in memory.

Monday, May 12, 2008

The ‘abstract’ keyword of Java Programming Language

One of the frequently asked questions in Java interviews are about abstract classes and abstract methods.

‘abstract’ is a non-access modifier that can be applied to classes and methods.

This modifier cannot be applied to instance variables and local variables.

If a class is marked as abstract, it cannot be instantiated. i.e we cannot create objects of abstract class. An abstract class must be sub classed (extended) and the first concrete ( non-abstract) class extending an abstract class must implement all the abstract methods of the super class (if not implemented in any of the super classes.

If there is any method in an abstract class marked as abstract, then the class has to be marked as abstract. But we can have an abstract class without any abstract methods.

An abstract keyword has a significant role in java polymorphism and inheritance concepts.

Abstract methods ends with a semicolon – instead of curly braces.

We cannot mark a class both as abstract and final.

We cannot mark a method as both abstract and synchronized.

We cannot mark a method as both abstract and native.

We cannot mark a method as both abstract and strictfp.

We cannot mark a method as both abstract and private.

All abstract methods must be implemented in first non-concrete subclass unless it is implemented in any of the super class which are also abstract.

Tuesday, May 6, 2008

final - modifier of Java

Some important facts about final keyword of Java Language

final is a keyword in java which is used as a modifier for a classes, methods, instance variables and local variables.

This is one of the non-access modifier.

When a class is marked as 'final', it can never be extended. i.e the final classes cannot be sub classed. We rarely mark a class as final because this stops us from using java inheritance - which is one of the key pillars of Java Technology. A class is marked as final so that no one can override the methods of that class - As a security measure. Imagine the consequences of badly overriding methods of java.lang.String class (which is a final class).

A class can never be marked as both 'final' and 'abstract', both of which are contradictory to each other.

When a method is marked as final, it can never be overridden, even though the class itself is non-final.

When an instance variable is marked as final, once it is given a value, it can never change. If we assign a reference variable to an object, then we can never reassign a new object to that reference variable. Although we can change the properties of that object. All final variable must be initialized by a value explicitly before each constructors finishes running. Else the compiler will throw an exception.

final is the only modifier that can be applied for a method local variable. It should be given a value during variable declaration.

Thursday, May 1, 2008

Declaration and Access Control - Quick Reference

Java Job Interview Questions - Quick Reference Points / Points to Remember




Declaration and Access Control - Quick Reference

Ø There can be only one public class per a source code file.

Ø The name of the source code file must be same as the public class in that file.

Ø A class file should first have a package name (if any) , then import statements (if any) and class declaration.

Ø A class can be marked either as public or with no access modifier, which specifies package (default) access.

Ø A class can be marked as strictfp, final or abstract.

Ø A class can not be declared as private or protected.

Ø A class cannot be marked as both abstract and final.

Ø A final class cannot be sub classed ( extended)

Ø An abstract class must be sub classed.

Ø An abstract class cannot be instantiated i.e it is not possible to create an object of an abstract class.

Ø Marking a class as final is to avoid overriding of its method in subclasses.

Ø An abstract class is used to define a generic behaviour of an object.

Ø If any method of a class is abstract, whole class must be marked as abstract.

Ø A class can be abstract even if there are no abstract methods.

Ø Abstract methods ends with a semicolon.

Ø Abstract classes let us to use polymorphism.

Ø Methods and instance variables of a class is collectively known as members of a class.

Ø Members of a class can have four different access levels – public, protected, default and
private.

Ø public – Access Anywhere

Ø protected – Access in the same package and in subclasses.

Ø default (no access modifier) – Access inside same package.

Ø private – Access inside same class.

Ø A member marked as private cannot be accessed outside the same class.

Sunday, April 27, 2008

Java Fundamentals - Points to remember

Java Fundamentals

Quick reference points

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

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

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

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

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

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

7. All integers are defined as int by default.

8. All floating point literals are double by default.

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

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

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

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

13. Arrays are always Objects.

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

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

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

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

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

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

Java as Object Oriented Programming Language

Java as Object Oriented Programming Language

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

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

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

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

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

For example

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

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

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

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

Now ,

Account savAcc = new SavingsAccount();

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

Account fixAcc = new FixedDepositAccount();

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


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

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

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

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

There are two types of inheritance,

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

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


Encapsulation – Data Hiding or Hiding the implementation details

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

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

For ex:

public class Bowling
{
private int noOfDeliveries;

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

Thursday, April 17, 2008

Interview Questions on Struts Framework

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

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

Frequently asked questions on Struts


1. What is Struts? Explain in some few words

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

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

2. What is Jakarta Struts Framework?

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

3. What is Action Servlet?

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

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

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

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

Example:
.

5. What is Action Class?

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

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

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

6. What is ActionForm?

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

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

7. What is Struts Validator Framework?

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

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

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

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

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

Following tag displays all the errors:


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

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

For example the code:


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

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

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

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


Will update some more questions soon.

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

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

Tuesday, April 15, 2008

Java interview discussions - 1

Java interview discussion

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

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

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

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

Interviewer : What do you mean by "Java Platform"

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

The Java platform has 2 components:

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

Wednesday, April 9, 2008

Java Collections – Part 1

Interview questions on Java Collections API

1. What is the Collections API?

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

2. What is the List interface?

The List interface provides support for ordered collections of objects.

3. What is the Vector class?

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

4. What is an Iterator interface?

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

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

The EventObject class and the EventListener interface support event processing.

6. What is the GregorianCalendar class?

The GregorianCalendar provides support for traditional Western calendars

7. What is the Locale class?

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

8. What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar.

9. What is the Map interface?

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

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

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

11. What is the Collection interface?

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

12. What is the Set interface?

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

13. What is the typical use of Hashtable?

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

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

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

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

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

16. Can a vector contain heterogeneous objects?

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

17. Can an ArrayList contain heterogeneous objects?

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

18. What is an enumeration?

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

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

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


- Vinay

Check out my other blogs

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

Some useful links
Java Website

Thursday, April 3, 2008

DataBase interview questions - Part 1

Collection of questions on DB and SQL

1. What is SQL?

SQL stands for 'Structured Query Language'.

2. What is SELECT statement?

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

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

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

4. What is the INSERT statement?

The INSERT statement lets you insert information into a database.

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

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

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

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

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

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

SELECT empname, age, city FROM emptable ORDER BY empname

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

You could use the COUNT keyword , example

SELECT COUNT(*) FROM emp WHERE age>40


9. What is GROUP BY?

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


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


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


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

Blob and Clob.


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

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

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

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


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

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


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

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


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

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


17. What is a self join?

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

Wednesday, April 2, 2008

JDBC interview questions - Part 1

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

1. What is JDBC?

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

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

2. What is a Transaction?

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

3. What are the steps in the JDBC connection?

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

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

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

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

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


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

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

5. Which are te types of JDBC drivers ?

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

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

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

7. How can we store java objects in database ?

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

8. What do you mean by isolation level?

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

9. List some exceptions thrown by JDBC

A. BatchUpdateException , DataTruncation , SQLException , SQLWarning

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

Ans: java.sql.Connection interface

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

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

12. How to check null value in JDBC?

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

Friday, March 28, 2008

Java Interview Questions - 2

Q1. How could Java classes direct program messages to the system console, but error messages, say to a file?

A. The class System 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. This how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);

* Q2. What's the difference between an interface and an abstract class?

A. An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.

* Q3. Why would you use a synchronized block vs. synchronized method?

A. Synchronized blocks place locks for shorter periods than synchronized methods.

* Q4. Explain the usage of the keyword transient?

A. This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

* Q5. How can you force garbage collection?

A. You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.

* Q6. How do you know if an explicit object casting is needed?

A. If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example:
Object a; Customer b; b = (Customer) a;

When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.

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

A. The code sleep(1000); puts thread aside 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.

* Q8. Can you write a Java class that could be used both as an applet as well as an application?

A. Yes. Add a main() method to the applet.

* Q9. What's the difference between constructors and other methods?

A. Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.

* Q10. Can you call one constructor from another if a class has multiple constructors

A. Yes. Use this() syntax.

* Q11. Explain the usage of Java packages.

A. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.

* Q12. If a class is located in a package, what do you need to change in the OS environment to be able to use it?

A. You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:
c:\>java com.xyz.hr.Employee

* Q13. What's the difference between J2SDK 1.5 and J2SDK 5.0?

A.There's no difference, Sun Microsystems just re-branded this version.

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

A. I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.

* Q15. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?

A. Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.

* Q16. Can an inner class declared inside of a method access local variables of this method?

A. It's possible if these variables are final.

* Q17. What can go wrong if you replace && with & in the following code:
String a=null; if (a!=null && a.length()>10) {...}
A. A single ampersand here would lead to a NullPointerException.

* Q18. What's the main difference between a Vector and an ArrayList

A. Java Vector class is internally synchronized and ArrayList is not.

* Q19. When should the method invokeLater()be used?

A. This method is used to ensure that Swing components are updated through the event-dispatching thread.
* Q20. How can a subclass call a method or a constructor defined in a superclass?

A. Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor.
** Q21. What's the difference between a queue and a stack?

A. Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule

** Q22. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?

A. Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.

** Q23. What comes to mind when you hear about a young generation in Java?

A. Garbage collection.

** Q24. What comes to mind when someone mentions a shallow copy in Java?

A. Object cloning.

** Q25. If you're overriding the method equals() of an object, which other method you might also consider?

A. hashCode()

** Q26. You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use:
ArrayList or LinkedList?

A. ArrayList

** Q27. How would you make a copy of an entire Java object with its state?

A. Have this class implement Cloneable interface and call its method clone().

** Q28. How can you minimize the need of garbage collection and make the memory use more effective?

A. Use object pooling and weak object references.

** Q29. 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?

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

** Q30. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?

A. You do not need to specify any access level, and Java will use a default package access level.

Wednesday, March 26, 2008

Java Object Initialization

Suppose class A extends one class B and implements an interface C as follows:

public class A extends B implements C
{


}

In this case, if we call new A(), how object initialization will happen? Remember class A and B, and interface C are not empty


Whenever we instantiate A with a call new A(),

The JVM will allocate enough space in the heap to hold all the instance variables defined in class A, and its super class –B and the fields defined in interface C.
The JVM will initialize instance variables. First class B’s fields will be initialized. Then interface C’s declared fields will be initialized and in the end, Class A’s instance variables will be initialized.
The JVM will call method of class A. Whenever we compile a class, the java compiler creates an instance initialization method for each constructor declared in the source code of the class. It has a name, return type void and a set of parameters that matches the constructor parameters. So in our case class A will have an method and class B will have an method (assuming that there is only one constructor for each class). This method will be created for the constructor having call to super() (implicitly or explicitly) and will be call only once for new class creation and also we can be sure that the init method will be executed before the constructor code for that class is executed.


Case 1: there are only default constructors in class A and Class B



The method of class A will invoke the method of class B which in turn will call method of Object class (which is super class of all java objects). The method of Object class will do nothing and return back to class B’s method. Then the class B constructor will be executed and then returned back to class A method where class A constructor will be completely executed.


Case 2 : class B has multiple constructors defined.

For example

public class B
{
private int count;

public B()
{
this.B(100);

}

public B(int i)
{
count = i;
}
}

public Class A extends B
{



}

Here the method of class A will result in call to super() which is constructor B() which in turn calls this.B(). There will be only one method for class B that is for constructor B(int i).This method will call Object classes method. The method of Object class will do nothing and return back to class B’s method. Then the class B constructor B(int i) will be executed completing B() then returned back to class A method where class A constructor will be completely executed.

Java Object Serialization

Serialization is a process of reading or writing an object. It is a process of saving an object’s state to a sequence of
bytes, as well as a process of rebuilding those bytes back into a live object at some future time. An object is
marked serializable by implementing the java.io.Serializable interface, which is only a marker interface -- it simply
allows the serialization mechanism to verify that the class can be persisted, typically to a file.

Transient variables cannot be serialized. The fields marked transient in a serializable object will not be
transmitted in the byte stream. An example would be a file handle or a database connection. Such objects are only
meaningful locally. So they should be marked as transient in a serializable class.
Serialization can adversely affect performance since it:
􀂃 Depends on reflection.
􀂃 Has an incredibly verbose data format.
􀂃 Is very easy to send surplus data.
When to use serialization? Do not use serialization if you do not have to. A common use of serialization is to use
it to send an object over the network or if the state of an object needs to be persisted to a flat file or a database.
Deep cloning or copy can be achieved through serialization. This may be fast
to code but will have performance implications .
The objects stored in an HTTP session should be serializable to support in-memory replication of sessions to
achieve scalability . Objects are passed in RMI (Remote Method Invocation)
across network using serialization.

The Java Virtual Machine

Each time a Java Application is executed then an instance of JVM ,responsible for its running,is created.A JVM instance is described in terms of subsystems, memory areas, data types, and instructions.The block diagram given below,depicts a view of Internal Architecture of JVM :



Each JVM has a class loader subsystem which loads classes and interfaces with fully qualified names.Each JVM has an execution engine too , which executes all instructions contained by methods of a loaded class.While executing a Java program,a JVM requires memory for storing bytecodes,objects ,local variables,method arguments,return values,intermediate computational results and JVM does that memory management on several runtime data areas.The specification of runtime data areas is quite abstract.This abstract nature of JVM specification helps different designers to provide implementation on wide variety of OS and as per choice of the designers.Some implementations may have a lot of memory in which to work, others may have very little. Some implementations may be able to take advantage of virtual memory, others may not.

Each instance of the Java virtual machine has one method area and one heap. These areas are shared by all threads running inside the virtual machine. When the virtual machine loads a class file, it parses information about a type from the binary data contained in the class file. It places this type information into the method area. As the program runs, the virtual machine places all objects the program instantiates onto the heap.

When a new thread is created, it gets its own pc register (program counter) and Java stack. If the thread is executing a Java method (not a native method), the value of the pc register indicates the next instruction to execute. A thread's Java stack stores the state of Java (not native) method which includes its local variables, the parameters with which it was invoked, its return value (if any), and intermediate calculations. The state of native method invocations is stored in an implementation-dependent way in native method stacks, in registers or other implementation-dependent memory areas.

The Java stack is composed of stack frames (or frames). A stack frame contains the state of one Java method invocation. When a thread invokes a method, the Java virtual machine pushes a new frame onto that thread's Java stack. When the method completes, the virtual machine pops and discards the frame for that method.

In JVM ,the instruction set uses the Java stack for storage of intermediate data values.The stack-based architecture of the JVM's instruction set optimizes code done by just-in-time and dynamic compilers.

Some more java interview questions

Is Vector is threadsafe ?

Ans : Yes, Vectors are threadsafe. Vectors are synchronized.


Why String objects are called immutable objects ?

String objects are called immutable because once you assign a value to a string object, you can never changes the value. String objects are immutable . String references are not.

If you redirect a String reference to a new String, the old String can be lost.

Can we override String methods ?

No...The String class is final—its methods can’t be overridden.

What is the difference between comparing two String objects and two StringBuffer objects using equals methods ?

String class overrides equal method of Object class but StringBuffer equals() is not overridden; it doesn’t compare values.

How many number of non-public class definition can a source file have
Unlimited
Can abstract class be instantiated

No.. abstract class cannot be be instantiated


What is a Java Virtual Machine (JVM)?


A Java Virtual Machine is a runtime environment required for execution of a Java application.Every Java application runs inside a runtime instance of some concrete implementation of abstract specifications of JVM.It is JVM which is crux of 'platform independent' nature of the language.

What is the difference between interpreted code and compiled code?


An interpreter produces a result from a program, while a compiler produces a program written in assembly language and in case of Java from bytecodes.The scripting languages like JavaScript,Python etc. require Interpreter to execute them.So a program written in scripting language will directly be executed with interpreter installed on that computer,if it is absent then this program will not execute.While in case of compiled code,an assembler or a virtual machine in case of Java is required to convert assembly level code or bytecodes into machine level instructions/commands.Generally, interpreted programs are slower than compiled programs, but are easier to debug and revise.

Friday, February 8, 2008

Some Interview Questions on Servlets

Q: Explain the life cycle methods of a Servlet.

A: The javax.servlet.Servlet interface defines the three methods known as life-cycle method.
public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()
First the servlet is constructed, then initialized wih the init() method.
Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet.

The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected and finalized.


Q: What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?

A: The getRequestDispatcher(String path) method of javax.servlet.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 javax.servlet.ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root.


Q: Explain the directory structure of a web application.

A: The directory structure of a web application consists of two parts.
A private directory called WEB-INF
A public resource directory which contains public resource folder.

WEB-INF folder consists of
1. web.xml
2. classes directory
3. lib directory


Q: What are the common mechanisms used for session tracking?

A: Cookies
SSL sessions
URL- rewriting


Q: Explain ServletContext.

A: ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web application or servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.


Q: What is preinitialization of a servlet?

A: A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.


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

A: A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following:
http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN
doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string.


Q: What is the difference between HttpServlet and GenericServlet?

A: A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1).
Both these classes are abstract.


Q: What is the difference between ServletContext and ServletConfig?

A: ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized

ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet.

Thursday, January 10, 2008

Java Frequently Asked Questions Collection

Q:

What is the difference between an Interface and an Abstract class?

A:

An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
.

Q:

What is the purpose of garbage collection in Java, and when is it used?

A:

The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

Q:

Describe synchronization in respect to multithreading.

A:

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 variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.

Q:

Explain different way of using thread?

A:

The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance, the only interface can help.

Q:

What are pass by reference and passby value?

A:

Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.

Q:

What is HashMap and Map?

A:

Map is Interface and Hashmap is class that implements that.

Q:

Difference between HashMap and HashTable?

A:

The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is non synchronized and Hashtable is synchronized.

Q:

Difference between Vector and ArrayList?

A:

Vector is synchronized whereas arraylist is not.

Q:

Difference between Swing and Awt?

A:

AWT are heavy-weight components. Swings are light-weight components. Hence swing works faster than AWT.

Q:

What is the difference between a constructor and a method?

A:

A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

Q:

What is an Iterators?

A:

Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.

Q:

State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.

A:

public : Public class is visible in other packages, field is visible everywhere (class must be public too)
private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature. This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default : What you get by default i.e., without any access modifier (i.e., public private or protected).It means that it is visible to all within a particular package.

Q:

What is an abstract class?

A:

Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (i.e., you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.

Q:

What is static in java?

A:

Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class. Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

Q:

What is final?

A:

A final class can't be extended i.e..; final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).

Q:

What if the main method is declared as private?

A:

The program compiles properly but at runtime it will give "Main method not public." message.

Q:

What if the static modifier is removed from the signature of the main method?

A:

Program compiles. But at runtime throws an error "NoSuchMethodError".

Q:

What if I write static public void instead of public static void?

A:

Program compiles and runs properly.

Q:

What if I do not provide the String array as the argument to the method?

A:

Program compiles but throws a runtime error "NoSuchMethodError".

Q:

What is the first argument of the String array in main method?

A:

The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.

Q:

If I do not provide any arguments on the command line, then the String array of Main method will be empty of null?

A:

It is empty. But not null.

Q:

How can one prove that the array is not null but empty?

A:

Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.

Q:

What environment variables do I need to set on my machine in order to be able to run Java programs?

A:

CLASSPATH and PATH are the two variables.

Q:

Can an application have multiple classes having main method?

A:

Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.

Q:

Can I have multiple main methods in the same class?

A:

No the program fails to compile. The compiler says that the main method is already defined in the class.

Q:

Do I need to import java.lang package any time? Why ?

A:

No. It is by default loaded internally by the JVM.

Q:

Can I import same package/class twice? Will the JVM load the package twice at runtime?

A:

One can import the same package or same class multiple times. Neither compiler nor JVM complains about it. And the JVM will internally load the class only once no matter how many times you import the same class.

Q:

What are Checked and UnChecked Exception?

A:

A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.
Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. e.g., IOException thrown by java.io.FileInputStream's read() method·
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the
exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. e.g., StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

Q:

What is Overriding?

A:

When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.
When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.

Q:

What are different types of inner classes?

A:

Nested top-level classes , Member classes, Local classes, Anonymous classes

Nested top-level classes - If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class.
Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. e.g., outer.inner. Top-level inner classes implicitly have access only to static variables. There can also be inner interfaces. All of these are of the nested top-level variety.

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a
more publicly available interface. Because local classes are not members, the modifiers public, protected, private, and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

Q:

Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?

A:

Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying,can not resolve symbol
symbol : class ABCD
location: package io
import java.io.ABCD;

Q:

Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?

A:

No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage.

Q:

What is the difference between declaring a variable and defining a variable?

A:

In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization.
e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.

Q:

What is the default value of an object reference declared as an instance variable?

A:

null unless we define it explicitly.

Q:

Can a top level class be private or protected?

A:

No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.

Q:

What type of parameter passing does Java support?

A:

In Java the arguments are always passed by value .

Q:

Primitive data types are passed by reference or pass by value?

A:

Primitive data types are passed by value.

Q:

Objects are passed by value or by reference?

A:

Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object .

Q:

What is serialization?

A:

Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.

Q:

How do I serialize an object to a file?

A:

The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.

Q:

Which methods of Serializable interface should I implement?

A:

The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods.

Q:

How can I customize the seralization process? i.e. how can one have a control over the serialization process?

A:

Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.

Q:

What is the common usage of serialization?

A:

Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed.

Q:

What is Externalizable interface?

A:

Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.

Q:

What happens to the object references included in the object?

A:

The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized along with the original object.

Q:

What one should take care of while serializing the object?

A:

One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.

Q:

What happens to the static fields of a class during serialization?

A:

There are three exceptions in which serialization does not necessarily read and write to the stream. These are
1. Serialization ignores static fields, because they are not part of ay particular state state.
2. Base class fields are only handled if the base class itself is serializable.
3. Transient fields.

Q:

Does Java provide any construct to find out the size of an object?

A:

No there is not sizeof operator in Java. So there is not direct way to determine the size of an object directly in Java.

Q:

Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?

A:

Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution.

To put it in code...

long start = System.currentTimeMillis ();
method ();
long end = System.currentTimeMillis ();

System.out.println ("Time taken for execution is " + (end - start));

Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing.

Q:

What are wrapper classes?

A:

Java provides specialized classes corresponding to each of the primitive data types. These are called wrapper classes. They are e.g. Integer, Character, Double etc.

Q:

Why do we need wrapper classes?

A:

It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object.

Q:

What are checked exceptions?

A:

Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions.

Q:

What are runtime exceptions?

A:

Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.

Q:

What is the difference between error and an exception?

A:

An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).

Q:

How to create custom exceptions?

A:

Your class should extend class Exception, or some more specific type thereof.

Q:

If I want an object of my class to be thrown as an exception object, what should I do?

A:

The class should extend from Exception class. Or you can extend your class from some more precise exception type also.

Q:

If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?

A:

One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well.

Q:

What happens to an unhandled exception?

A:

One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well.

Q:

How does an exception permeate through the code?

A:

An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.

Q:

What are the different ways to handle exceptions?

A:

There are two ways to handle exceptions,
1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and
2. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions.

Q:

Q: What is the basic difference between the 2 approaches to exception handling...1> try catch block and 2> specifying the candidate exceptions in the throws clause?
When should you use which approach?

A:

In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.

Q:

Is it necessary that each try block must be followed by a catch block?

A:

It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

Q:

If I write return at the end of the try block, will the finally block still execute?

A:

Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.

Q:

If I write System.exit (0); at the end of the try block, will the finally block still execute?

A:

No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.

Q:

How are Observer and Observable used?

A:

Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

Q:

What is synchronization and why is it important?

A:

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.

Q:

How does Java handle integer overflows and underflows?

A:

It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

Q:

Does garbage collection guarantee that a program will not run out of memory?

A:

Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection
.

Q:

What is the difference between preemptive scheduling and time slicing?

A:

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

Q:

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

A:

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

Q:

What is the purpose of finalization?

A:

The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

Q:

What is the Locale class?

A:

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

Q:

What is the difference between a while statement and a do statement?

A:

A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.

Q:

What is the difference between static and non-static variables?

A:

A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.

Q:

How are this() and super() used with constructors?

A:

Othis() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

Q:

What are synchronized methods and synchronized statements?

A:

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.

Q:

What is daemon thread and which method is used to create the daemon thread?

A:

Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.

Q:

Can applets communicate with each other?

A:

At this point in time applets may communicate with other applets running in the same virtual machine. If the applets are of the same class, they can communicate via shared static variables. If the applets are of different classes, then each will need a reference to the same class with static variables. In any case the basic idea is to pass the information back and forth through a static variable.

An applet can also get references to all other applets on the same page using the getApplets() method of java.applet.AppletContext. Once you\'ve got a reference to an applet, you can communicate with it by using its public members.

It is conceivable to have applets in different virtual machines that talk to a server somewhere on the Internet and store any data that needs to be serialized there. Then, when another applet needs this data, it could connect to this same server. Implementing this is non-trivial.

Q:

What are the steps in the JDBC connection?

A:

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

Step 1 : Register the database driver by using :

Class.forName(\" driver classs for that specific database\" );

Step 2 : Now create a database connection using :

Connection con = DriverManager.getConnection(url,username,password);

Step 3: Now Create a query using :

Statement stmt = Connection.Statement(\"select * from TABLE NAME\");

Step 4 : Exceute the query :

stmt.exceuteUpdate();

Q:

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

A:

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 exceptionis executed. The remaining catch clauses are ignored.

Q:

Can an unreachable object become reachable again?

A:

An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects.

Q:

What method must be implemented by all threads?

A:

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

Q:

What are synchronized methods and synchronized statements?

A:

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.

Q:

What is Externalizable?

A:

Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)

Q:

What modifiers are allowed for methods in an Interface?

A:

Only public and abstract modifiers are allowed for methods in interfaces.

Q:

What are some alternatives to inheritance?

A:

Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn't force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

Q:

What does it mean that a method or field is "static"?

A:

Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class.

Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That's how library methods like System.out.println() work out is a static field in the java.lang.System class.

Q:

What is the difference between preemptive scheduling and time slicing?

A:

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

Q:

What is the catch or declare rule for method declarations?

A:

If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.