Sie sind auf Seite 1von 14

Q1. Write a program to demonstrate the concept of I/O streams in Java. Ans.

Stream Input/Output MS dot NET Streams Disk input > FileStream > Memory Stream > Compression Stream > Crypto Stream > output using System; using System.IO; class Class1 { static void Main() { using (TextWriter w = File.CreateText("out.txt"); { w.WriteLine ("Log: <{0}> {1:MM.dd.yy HH:MM}", Environment.UserName, DateTime.Now); } using (TextReader r = File.OpenText ("out.txt"); { Console.WriteLine ( r.ReadLine() ); } } } This sample coding uses the FileInputStream and FileOutputStream classes from the java.io package to read data from a user-specified file to a buffer, and then out to standard output and a user-specified file. import java.io.*; public class myFileStreamsExample { public static void main (String args[]) throws IOException { File myFile = new File(args[0]); File newFile = new File(args[1]); System.out.println(); if(myFile.exists()) { System.out.println(args[0] + " exists!\n"); FileInputStream inputFile = new FileInputStream(myFile); // Copy entire input file to a buffer: int bytesAvailable = inputFile.available(); byte[] buffer = new byte[bytesAvailable]; int bytes = inputFile.read(buffer);

System.out.println("Copying contents to " + args[1]); FileOutputStream outputFile = new FileOutputStream(newFile); outputFile.write(buffer); // writes entire file from buffer. outputFile.close(); // Write input file to Standard System.Output once: System.out.println("inputFile named " + args[0] + " has " + bytesAvailable + " bytes in file" ); while(bytes != -1) { System.out.write(buffer, 0, bytes); // 0 = offset bytes = inputFile.read(buffer); } inputFile.close(); } else { System.out.println(args[0] + " does not exist\n"); } System.out.println(); } } Q 2. How do you implements inheritance in java? Ans. Inheritance in Java Inheritance is a compile-time mechanism in Java that allows you to extend a class (called the base class or superclass) with another class (called the derived class or subclass). In Java, inheritance is used for two purposes: 1. class inheritance - create a new class as an extension of another class, primarily for the purpose of code reuse. That is, the derived class inherits the public methods and public data of the base class. Java only allows a class to have one immediate base class, i.e., single class inheritance. 2. interface inheritance - create a new class to implement the methods defined as part of an interface for the purpose of subtyping. That is a class that implements an interface conforms

to (or is constrained by the type of) the interface. Java supports multiple interface inheritance. In Java, these two kinds of inheritance are made distinct by using different language syntax. For class inheritance, Java uses the keyword extends and for interface inheritance Java uses the keyword implements. public class derived-class-name extends base-class-name { // derived class methods extend and possibly override // those of the base class } public class class-name implements interface-name { // class provides an implementation for the methods // as specified by the interface } Example of class inhertiance package MyPackage; class Base { private int x; public int f() { ... } protected int g() { ... } } class Derived extends Base { private int y; public int f() { /* new implementation for Base.f() */ } public void h() { y = g(); ... } } In Java, the protected access qualifier means that the protected item (field or method) is visible to a any derived class of the base class containing the protected item. It also means that the protected item is visible to methods of other classes in the same package. This is different from C++. Q: What is the base class of class Object? I.e., what would you expect to get if you executed the following code? Object x = new Object(); System.out.println(x.getClass().getSuperclass());

Q 3. Draw and explain the JDBC Application Architecture? Ans. The JDBC API supports both two-tier and three-tier processing models for Database access. In the two-tier model, a Java application talks directly to the data source. This is referred to as a client/server configuration, with the user's machine as the client, and the machine housing the data source as the server. In the three-tier model, commands are sent to a "middle tier" of services, which then sends the commands to the data source. The middle tier makes it possible to maintain control over access and the kinds of updates that can be made to corporate data. Another advantage is that it simplifies the deployment of applications. Finally, in many cases, the three-tier architecture can provide performance advantages. The JDBC API is also what allows access to a data source from a Java middle tier.

Q 4. What are the difference between an interface and an abstract class? Ans. An abstract class is a class that leaves one or more method implementations unspecified by declaring one or more methods abstract. An abstract method has no body (i.e., no implementation). A subclass is required to override the abstract method and provide an implementation. Hence, an abstract class is incomplete and cannot be instantiated, but can be used as a base class. abstract public class abstract-base-class-name { // abstract class has at least one abstract method public abstract return-type abstract-method-name ( formal-params ); ... // other abstract methods, object methods, class methods } public class derived-class-name extends abstract-base-class-name { public return-type abstract-method-name (formal-params) { stmt-list; } ... // other method implementations } It would be an error to try to instantiate an object of an abstract type: abstract-class-name obj = new abstract-class-name(); // ERROR! That is, operator new is invalid when applied to an abstract class. An interface is a specification, or contract, for a set of methods that a class that implements the interface must conform to in terms of the type signature of the methods. The class that implements the interface provides an implementation for each method, just as with an abstract method in an abstract class. So, you can think of an interface as an abstract class with all abstract methods. The interface itself can have either public, package, private or protected access defined. All methods declared in an interface are implicitly abstract and implicitly public. It is not necessary, and in fact considered redundant to declare a method in an interface to be abstract. You can define data in an interface, but it is less common to do so. If there are data fields defined in an interface, then they are implicitly defined to be: public. static, and final In other words, any data defined in an interface are treated as public constants.

Note that a class and an interface in the same package cannot share the same name. Methods declared in an interface cannot be declared final. Why? Interface declaration Interface names and class names in the same package must be distinct. public interface interface-name { // if any data are defined, they must be constants public static final type-name var-name = constant-expr; // one or more implicitly abstract and public methods return-type method-name ( formal-params ); } When to use an Interface vs when to use an abstract class Having reviewed their basic properties, there are two primary differences between interfaces and abstract classes: an abstract class can have a mix of abstract and non-abstract methods, so some default implementations can be defined in the abstract base class. An abstract class can also have static methods, static data, private and protected methods, etc. In other words, a class is a class, so it can contain features inherent to a class. The downside to an abstract base class, is that since their is only single inheritance in Java, you can only inherit from one class. an interface has a very restricted use, namely, to declare a set of public abstract method signatures that a subclass is required to implement. An interfaces defines a set of type constraints, in the form of type signatures, that impose a requirement on a subclass to implement the methods of the interface. Since you can inherit multiple interfaces, they are often a very useful mechanism to allow a class to have different behaviors in different situations of usage by implementing multiple interfaces. It is usually a good idea to implement an interface when you need to define methods that are to be explicitly overridden by some subclass. If you then want some of the methods implemented with default implementations that will be inherited by a subclass, then create an implementation class for the interface, and have other class inherit (extend) that class, or just use an abstract base class instead of an interface.

Q 5. Explain the working of struts with an example? Ans. Struts is modeled after the MVC design pattern, you can follow a standard development process for all of your Struts Web applications. Identificaty of the application Views, the Controller objects that will service those Views, and the Model components being operated on. 1. Define and create all of the Views, in relation to their purpose, that will represent the user interface of our application. Add all Action Forms used by the created Views to the struts-config.xml file. 2. Create the components of the applications Controller. 3. Define the relationships that exist between the Views and the Controllers (struts-config.xml). 4. Make the appropriate modifications to the web.xml file, describe the Struts components to the Web application. Lets Start with step one. we will create the view file named index.jsp index.jsp <%@ page language="java" %> <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> <html> <head> <title>Sample Struts Application</title> </head> <body> <html:form action="Name" name="nameForm" type="example.NameForm"> <table width="80%" border="0"> <tr> <td>Name:</td> <td><html:text property="name" /></td> </tr> <tr> <td><html:submit /></td> </tr> </table> </html:form> </body> </html> action : Represents the URL to which this form will be submitted. This attribute is also used to find the appropriate Action Mapping in the Struts configuration file, which we will describe later in this section. The value used in our example is Name, which will map to an Action Mapping with a path attribute equal to Name.

Name :Identifies the key that the ActionForm will be referenced by. We use the value NameForm. An ActionForm is an object that is used by Struts to represent the form data as a JavaBean. It main purpose is to pass form data between View and Controller components. We will discuss NameForm later in this section. Type :Names the fully qualified class name of the form bean to use in this request. For this example, we use thevalue example.NameForm, which is an ActionForm object containing data members matching the inputs of this form. NameForm.java package example; //import statements import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; public class NameForm extends ActionForm { private String name = null; public String getName() { return (name); } public void setName(String name) { this.name = name; } public void reset(ActionMapping mapping, HttpServletRequest request) { this.name = null; } } displayname.jsp <html> <head> <title>Sample Struts Display Name</title> </head> <body> <table width="80%" border="0"> <tr> <td>Hello <%= request.getAttribute("NAME") %> !!</td> </tr> </table> </body> </html> NameAction.java package example; import java.io.IOException;

import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class NameAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String target = new String("success"); if ( form != null ) { // Use the NameForm to get the request parameters NameForm nameForm = (NameForm)form; String name = nameForm.getName(); } // if no mane supplied Set the target to failure if ( name == null ) { target = new String("failure"); } else { request.setAttribute("NAME", name); } return (mapping.findForward(target)); } } Moving to step three, to deploy the NameAction to our Struts application, we need to compile the NameAction class and move the class file to /WEBINF/classes/example directory, and add the following entry to the <actionmappings> section of the /WEB-INF/struts-config.xml file: <action path="/Name" type="example.NameAction" name="nameForm" input="/index.jsp"> <forward name="success" path="/displayname.jsp"/> <forward name="failure" path="/index.jsp"/> </action> For step four we modify the web.xml file. We have to to tell the Web application about our ActionServlet. This is accomplished by adding the following servlet definition to the /WEB-INF/web.xml file: <servlet> <servlet-name>action</servlet-name> <servlet-class> org.apache.struts.action.ActionServlet </servlet-class> <init-param> <param-name>config</param-name>

<param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> Once we have told the container about the ActionServlet, we need to tell it when the action should be executed. To do this, we have to add a <servlet-mapping> element to the /WEB-INF/ web.xml file: <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>

Q 6. What is the difference between JavaBeans and NetBeans? Ans. We want to know your opinion on the sensitive issue affecting the Java Beans functionality in the NetBeans IDE. Many releases of NetBeans contained the Beans module - a robust visual tool to create a custom bean, add a property with the Bean Pattern, and edit bean info with the BeanInfo editor. Those features were covered in the Java Beans trail of the Java Tutorial, and some features were discussed in this blog. Unfortunately, due to a variety of circumstances (see the NetBeans project page for more information) the Beans module was dropped from the 6.0 release of NetBeans. This may impede bean application development. Many typical bean operations are not available through the NetBeans 6.0 GUI, which makes creating a custom bean more than a five-minute task. Additionally, the newly introduced binding functionality will be cruelly limited in the IDE, because even to simply add a bound property you will have to code the getter and setter methods by hand. So this blog offers you a chance to vote for bringing back the Beans module in the upcoming update release of NetBeans. Please leave your comments in support of the Java Beans functionality.

Q 7. Explain the life cycle of a Servlet ? Ans. Servlet Life Cycle The life cycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps. 1. If an instance of the servlet does not exist, the Web container 1. Loads the servlet class. 2. Creates an instance of the servlet class. 3. Initializes the servlet instance by calling the init method. 2. Invokes the service method, passing a request and response object. If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's destroy method. Handling Servlet Life-Cycle Events You can monitor and react to events in a servlet's life cycle by defining listener objects whose methods get invoked when life cycle events occur. To use these listener objects, you must define the listener class and specify the listener class. The listeners.ContextListener class creates and removes the database helper and counter objects used in the Duke's Bookstore application. The methods retrieve the Web context object from ServletContextEvent and then store (and remove) the objects as servlet context attributes. CODE: import database.BookDB; import javax.servlet.*; import util.Counter; public final class ContextListener implements ServletContextListener { private ServletContext context = null; public void contextInitialized(ServletContextEvent event) {

context = event.getServletContext(); try { BookDB bookDB = new BookDB(); context.setAttribute("bookDB", bookDB); } catch (Exception ex) { System.out.println( "Couldn't create database: " + ex.getMessage()); } Counter counter = new Counter(); context.setAttribute("hitCounter", counter); context.log("Created hitCounter" + counter.getCounter()); counter = new Counter(); context.setAttribute("orderCounter", counter); context.log("Created orderCounter" + counter.getCounter()); } public void contextDestroyed(ServletContextEvent event) { context = event.getServletContext(); BookDB bookDB = context.getAttribute( "bookDB"); bookDB.remove(); context.removeAttribute("bookDB"); context.removeAttribute("hitCounter"); context.removeAttribute("orderCounter"); } }

Q 8. Explain the importance, applications and working of Java Struts. Ans. Struts is an application development framework that is designed for and used with the popular J2EE (Java 2, Enterprise Edition) platform. It cuts time out of the development process and makes developers more productive by providing them a series of tools and components to build applications with. Struts falls under the Jakarta subproject of the Apache Software Foundation and comes with an Open Source license.

An example of a Struts Flow server-side script which logs the user on to an application: function login() { userManager = struts.applicationScope["userManager"]; error = ""; while (struts.sessionScope["curUser"] == null) { forwardAndWait("loginForm", {"error" : error}); user = struts.param["user"]; passwd = struts.param["passwd"]; if (userManager.login(user, passwd)) { struts.sessionScope["curUser"] = user; } else { error = "Invalid login, please try again"; } } } Features of Struts are as follows: Easily script complex workflows Full access to Struts features Can exist side-by-side regular Struts actions Ability to run in non-Struts environments (uses Jakarta's Commons-Chain) Enhanced Java API methods and Collections integration Remote RPC support (termed Ajax but with JSON instead of XML) for calling flow methods from the client Includes Wizard library to help easily create complex wizards Includes Javascript Templates library to replace JSP for a 100% Javascript view layer. Includes number guessing, remote rpc, Javascript Templates, and wizard examples Struts are a Web Application 'Framework'. Strutsa collection of Java code designed to help you build solid applications while saving time. Struts are based on the time-proven Model-View-Controller (MVC) design pattern. The MVC pattern is widely recognized as being among the most well-developed and mature design patterns in use. By using the MVC design pattern, processing is broken into three distinct sections aptly named the Model, the View, and the Controller. Model Components

Model components are generally standard Java classes. View Components View components are generally built using Java Server Page (JSP) files. Controller Components Controller components in Struts are Java classes and must be built using specific rules. They are usually referred to as "Action classes."