Monday, November 29, 2010

OOPS and CORE JAVA

· What is JVM (Java Virtual Machine)?
· What is JIT (Just- in-Time) Compilation?
· What is Object Oriented Programming?
· What’s a Class?
· What’s an Object?
· What’s the relation between Classes and Objects?
· What are different properties provided by Object-oriented systems?
· How do you implement inheritance in Java?
· How can we implement polymorphism in Java?
· What is an Abstract class?
· What are Abstract methods?
· What’s the difference between “Abstract” classes and “Interfaces”?
· What’s difference between Static and Non-Static fields of a class?
· What are inner classes and what’s the practical implementation of inner classes?
· What are packages?
· What is a constructor in class?
· Can constructors be parameterized?
· What is the use if “instance of” keyword?
· What are Native methods in Java?
· How do refer to a current instance of object?
· Explain in depth Garbage collector?
· How does the garbage collector determine that the object has to be marked for
deletion?
· Can you explain “finalize ()” method?
· How can we force the garbage collector to run?
· What’s the main difference between “Switch” and “If” comparison?
· What’s the use of JAVAP tool?
· What are applets?
· In which package is, the applet class located?
· What are native interfaces in Java?
· What are Class loaders?
· What is Bootstrap, Extension and System Class loader?
· Can you explain the flow between bootstrap, extension and system class loader?
· Can you explain how can you practically do dynamic loading?
· What is Reflection API in Java?
· What’s the difference between static and dynamic class loading?
· How can you copy one array in to a different array?
· Can you explain the core collection interfaces?
· Can you explain in brief the collection classes which implement the collection
interfaces?
· What’s the difference between standard JAVA array and Array List class?
· What’s the use of “ensure Capacity” in Array List class?
· How can we obtain an array from an Array List class?
· What is “Linked List” class for?
· Can you explain Hash Set class in collections?
· What is Linked Hash Set class?
· What is a Tree Set class?
· What’s the use of Comparator Interface?
· How can we access elements of a collection?
· What is Map and SortedMap Interface?
· Have you used any collection algorithm?
· Why do we use collections when we had traditional ways for collection?
· Can you name the legacy classes and interface for collections?
· What is Enumeration Interface?
· What’s the main difference between Array List / Hash Map and Vector / Hash
table?
· Are String object Immutable, Can you explain the concept?
· What is a String Buffer class and how does it differs from String class?
· What is the difference between String Builder and String Buffer class?
· What is Pass by Value and Pass by reference? How does JAVA handle the same?
· What are access modifiers?
· What is Assertion?
· Can you explain the fundamentals of deep and shallow Cloning?
· How do we implement shallow cloning?
· How do we implement deep cloning?
· What’s the impact of private constructor?
· What are the situations you will need a constructor to be private?
· Can you explain final modifier?
· What are static Initializes?
· If we have multiple static initialize blocks how are the sequence handled?
· Define casting? What are the different types of Casting?
· Can you explain Widening conversion and Narrowing conversion?
· Can we assign parent object to child objects?
· Define exceptions?
· Can you explain in short how JAVA exception handling works?
· Can you explain different exception types?
· Can you explain checked and unchecked exceptions?
· Can we create our own exception class?
· What are chained exceptions?
· What is serialization?
· How do we implement serialization actually?
· What’s the use of Externalizable Interface?
· What is JAVA doc utility?
Chapter 2: Threading
· What’s difference between thread and process?
· What is thread safety and synchronization?
· What is semaphore?
· What are monitors?
· What’s the importance of synchronized blocks?
· How do we create threads?
· What’s the difference in using run able and extends in threads?
· Can you explain Thread. Sleep?
· How to stop a thread?
· What is wait () and notify ()?
· Can you explain how Scheduling and Priority works in threads?
· Can you explain Yielding in threading?
· What are daemon threads?
· How do we implement single threaded model in servlets?
Chapter 3: JDBC
· How does JAVA interact with databases?
· Can we interact with non-relational sources using JDBC?
· Can you explain in depth the different sections in JDBC?
· Can you explain in short how you go about using JDBC API in code?
· How do you handle SQL exceptions?
Twist: - (A) Can you explain “SQL Exception” class in detail?
Twist: - (A) what is SQL State in SQL Exceptions?
· If there is more than one exception in SQL Exception” class how to go about
displaying it?
· Explain Type1, Type2, Type3, and Type4 drivers in JDBC?
· What are the advantages and disadvantages of using JDBC-ODBC bridge driver?
· What are the advantages and disadvantages of using Native-API/ Partially Java
Driver?
· What are the advantages and disadvantages of using Net-Protocol/ All-Java
driver?
· What are the advantages and disadvantages of using Native-protocol/ All-Java
driver?
· Advantages of using JDBC-ODBC bridge driver:-
· Disadvantages of using JDBC-ODBC bridge driver:-
· Advantages of using Native-API/ Partially Java Driver:-
· Dis-advantages of using Native-API/ Partially Java Driver:-
· Advantages of using Net-Protocol/ All-Java driver:-
· Disadvantages of using Net-Protocol/ All- Java driver:-
· Advantages of using Native-protocol/ All-Java driver:-
· Disadvantages of using Native-protocol/ All-Java driver:-
· Define meta-data?
· What is Database Metadata?
· Can you explain “Connection Factory” class?
· I want to display tables of a database how do I do it?
· Define “Result Set Meta Data”?
· What is the difference between “Result Set” and “Row Set”?
· Can “Result Set” objects be serialized?
· Explain “Result Set”, “Row Set”, “Cached Row set”, “JdbcRowset” and “Web
Row Set”?
· What are the different types of result set?
· Explain the concept of “Prepared Statement “statement interface?
· What’s the difference between “Statement” and “Prepared Statement”?
· How can we call stored procedure using JDBC?
· Can you explain “Callable Statement” interface in detail?
· How do you get a result set object from stored procedure?
· (A) How can we do batch updates using “Callable Statement” Interface?
· Define transactions?
· What is ACID in transaction?
· What are the four essential properties of a transaction?
· Explain concurrency and locking?
· What are different types of locks?
· What are the different types of levels of resource on which locks can be placed?
· Define lock escalation?
· What is Table level and Row level locking?
· What are the problems that can occur if you do not implement locking properly?
· What are different transaction levels?
· Twist: - what are different types of locks?
· What is difference between optimistic and pessimistic locking?
· What are deadlocks?
· How can we set transaction level through JDBC API?
· Can you explain transaction control in JDBC?
· What are Save points in a transaction?
Chapter 4: Servlets and JSP
· What are Servlets?
· What are advantages of servlets over CGI?
· Can you explain Servlet life cycle?
· What are the two important API’s in for Servlets?
· Can you explain in detail “javax.servlet” package?
· What’s the use of Servlet Context?
· How do we define an application level scope for servlet?
· What's the difference between Generic Servlet and Http Servlet?
· Can you explain in detail javax.servlet.http package?
· What’s the architecture of a Servlet package?
· Why is HTTP protocol called as a stateless protocol?
· What are the different ways we can maintain state between requests?
· What is URL rewriting?
· What are cookies?
· What are sessions in Servlets?
· What the difference is between get Session (true) and get Session (false)?
· What’s the difference between “do Post” and “do get” methods?
· Which are the different ways you can communicate between servlets?
· What is functionality of “Request Dispatcher” object?
· How do we share data using “get Servlet Context ()”?
· Explain the concept of SSI?
· What are filters in JAVA?
· Can you explain in short how do you go about implementing filters using Apache
Tomcat?
· Twist: - Explain step by step of how to implement filters?
· What’s the difference between Authentication and authorization?
· Explain in brief the directory structure of a web application?
· Can you explain JSP page life cycle?
· What is EL?
· How does EL search for an attribute?
· What are the implicit EL objects in JSP?
· How can we disable EL?
· What is JSTL?
· Can you explain in short what the different types of JSTL tags are?
· (I) How can we use beans in JSP?
· What is the use of ?
· What is tag for?
· What are JSP directives?
· What are Page directives?
· What are including directives?
· Can you explain taglib directives?
· How does JSP engines instantiate tag handler classes’ instances?
· What’s the difference between JavaBeans and taglib directives?
· What are the different scopes an object can have in a JSP page?
· What are different implicit objects of JSP?
· What are different Authentication Options available in servlets?
· Can you explain how do we practically implement security on a resource?
· How do we practically implement form based authentication?
· How do we authenticate using JDBC?
· Can you explain JDBCRealm?
· Can you explain how do you configure JNDIRealm?
· How did you implement caching in JSP?
· What is the difference between Servletcontext and ServletConfig?
· How do we prevent browser from caching output of my JSP pages?
· Can we explicitly destroy a servlet object?
Chapter 5: EJB
· What is EJB?
· What are the different kind of Ebb’s?
· You are designing architecture for a project how do you decide whether you
should use session, entity or message driven bean?
· Can you explain “EJBHome” and “EJBObject” in EJB?
· Can client directly create object of session or entity beans?
· Can you explain the concept of local interfaces?
· What are the limitations of using Local object?
· Which application server have you used for EJB?
· Can you explain step by step practically developing and deploying EJB
component?
· What is Passivation and Activation in EJB?
· Can beans who are involved in transaction have “Passivation” process?
· How does the server decide which beans to passivity and activate?
· In what format is the conversational data written to the disk?
· Can you explain in brief Life cycle for Stateless and Stateful beans?
Chapter 6: Struts
· (I)What’s MVC pattern?
· (B) Define struts?
· (A) Can you explain the directory structure for a struts folder in brief?
· (I) Can you give an overview of how a struts application flows?
· Twist: - What are action and action form classes in Struts?
Chapter 7: XML and Web Services
· What is XML?
· What is the version information in XML?
· What is ROOT element in XML?
· If XML does not have closing tag will it work?
· Is XML case sensitive?
· What is the difference between XML and HTML?
· Is XML meant to replace HTML?
· Can you explain why your project needed XML?
· What is DTD (Document Type definition)?
· What is well formed XML?
· What is a valid XML?
· What is CDATA section in XML?
· What is CSS?
· What is XSL?
· What is element and attributes in XML?
· What are the standard ways of parsing XML document?
· In What scenarios will you use a DOM parser and SAX parser?
· What is XSLT?
· Define XPATH?
· What is the concept of XPOINTER?
· What is a Web Service?
· What is DISCO?
· What is SOAP?
· What is WSDL?
· Can you explain UDDI?
· Can you explain JAXP?
· What is a XML registry?
· What is JAXR?
· What is JAXM?
· Can you explain JAX-RPC?
· How do you practically implement Web Services?
· How do we consume a web service?
· Are web services Stateful?
Chapter 8: Internationalization
· Can you explain i18n and l10n?
· Can you explain internationalization and localization?
· What is Locale?
· How do we display numbers, currency and Dates according to proper Locale
format?
· what are resource bundles?
· How do we load a resource bundle file?
· How can we do inheritance in resource bundles?
Chapter 9: JNI
· What is Native Interface in JAVA?
· Can you say in brief steps required to implement Native interfaces in Java?
· Can JNI be used for VB6, C# or VB.NET directly?
· What are JNI functions and pointers?
· How does the garbage collector know JNI objects are no more used?
· Twist: - What are the different types of references JNI supports?
· Twist: - How to do you delete global objects?
· How does the native language C or C++ understand data types in JAVA?
· Can you explain exception handling in JNI?
· What are limitations for “JNIEnv” pointer in multi- threading scenarios?
· What are the advantages and disadvantages of using “JNI”?
Chapter 10: Architecture
· What are design patterns?
· Can you list down all patterns and their classification?
· What is the difference between Factory and Abstract Factory Patterns?
· What is MVC pattern?
· How can we implement singleton pattern in JAVA?
· How do you implement prototype pattern in JAVA?
· Can you give a practical implementation of FAÇADE patterns?
· How can we implement observer pattern in JAVA?
· What is three tier architecture?
· What is Service Oriented architecture?
· What is aspect oriented programming?
· How can you implement AOP practically in JAVA?
· What is Inversion of control?
· What is OR mapping?
Chapter 11: UML
· What is UML?
· How many types of diagrams are there in UML?
· What are advantages of using UML?
· What is the sequence of UML diagrams in project?
· Give a small brief explanation of all Elements in activity diagrams?
· Explain Different elements of a collaboration diagram?
· Explain Component diagrams?
· Describe the various components in sequence diagrams?
· What are the elements in State Chart diagrams?
· Describe different elements in Static Chart diagrams?
· Explain the different elements of a Use Case?
Chapter 12: Project Management
· What is project management?
· Is spending in IT projects constant through out the project?
· Who is a stakeholder?
· Can you explain project life cycle?
· Are risk constant through out the project?
· Can you explain different software development life cycles?
· What is triple constraint triangle in project management?
· What is a project baseline?
· What is effort variance?
· How is normally a project management plan document organized?
· (I)How do you estimate a project?
· What is CAR (Causal Analysis and Resolution)?
· What is DAR (Decision Analysis and Resolution)?
· What is a fish bone diagram?
· What is pare to principle?
· How do you handle change request?
· What is internal change request?
· What is difference between SITP and UTP in testing?
· What is the software you have used for project management?
· What are the metrics followed in project management?
· You have people in your team who do not meet there deadlines or do not perform
what are the actions you will take?
· What is black box testing and White box testing?
· What’s the difference between Unit testing, Assembly testing and Regression
testing?
· What is V model in testing?
· How do you start a project?
· How did you do resource allocations?
· How will you do code reviews?
· What is CMMI?
· What are the five levels in CMMI?
· What is continuous and staged representation?
· Can you explain the process areas?
· What is SIX sigma?
· What is DMAIC and DMADV?
· What are the various roles in Six Sigma implementation?
· What are function points?
· What are the different types of elementary process in FPA?
· What are the different elements in Functions points?
· Can you explain in GSC and VAF in function points?
· What are unadjusted function points and how is it calculated?
· Can you explain steps in function points?
· What is the FP per day in your current company?
· Do you know Use Case points?
· What is COCOMO I, COCOMOII and COCOMOIII?
· What is SMC approach of estimation?
· How do you estimate maintenance project and change requests?
Chapter 13: Database
· What is database or database management systems (DBMS)?
· What is SQL?
· What’s difference between DBMS and RDBMS?
· What are CODD rules?
· What are E-R diagrams?
· How many types of relationship exist in database designing? What is
normalization? What are different type of normalization?
· What is denormalization?
· Can you explain Fourth Normal Form?
· Can you explain Fifth Normal Form?
· What’s the difference between Fourth and Fifth normal form?
· Have you heard about sixth normal form?
· What are DML and DDL statements?
· How do we select distinct values from a table?
· What is like operator for and what are wild cards?
· Can you explain Insert, Update and Delete query?
· What is order by clause?
· What is the SQL In clause?
· Can you explain the between clause?
· I have an employee salary table how do we find the second highest from it?
· What are different types of joins in SQL?
· What is “CROSS JOIN”?
· You want to select the first record in a given set of rows?
· What is the default “SORT” order for a SQL?
· What is a self-join?
· What’s the difference between DELETE and TRUNCATE?
· .What are Wildcard operators?
· Twist: - What is like clause in SQL?
· What’s the difference between “UNION” and “UNION ALL”?
· What are cursors and what are the situations you will use them?
· What are the steps to create a cursor?
· What is “Group by” clause?
· What is the difference between “HAVING” and “WHERE” clause?
· What is a Sub-Query?
· What are Aggregate and Scalar Functions?
· Can you explain the SELECT INTO Statement?
· What is a View?
· What is “Correlated Sub queries”?
· What is SQl injection?
· What is “Data Warehousing”?
· What are Data Marts?
· What are Fact tables and Dimension Tables?
· Twist: - What is Dimensional Modeling?
· Twist: - What is Star Schema Design?
· What is Snow Flake Schema design in database?
· Twist: - What’s the difference between Star and Snow flake schema?
· What is ETL process in Data warehousing?
· Twist: - What are the different stages in “Data warehousing”?
· What is “Data mining”?
· Compare “Data mining” and “Data Warehousing”?
· What are indexes?
· What are B-Trees?
· I have a table which has lot of inserts, is it a good database design to create
indexes on that table?
· Twist: - Insert’s are slower on tables which have indexes, justify it?
· Twist: - Why do page splitting happen?
· What are “Table Scan’s” and “Index Scan’s”?
· What are the two types of indexes and explain them in detail?
· Twist: - What’s the difference between clustered and non-clustered indexes

Software Architecture Interview Questions

Basic architecture Interview questions
(B) What is the definition of software architecture?
(B) Can you explain your current project architecture?
(B) Which design pattern have you worked with?
(B) Which UML diagram have you used in your project?
(I) what things do you include in the technical document?
(A) Can you explain different software development life cycles?
(I) what is a definition of enterprise architecture?
(B) What is TOGAF ?
(I) Can you explain OOA and OOD ?
(A) What is the concept of load balancing?
(A) Can you explain stateless load balancing?
(I) Can you explain stateful load balancing?
(I) what is round-robin?
(A) Can you explain least connections, weighted distribution and response time ?
OOP
(B) What is OOP?
(B) What are the advantages of using OOP over functional programming?
(B) What are the characteristic of OOP?
(I) Can you explain interfaces?
(B) Can you explain aggregation and composition ?
(B) What are abstract classes?
(B) What’s the difference between abstract classes and interfaces?
(I) Can we create a object of a class whose constructor is private?
UML
(B) Define UML?
(I) Can you explain use case diagrams?
(I) Can you explain primary and secondary actors?
(I) How does a simple use case look like?
(I) Can you explain ‘Extend’ and ‘Include’ in use cases?
(I) Can you explain class diagrams?
(B) How do we represent private, public and protected in class diagrams?
(I) what does associations in a class diagram mean?
(I) Can you explain aggregation and composition in class diagrams?
(A) What are composite structure diagram and reflexive association in class diagrams?
(I) Can you explain business entity and service class?
(I) Can you explain System entity and service class?
(B) Can you explain generalization and specialization?
(B) How do we represent an abstract class and interface UML?
(B) How do we achieve generalization and specialization?
(I) Can you explain object diagrams in UML?
(I) Can you explain sequence diagrams?
(I) Can you explain collaboration diagrams ?
(I) Can you explain activity diagrams?
(I) What is state chart diagram?
(I) Can you explain stereotypes in UML?
(I) Can you explain package diagrams?
(B) Can you explain component diagrams?
(B) Can you explain deployment diagrams?
(I) Can you explain how UML flows in actual project?
Design Patterns
(B) What are design patterns?
(I) Which are the three main categories of design patterns?
(A) Can you explain factory pattern?
(I) Can you explain abstract factory pattern?
(I)Can you explain builder pattern?
(I) Can you explain prototype pattern?
(A) Can you explain shallow copy and deep copy in prototype patterns?
(B) Can you explain singleton pattern?
(A) Can you explain command patterns?
(I) what is Interpreter pattern?
(B) Can you explain iterator pattern?
(A) Can you explain mediator pattern?
(I) Can you explain memento pattern?
(B) Can you explain observer pattern?
(I) Can you explain state pattern?
(I) Can you explain strategy pattern?
(A) Can you explain visitor pattern?
(A) What the difference between visitor and strategy pattern?
(A) Can you explain adapter pattern?
(I) What is fly weight pattern?
(A) Can you explain bridge pattern?
(A) Can you explain composite pattern?
(I) Can you explain decorator pattern ?
(A) Can you explain Façade pattern?
(A) Can you explain chain of responsibility ( COR)?
(I) Can you explain proxy pattern?
(B) Can you explain template pattern?
(B)Can you explain MVC?
(A)What is aspect oriented programming?
(A)What is Inversion of control?
(I)What is OR mapping?
SOA (Service oriented architecture)
(B) What is SOA?
(I) In SOA do we need to build systems from scratch?
(I) Can you explain business layers and plumbing layers in SOA?
(I) what’s the difference between services and components?
(A) Can you describe the complete architecture of SOA?
(I) Can you explain a practical example in SOA?
(I) What are ends, contract, address, and bindings?
(I) Are web-services SOA ?
(B) What is SOAP?
(B) What is WSDL ?
(B) Can you explain UDDI ?
(A) What is BPEL?
(A) What are WS-* specifications?
(A) Can you explain SOA governance?
Estimation, Metrics and Measure
(B) What is meant by measure and metrics?
(B) What are the various common ways of estimation?
(B) Can you explain LOC method of estimation?
(B) How do we convert LOC in to effort?
(B) Can you explain COCOMO?
(I) Can you explain Intermediate COCOMO and COCOMO II?
(B) How do you estimate using LOC?
(A) Can you explain in brief Function points?
(B) Can you explain the concept Application boundary?
(B) Can you explain the concept of elementary process?
(B) Can you explain the concept of static and dynamic elementary process?
(I) Can you explain concept of FTR, ILF, EIF, EI, EO , EQ and GSC ?
(A) How can you estimate number of acceptance test cases in a project?
(I) Can you explain the concept of Use Case’s?
(I) Can you explain the concept of Use case points?
(B) What is a use case transaction?

Tuesday, October 12, 2010

Hashtable Vs Hashmap, Vector Vs ArrayList

A Map is a class that stores key-value pairs and provides a way to locate a value based on the key. The Hashtable class is a synchronized implementation of the Map interface. The HashMap is better in terms performance because the hashing algorithm it uses. The Hashtable is synchronized so performance is slightly worse.

As to the difference between a Vector and an ArrayList:

I. Synchronization

Vectors are synchronized. Any method that touches the Vector’s contents is thread safe. ArrayList, on the other hand, is unsynchronized, making them, therefore, not thread safe. With that difference in mind, using synchronization will incur a performance hit. So if you don’t need a thread-safe collection, use the ArrayList. Why pay the price of synchronization unnecessarily?

II. Data growth

Internally, both the ArrayList and Vector hold onto their contents using an Array. You need to keep this fact in mind while using either in your programs. When you insert an element into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. Depending on how you use these classes, you could end up taking a large performance hit while adding new elements. It’s always best to set the object’s initial capacity to the largest capacity that your program will need. By carefully setting the capacity, you can avoid paying the penalty needed to resize the internal array later. If you don’t know how much data you’ll have, but you do know the rate at which it grows, Vector does possess a slight advantage since you can set the increment value.

III. Usage patterns

Both the ArrayList and Vector are good for retrieving elements from a specific position in the container or for adding and removing elements from the end of the container. All of these operations can be performed in constant time — O(1). However, adding and removing elements from any other position proves more expensive — linear to be exact: O(n-i), where n is the number of elements and i is the index of the element added or removed. These operations are more expensive because you have to shift all elements at index i and higher over by one element. So what does this all mean? It means that if you want to index elements or add and remove elements at the end of the array, use either a Vector or an ArrayList. If you want to do anything else to the contents, go find yourself another container class. For example, the LinkedList can add or remove an element at any position in constant time — O(1). However, indexing an element is a bit slower — O(i) where i is the index of the element. Traversing an ArrayList is also easier since you can simply use an index instead of having to create an iterator. The LinkedList also creates an internal object for each element inserted. So you have to be aware of the extra garbage being created.

Java performance tips – Part 1 : Vector, ArrayList & LinkedList

When, where & how to use Vector & ArrayList

Even though both Vector & ArrayList are used for the same purpose – as a dynamic collection of related objects – there is a right time and place to use them. As we all know there is a major difference: Vector is thread-safe but ArrayList is not. If there is no need of synchronization we can use ArrayList instead of Vector. And that will definitely be a performance booster.

When size matters

Internally both Vector & ArrayList uses arrays to hold the elements. Both supports an initialCapacity parameter which decides the initial size of the array. (I really don’t remember the default value). Once if the capacity becomes insufficient to accommodate new elements either of these collections need to expand their capacity. Both Vector & ArrayList do it differently. Vector doubles the current capacity & ArrayList increases the capacity by 50%. Whenever we create a Vector we can specify a capacityIncrement parameter; which is an integer using which the capacity will get incremented whenever the Vector overflows.

Its also advised that, if we know the maximum number of elements that gonna be inserted in to the collection, we should set it as the initialCapacity while creating the collection itself. But its not practically possible every time.

Element access & performance

In both Vector & ArrayList addition/deletion of elements at one end & accessing the elements at a particular index wont take much effort (just O(1) ). But adding or deleting an element at the i-th position will take some effort based on the value of i (O(n-i), where n is the size of the collection). Use of a LinkedList can help us here. B’ coz in a LinkedList addition/deletion of elements is pretty easy as it’s a matter of adjusting the pointers (just O(1)).

LinkedList is good, but…

The problem with LinkedList is that it will create an object for each element being added to the list. Means double the duty for the garbage collector. And as LinkedList is not using arrays to hold elements, it’s a bit painful for it to access elements at a particular index (O(i), where i the index).

So, programmers should decide when to use what based on the requirement.

Thursday, September 16, 2010

Java - Multithreading

Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.

A multithreading is a specialized form of multitasking. Multitasking threads require less overhead than multitasking processes.

I need to define another term related to threads: process: A process consists of the memory space allocated by the operating system that can contain one or more threads. A thread cannot exist on its own; it must be a part of a process. A process remains running until all of the non-daemon threads are done executing.

Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum.
Life Cycle of a Thread:






A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread.
Java Thread

Above mentioned stages are explained here:

*

New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.
*

Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.
*

Waiting: Sometimes a thread transitions to the waiting state while the thread waits for another thread to perform a task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.
*

Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.
*

Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.

Thread Priorities:

Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.

Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).

Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependentant.
Creating a Thread:

Java defines two ways in which this can be accomplished:

*

You can implement the Runnable interface.
*

You can extend the Thread class, itself.

Create Thread by Implementing Runnable:

The easiest way to create a thread is to create a class that implements the Runnable interface.

To implement Runnable, a class need only implement a single method called run( ), which is declared like this:

public void run( )

You will define the code that constitutes the new thread inside run() method. It is important to understand that run() can call other methods, use other classes, and declare variables, just like the main thread can.

After you create a class that implements Runnable, you will instantiate an object of type Thread from within that class. Thread defines several constructors. The one that we will use is shown here:

Thread(Runnable threadOb, String threadName);

Here threadOb is an instance of a class that implements the Runnable interface and the name of the new thread is specified by threadName.

After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. The start( ) method is shown here:

void start( );

Example:

Here is an example that creates a new thread and starts it running:

// Create a new thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}

// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// Let the thread sleep for a while.
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}

class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

This would produce following result:

Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

Create Thread by Extending Thread:

The second way to create a thread is to create a new class that extends Thread, and then to create an instance of that class.

The extending class must override the run( ) method, which is the entry point for the new thread. It must also call start( ) to begin execution of the new thread.
Example:

Here is the preceding program rewritten to extend Thread:

// Create a second thread by extending Thread
class NewThread extends Thread {
NewThread() {
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}

// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// Let the thread sleep for a while.
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}

class ExtendThread {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

This would produce following result:

Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

Thread Methods:

Following is the list of important medthods available in the Thread class.
SN Methods with Description
1 public void start()
Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.
2 public void run()
If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object.
3 public final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for retrieving the name.
4 public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 10.
5 public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread.
6 public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes.
7 public void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any reason.
8 public final boolean isAlive()
Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion.

The previous methods are invoked on a particular Thread object. The following methods in the Thread class are static. Invoking one of the static methods performs the operation on the currently running thread
SN Methods with Description
1 public static void yield()
Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled
2 public static void sleep(long millisec)
Causes the currently running thread to block for at least the specified number of milliseconds
3 public static boolean holdsLock(Object x)
Returns true if the current thread holds the lock on the given Object.
4 public static Thread currentThread()
Returns a reference to the currently running thread, which is the thread that invokes this method.
5 public static void dumpStack()
Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded application.
Example:

The following ThreadClassDemo program demonstrates some of these methods of the Thread class:

// File Name : DisplayMessage.java
// Create a thread to implement Runnable
public class DisplayMessage implements Runnable
{
private String message;
public DisplayMessage(String message)
{
this.message = message;
}
public void run()
{
while(true)
{
System.out.println(message);
}
}
}

// File Name : GuessANumber.java
// Create a thread to extentd Thread
public class GuessANumber extends Thread
{
private int number;
public GuessANumber(int number)
{
this.number = number;
}
public void run()
{
int counter = 0;
int guess = 0;
do
{
guess = (int) (Math.random() * 100 + 1);
System.out.println(this.getName()
+ " guesses " + guess);
counter++;
}while(guess != number);
System.out.println("** Correct! " + this.getName()
+ " in " + counter + " guesses.**");
}
}

// File Name : ThreadClassDemo.java
public class ThreadClassDemo
{
public static void main(String [] args)
{
Runnable hello = new DisplayMessage("Hello");
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.start();

Runnable bye = new DisplayMessage("Goodbye");
Thread thread2 = new Thread(hello);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setDaemon(true);
System.out.println("Starting goodbye thread...");
thread2.start();

System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try
{
thread3.join();
}catch(InterruptedException e)
{
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);

thread4.start();
System.out.println("main() is ending...");
}
}

This would produce following result. You can try this example again and again and you would get different result every time.

Starting hello thread...
Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Thread-2 guesses 27
Hello
** Correct! Thread-2 in 102 guesses.**
Hello
Starting thread4...
Hello
Hello
..........remaining result produced.

Major Thread Concepts:

While doing Multithreading programming, you would need to have following concepts very handy:

*

Thread Synchronization
*

Interthread Communication
*

Thread Deadlock
*

Thread Control: Suspend, Stop and Resume

Using Multithreading:

The key to utilizing multithreading support effectively is to think concurrently rather than serially. For example, when you have two subsystems within a program that can execute concurrently, make them individual threads.

With the careful use of multithreading, you can create very efficient programs. A word of caution is in order, however: If you create too many threads, you can actually degrade the performance of your program rather than enhance it.

Remember, some overhead is associated with context switching. If you create too many threads, more CPU time will be spent changing contexts than executing your program!

Web Service Questions and Answers

What is a Web service?
Many people and companies have debated the exact definition of Web services. At a minimum, however, a Web service is any piece of software that makes itself available over the Internet and uses a standardized XML messaging system.
XML is used to encode all communications to a Web service. For example, a client invokes a Web service by sending an XML message, then waits for a corresponding XML response. Because all communication is in XML, Web services are not tied to any one operating system or programming language--Java can talk with Perl; Windows applications can talk with Unix applications.
Beyond this basic definition, a Web service may also have two additional (and desirable) properties:
First, a Web service can have a public interface, defined in a common XML grammar. The interface describes all the methods available to clients and specifies the signature for each method. Currently, interface definition is accomplished via the Web Service Description Language (WSDL). (See FAQ number 7.)
Second, if you create a Web service, there should be some relatively simple mechanism for you to publish this fact. Likewise, there should be some simple mechanism for interested parties to locate the service and locate its public interface. The most prominent directory of Web services is currently available via UDDI, or Universal Description, Discovery, and Integration. (See FAQ number 8.)
Web services currently run a wide gamut from news syndication and stock-market data to weather reports and package-tracking systems. For a quick look at the range of Web services currently available, check out the XMethods directory of Web services.

What is new about Web services?
People have been using Remote Procedure Calls (RPC) for some time now, and they long ago discovered how to send such calls over HTTP.
So, what is really new about Web services? The answer is XML.
XML lies at the core of Web services, and provides a common language for describing Remote Procedure Calls, Web services, and Web service directories.
Prior to XML, one could share data among different applications, but XML makes this so much easier to do. In the same vein, one can share services and code without Web services, but XML makes it easier to do these as well.
By standardizing on XML, different applications can more easily talk to one another, and this makes software a whole lot more interesting.

I keep reading about Web services, but I have never actually seen one. Can you show me a real Web service in action?
If you want a more intuitive feel for Web services, try out the IBM Web Services Browser, available on the IBM Alphaworks site. The browser provides a series of Web services demonstrations. Behind the scenes, it ties together SOAP, WSDL, and UDDI to provide a simple plug-and-play interface for finding and invoking Web services. For example, you can find a stock-quote service, a traffic-report service, and a weather service. Each service is independent, and you can stack services like building blocks. You can, therefore, create a single page that displays multiple services--where the end result looks like a stripped-down version of my.yahoo or my.excite.

What is the Web service protocol stack?

The Web service protocol stack is an evolving set of protocols used to define, discover, and implement Web services. The core protocol stack consists of four layers:
Service Transport: This layer is responsible for transporting messages between applications. Currently, this includes HTTP, SMTP, FTP, and newer protocols, such as Blocks Extensible Exchange Protocol (BEEP).
XML Messaging: This layer is responsible for encoding messages in a common XML format so that messages can be understood at either end. Currently, this includes XML-RPC and SOAP.
Service Description: This layer is responsible for describing the public interface to a specific Web service. Currently, service description is handled via the WSDL.
Service Discovery: This layer is responsible for centralizing services into a common registry, and providing easy publish/find functionality. Currently, service discovery is handled via the UDDI.
Beyond the essentials of XML-RPC, SOAP, WSDL, and UDDI, the Web service protocol stack includes a whole zoo of newer, evolving protocols. These include WSFL (Web Services Flow Language), SOAP-DSIG (SOAP Security Extensions: Digital Signature), and USML (UDDI Search Markup Language). For an overview of these protocols, check out Pavel Kulchenko's article, Web Services Acronyms, Demystified, on XML.com.
Fortunately, you do not need to understand the full protocol stack to get started with Web services. Assuming you already know the basics of HTTP, it is best to start at the XML Messaging layer and work your way up.

What is XML-RPC?
XML-RPC is a protocol that uses XML messages to perform Remote Procedure Calls. Requests are encoded in XML and sent via HTTP POST; XML responses are embedded in the body of the HTTP response.
More succinctly, XML-RPC = HTTP + XML + Remote Procedure Calls.
Because XML-RPC is platform independent, diverse applications can communicate with one another. For example, a Java client can speak XML-RPC to a Perl server.
To get a quick sense of XML-RPC, here is a sample XML-RPC request to a weather service (with the HTTP Headers omitted):


weather.getWeather

10016


The request consists of a simple element, which specifies the method name (getWeather) and any method parameters (zip code).

Here is a sample XML-RPC response from the weather service:





65



The response consists of a single element, which specifies the return value (the current temperature). In this case, the return value is specified as an integer.
In many ways, XML-RPC is much simpler than SOAP, and therefore represents the easiest way to get started with Web services.
The official XML-RPC specification is available at XML-RPC.com. Dozens of XML-RPC implementations are available in Perl, Python, Java, and Ruby. See the XML-RPC home page for a complete list of implementations.



What is SOAP?
SOAP is an XML-based protocol for exchanging information between computers. Although SOAP can be used in a variety of messaging systems and can be delivered via a variety of transport protocols, the main focus of SOAP is Remote Procedure Calls (RPC) transported via HTTP. Like XML-RPC, SOAP is platform independent, and therefore enables diverse applications to communicate with one another.

To get a quick sense of SOAP, here is a sample SOAP request to a weather service (with the HTTP Headers omitted):


xmlns:SOAP-ENV="http://www.w3.org/2001/09/soap-envelope"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">

xmlns:ns1="urn:examples:weatherservice"
SOAP-ENV:encodingStyle=" http://www.w3.org/2001/09/soap-encoding
10016



As you can see, the request is slightly more complicated than XML-RPC and makes use of both XML namespaces and XML Schemas. Much like XML-RPC, however, the body of the request specifies both a method name (getWeather), and a list of parameters (zipcode).

Here is a sample SOAP response from the weather service:


xmlns:SOAP-ENV="http://www.w3.org/2001/09/soap-envelope"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">

xmlns:ns1="urn:examples:weatherservice"
SOAP-ENV:encodingStyle="http://www.w3.org/2001/09/soap-encoding">
65




The response indicates a single integer return value (the current temperature).
The World Wide Web Consortium (W3C) is in the process of creating a SOAP standard. The latest working draft is designated as SOAP 1.2, and the specification is now broken into two parts. Part 1 describes the SOAP messaging framework and envelope specification. Part 2 describes the SOAP encoding rules, the SOAP-RPC convention, and HTTP binding details.

What is WSDL?

The Web Services Description Language (WSDL) currently represents the service description layer within the Web service protocol stack.
In a nutshell, WSDL is an XML grammar for specifying a public interface for a Web service. This public interface can include the following:

Information on all publicly available functions.
Data type information for all XML messages.
Binding information about the specific transport protocol to be used.
Address information for locating the specified service.

WSDL is not necessarily tied to a specific XML messaging system, but it does include built-in extensions for describing SOAP services.

Below is a sample WSDL file. This file describes the public interface for the weather service used in the SOAP example above. Obviously, there are many details to understanding the example. For now, just consider two points.
First, the elements specify the individual XML messages that are transferred between computers. In this case, we have a getWeatherRequest and a getWeatherResponse. Second, the element specifies that the service is available via SOAP and is available at a specific URL.


targetNamespace="http://www.ecerami.com/wsdl/WeatherService.wsdl"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.ecerami.com/wsdl/WeatherService.wsdl"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">















transport="http://schemas.xmlsoap.org/soap/http"/>



encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:weatherservice"
use="encoded"/>


encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
namespace="urn:examples:weatherservice"
use="encoded"/>





WSDL File for Weather Service

location="http://localhost:8080/soap/servlet/rpcrouter"/>



Using WSDL, a client can locate a Web service, and invoke any of the publicly available functions. With WSDL-aware tools, this process can be entirely automated, enabling applications to easily integrate new services with little or no manual code. For example, check out the GLUE platform from the Mind Electric.
WSDL has been submitted to the W3C, but it currently has no official status within the W3C. See this W3C page for the latest draft.

What is UDDI?
UDDI (Universal Description, Discovery, and Integration) currently represents the discovery layer within the Web services protocol stack.
UDDI was originally created by Microsoft, IBM, and Ariba, and represents a technical specification for publishing and finding businesses and Web services.
At its core, UDDI consists of two parts.
First, UDDI is a technical specification for building a distributed directory of businesses and Web services. Data is stored within a specific XML format, and the UDDI specification includes API details for searching existing data and publishing new data.
Second, the UDDI Business Registry is a fully operational implementation of the UDDI specification. Launched in May 2001 by Microsoft and IBM, the UDDI registry now enables anyone to search existing UDDI data. It also enables any company to register themselves and their services.
The data captured within UDDI is divided into three main categories:
White Pages: This includes general information about a specific company. For example, business name, business description, and address.
Yellow Pages: This includes general classification data for either the company or the service offered. For example, this data may include industry, product, or geographic codes based on standard taxonomies.
Green Pages: This includes technical information about a Web service. Generally, this includes a pointer to an external specification, and an address for invoking the Web service.
You can view the Microsoft UDDI site, or the IBM UDDI site. The complete UDDI specification is available at uddi.org.
Beta versions of UDDI Version 2 are available at:
Hewlett Packard
IBM
Microsoft
SAP

How do I get started with Web Services?
The easiest way to get started with Web services is to learn XML-RPC. Check out the XML-RPC specification or read my book, Web Services Essentials. O'Reilly has also recently released a book on Programming Web Services with XML-RPC by Simon St.Laurent, Joe Johnston, and Edd Dumbill.
Once you have learned the basics of XML-RPC, move onto SOAP, WSDL, and UDDI. These topics are also covered in Web Services Essentials. For a comprehensive treatment of SOAP, check out O'Reilly's Programming Web Services with SOAP, by Doug Tidwell, James Snell, and Pavel Kulchenko.

Does the W3C support any Web service standards?
The World Wide Web Consortium (W3C) is actively pursuing standardization of Web service protocols. In September 2000, the W3C established an XML Protocol Activity. The goal of the group is to establish a formal standard for SOAP. A draft version of SOAP 1.2 is currently under review, and progressing through the official W3C recommendation process.
On January 25, 2002, the W3C also announced the formation of a Web Service Activity. This new activity will include the current SOAP work as well as two new groups. The first new group is the Web Services Description Working Group, which will take up work on WSDL. The second new group is the Web Services Architecture Working Group, which will attempt to create a cohesive framework for Web service protocols.

Tuesday, September 14, 2010

Difference between ServletContext and ServletConfig

What the difference between ServletContext and ServletConfig apart from the fact that Context gives environmental details and Config abt the initialisation params?? Another other substantial diff??

I have mentioned some tips regarding ServletContext and ServletConfig. okey Do well

ServletContext Defines a set of methods that a servlet uses to communicate with its servlet container.
ServletConfig is a servlet configuration object used by a servlet container used to pass information to a servlet during initialization. All of its initialization parameters can ONLY be set in deployment descriptor.

The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized.

You can specify param-value pairs for ServletContext object in tags in web.xml file.

The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets.

The ServletContext parameters are specified for an entire application outside of any particular servlet and are available to all the servlets within that application.



For ex: If you want the name of your company or your E-mail address appear in all the pages of your web application then you use ServletContext.



Developer
Crazy@weird.com











In the above xml entry you set the value of Context Parameter i.e Developer as Crazy@Weird.com. By making the above entry into your web.xml file you can get the value of the ontext parameter 'Developer' anywhere throughout your web application. You can have any number of such context parameters.

String s =
getServletContext.getInitParameter("Developer");

You can have the above statement in any of your servlets to get the value of the String s as "Crazy@Wierd.com". So you are setting the parameter Developer in the web.xml as a Context paramter (which is available throughout the webapp). You get these Context Paramters using a ServletContext object as shown in the statement above.

Coming to ServletConfig, its a more specific one. The ServletContext is for the whole web-app but the ServletConfig is for one particular Servlet.

When you want paramters which cannot be hardcoded in your servlet you use ServletConfig. I cant think of a good example at the moment. Lets do with a lame one;). Lets consider you need to have a String value which tells you what a particular servlet does. Remember ServletConfig is for a particular servlet and not for the entire Application.

The web.xml file may look like this:



Select
Select

About the Servlet
This Servlet gives you a list of
colors to select from








The above entry into a web.xml file is for a servlet named Select. Within the Servlet tag you set the value for a Servlet paramter called "About the Servlet".

So whenever you do getServletConfig().getInitParamter("About the Servlet") you will get a string "This Servlet gives you a list of colors to select from". You get this value only when you call within the servlet called Select because you have set the paramter only for that particular servlet. Unlike context paramters which you could access anywhere using ServletContext.

To sum it up, every servlet has the same ServletContext but it also has its own ServletConfig.



http://www.sap-img.com/java/difference-between-servletcontext-and-servletconfig.htm

Sunday, September 12, 2010

What is difference between LookupDispatchAction and DispatchAction?

The difference between LookupDispatchAction and DispatchAction is that the actual method that gets called in LookupDispatchAction is based on a lookup of a key value instead of specifying the method name directly.

Details :

LookupDispatchAction is subclass of DispatchAction.
In case of DispatchAction, you have to declare the method name in the JSP page.
For Example :
http://localhost:8080/emp/empaction.do?step=add // IN CASE OF DispatchAction
here step=add , we are delaring method name in JSP.
or
Add //IN CASE OF DispatchAction
so we can't use localization for button.


To over come both the issues below
a)method name declaration in JSP
b)can't use localization for button
We will go for LookupDispatchAction.

In the LookupDispatchAction :
For example :
If there are three operation like add, delete, update employee.
You can create three different Actions ?
AddEmpAction, DeleteEmpAction and UpdateEmpAction.
This is a valid approach, although not elegant since there might be duplication of code across
the Actions since they are related. LookupDispatchAction is the answer to this
problem. With LookupDispatchAction, you can combine all three Actions into one.

Example :
Step 1.
three buttons might be










//No need method name declaration in JSP . Button name from resource bundle.

Step 2.
In the the Resource Bundle. //Here you can add localization.
button.add=Add
button.delete=Delete
button.update=Update

Step 3.
Implement a method named getKeyMethodMap() in the subclass of the
LookupDispatchAction. The method returns a java.util.Map. The
keys used in the Map should be also used as keys in Message Resource
Bundle.

public class EmpAction extends LookupDispatchAction {

public Map getKeyMethodMap()
{
Map map = new HashMap();
map.put("button.add", "add");
map.put("button.delete", "delete");
map.put("button.update", "update");
}


public ActionForward add(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
//your logic
mapping.findForward("add-success");
}

public ActionForward delete(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
//your logic
mapping.findForward("delete-success");
}

public ActionForward update(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
//your logic
mapping.findForward("update-success");
}

}

in struts-config.xml

input="/empform.jsp"
type="list.EmpAction"
parameter="step"
scope="request"
validate="false">
path="addEmpSuccess.jsp"
redirect="true"/>
path="deleteEmpSuccess.jsp"
redirect="true"/>
path="updateEmpSuccess.jsp"
redirect="true"/>


for every form submission, LookupDispatchAction does the
reverse lookup on the resource bundle to get the key and then gets the method
whose name is associated with the key from
getKeyMethodmap().


Flow of LookupDispatchAction:
a) Form the button name "Add" get the key "button.add" fro resource bundle.
b) then in the Map getKeyMethodMap() find the value associated with the key "button.add".
c) value from the Map is "add" . then call add() method of the same action class.

Thursday, September 9, 2010

struts2 tutorials

http://www.vaannila.com/struts-2

struts2 tutorials

http://www.vaannila.com/struts-2

Tuesday, September 7, 2010

JDBC ResultSet

Types of Result Sets
The ResultSet interface provides methods for retrieving and manipulating the results of executed queries, and ResultSet objects can have different functionality and characteristics. These characteristics are result set type, result set concurrency, and cursor holdability.

The type of a ResultSet object determines the level of its functionality in two areas: the ways in which the cursor can be manipulated, and how concurrent changes made to the underlying data source are reflected by the ResultSet object.

The sensitivity of the ResultSet object is determined by one of three different ResultSet types:

# TYPE_FORWARD_ONLY — the result set is not scrollable i.e. the cursor moves only forward, from before the first row to after the last row.
# TYPE_SCROLL_INSENSITIVE — the result set is scrollable; its cursor can move both forward and backward relative to the current position,
and it can move to an absolute position.
# TYPE_SCROLL_SENSITIVE — the result set is scrollable; its cursor can move both forward and backward relative to the current position, and it can move to an absolute position.

Before you can take advantage of these features, however, you need to create a scrollable ResultSet object. The following line of code illustrates one way to create a scrollable ResultSet object:

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery(".....");

The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, and TYPE_SCROLL_SENSITIVE. The second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.
Result Set Methods
When a ResultSet object is first created, the cursor is positioned before the first row. To move the cursor, you can use the following methods:

# next() - moves the cursor forward one row. Returns true if the cursor is now positioned on a row and false if the cursor is positioned after the last row.
# previous() - moves the cursor backwards one row. Returns true if the cursor is now positioned on a row and false if the cursor is positioned before the first row.
# first() - moves the cursor to the first row in the ResultSet object. Returns true if the cursor is now positioned on the first row and false if the ResultSet object
does not contain any rows.
# last() - moves the cursor to the last row in the ResultSet object. Returns true if the cursor is now positioned on the last row and false if the ResultSet object
does not contain any rows.
# beforeFirst() - positions the cursor at the start of the ResultSet object, before the first row. If the ResultSet object does not contain any rows, this method has
no effect.
# afterLast() - positions the cursor at the end of the ResultSet object, after the last row. If the ResultSet object does not contain any rows, this method has no effect.
# relative(int rows) - moves the cursor relative to its current position.
# absolute(int n) - positions the cursor on the n-th row of the ResultSet object.

Wednesday, August 25, 2010

What is the difference between interface and abstract class?

* interface contains methods that must be abstract; abstract class may contain concrete methods.
* interface contains variables that must be static and final; abstract class may contain non-final and final variables.
* members in an interface are public by default, abstract class may contain non-public members.
* interface is used to "implements"; whereas abstract class is used to "extends".
* interface can be used to achieve multiple inheritance; abstract class can be used as a single inheritance.
* interface can "extends" another interface, abstract class can "extends" another class and "implements" multiple interfaces.
* interface is absolutely abstract; abstract class can be invoked if a main() exists.
* interface is more flexible than abstract class because one class can only "extends" one super class, but "implements" multiple interfaces.
* If given a choice, use interface instead of abstract class.



if req more info please go through below URL


http://www.interview-questions-java.com/abstract-class-interface.htm

Monday, August 23, 2010

Mysql tutorials

http://www.tizag.com/mysqlTutorial/mysqljoins.php

Wednesday, August 11, 2010

SCJP mock test

http://www21.brinkster.com/infoway02/SCJP2.asp

Tuesday, August 10, 2010

best Jsp tutorial

http://java.sun.com/products/jsp/tags/11/syntaxref11.fm14.html#8865


http://java.sun.com/products/jsp/tags/11/syntaxref11.fm9.html

http://www.jchq.net/mockexams/exam3.htm

http://www.jchq.net/mockexams/exam3.htm

Core java SCJP Mock test1

1 public class MyClass{
int x = 10;
static final int y= 5;

public void method (int z){
int a = 10;
final float b = 10;

class LocalClass {
int c = 3;

public void method (int d){
System.out.println (??); // -- 1
}
}

public static void main (String args[]){
new MyClass();
}
}
Which of the following variable names can be replaced ?? at line no marked as 1,without compiler error?
A x
B a
C b
D c



A , C and D

Local classes can access all the variables from
the enclosing classes. But it can access only the
final variables of the enclosing method or the method parameter.
The above constraint is applicable if the Local class
is declared inside the non-static context.
since, if the Local class is declared inside the static
context it can access only the static members of the enclosing class.





2 public class MyClass{
public static void main (String args[]){
String str = "Hello World";
System.out.print(str.indexOf('d'));
System.out.print(str.indexOf('h'));
System.out.print(str.indexOf('a'));
}
}
What will be the output?
A 10 -1 -1
B 9 -1 -1
C 10 0 -1
D 10 1 -1



A

IndexOf() returns the index within this string
of the first occurrence of the specified character.
IndexOf() method returns -1 if it cannot
find the specified character.
The search is case sensitive. So. it returns -1 for indexOf('a').






3 What is the range of values that can be stored in a short primitive variable?
A 0 - 656535
B -32768 to 32767
C -32768 to 32768
D -32767 to 32768



B

The short is a 16 bit signed integer. Its value ranges from -216 to 216-1





4 Which of the following lines will compile without warning or error.
A float f=1.3;
B int i=10;
C byte b=257;
D char c="a";



B

Always real values default o double.
So when compiler sees a value like 1.3 ,
it will treat it as double and will complain.
Choice C is incorrect because the byte value
ranges from -128 to +127. Here also the compiler
will show the same error message,' possible loss of precision'.
Choice D is incorrect because , we cannot assign a
String to a char, even though the length is one. ie,
anything comes inside " " is a string.





5
What will happen if you try to compile and run the following code ?
public class MyClass {
public static void main (String arguments[]) {
amethod( arguments) ;
}
public void amethod (String[] arguments) {
System.out.println (arguments) ;
System.out.println (arguments[1]) ;
}
}

A Error Can't make static reference to void amethod.
B Error Incorrect main method.
C amethod must be declared with String
D Compiles and executes fine.



A

We cannot call a non static method from a static context.





6 Which of the following will compile without error ?
A import java.util.*;
package mypack;
class MyClass {}
B package mypack;
import java.uril.*;
class MyClass{}
C /*This is a comment */
package MyPackage;
import java.awt.*;
class MyClass{}
D All of the above



B and C

The order of different statements and blocks
in a java program is as follows. package declaration first,
then imports, then class declaration.
if a package declaration exist, it =must be the first non
comment code in the file.





7 Float f= new Float( 1.0F );
String str = "value is " +f;
System.out.println( str );

What will be the output of executing the above code snippet?
A Compiler error invalid character in constructor

B Runtime exception invalid character in constructor.
C Compiles and prints 'value is 1.0'

D Compiles and prints 'value is 1'



C

Choice A and B is incorrect because we can use
'F' to specify the given number is float.





8 Which of the following are java keywords
?
A null
B const
C volatile
D true



B and C

Choices B and C are java keywords.
Choice A and D are not java keywords,
but they are treated as reserved words in java.





9 What will be printed out if this code is run
with the following command line : java myprog good morning
public class myprog {
public static void main (String argv[]) {
System.out.println(argv[2])
}
}
A myprog
B good
C morning
D Exception raised: java.lang.ArrayIndexOutOfBoundsException: 2



D

Unlike C++ , java command line arguments
does not include the java program name
in the argument list. So in our program
we actually passing only two arguments.
But when printing we are printing the third
argument (since array index always start at zero)
and as a result it will cause a RuntimeException.





10 What is the range of a byte
A 0 - 256
B -128 to 127
C -127 to 128
D -255 to 256



B

The size of a byte is 1 byte. So its range is from -28 to +28-1.







11 Which of the following are legal identifiers ?
A 1variable
B variable1
C $anothervar
D _anothervar
E %anothervar



B , C and D

A variable name should start with a letter, under score or a dollar sign.
A valid variable can contain letters and digits.





12 What will happen when you compile the following code
public class MyClass{
static int i;
public static void main (String argv[]) {
System.out.println(i) ;
}
}
A 0
B 1
C Compiler
Error variable 'i' may not have initialized.

D null



A

All the class level variables are automatically
initialized to a default value. Since 'i' is of type int, it is initialized to zero.





13 What will be the output on executing the following code.
public class MyClass {
public static void main (String args[] ) {
int abc[] = new int [] {1, 2, 3, 4};
System.out.println(abc[2]);
}
}
A ArrayIndexOutofBoudsException will be thrown.
B 2
C 3
D 4



C

Always array elements starts with index zero.
The element at index 2, ie, the e3lement at position 3 is 3 .
So the correct answer is C.





14 What will be the output on executing the following code.
public class MyClass {
public static void main (String args[] ) {
int abc[] = new int [5];
System.out.println(abc);
}
}
A Error array not initialized
B 5
C null
D Print some junk characters




D

It will print some junk characters to the output.
Here it will not give any compile time or runtime error
because we have declared and initialized the array properly.
Event if we are not assigning a value to the array, it will always initialized to its defaults.





15
What will be the output on executing the following code.
public class MyClass {
public static void main (String args[] ) {
int abc[] = new int [5];
System.out.println(abc[0]);
}
}

A Error array not initialized
B 5
C 0
D Print some junk characters



C

Here it will not give any compile time or runtime
error because we have declared and initialized the
array properly. Event if we are not assigning a value to the array,
it will always initialized to its defaults.
So the array will be initialized with values zero.





16 What will be the result of attempting to compile and run the following code ?
abstract class MineBase {
abstract void amethod() ;
static int i;
}

public class Mine extends MineBase {
public static void main( String argv[]) {
int[] ar=new int[5];
for (i=0;i < ar.length;i++)
System.out.println (ar[i]) ;
}
}
A A sequence of 5 0's will be printed
B Error: variable 'ar' may not have initialized .
C Error Mine must be declared abstract
D Error MineBase cannot be declared abstract.



C

If we are extending an abstract class,
we need to provide implementations for every abstract method.
If we are not able to provide the implementation
we have to declare our child class as abstract.
Otherwise the compiler will flag an error message.





17 What will be printed out if you attempt to compile and run the following code ?
int i=1;
switch (i) {
case 0:
System.out.println ("zero") ;
break;
case 1:
System.out.println("one") ;
break;
case 2:
System.out.println("two") ;
break;
default:
System.out.println("default") ;
}
A one
B zero
C one default
D one two default



A

It is obvious. It printed the value corresponding for the case label 1.





18
What will be printed out if you attempt to compile and run the following code ?
int i=1;
switch (i) {
case 0:
System.out.println ("zero") ;
break;
case 1:
System.out.println("one") ;
case 2:
System.out.println("two") ;
break;
}

A zero
B one
C one two
D Error no default specified.



C

Choice C is the correct because, since the value of i is one,
it will start executing the case 1.
But it will continue its execution till it finds a break
or till it reach the end of switch statement,
so the value one followed by two will be printed.
Choice D is incorrect because, the use of default in switch expression is optional.





19 What will be printed out if you attempt to compile and run the following code ?
int i=10;
switch (i) {
default:
System.out.println("Default");
case 0:
System.out.println ("zero") ;
break;
case 1:
System.out.println("one") ;
case 2:
System.out.println("two") ;
break;
}
A default
B default zero
C Error , default cannot be the first statement in switch.
D default zero one two



B

Since there is no matching case labels,
it will start its execution in default,
and continue till the first break statement.
The order of case labels in switch statement does not matter.





20 Which of the following data types
can appear inside a switch statement as its label ?
A String
B char
C int
D byte



B , C and D

The valid types for the switch statement is byte, char, short and int.

Friday, August 6, 2010

Jsp interview questions

1.What are the advantages of JSP over Servlet?

JSP is a serverside technology to make content generation a simple appear.The advantage of JSP is that they are document-centric. Servlets, on the other hand, look and act like programs. A Java Server Page can contain Java program fragments that instantiate and execute Java classes, but these occur inside an HTML template file and are primarily used to generate dynamic content. Some of the JSP functionality can be achieved on the client, using JavaScript. The power of JSP is that it is server-based and provides a framework for Web application development.


2.What is the life-cycle of JSP?

When a request is mapped to a JSP page for the first time, it translates the JSP page into a servlet class and compiles the class. It is this servlet that services the client requests.
A JSP page has seven phases in its lifecycle, as listed below in the sequence of occurrence:

* Translation
* Compilation
* Loading the class
* Instantiating the class
* jspInit() invocation
* _jspService() invocation
* jspDestroy() invocation

More about JSP Life cycle


3.What is the jspInit() method?

The jspInit() method of the javax.servlet.jsp.JspPage interface is similar to the init() method of servlets. This method is invoked by the container only once when a JSP page is initialized. It can be overridden by a page author to initialize resources such as database and network connections, and to allow a JSP page to read persistent configuration data.

4.What is the _jspService() method?

SThe _jspService() method of the javax.servlet.jsp.HttpJspPage interface is invoked every time a new request comes to a JSP page. This method takes the HttpServletRequest and HttpServletResponse objects as its arguments. A page author cannot override this method, as its implementation is provided by the container.

5.What is the jspDestroy() method?

The jspDestroy() method of the javax.servlet.jsp.JspPage interface is invoked by the container when a JSP page is about to be destroyed. This method is similar to the destroy() method of servlets. It can be overridden by a page author to perform any cleanup operation such as closing a database connection.

6.What JSP lifecycle methods can I override?

You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy().

7.How can I override the jspInit() and jspDestroy() methods within a JSP page?

The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and are typically declared as JSP declarations:

<%!
public void jspInit() {
. . .
}
%>
<%!
public void jspDestroy() {
. . .
}
%>


8.What are implicit objects in JSP?

Implicit objects in JSP are the Java objects that the JSP Container makes available to developers in each page. These objects need not be declared or instantiated by the JSP author. They are automatically instantiated by the container and are accessed using standard variables; hence, they are called implicit objects.The implicit objects available in JSP are as follows:

* request
* response
* pageContext
* session
* application
* out
* config
* page
* exception

The implicit objects are parsed by the container and inserted into the generated servlet code. They are available only within the jspService method and not in any declaration.

9.What are the different types of JSP tags?

The different types of JSP tags are as follows:
page directive
include directive
taglib directive

10.What are JSP directives?

* JSP directives are messages for the JSP engine. i.e., JSP directives serve as a message from a JSP page to the JSP container and control the processing of the entire page
* They are used to set global values such as a class declaration, method implementation, output content type, etc.
* They do not produce any output to the client.
* Directives are always enclosed within <%@ ….. %> tag.
* Ex: page directive, include directive, etc.


11.What is page directive?

* A page directive is to inform the JSP engine about the headers or facilities that page should get from the environment.
* Typically, the page directive is found at the top of almost all of our JSP pages.
* There can be any number of page directives within a JSP page (although the attribute – value pair must be unique).
* The syntax of the include directive is: <%@ page attribute="value">
* Example:<%@ include file="header.jsp" %>


12.What are the attributes of page directive?

There are thirteen attributes defined for a page directive of which the important attributes are as follows:

* import: It specifies the packages that are to be imported.
* session: It specifies whether a session data is available to the JSP page.
* contentType: It allows a user to set the content-type for a page.
* isELIgnored: It specifies whether the EL expressions are ignored when a JSP is translated to a servlet.


13.What is the include directive?

There are thirteen attributes defined for a page directive of which the important attributes are as follows:

* The include directive is used to statically insert the contents of a resource into the current JSP.
* This enables a user to reuse the code without duplicating it, and includes the contents of the specified file at the translation time.
* The syntax of the include directive is as follows:
<%@ include file = "FileName" %>
* This directive has only one attribute called file that specifies the name of the file to be included.


14.What are the JSP standard actions?

* The JSP standard actions affect the overall runtime behavior of a JSP page and also the response sent back to the client.
* They can be used to include a file at the request time, to find or instantiate a JavaBean, to forward a request to a new page, to generate a browser-specific code, etc.
* Ex: include, forward, useBean,etc. object


15.What are the standard actions available in JSP?

The standard actions available in JSP are as follows:

* : It includes a response from a servlet or a JSP page into the current page. It differs from an include directive in that it includes a resource at request processing time, whereas the include directive includes a resource at translation time.
* : It forwards a response from a servlet or a JSP page to another page.
* : It makes a JavaBean available to a page and instantiates the bean.
* : It sets the properties for a JavaBean.
* : It gets the value of a property from a JavaBean component and adds it to the response.
* : It is used in conjunction with ;, ; to add a parameter to a request. These parameters are provided using the name-value pairs.
* : It is used to include a Java applet or a JavaBean in the current JSP page.


16.What is the standard action?

The standard action is used to locate an existing JavaBean or to create a JavaBean if it does not exist. It has attributes to identify the object instance, to specify the lifetime of the bean, and to specify the fully qualified classpath and type.

17.What are the scopes available in ?

The scopes available in are as follows:

* page scope:: It specifies that the object will be available for the entire JSP page but not outside the page.
* request scope: It specifies that the object will be associated with a particular request and exist as long as the request exists.
* application scope: It specifies that the object will be available throughout the entire Web application but not outside the application.
* session scope: It specifies that the object will be available throughout the session with a particular client.


18.What is the standard action?

* The standard action forwards a response from a servlet or a JSP page to another page.
* The execution of the current page is stopped and control is transferred to the forwarded page.
* The syntax of the standard action is :

Here, targetPage can be a JSP page, an HTML page, or a servlet within the same context.

* If anything is written to the output stream that is not buffered before , an IllegalStateException will be thrown.

Note : Whenever we intend to use or in a page, buffering should be enabled. By default buffer is enabled.

19.What is the standard action?

The standard action enables the current JSP page to include a static or a dynamic resource at runtime. In contrast to the include directive, the include action is used for resources that change frequently. The resource to be included must be in the same context.The syntax of the standard action is as follows:

Here, targetPage is the page to be included in the current JSP.

20.What is the difference between include directive and include action?

Include directive Include action
The include directive, includes the content of the specified file during the translation phase–when the page is converted to a servlet. The include action, includes the response generated by executing the specified page (a JSP page or a servlet) during the request processing phase–when the page is requested by a user.
The include directive is used to statically insert the contents of a resource into the current JSP. The include standard action enables the current JSP page to include a static or a dynamic resource at runtime.
Use the include directive if the file changes rarely. It’s the fastest mechanism. Use the include action only for content that changes often, and if which page to include cannot be decided until the main page is requested.


21.Differentiate between pageContext.include and jsp:include?

The standard action and the pageContext.include() method are both used to include resources at runtime. However, the pageContext.include() method always flushes the output of the current page before including the other components, whereas flushes the output of the current page only if the value of flush is explicitly set to true as follows:




22.What is the jsp:setProperty action?

You use jsp:setProperty to give values to properties of beans that have been referenced earlier. You can do this in two contexts. First, you can use jsp:setProperty after, but outside of, a jsp:useBean element, as below:


...


In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an existing bean was found.

A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as below:


...
property="someProperty" ... />


Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was found.



23.What is the jsp:getProperty action?

The action is used to access the properties of a bean that was set using the action. The container converts the property to a String as follows:

* If it is an object, it uses the toString() method to convert it to a String.
* If it is a primitive, it converts it directly to a String using the valueOf() method of the corresponding Wrapper class.
* The syntax of the method is:

Here, name is the id of the bean from which the property was set. The property attribute is the property to get. A user must create or locate a bean using the action before using the action.



24.What is the standard action?

The standard action is used with or to pass parameter names and values to the target resource. The syntax of the standard action is as follows:


25.What is the jsp:plugin action ?

This action lets you insert the browser-specific OBJECT or EMBED element needed to specify that the browser run an applet using the Java plugin.

26.What are scripting elements?

JSP scripting elements let you insert Java code into the servlet that will be generated from the current JSP page. There are three forms:

1. Expressions of the form <%= expression %> that are evaluated and inserted into the output,
2. Scriptlets of the form <% code %> that are inserted into the servlet's service method,
3. Declarations of the form <%! code %> that are inserted into the body of the servlet class, outside of any existing methods.


27.What is a scriptlet?

A scriptlet contains Java code that is executed every time a JSP is invoked. When a JSP is translated to a servlet, the scriptlet code goes into the service() method. Hence, methods and variables written in scriptlets are local to the service() method. A scriptlet is written between the <% and %> tags and is executed by the container at request processing time.


28.What are JSP declarations?

As the name implies, JSP declarations are used to declare class variables and methods in a JSP page. They are initialized when the class is initialized. Anything defined in a declaration is available for the whole JSP page. A declaration block is enclosed between the <%! and %> tags. A declaration is not included in the service() method when a JSP is translated to a servlet.

29.What is a JSP expression?

A JSP expression is used to write an output without using the out.print statement. It can be said as a shorthand representation for scriptlets. An expression is written between the <%= and %> tags. It is not required to end the expression with a semicolon, as it implicitly adds a semicolon to all the expressions within the expression tags.

30.How is scripting disabled?

Scripting is disabled by setting the scripting-invalid element of the deployment descriptor to true. It is a subelement of jsp-property-group. Its valid values are true and false. The syntax for disabling scripting is as follows:


*.jsp
true