Monday, June 18, 2007

JSR 168 Portlet life cycle

Portlet life cycle

The basic portlet life cycle of a JSR 168 portlet is:

  • Init: initialize the portlet and put the portlet into service
  • Handle requests: process different kinds of action- and render-requests
  • Destroy: put portlet out of service

The portlet container manages the portlet life cycle and calls the corresponding methods on the portlet interface.

Portlet interface

Every portlet must implement the portlet interface, or extend a class that implements the portlet interface. The portlet interface consists of the following methods:

  • init(PortletConfig config): to initialize the portlet. This method is called only once after instantiating the portlet. This method can be used to create expensive objects/resources used by the portlet.
  • processAction(ActionRequest request, ActionResponse response): to notify the portlet that the user has triggered an action on this portlet. Only one action per client request is triggered. In an action, a portlet can issue a redirect, change its portlet mode or window state, modify its persistent state, or set render parameters.
  • render(RenderRequest request, RenderResponse response): to generate the markup. For each portlet on the current page, the render method is called, and the portlet can produce markup that may depend on the portlet mode or window state, render parameters, request attributes, persistent state, session data, or backend data.
  • destroy(): to indicate to the portlet the life cycle's end. This method allows the portlet to free up resources and update any persistent data that belongs to this portlet.

Portlet modes

A portlet mode indicates the function a portlet performs. Usually, portlets execute different tasks and create different content depending on the functions they currently perform. A portlet mode advises the portlet what task it should perform and what content it should generate. When invoking a portlet, the portlet container provides the current portlet mode to the portlet. Portlets can programmatically change their mode when processing an action request.

JSR 168 splits portlet modes into three categories:

  1. Required modes: Every portal must support the modes Edit, Help, and View. A portlet must at least support the View mode used to render markup for a page. The Edit mode is used to change per-user settings to customize the portlet markup, and the Help mode is used to show a help screen.
  2. Optional custom modes: These are modes that a portal may support; while in an optional mode, a portlet might not be called. The optional modes include the About mode to display an "about" message; the Config mode to let administrators configure the portlet; Edit_defaults mode to let an administrator preset the Edit mode's values; the Preview mode to show the portlet's preview; and the Print mode to render a view that can easily print.
  3. Portal vendor-specific modes: These modes are not defined in the specification and are therefore vendor specific.

Window states

A window state indicates the amount of portal page space that will be assigned to the content generated by a portlet. When invoking a portlet, the portlet container provides the current window state to the portlet. The portlet may use the window state to decide how much information it should render. Portlets can programmatically change their window state when processing an action request.

JSR 168 defines the following window states:

  • Normal: Indicates that a portlet may share the page with other portlets. This is the default window state.
  • Maximized: Indicates that a portlet may be the only portlet on the portal page or that the portlet has more space compared to other portlets in the portal page, and can therefore produce richer content than in a normal window state.
  • Minimized: Indicates that the portlet should only render minimal output or no output at all.

Friday, June 8, 2007

Spring Hibernate FAQ

Q. Explain DI or IOC pattern. A: Dependency injection (DI) is a programming design pattern and architectural model, sometimes also referred to as inversion of control or IOC, although technically speaking, dependency injection specifically refers to an implementation of a particular form of IOC. Dependancy Injection describes the situation where one object uses a second object to provide a particular capacity. For example, being passed a database connection as an argument to the constructor instead of creating one internally. The term "Dependency injection" is a misnomer, since it is not a dependency that is injected, rather it is a provider of some capability or resource that is injected. There are three common forms of dependency injection: setter-, constructor- and interface-based injection. Dependency injection is a way to achieve loose coupling. Inversion of control (IOC) relates to the way in which an object obtains references to its dependencies. This is often done by a lookup method. The advantage of inversion of control is that it decouples objects from specific lookup mechanisms and implementations of the objects it depends on. As a result, more flexibility is obtained for production applications as well as for testing. Q. What are the different IOC containers available? A. Spring is an IOC container. Other IOC containers are HiveMind, Avalon, PicoContainer. Q. What are the different types of dependency injection. Explain with examples. A: There are two types of dependency injection: setter injection and constructor injection. Setter Injection: Normally in all the java beans, we will use setter and getter method to set and get the value of property as follows:

public class namebean { String name; public void setName(String a) { name = a; } public String getName() { return name; } }
We will create an instance of the bean 'namebean' (say bean1) and set property as bean1.setName("tom"); Here in setter injection, we will set the property 'name' in spring configuration file as showm below: tom The subelement sets the 'name' property by calling the set method as setName("tom"); This process is called setter injection. To set properties that reference other beans , subelement of is used as shown below,

Constructor injection: For constructor injection, we use constructor with parameters as shown below,

public class namebean { String name; public namebean(String a) { name = a; } }
We will set the property 'name' while creating an instance of the bean 'namebean' as namebean bean1 = new namebean("tom");
Here we use the element to set the the property by constructor injection as My Bean Value

Q. What is spring? What are the various parts of spring framework? What are the different persistence frameworks which could be used with spring? A. Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development. The Spring modules are built on top of the core container, which defines how beans are created, configured, and managed, as shown in the following figure. Each of the modules (or components) that comprise the Spring framework can stand on its own or be implemented jointly with one or more of the others. The functionality of each component is as follows: The core container: The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application’s configuration and dependency specification from the actual application code. Spring context: The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality. Spring AOP: The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components. Spring DAO: The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connections. Spring DAO’s JDBC-oriented exceptions comply to its generic DAO exception hierarchy. Spring ORM: The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Spring’s generic transaction and DAO exception hierarchies. Spring Web module: The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects. Spring MVC framework: The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and POI. Q. What is AOP? How does it relate with IOC? What are different tools to utilize AOP? A: Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules. AOP and IOC are complementary technologies in that both apply a modular approach to complex problems in enterprise application development. In a typical object-oriented development approach you might implement logging functionality by putting logger statements in all your methods and Java classes. In an AOP approach you would instead modularize the logging services and apply them declaratively to the components that required logging. The advantage, of course, is that the Java class doesn't need to know about the existence of the logging service or concern itself with any related code. As a result, application code written using Spring AOP is loosely coupled. The best tool to utilize AOP to its capability is AspectJ. However AspectJ works at he byte code level and you need to use AspectJ compiler to get the aop features built into your compiled code. Nevertheless AOP functionality is fully integrated into the Spring context for transaction management, logging, and various other features. In general any AOP framework control aspects in three possible ways:

Joinpoints: Points in a program's execution. For example, joinpoints could define calls to specific methods in a class Pointcuts: Program constructs to designate joinpoints and collect specific context at those points Advices: Code that runs upon meeting certain conditions. For example, an advice could log a message before executing a joinpoint

Q. What are the advantages of spring framework? A.

  1. Spring has layed architecture. Use what you need and leave you don't need now.
  2. Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continous integration and testability.
  3. Dependency Injection and Inversion of Control Simplifies JDBC (Read the first question.)
  4. Open source and no vendor lock-in.

Q. Can you name a tool which could provide the initial ant files and directory structure for a new spring project. A: Appfuse or equinox. Q. Explain BeanFactory in spring. A: Bean factory is an implementation of the factory design pattern and its function is to create and dispense beans. As the bean factory knows about many objects within an application, it is able to create association between collaborating objects as they are instantiated. This removes the burden of configuration from the bean and the client. There are several implementation of BeanFactory. The most useful one is "org.springframework.beans.factory.xml.XmlBeanFactory" It loads its beans based on the definition contained in an XML file. To create an XmlBeanFactory, pass a InputStream to the constructor. The resource will provide the XML to the factory. BeanFactory factory = new XmlBeanFactory(new FileInputStream("myBean.xml")); This line tells the bean factory to read the bean definition from the XML file. The bean definition includes the description of beans and their properties. But the bean factory doesn't instantiate the bean yet. To retrieve a bean from a 'BeanFactory', the getBean() method is called. When getBean() method is called, factory will instantiate the bean and begin setting the bean's properties using dependency injection. myBean bean1 = (myBean)factory.getBean("myBean"); Q. Explain the role of ApplicationContext in spring. A. While Bean Factory is used for simple applications, the Application Context is spring's more advanced container. Like 'BeanFactory' it can be used to load bean definitions, wire beans together and dispense beans upon request. It also provide

1) a means for resolving text messages, including support for internationalization. 2) a generic way to load file resources. 3) events to beans that are registered as listeners.

Because of additional functionality, 'Application Context' is preferred over a BeanFactory. Only when the resource is scarce like mobile devices, 'BeanFactory' is used. The three commonly used implementation of 'Application Context' are

1. ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application's classpath by using the code ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); 2. FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml"); 3. XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.

Q. How does Spring supports DAO in hibernate? A. Spring’s HibernateDaoSupport class is a convenient super class for Hibernate DAOs. It has handy methods you can call to get a Hibernate Session, or a SessionFactory. The most convenient method is getHibernateTemplate(), which returns a HibernateTemplate. This template wraps Hibernate checked exceptions with runtime exceptions, allowing your DAO interfaces to be Hibernate exception-free. Example:

public class UserDAOHibernate extends HibernateDaoSupport {
public User getUser(Long id) { return (User) getHibernateTemplate().get(User.class, id); } public void saveUser(User user) { getHibernateTemplate().saveOrUpdate(user); if (log.isDebugEnabled()) { log.debug(“userId set to: “ + user.getID()); } } public void removeUser(Long id) { Object user = getHibernateTemplate().load(User.class, id); getHibernateTemplate().delete(user); }
}

Q. What are the id generator classes in hibernate? A: increment: It generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. It should not the used in the clustered environment. identity: It supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int. sequence: The sequence generator uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int hilo: The hilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database. Do not use this generator with connections enlisted with JTA or with a user-supplied connection. seqhilo: The seqhilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence. uuid: The uuid generator uses a 128-bit UUID algorithm to generate identifiers of type string, unique within a network (the IP address is used). The UUID is encoded as a string of hexadecimal digits of length 32. guid: It uses a database-generated GUID string on MS SQL Server and MySQL. native: It picks identity, sequence or hilo depending upon the capabilities of the underlying database. assigned: lets the application to assign an identifier to the object before save() is called. This is the default strategy if no element is specified. select: retrieves a primary key assigned by a database trigger by selecting the row by some unique key and retrieving the primary key value. foreign: uses the identifier of another associated object. Usually used in conjunction with a primary key association. Q. How is a typical spring implementation look like? A. For a typical Spring Application we need the following files

1. An interface that defines the functions. 2. An Implementation that contains properties, its setter and getter methods, functions etc., 3. A XML file called Spring configuration file. 4. Client program that uses the function.

Q. How do you define hibernate mapping file in spring? A. Add the hibernate mapping file entry in mapping resource inside Spring’s applicationContext.xml file in the web/WEB-INF directory.

org/appfuse/model/User.hbm.xml

Q. How do you configure spring in a web application? A. It is very easy to configure any J2EE-based web application to use Spring. At the very least, you can simply add Spring’s ContextLoaderListener to your web.xml file:

org.springframework.web.context.ContextLoaderListener

Q. Can you have xyz.xml file instead of applicationcontext.xml? A. ContextLoaderListener is a ServletContextListener that initializes when your webapp starts up. By default, it looks for Spring’s configuration file at WEB-INF/applicationContext.xml. You can change this default value by specifying a element named “contextConfigLocation.” Example:

org.springframework.web.context.ContextLoaderListener
contextConfigLocation /WEB-INF/xyz.xml

Q. How do you configure your database driver in spring? A. Using datasource "org.springframework.jdbc.datasource.DriverManagerDataSource". Example:

org.hsqldb.jdbcDriver jdbc:hsqldb:db/appfuse sa

Q. How can you configure JNDI instead of datasource in spring applicationcontext.xml? A. Using "org.springframework.jndi.JndiObjectFactoryBean". Example:

java:comp/env/jdbc/appfuse

Q. What are the key benifits of Hibernate? A: These are the key benifits of Hibernate:

  • Transparent persistence based on POJOs without byte code processing
  • Powerful object-oriented hibernate query language
  • Descriptive O/R Mapping through mapping file.
  • Automatic primary key generation
  • Hibernate cache : Session Level, Query and Second level cache.
  • Performance: Lazy initialization, Outer join fetching, Batch fetching

Q. What is hibernate session and session factory? How do you configure sessionfactory in spring configuration file? A. Hibernate Session is the main runtime interface between a Java application and Hibernate. SessionFactory allows applications to create hibernate session by reading hibernate configurations file hibernate.cfg.xml.

// Initialize the Hibernate environment Configuration cfg = new Configuration().configure(); // Create the session factory SessionFactory factory = cfg.buildSessionFactory(); // Obtain the new session object Session session = factory.openSession();

The call to Configuration().configure() loads the hibernate.cfg.xml configuration file and initializes the Hibernate environment. Once the configuration is initialized, you can make any additional modifications you desire programmatically. However, you must make these modifications prior to creating the SessionFactory instance. An instance of SessionFactory is typically created once and used to create all sessions related to a given context. The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes. Instances may exist in one of three states:

transient: never persistent, not associated with any Session persistent: associated with a unique Session detached: previously persistent, not associated with any Session

A Hibernate Session object represents a single unit-of-work for a given data store and is opened by a SessionFactory instance. You must close Sessions when all work for a transaction is completed. The following illustrates a typical Hibernate session: Session session = null; UserInfo user = null; Transaction tx = null; try { session = factory.openSession(); tx = session.beginTransaction(); user = (UserInfo)session.load(UserInfo.class, id); tx.commit(); } catch(Exception e) { if (tx != null) { try { tx.rollback(); } catch (HibernateException e1) { throw new DAOException(e1.toString()); } } throw new DAOException(e.toString()); } finally { if (session != null) { try { session.close(); } catch (HibernateException e) { } } } Q. What is the difference between hibernate get and load methods? A. The load() method is older; get() was added to Hibernate’s API due to user request. The difference is trivial: The following Hibernate code snippet retrieves a User object from the database: User user = (User) session.get(User.class, userID); The get() method is special because the identifier uniquely identifies a single instance of a class. Hence it’s common for applications to use the identifier as a convenient handle to a persistent object. Retrieval by identifier can use the cache when retrieving an object, avoiding a database hit if the object is already cached. Hibernate also provides a load() method: User user = (User) session.load(User.class, userID); If load() can’t find the object in the cache or database, an exception is thrown. The load() method never returns null. The get() method returns null if the object can’t be found. The load() method may return a proxy instead of a real persistent instance. A proxy is a placeholder instance of a runtime-generated subclass (through cglib or Javassist) of a mapped persistent class, it can initialize itself if any method is called that is not the mapped database identifier getter-method. On the other hand, get() never returns a proxy. Choosing between get() and load() is easy: If you’re certain the persistent object exists, and nonexistence would be considered exceptional, load() is a good option. If you aren’t certain there is a persistent instance with the given identifier, use get() and test the return value to see if it’s null. Using load() has a further implication: The application may retrieve a valid reference (a proxy) to a persistent instance without hitting the database to retrieve its persistent state. So load() might not throw an exception when it doesn’t find the persistent object in the cache or database; the exception would be thrown later, when the proxy is accessed. Q. What type of transaction management is supported in hibernate? A. Hibernate communicates with the database via a JDBC Connection; hence it must support both managed and non-managed transactions. non-managed in web containers:

managed in application server using JTA:

Q. What is lazy loading and how do you achieve that in hibernate? A. Lazy setting decides whether to load child objects while loading the Parent Object. You need to specify parent class.Lazy = true in hibernate mapping file. By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent. In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object. But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database. Examples: Address child of User class can be made lazy if it is not required frequently. But you may need to load the Author object for Book parent whenever you deal with the book for online bookshop. Hibernate does not support lazy initialization for detached objects. Access to a lazy association outside of the context of an open Hibernate session will result in an exception. Q. What are the different fetching strategy in Hibernate? A. Hibernate3 defines the following fetching strategies:

Join fetching - Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN. Select fetching - a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association. Subselect fetching - a second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.Batch fetching - an optimization strategy for select fetching - Hibernate retrieves a batch of entity instances or collections in a single SELECT, by specifying a list of primary keys or foreign keys. For more details read short primer on fetching strategy at http://www.hibernate.org/315.html

Q. What are different types of cache hibernate supports ? A. Caching is widely used for optimizing database applications. Hibernate uses two different caches for objects: first-level cache and second-level cache. First-level cache is associated with the Session object, while second-level cache is associated with the Session Factory object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications. To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided. In addition, you can use a query-level cache if you need to cache actual query results, rather than just persistent objects. The query cache should always be used in conjunction with the second-level cache. Hibernate supports the following open-source cache implementations out-of-the-box:

  • EHCache is a fast, lightweight, and easy-to-use in-process cache. It supports read-only and read/write caching, and memory- and disk-based caching. However, it does not support clustering.
  • OSCache is another open-source caching solution. It is part of a larger package, which also provides caching functionalities for JSP pages or arbitrary objects. It is a powerful and flexible package, which, like EHCache, supports read-only and read/write caching, and memory- and disk-based caching. It also provides basic support for clustering via either JavaGroups or JMS.
  • SwarmCache is a simple cluster-based caching solution based on JavaGroups. It supports read-only or nonstrict read/write caching (the next section explains this term). This type of cache is appropriate for applications that typically have many more read operations than write operations.
  • JBoss TreeCache is a powerful replicated (synchronous or asynchronous) and transactional cache. Use this solution if you really need a true transaction-capable caching architecture.
  • Commercial Tangosol Coherence cache.

Q. What are the different caching strategies? A. The following four caching strategies are available:

  • Read-only: This strategy is useful for data that is read frequently but never updated. This is by far the simplest and best-performing cache strategy.
  • Read/write: Read/write caches may be appropriate if your data needs to be updated. They carry more overhead than read-only caches. In non-JTA environments, each transaction should be completed when Session.close() or Session.disconnect() is called.
  • Nonstrict read/write: This strategy does not guarantee that two transactions won't simultaneously modify the same data. Therefore, it may be most appropriate for data that is read often but only occasionally modified.
  • Transactional: This is a fully transactional cache that may be used only in a JTA environment.

Q. How do you configure 2nd level cach in hibernate? A. To activate second-level caching, you need to define the hibernate.cache.provider_class property in the hibernate.cfg.xml file as follows: org.hibernate.cache.EHCacheProvider By default, the second-level cache is activated and uses the EHCache provider. To use the query cache you must first enable it by setting the property hibernate.cache.use_query_cache to true in hibernate.properties.

Q. What is the difference between sorted and ordered collection in hibernate? A. A sorted collection is sorted in-memory using java comparator, while order collection is ordered at the database level using order by clause.

Q. What are the types of inheritence models and describe how they work like vertical inheritence and horizontal? A. There are three types of inheritance mapping in hibernate :

Example: Let us take the simple example of 3 java classes. Class Manager and Worker are inherited from Employee Abstract class. 1. Table per concrete class with unions : In this case there will be 2 tables. Tables: Manager, Worker [all common attributes will be duplicated] 2. Table per class hierarchy: Single Table can be mapped to a class hierarchy. There will be only one table in database called 'Employee' that will represent all the attributes required for all 3 classes. But it needs some discriminating column to differentiate between Manager and worker; 3. Table per subclass: In this case there will be 3 tables represent Employee, Manager and Worker

Thursday, June 7, 2007

Versions

JDK 1.4 and 1.5 Struts 1.3 Hibernet 3.1.3 Spring 1.2.8 Apache Tomcat Eclipse RAD WAS

Testing

RFT

UML diagrams

http://www.holub.com/goodies/uml/

Security JAAS and LDAP.

Webservices

1. How to implement Webservice. steps.

Patterns

1.Different types of patterns.

Creational Patterns --- Abstract Factory --- Builder --- Factory Method --- Prototype --- Singleton Structural Patterns --- Adapter --- Bridge --- Composite --- Decorator --- Façade --- Flyweight --- Proxy Behavioral Patterns --- Chain of Responsibility --- Command --- Interpreter --- Iterator --- Mediator --- Memento --- Observer --- State --- Strategy --- Template Method --- Visitor J2EE Patterns --- MVC --- Business Delegate --- Composite Entity --- Data Access Object --- Front Controller --- Intercepting Filter --- Service Locator --- Transfer Object
http://www.javacamp.org/designPattern/

JMS.

1.How to do lookup in JMS.

What is the difference between topic and queue? A topic is typically used for one to many messaging i.e. it supports publish subscribe model of messaging. While queue is used for one-to-one messaging i.e. it supports Point to Point Messaging.
2.JMS step by step. Queue Topic Connection define JNDI name for queue

JMS API Architecture

A JMS application is composed of the following parts.

  • A JMS provider is a messaging system that implements the JMS interfaces and provides administrative and control features. An implementation of the J2EE platform at release 1.3 and later includes a JMS provider.
  • JMS clients are the programs or components, written in the Java programming language, that produce and consume messages. Any J2EE application component can act as a JMS client.
  • Messages are the objects that communicate information between JMS clients.
  • Administered objects are preconfigured JMS objects created by an administrator for the use of clients. Message Queue --Point-to-Point A message queue, used in a Point-to-Point messaging system, receives messages from many senders and puts them in one queue to one receiver. A point-to-point (PTP) product or application is built on the concept of message queues, senders, and receivers. Each message is addressed to a specific queue, and receiving clients extract messages from the queues established to hold their messages. Queues retain all messages sent to them until the messages are consumed or until the messages expire. Topic -- Publish-Subscribe A topic, used in a Publish-Subscribe messaging system, receives messages from many senders and sends them to many receivers, which subscribe to the topic.

    Pub/sub messaging has the following characteristics.

    • Each message can have multiple consumers.
    • Publishers and subscribers have a timing dependency. A client that subscribes to a topic can consume only messages published after the client has created a subscription, and the subscriber must continue to be active in order for it to consume messages.
    Steps for Creating Messages.
     /*
           * Look up connection factory and queue.  If either does
           * not exist, exit.
           */
          try {
              queueConnectionFactory = (QueueConnectionFactory)
    jndiContext.lookup("java:comp/env/jms/MyQueueConnectionFactory");
              queue = (Queue)
                 jndiContext.lookup("java:comp/env/jms/QueueName");
          } catch (NamingException e) {
              System.out.println("JNDI lookup failed: " +
                  e.toString());
              System.exit(1);
          }
    
          /*
           * Create connection.
           * Create session from connection; false means session is
           * not transacted.
           * Create sender and text message.
           * Send messages, varying text slightly.
           * Finally, close connection.
           */
          try {
              queueConnection =
                  queueConnectionFactory.createQueueConnection();
              queueSession =
                  queueConnection.createQueueSession(false,
                      Session.AUTO_ACKNOWLEDGE);
              queueSender = queueSession.createSender(queue);
              message = queueSession.createTextMessage();
              for (int i = 0; i < NUM_MSGS; i++) {                message.setText("This is message " + (i + 1));                System.out.println("Sending message: " +                    message.getText());                queueSender.send(message);            }  
    
    
     Receiving Message Using MDB
    ---------------------------
    
    public interface TextMessage extends Message
    A TextMessage object is used to send a message containing a  java.lang.String.
    It inherits from the Message interface and adds a text message  body.
    
    
    implement the Message Driven Bean with
    implements MessageDrivenBean,  MessageListener
    
    
    /**
       * onMessage method, declared as public (but not final or
       * static), with a return type of void, and with one argument
       * of type javax.jms.Message.
       *
       * Casts the incoming Message to a TextMessage and displays
       * the text.
       *
       * @param inMessage    the incoming message
       */
      public void onMessage(Message inMessage) {
          TextMessage msg = null;
    
          try {
              if (inMessage instanceof TextMessage) {
                  msg = (TextMessage) inMessage;
                  System.out.println("MESSAGE BEAN: Message " +
                      "received: " + msg.getText());
              } else {
                  System.out.println("Message of wrong type: " +
                      inMessage.getClass().getName());
              }
          } catch (JMSException e) {
              System.err.println("MessageBean.onMessage: " +
                  "JMSException: " + e.toString());
              mdc.setRollbackOnly();
          } catch (Throwable te) {
              System.err.println("MessageBean.onMessage: " +
                  "Exception: " + te.toString());
          }
      }
    
    
            } catch (JMSException e) {

    JDBC

    1. How to do JDBC connection 2. Prepared statement

    EJB

    BMP and CMB 1. Methods in EJB 2. EJB life cycle

    Stateless session bean life cycle

    Life cycle means when an EJBean is created and removed by EJB Container, and when the Container calls methods of EJBean. The following figure illustrates the life cycle of Stateless session bean.

    Stateless session bean figure

    You can control life cycle by mentioning instance pool size in vendor specific deployment descriptor. For example weblogic server's weblogic-ejb-jar.xml has element for instance pool size

    100

    50

    and JBoss server's jboss.xml has an element to mention pool size. See vendors documentation for information for other servers. Here you can specify initial beans and maximum beans in pool. If you mention for example 50 beans in initial beans and 100 for maximum beans in the pool, the life cycle starts when the server starts up.

    When the server starts up, the EJB Container/Server creates 50 beans using Class.newInstance() method and puts it in the pool and it calls the following call back methods of the bean.

    setSessionContext(ctx) and

    ejbCreate() methods

    these 50 beans are ready to be accessed by 50 clients concurrently. If the client accesses exceed 50 then the Container creates beans and calls the above methods till the number of beans is equal to 100 (maximum beans in the pool). So at any time the Container can only have a maximum of 100 beans to serve clients. What will happen if the concurrent clients are more than 100? Then the container puts clients in the queue. We will discuss about this in the next section on how you can tune the pool size.

    The Container removes the beans from the pool if the number of clients accessing beans are less. When the Container removes the beans depending on its specific algorithms ( perhaps LRU, Least Recently Used). At this time Container calls ejbRemove() method of the bean.

    If the client calls the home.create() method, the Container creates EJBObject and assigns existing bean from the pool to the the client, at this time client neither creates a bean nor calls ejbCreate() method because it is already called when it created and is put in the pool. In the same manner, if the client calls home.remove() / remote.remove() method, the Container removes EJBObject and deassigns the bean from the client and puts it back to the pool but does not remove from the pool. In Stateless session bean life cycle, Client does not have control over bean's life cycle and bean's call back methods, it does not know when the creation, destruction and call back methods occur. So In Stateless session beans the creation, destruction and call back methods depend upon the pool size, clients concurrent access and Container algorithms.

    As the name implies, a Stateless session bean does not maintain any state ( instance variables values) across methods, that is the reason why ejbActivate() and ejbPassivate() methods do not have significance in Stateless session bean. So the Container can assign different beans from the pool to the client for successive methods.

    With this discussion, we understand the importance of pool size and when the call back methods are executed in Stateless session beans. Now let us discuss how we can tune Stateless session beans.

    Tune Stateless session beans instance pool size

    The creation and destruction of beans is expensive. To reduce this cost, The EJB Container/Server creates pool of beans that depending upon vendor specific configuration, you need to give a proper value for this pool size to increase performance. As we discussed above, configure pool size, for example weblogic's weblogic-ejb-jar.xml has an element and JBoss server's jboss.xml has an element . see your vendor documentation for configuring your EJB server pool size.

    The number of maximum beans in pool impacts performance. If this is less, then the Container has to put the clients in the queue when the number of clients accessing is more than the maximum pool size. This degrades the performance and clients take more time to execute. For best performance, give maximum beans as equal to number of maximum clients accesses.

    Stateful session bean life cycle

    The life cycle of Stateful and Stateless bean is differs. The reason is, Stateful session bean has to maintain state (instance variables values) across the methods for a client. That means once a client assigns values for instance variables using one method, those values are available for other methods also. The following figure illustrates the life cycle of Stateful session bean.

    Figure7: Stateful session bean life cycle

    Stateful session bean figure

    Here you see the instance cache instead of instance pool. Cache maintains beans that have state (Stateful) whereas pool maintains beans that don't have state (Stateless). You can control life cycle by describing instance cache size in vendor specific deployment descriptor file. For example weblogic's weblogic-ejb-jar.xml has element for instance cache size

    100

    and JBoss server's jboss.xml has an element

    5

    10

    For detailed information, look at their documentation and for other servers look at vendors documentation for instance cache configuration.

    Here you can specify minimum beans and maximum beans in cache. Some vendors such as weblogic do not support configuring minimum beans but support configuring maximum beans. So look at your vendor documentation for detailed information on what your EJB Container/server supports.

    Here life cycle of stateful session bean starts when the client calls create() method. When the the client calls create() method, the Container creates the bean using Class.newInstance() and calls

    setSessionContext(ctx) and

    ejbCreate() methods

    and puts it in the instance cache. Then onwards, the client is assigned to that bean till client calls remove() method, thus container calls ejbRemove() and destroys the bean. In Stateful session bean, the client controls life cycle ( creation and removal but not activation and passivation). So when does container call ejbActivate() and ejbPassivate() methods? For example, if you set maximum beans in cache as 100 beans, when clients are accessing a bean concurrently, container creates beans till 100 (maximum bean limit) and assigns those beans to clients. After this limit, if the 101st client accesses this bean, Container passivates some of the idle beans that depending on Container algorithms. Just before passivating beans, it calls ejbPassivate() method. Here passivation means, it stores the bean's state (instance variables values) in the secondary storage (file storage or database). The passivation happens through Serialization. Later if the the idle client accesses the bean again, then Container activates the bean and reassigns the passivated values to its instance variables and calls ejbActivate() method.

    Here what we understand is that client controls creation and destruction of beans but not activation and passivation. Activation and passivation are controlled by Container and depend on instance cache size.

    With this discussion, we understand the importance of instance cache size and when the call back methods are executed in Stateful session beans. Now let us discuss how we can tune Stateful session beans.

    Tune Stateful session beans instance cache size

    As discussed above, You control activation and passivation indirectly by describing instance cache size in vendor specific deployment descriptor file . Activation and passivation is expensive because of serialization process. If the instance cache size is less and concurrent active clients are more than instance cache size then activation and passivation occur often, thus degrading performance. So in order to increase performance, give optimal cache size.

    Set optimal bean age for Stateful session beans

    The removal of EJBean instance by the Container from the instance cache depends not only on when the client calls remove() method but also on EJBean time out value (bean age) that you can configure in the vendor specific descriptor file. If the beans time out value is less, the Container needs to remove and create often,which is expensive. So set optimal bean age to minimise removal and creation process.

    Entity bean life cycle

    The life cycle of Entity beans is a combination of Stateless and Stateful bean life cycles. There is slight difference between Container managed persistence (CMP) and Bean managed persistence (BMP) entity bean's life cycle that is negligible. So here we will discuss a generalized life cycle that applies to both.

    The following figure illustrates the life cycle of Entity beans.

    Figure7: Entity session bean life cycle

    Here you see both instance pool and instance cache. instance pool maintains entity beans without state data and instance cache maintains entity beans with state data.

    You can control life cycle in Entity beans by mentioning instance pool size and instance cache size in vendor specific deployment descriptor. For example weblogic's weblogic-ejb-jar.xml has element for instance pool size,

    100

    50

    and instance cache size

    100

    and in JBoss, jboss.xml has an element

    to mention pool size.

    and for instance cache size

    5

    10

    If you mention 50 beans as initial beans and 100 beans as maximum beans for instance pool, 50 (min) and 100(max) for instance cache, life cycle starts when the server starts up.

    When the server starts up, First, the EJB Container/Server creates 50 beans using Class.newInstance() method and puts them in the pool and it calls setEntityContext() method on each bean. The Container can remove beans from the pool depending on clients accesses and idle time of beans in the pool. When it removes the bean from the pool it calls unSetEntityContext() method on the bean.

    Next, When the client calls the create() method, the Container calls corresponding ejbCreate() method on one of the beans in the instance pool and creates a row in the database and populates the values to the variables and puts it in the instance cache after returning primary key. At this stage an EJBObject is assigned to the client that communicates to the bean in the instance cache. Next, the Container calls ejbPostCreate() method. At this stage, the bean is moved from pool to cache and is ready to serve clients business methods.

    Next, When the client calls the business method, the Container calls ejbLoad() that updates the beans state, executes the business method, and calls ejbStore() method to store the data in the database. If the concurrent active clients are more than cache size then the container passivates a bean and calls ejbStore(), ejbPassivate() methods and puts it back in the instance pool. If the idle client calls again after some time, container calls ejbLoad() to get latest data, and calls ejbActivate() method and puts it in the instance cache.

    Next, If the client calls remove() method, the Container calls ejbRemove() method that removes the data from the database and puts the bean back in the instance pool from instance cache.

    With this discussion, we understand that

    1. Client controls life cycle of a bean that involves creation of data in the database thus moving the bean from pool to the cache and removal of data from the database thus moving the bean from cache to the pool.

    2. Container controls the life cycle in the pool and cache and also activation and passivation process in the cache.

    3. Both client and container control ejbLoad() and ejbStore() methods depending upon client's method calls and Container activation and passivation process.

    Finally the overall life cycle depends upon clients concurrent operations, instance pool size and instance cache size.

    Now let us discuss how we can tune Entity beans.

    Tune Entity beans instance pool size

    As per Entity bean life cycle discussion, we understand that we can control creation and destruction of beans by describing pool size(min and max) in vendor specific deployment descriptor (or other vendor specific manner). If this size is less (if your default size is less or you configure a smaller size) then the Container has to put the clients in the queue when the number of concurrent clients accessing ( create/finder/home methods) are more than the max pool size. And also instance cache depends up on instance pool because the instance cache needs to get beans from the instance pool. So if the pool size is less, It degrades the performance and clients take more time to execute. For best performance, give maximum beans in pool as equal to number of maximum concurrent client accesses (create/finder/home methods), so that it reduces creation and destruction of beans.

    You can configure your pool size in vendor specific deployment descriptor ( or other vendor specific manner). In the above Entity bean life cycle section, We discussed how to configure this pool size in Weblogic and JBoss servers.

    4. Different EJB's 5. How to do lookup.

    Hibernate

    1. Difference between SQL and HQL 2. Why is hbernate useful 3. How is it used step by step Mapping is done in .hbm.xml applicationContext-hibernate.xml An ApplicationContext provides the following functionalities: * Bean factory methods, inherited from ListableBeanFactory. This avoids the need for applications to use singletons. * The ability to resolve messages, supporting internationalization. Inherited from the MessageSource interface. * The ability to load file resources in a generic fashion. Inherited from the ResourceLoader interface. * The ability to publish events. Implementations must provide a means of registering event listeners. * Inheritance from a parent context. Definitions in a descendant context will always take priority. This means, for example, that a single parent context can be used by an entire web application, while each servlet has its own child context that is independent of that of any other servlet. Things to be defined in the applicationContext DriverManagerDataSource LocalSessionFactoryBean -- HibernateTransactionManager DAOImplementation TransactionProxyFactoryBean PROPAGATION_REQUIRED,readOnly PROPAGATION_REQUIRED,readOnly PROPAGATION_REQUIRED,readOnly PROPAGATION_REQUIRED Mail 4. Foreign keys. 5. Multiple of single type

    Struts

    Model-View-Controller (MVC) MVC Model 2 MVC Model 2

    • Model The model contains the core of the application's functionality. The model encapsulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller.
    • View The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur.
    • Controller The controller reacts to the user input. It creates and sets the model.
    Model 1: - coupling of controller and view JSP - Controller and a View Java Bean - Model Model 2: decoupling of controller and view delegation of control is easier and therefore decoupling of the view lets you define and choose a technology and implementation for the view that you prefer Servlet - Controller Java Bean - Model JSP (possible others like XSL) - View

    1. Different classes in Struts. 2. Objects in struts 3. Steps in Struts with Flow and the Class Figure 5. Struts overview Struts overview

    Struts overview

    • Client browser An HTTP request from the client browser creates an event. The Web container will respond with an HTTP response.
    • Controller The Controller receives the request from the browser, and makes the decision where to send the request. With Struts, the Controller is a command design pattern implemented as a servlet. The struts-config.xml file configures the Controller.
    • Business logic The business logic updates the state of the model and helps control the flow of the application. With Struts this is done with an Action class as a thin wrapper to the actual business logic.
    • Model state The model represents the state of the application. The business objects update the application state. ActionForm bean represents the Model state at a session or request level, and not at a persistent level. The JSP file reads information from the ActionForm bean using JSP tags.
    • View The view is simply a JSP file. There is no flow logic, no business logic, and no model information -- just tags. Tags are one of the things that make Struts unique compared to other frameworks like Velocity.
    UML diagram of the relationship of the Command (ActionServlet) to the Model (Action) Relationship of ActionServlet to Action

    The ActionMapping class An incoming event is normally in the form of an HTTP request, which the servlet Container turns into an HttpServletRequest. The Controller looks at the incoming event and dispatches the request to an Action class. The struts-config.xml determines what Action class the Controller calls. The struts-config.xml configuration information is translated into a set of ActionMapping, which are put into container of ActionMappings. (If you have not noticed it, classes that end with s are containers)

    The ActionMapping contains the knowledge of how a specific event maps to specific Actions. The ActionServlet (Command) passes the ActionMapping to the Action class via the perform() method. This allows Action to access the information to control flow.

    ActionMappings ActionMappings is a collection of ActionMapping objects.

    Spring.

    1. Spring Layers

    *. Core Container: The core container provides the fundamental functionality of Spring. It's primary component is the 'BeanFactory', an implementation of the Factory pattern. The BeanFactory applies the IOC pattern to separate an application's configuration and dependency specification from the actual application code.

    *. Spring Context/Application Context:

    The Spring context is a configuration file that provides context information to the Spring framework . The Spring context supplies enterprise services such as JNDI access, EJB integration, e-mail, internalization, validation, and scheduling functionality.

    *. Spring AOP:(Aspect-Oriented)

    The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result we can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP we can incorporate declarative transaction management into our applications without relying on EJB components. The Spring AOP module also introduces metadata programming to Spring. Using this we can add annotation to the source code that instructs Spring on where and how to apply aspects.

    *. Spring DAO:

    The Spring's JDBC and DAO abstraction layer offers a meaningful exception hierarchy for managing the databaase connection, exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of code that we need to write, such as opening and closing connections. This module also provide transaction management services for objects in a spring application.

    *. Spring ORM:

    The Spring framework can be integrated to several ORM frameworks to provide Object Relational tool, including JDO, Hibernate, OJB and iBatis SQL Maps.

    *. Spring Web module:

    The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts, JSF and webworks. The Web module also eases the tasks of handling multipart requests and binding request parameters to domain objects.

    *. Spring MVC Framework:

    The MVC framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles and the generation of PDF and Excel Files.

    Declerative Management

    We don't directly connect our components and services together in code but describe which services are needed by which components in a configuration file. A container is responsible for hooking it up. This concept is similar to 'Declarative Management'.

    Dependency Lookup:

    The container provides callbacks to components and a lookup context. The managed objects are responsible for their other lookups Dependency Injection: In this application objects is not responsible for looking up resources they depend on. Instead IoC container configures the object externalizing resource lookup from application code into the container. That is, dependencies are injected into objects. Thus lookups are completely removed from application objects and it can be used outside the container also. cle

    1. Spring methods 2. POJO Plain Old Java Objects 3. Object Decoupling 4. What is Inversion of control Model of a Beanfactory. 5. Object Injection 6. Describe Spring. 7. Steps in Spring 8. Some classes in Spring

    Session object in Servlet

    HttpSession

    Servlet life cycle

    init() doGet() doPost() destroy() What are the different cases for using sendRedirect() vs. getRequestDispatcher()?

    When you want to preserve the current request/response objects and transfer them to another resource WITHIN the context, you must use getRequestDispatcher or getNamedDispatcher.

    If you want to dispatch to resources OUTSIDE the context, then you must use sendRedirect. In this case you won't be sending the original request/response objects, but you will be sending a header asking to the browser to issue a request to the new URL.

    http://faqs.javabeat.net/servlet/java-servlets-interview-questions-faqs-8.php

    Methods in Servlet

    ServletContext, HttpSession, ServletConfig

    JSP/Servlet.

    Implicit objects in JSP request - the HttpServletRequest associated with request. response - the HttpServletResponse associated with response to client. out - the JspWriter (PrintWriter subclass) used to send output to the client. session - the HttpSession object associated with request. application -the ServletContext as obtained by getServletConfig().getContext(). Shared by all servlets and JSP pages on server or in Web application. config - the ServletConfig object for this page. pageContext-the PageContext object associated with current page. page - synonym for this (current servlet instance); not very useful now. Placeholder for future. Context Application, Session , request, page.

    Pass By Value Pass By reference

    Java pass everything by Value. Objects are manuplated by refrence though for methods its all Value.

    When to use Vector? When to use ArrayList?

    * ArrayList is faster when compared to Vector since ArrayList is unsynchronized. So, if the List will be modified by only one thread, use ArrayList. If the list is a local variable, you can always use ArrayList. *If the List will be accessed by multiple threads, always use Vector, otherwise you should take care of synchronization manually.
    1. Use Vector if there are multiple threads and ArrayList if there is only a single thread. 2. Use Hashtable if there are multiple threads and HashMap if there is only a single thread. 3. Use StringBuffer if there are multiple threads and StringBuilder if there is only a single thread.

    ArrayList v/s Vector

    Arraylist is not synchronized while vector is. (not thread safe) Arraylist has no default size while vector has a default size of 10. Arraylist don't define any increment size while vector does. ArrayList implements Iterator Interface for traversing While Vector implements Innumerator Interface for traverse.

    Iterator

    using for loop while loop

    Singleton

    Creating only one instance of the class

    With the Singleton design pattern you can: * Ensure that only one instance of a class is created * Provide a global point of access to the object * Allow multiple instances in the future without affecting a singleton class's clients
    public class ClassicSingleton { private static ClassicSingleton instance = null; protected ClassicSingleton() { // Exists only to defeat instantiation. } public static ClassicSingleton getInstance() { if(instance == null) { instance = new ClassicSingleton(); } return instance; }

    Static Class

    A static member class will have the static keyword

    Final , Finaly and Finalize

    Final data

    Many programming languages have a way to tell the compiler that a piece of data is “constant.” A constant is useful for two reasons:

    1. It can be a compile-time constant that won’t ever change.
    2. It can be a value initialized at run time that you don’t want changed.
    With a primitive, final makes the value a constant, but with an object reference, final makes the reference a constant. Once the reference is initialized to an object, it can never be changed to point to another object. However, the object itself can be modified; Java does not provide a way to make any arbitrary object a constant.

    Final methods

    There are two reasons for final methods. The first is to put a “lock” on the method to prevent any inheriting class from changing its meaning. This is done for design reasons when you want to make sure that a method’s behavior is retained during inheritance and cannot be overridden. Feedback

    The second reason for final methods is efficiency. If you make a method final, you are allowing the compiler to turn any calls to that method into inline calls. When the compiler sees a final method call, it can (at its discretion) skip the normal approach of inserting code to perform the method call mechanism (push arguments on the stack, hop over to the method code and execute it, hop back and clean off the stack arguments, and deal with the return value) and instead replace the method call with a copy of the actual code in the method body. This eliminates the overhead of the method call.

    Final classes

    When you say that an entire class is final (by preceding its definition with the final keyword), you state that you don’t want to inherit from this class or allow anyone else to do so. In other words, for some reason the design of your class is such that there is never a need to make any changes, or for safety or security reasons you don’t want subclassing

    Finaly The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated. Finalize.
    • every class inherits the finalize() method from java.lang.Object
    • the method is called by the garbage collector when it determines no more references to the object exist
    • the Object finalize method performs no actions but it may be overridden by any class
    • normally it should be overridden to clean-up non-Java resources ie closing a file

    UnChecked Exception

    *"Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time." * are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, or IllegalStateException * a method is not obliged to establish a policy for the unchecked exceptions thrown by its implementation.

    Exception

    Checked Exception * represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files) * are subclasses of Exception * a method is obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow)

    Thread lifecycle

    Extend the Abstract Class Thread or implement Runnabel overide the run method. call the start method to ivoke the run start--> run() Yield method is used to allow other thread to use the resource. sleep also can be used to pause for execution the thread Demon Thread. A demon thread is one that is supposed to provide a general service in the background as long as the program is running, this have to be called before start

    Package

    A Java package is a mechanism for organizing Java classes into namespaces A package provides a unique namespace for the types it contains. Classes in the same package can access each other's protected members.

    Encapsulation.

    Encapsulation is the ability of an object to be a container (or capsule) for related properties (ie. data variables) and methods (ie. functions). Data hiding is the ability of objects to shield variables from external access. These private variables can only be seen or modified by use of object accessor and mutator methods. Private, Public and Protected. usage of Package. etc.

    Polymorphisms

    Polymorphisms is the capability of an action or method to do different things based on the object that it is acting upon. method overloading , overriding and dynamic method binding. Overloading It happens in same Class. method name should be the same but argument and return type can change Overriding It happens in the derived Class with specif new definition should have same method name , argument and return type like the parent class. Dynamic Binding A mechanism by which, when the compiler can't determine which method implementation to use in advance, the runtime system (JVM) selects the appropriate method at runtime, based on the class of the object

    Inheritance

    Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. An example of where this could be useful is with an employee records system. You could create a generic employee class with states and actions that are common to all employees. Then more specific classes could be defined for salaried, commissioned and hourly employees. The generic class is known as the parent (or superclass or base class) and the specific classes as children (or subclasses or derived classes). The concept of inheritance greatly enhances the ability to reuse code as well as making design a much simpler and cleaner process.

    OOPS !

    Corner Stone. Polymorphisms , Inheritance, Encapsulation

    Object

    2. What is an Object An Object is a instance of class. An Object has state, behavior and identity. Object Class The Object class is the superclass of Java. All other classes are subclasses of the Object class. The object class includes methods such as: clone() finalize() hashCode() toString() copy(Object src) getClass() notifyAll() wait()

    Class

    1. What is a Class * Class describes a set of objects that have identical characteristics (data elements) and behaviors (functionality). * A class is a definition or prototype whereas an object is an instance or living representation of the prototype. * A class specifies the properties (data) and methods (actions) that objects can work with. It is a template or prototype for each of many objects made to the class design.