Radio

Tuesday, June 26, 2012

What is Enterprise Computing Software applications are executed on network environments such as LAN and WANs. Enterprise Application consists of number of layers such as Data Layer Business Layer Presentation Layer Data layer consists of data store and it stores on server computer. Presentation layer consists of user interfaces and it store on client computers. Business layer consists of business logic and it stores on server.
Multi Tier Architecture Enterprise Application consists of number of layers or tiers such as (three tier architecture) Data Layer Business Layer Presentation Layer Data Layer Data layer consists of data store and it stores on server computer. This tier related with following Database Design the database structure Normalization Directory Servers Database Management System to implement the database Relational Database Management Systems (RDBMS) Data Access Database access drivers Eg. JDBC Business Layer In this business layer, then, data is manipulated, transformed, and converted into content suitable for presentation. The core of this layer is the code that actually executes business logic. This code maps to a company's business processes; in the best case, a single module of code represents a single business process. These modules can then be called to obtain a client's outstanding balance, for example. This figure is rarely stored in the database, but instead is calculated from the client's purchases subtracted from his or her assets. This allows the raw data to be masked from the presentation layer of an application; instead of asking for data and performing calculations, the application needs to request only the business process that results in a client's account balance, and format the result. However, this is not entirely for the sake of another book; it is also to show you that the details of the data and business layers are often completely isolated from the presentation layer. This means that two groups could design these at different times, or you could even develop a set of data stores and business rules without worrying about presentation until later (the approach taken by this book). This method forces you to uncouple these layers, which is critical to good application design. It also allows an easy conversion of an application to a set of web services; since your business layer is not specifically aimed at a web application, it is easy to expose beans and other business components as web services down the line. So I'll leave this area intentionally open for interpretation. Of course, this doesn't prevent a basic diagramming of how the presentation layer (be it servlets, web services, Java Swing, or anything else) interacts with the other layers in the application. The Java 2 Enterprise Edition Specification (J2EE) In addition to defining the interfaces required for building an enterprise-distributed application, the best feature about the J2EE specification is that it describes what is required from vendor providers, but does not suggest how interfaces should be implemented. Therein lies the formula for success: flexibility, scalability, and making provisions for J2EE and the other specifications’ growth by receiving input from other major third-party vendors and the entire Java community. J2EE is the obvious choice for developing secure distributed applications. The J2EE’s multi component infrastructure is defined as five functional technologies. Communications Presentation Business applications Security Enterprise information system enabling technologies The Client Tier A rich client can be both proprietary standalone Java applications and non-Java applications. Rich clients are capable of accessing both RDBMS and ERP services directly via JDBC connectors. They may also access the EJB web container residing within WebSphere or BEA’s WebLogic. The web container contains both servlets and JSP pages that can access the Enterprise JavaBeans. A thin client residing on a client tier supports the HTML container (browser), HTML, and applets. Thin clients access the web container via HTTP/HTTPS, XML, and HTML. They are also capable of using JDBC connectors to access a relational database and ERP applications. The Presentation Tier This tier hosts the web container that supports Java servlets, Java Server Pages, and Java API for XML Parsing, and the XSLT transformation services. These technologies employ both RMI-IIOP and vendor-proprietary protocols for accessing the remote objects. The Business Tier This tier hosts the EJB container and provides support for business transactions executed by EJBs. The business beans utilize the JDBC and JTC connectors to interact with an RDBMS and ERP business solution. The Enterprise Information Services Tier This tier facilitates cross-platform interaction with enterprise legacy systems. It separates data, including the database, enterprise resource planning, and mainframe transaction processing, from the business and client tiers. J2EE designates two technologies for providing portable access to the EIS tier: JDBC and the Connector technology. The Communication Technologies The eight Java technologies that make up the communications component facilitate client-side business component communications. They are described briefly in the following sections. Java Message Service (JMS) 1.0.2 Business enterprise applications require facilities for exchanging messages. JMS offers a unified-standard messaging API for supporting several different messaging formats, including XML. The JMS API supports two types of messages: Point-to-point Publish-subscribe Java Mail (JavaMail) 1.2 Email pervades our professional and personal lives every day. An email is both platform and protocol agnostic Java Bean Activation Framework (JAF) 1.0.1 The JAF represents a “smart” application framework. It is capable of analyzing new data, abstracting the data’s operations, and making them available to other application components. This is essential where new data formats are evolving. The JAF is somewhat comparable in functionality to Microsoft .NET’s Framework v.1.1. Frameworks are where all application-centric functionality is defined and managed. As new technologies evolve, and as new data types and development languages emerge, they rely on the framework to support and manage the new technologies. Java Interface Definition Language (JavaIDL) 1.3 Typically, business applications contain legacy applications that need to be integrated with newly created Java applications. The Java IDL is an Object Request Broker that comes bundled with the Java 2 Standard Edition (J2SE) and allows J2EE components to invoke requests on external CORBA objects using IIOP as the protocol. Java Naming and Directory Interface (JNDI) 1.2 In a distributed environment, services and objects require a standard, uniform, and transparent method for locating objects residing on different servers on a network. JNDI provides this methodology. It enables applications to access resources distributed throughout the network. J2EE uses JNDI and RMI-IIOP for finding the remote objects. Java Authentication and Authorization Service (JAAS) Security-enabling technologies facilitate J2EE application security implementations by providing authentication and authorization services to users before accessing enterprise resources. JAAS is the primary technology for supporting these services. A container such as WebSphere automatically provides them. Java API for XML Parsing (JAXP) 1.1 JAXP is the technology employed for parsing and transforming XML documents into an appropriate format using the standard Java APIs. JAXP supports the Simple API for XML (SAX 2.0), Document Object Model (DOM), and XSLT, the XML designated transformation language.

Servlets
 Unit IT34
Lesson 2
          Java introduce applets for client side programming
          Java introduce servlets for server side programming
          Servlets can be loaded dynamically and use to create dynamic web pages
          Web Designing/ Static Web Pages  2 side web browser. client - static web pages.server.web server
          Web Developing/ Dynamic Web Pages diagrame here
          Common Gateway Interface/ CGI programs initially used to generate dynamic web pages
          Drawback of CGI is it generate separate process for each request and therefore sever can handle limited number of requests eg. Perl
          Netscape Java Script and Server side API known as NSAPI
          Microsoft ASP and Server side API ISAPI
Java Servlets
          Server side java programs that can be loaded dynamically
          Servlets runs inside a JVM on the server
          Multithreading for handle number of requests
          Portable across the OSs and web servers
          Most of web servers supports servlets
          Add on servlet engine can be used with web server eg. Microsoft’s IIS, IBM’s WebSphere
Java Servlet API
          Servlet API is not a part of JDK, you have to install JSDK (Java Servlets Developer’s Kit)
          Two packages
        javax.servlet
        javax.servlet.http
          javax.servlet package is used to create protocol independent servlets
          The java.servlet.http package used to create HTTP servlets
          All servlets must implement servlet interface
Java Servlet API
          A protocol independent servlet can extend from the class javax.servlet.GenericServlet
          A HTTP servlet can extend from the class javax.servlet.http.HttpServlet
          HttpServlet class is a sub class of GenericServlet class
Creating a Servlet
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Welcome extends HttpServlet
{
                public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
                {
                PrintWriter out = response.getWriter();
                String host=request.getRemoteHost();
                String address=request.getRemoteAddr();
                out.println("<HTML>");
                out.println("<H EAD><TITLE>Welcome to my page</TITLE></HEAD>");
                out.println("<BODY>");
                out.println("<BIG>Welcom to my page</BIG>");
                out.println("Your host name is : "+host+" and address is : "+address);
                out.println("</BODY></HTML>");
  }
}
Creating a Servlet
          Save the file as Welcome.java
          Compile the file
javac Welcome.java –classpath “c:\jsdk2.0\lib\jsdk.jar”
          To run the servlet you can use servletrunner utility in jSDK
servletrunner –d c:\servlet_home –s c:\jsdk2.0\examples\servlet.properties
          Servlet_home is a directory which kept the Welcome.class file
          Web browser
Calling Servlet from HTML form
<html>
                <head>
                <title>Let’s introduce ourselves</title>
                </head>
                <body>
                                <form method=get action="http://localhost:8080/servlet/Welcome1">
                                What is your name ?
<input type=text name=“username">
<input type=submit>
                                                </form>
</body>
</html>
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Welcome extends HttpServlet
{
                public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
                {
                PrintWriter out = response.getWriter();
                String host=request.getRemoteHost();
                String address=request.getRemoteAddr();
                String name=request.getParameter(“username”);
                out.println("<HTML>");
                out.println("<H EAD><TITLE>Welcome to my page</TITLE></HEAD>");
                out.println("<BODY>");
                out.println("<BIG>”+name+” Welcom to my page</BIG>");
                out.println("Your host name is : "+host+" and address is : "+address);
                out.println("</BODY></HTML>");
  }
}
Servlets
 Unit IT34
Lesson 3
Login Servlet
          The following Servlet program illustrates HTML form which used to Login to a intranet.
          import java.io.*;
          import javax.servlet.*;
          import javax.servlet.http.*;
          public class LoginServlet extends HttpServlet
          {
          public void doGet(HttpServletRequest req, HttpServletResponse res)
          throws ServletException,IOException
          {
          res.setContentType("text/html");
          PrintWriter out = res.getWriter();
          String user=req.getParameter("user");
          String password=req.getParameter("pwd");
                          out.println("<HTML>");
          out.println("<HEAD><TITLE>Login Servlet</TITLE></HEAD>");
          out.println("<BODY>");
          if("student".equalsIgnoreCase(user)&&"hardy123".equalsIgnoreCase(password))
          out.println("Welcome to Hardy Advanced Technological Institute");
          else
          out.println("User Name and/or Password combination is invalid");
          out.println("</BODY></HTML>");
          }
          }
          The getParameter() method accept parameter from web page to servlet.
          Servlet checks user name and password and returns the response as a dynamic web page.

HTML Page>
<html>
<head>
<title>Student Login</title>
</head>
<body>
<p>
<form method=get
action="http://localhost:8080/servlet/LoginServlet">
Enter User Name <input type=text name="user">
<p>
Enter Password <input type=password name="pwd">
<p>
<input type="Submit" value="Login">
<input type="reset">
</form>
</body>
</html>
Servlet Design
          A servlet represents a Java class running within a Java Virtual Machine (JVM) related to a web server. Servlets interact with a collection of JavaBeans or Enterprise JavaBeans (EJBs) to execute any described business logic. As previously stated, servlets add functionality by providing session management and other related functions such as user authentication and authorization. The following topics provide a framework for understanding a servlet’s responsibilities:
          HTTP essentials
          Servlet life cycle
          Servlet primary classes
          Advantages of Servlets over the Traditional CGI
          Efficient. With traditional CGI, a new process is started for each HTTP request. If the CGI program does a relatively fast operation, the overhead of starting the process can dominate the execution time. With servlets, the Java Virtual Machine stays up, and each request is handled by a lightweight Java thread, not a heavyweight operating system process. Similarly, in traditional CGI, if there are N simultaneous request to the same CGI program, then the code for the CGI program is loaded into memory N times. With servlets, however, there are N threads but only a single copy of the servlet class. Servlets also have more alternatives than do regular CGI programs for optimizations such as caching previous computations, keeping database connections open, and the like.
Advantages of Servlets over the Traditional CGI
          Convenient. Hey, you already know Java. Why learn Perl too? Besides the convenience of being able to use a familiar language, servlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such utilities.
          Powerful. Java servlets let you easily do several things that are difficult or impossible with regular CGI. For one thing, servlets can talk directly to the Web server (regular CGI programs can't). This simplifies operations that need to look up images and other data stored in standard places. Servlets can also share data among each other, making useful things like database connection pools easy to implement. They can also maintain information from request to request, simplifying things like session tracking and caching of previous computations.
          Portable. Servlets are written in Java and follow a well-standardized API. Consequently, servlets written for, say I-Planet Enterprise Server can run virtually unchanged on Apache, Microsoft IIS, or WebStar. Servlets are supported directly or via a plugin on almost every major Web server.
          Inexpensive. There are a number of free or very inexpensive Web servers available that are good for "personal" use or low-volume Web sites. However, with the major exception of Apache, which is free, most commercial-quality Web servers are relatively expensive. Nevertheless, once you have a Web server, no matter the cost of that server, adding servlet support to it (if it doesn't come preconfigured to support servlets) is generally free or cheap.
HTTP and Servlets
          HTTP, which provides the basic services for the Web, is built on the TCIP/IP protocol and is employed for application-level data transmission. One of the primary beneficial characteristics of HTTP is its request-response protocol. It is the transmission protocol of choice because it facilitates transmission of data through corporate firewalls. It also allows requests and responses to exist as MIME-like messages.
          From an application-level perspective, HTTP has its drawbacks. It is both stateless and connectionless. It is based on a web server and has the following format: it receives client requests and sends a response back to the client. It is important to understand that neither the client nor server retains any state information whatsoever. Incidentally, servlets take over where HTTP is unable to preserve state. Servlets support session state. A client can be one of the following:
                A web-enabled browser               A Java applet
                Another web server                       Another web-enabled                                                                                   application
The Servlet Life Cycle
          The process of loading a servlet into memory, executing the servlet, and then unloading the servlet from memory is the servlet life cycle. For example, a servlet is accessed by typing the following URL: http://localhost/servlet/GreetingsServlet. Typing the keyword servlet in the URL path informs the web server that the client request is designated for a particular servlet and not an HTML page.
          Creating a servlet requires the following steps:
          Create a GenericServlet subclass, essentially the class javax.servlet.http.HttpServlet, meaning you invoke the servlet via HTTP.
          Supply the minimum doGet() or a doPost() method to make the servlet workable. When the servlet is requested for the first time, the web server asks the servlet engine to load the designated server class and all of its methods into memory on the servlet engine node.
The Servlet Life Cycle
          Pass control to the init() method. Note that GenericServlet provides a default empty init() method. Here is where you perform any initialization tasks, such as connecting to a database. The init() method receives only one initial call, which occurs immediately after the servlet is loaded into memory. The following code demonstrates how to write the init() method:
          public void init(javax.servlet.ServletConfig config) throws ServletException
{super.init (config);
// place your code here to perform any initialization tasks
}
          Each time a servlet is called, a new thread is created, and that thread executes over the service() method.
          Override the service() method in order to perform any work. This method is where a servlet performs its multifarious tasks. Because the service() method is always executed within a new thread, make sure that everything executed within this method is reentrant (thread safe).
          Finally, call the destroy() method when the web server senses that the servlet’s tasks are complete. The destroy() method unloads the servlet from memory. Typically, tasks such as closing database connections, closing files, and other administrative tasks are performed in this context.
Servlet Interfaces and Classes
          The Java Servlet API 2.1 offers developers an extensive set of classes and interfaces with which to develop web applications. APIs are contained within three distinct packages. The developer is required to supply implementations for these interfaces:
          javax.servlet
          javax.servlet.http
          javax.servlet.jsp
The javax.servlet Package
          The javax.servlet package represents a collection of basic APIs for servlets. However, they are not bound to any particular schema or protocol that defines how they should be implemented. Table 2-2 lists the classes and interfaces in the javax.servlet package.
Table 2-2: Classes and Interfaces in the javax.servlet Package
Servlet Interface
          The Servlet interface defines the essential APIs for servlets that include the init(), service(), and destroy() methods.
          Note All servlets implement this interface by subclassing the GenericServlet class or, alternatively, the HttpServlet class.
ServletContext Interface
          For each servlet, a context is required because communication must be established with a servlet in a nonrequest-specific manner. Requirements for this include locating path information, accessing different servlets running on a web server, and writing to the server log file.
          Note If a server supports multiple virtual hosts, the ServletContext object must be unique. The ServletContext object resides within the ServletConfig object. You can access this object by employing the Servlet.getServletConfig() method.
GenericServlet Class
          This class is abstract and provides the primary behavior for the Servlet interface. This class also implements the ServletConfig interface, thereby offering a convenient way to access the ServletContext and initialization parameters. It also implements the init() and destroy() methods. All subclasses should override both the init() method and destroy() method and call the super-class implementation for the GenericServlet class.
ServletRequest Interface
          The ServletRequest interface prescribes an object as the first parameter passed in a call to the service() method for a GenericServlet. This provides the servlet with metadata about the request originating from a client call. It includes data, parameter name, values, attributes, and an input stream. For example, the HttpServletRequest provides HTTP data. Furthermore, a servlet request represents a MIME body request. Conversely, the response provides a MIME body response. It is always wise to use the getReader() method when the body contains text. If the body contains binary data, use the getInputStream() method.
ServletResponse Interface
          This interface defines an object used in transmitting MIME-encoded data from the servlet to a client. The servlet engine creates a ServletResponse object and transmits it as an argument in the servlet’s service method. Always call the SetContentType() method before calling either the getWriter() or the getOutputStream() method.
RequestDispatcher Interface
          This interface defines an object that receives requests from a client and forwards them to a resource, such as a servlet, an HTML file, or a JSP file on the server. The servlet engine creates a RequestDispatcher object, which wraps a server resource residing on a specified path. The intent is wrapping servlets. However, a servlet engine can create RequestDispatcher objects to wrap any type of repository resource.
          A RequestDispatcher is obtained from the ServletContext by utilizing the ServletContext.getRequestDispatcher(“resource-name”). Once the dispatcher is obtained, a servlet can forward the request to the named resource in getRequestDispatcher(). An alternative is to use RequestDispatcher() for sending a request to a Java Server Page for display.
HttpServlet Class
          The GenericServlet provides the basic behavior for a servlet. However, a separate mechanism for processing HTTP requests is essential. The HttpServlet, a subclass of GenericServlet, provides the additional behavior for HTTP requests. The GET and POST methods are most commonly used. HttpServlet includes the doGet() and doPost() methods for handling both HTTP GET and HTTP POST.
          When an HttpServlet is requested via a URL, the service() method examines the HTTP header and determines which HTTP method to invoke. The programmer must provide overrides for doGet() and doPost() in order to achieve the servlet’s requested tasks. Both the service() and do() methods require two parameters, which represent instances of the HttpServletRequest and HttpServletResponse interfaces.
          These versions of the request and response objects contain HTTP-specific items such as cookies, headers, and sessions.
HttpServletRequest Interface
          This interface extends the ServletRequest interface by defining a request object associated with the HTTP request. Special items included in this category are authentication through the getAuth() method, the list of cookies through the getCookies() method, and the query string through the getQueryString() method. The servlet engine implements this interface.
HttpServletResponse Interface
          This interface extends the ServletResponse interface and defines a response object corresponding with an HTTP response. This interface permits the servlet’s service() method both to access and set HTTP headers and to return data (HTML) to a client.
HttpSession Interface
          This interface establishes an application-level connection between the web browser and the web server. Utilizing sessions enables the developer to store session-specific data in the servlet engine. The session persists for a specific time period spanning more than one connection or page request from the user. Typically, a session corresponds to a single user who may visit the same site repeatedly. The server can maintain a session by leveraging the services of a cookie or by rewriting URLs.
HttpUtils Class
          This interface represents a concrete class providing a collection of methods that a developer can use when creating HttpServlet subclasses. The getRequestURI() method, a static method, facilitates the ability to reconstruct the request URI for use by the server.
          Nonstatic methods include parsePostData(), for parsing the parameters of a POST, and parseQueryString(), for parsing a GET request’s query string.
Accept Data from Form by using Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
/** Shows all the parameters sent to the servlet via either
 *  GET or POST. Specially marks parameters that have no values or
 *  multiple values.
 */
public class ShowParameters extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading All Request Parameters";
out.println("Form Details" +"<BODY BGCOLOR=\"#FDF5E6\">\n"+"<H1 ALIGN=CENTER>"+title+"</H1>\n"+
"<TABLE BORDER=1 ALIGN=CENTER>\n" +
 "<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Parameter Name<TH>Parameter Value(s)");
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements())
{
String paramName = (String)paramNames.nextElement();
 out.println("<TR><TD>" + paramName + "\n<TD>");
String[] paramValues = request.getParameterValues(paramName);
if (paramValues.length == 1)
{
String paramValue = paramValues[0];
if (paramValue.length() == 0)
 out.print("<I>No Value</I>");
else
 out.print(paramValue);
}
else
{
out.println("<UL>");
for(int i=0; i<paramValues.length; i++)
{
out.println("<LI>" + paramValues[i]);
}
out.println("</UL>");
}
}
out.println("</TABLE>\n</BODY></HTML>");
}
Accept Data from Form by using Servlet
<HTML>
<HEAD>
  <TITLE>A Sample FORM using POST</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H1 ALIGN="CENTER">A Sample FORM using POST</H1>
<FORM ACTION="http://localhost:8080/servlet/ShowParameters"
      METHOD="POST">
  Item Number:
  <INPUT TYPE="TEXT" NAME="itemNum"><BR>
  Quantity:
  <INPUT TYPE="TEXT" NAME="quantity"><BR>
  Price Each:
  <INPUT TYPE="TEXT" NAME="price" VALUE="$"><BR>
  <HR>
  First Name:
  <INPUT TYPE="TEXT" NAME="firstName"><BR>
  Last Name:
  <INPUT TYPE="TEXT" NAME="lastName"><BR>
  Middle Initial:
  <INPUT TYPE="TEXT" NAME="initial"><BR>
  Shipping Address:
  ---Accept Data from Form by using Servlet—
<TEXTAREA NAME="address" ROWS=3 COLS=40></TEXTAREA><BR>
  Credit Card:<BR>
    <INPUT TYPE="RADIO" NAME="cardType"
                     VALUE="Visa">Visa<BR>
    <INPUT TYPE="RADIO" NAME="cardType"
                     VALUE="Master Card">Master Card<BR>
    <INPUT TYPE="RADIO" NAME="cardType"
                     VALUE="Amex">American Express<BR>
    <INPUT TYPE="RADIO" NAME="cardType"
                     VALUE="Discover">Discover<BR>
    <INPUT TYPE="RADIO" NAME="cardType"
                     VALUE="Java SmartCard">Java SmartCard<BR>
  Credit Card Number:
  <INPUT TYPE="PASSWORD" NAME="cardNum"><BR>
  Repeat Credit Card Number:
  <INPUT TYPE="PASSWORD" NAME="cardNum"><BR><BR>
  <CENTER>
    <INPUT TYPE="SUBMIT" VALUE="Submit Order">
  </CENTER>
</FORM>
</BODY>
</HTML>
Servlets
 Unit IT34
Lesson 4
Managing Session State with Servlets
          As a developer, one of the biggest challenges is maintaining an identity with users as they revisit your site multiple times. The information collected during these visits is called session data. Making the distinction between session data and transaction data is easy. Session data is temporary, whereas transaction data is persisted in a repository such as DB2 or Oracle. You can easily convert session data to transaction data by using an interface provided by the Java Servlet API. As each session is created, it is assigned a unique identifier. The ID is subsequently associated with the user and becomes the key ultimately used for locating the proper session for subsequent visits.
          The HttpSession interface facilitates both storing and retrieving application state information. To begin, an instance of the HttpSession is procured through the HttpServletRequest interface. The required interface method is the HttpSession getSession(boolean). The Boolean argument, if determined to be true, creates a new session. Many times, it is desirable to ascertain whether the HttpSession returned was in fact a newly created session or one previously created. Accomplish this by using the HttpSession interface method boolean isNew(). It returns a Boolean to indicate whether the sessionID was returned in the current HttpServletRequest object. It is also possible to discard a session by using the void invalidate() method.
          public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
                          {
String id=request.getPararameter("id");
Employee emp = Employee.getEmployeeFor(id);
                HttpSession session = request.getSession(true);
                          /*check to see if the session is new.
If not true, invalidate the current session and create a new session */
                          if(session.isNew()==false)
                          {
 session.invalidate();
 session=request.getSession(true);
}
session.putValue("employee",emp);
}
          Assume the user has decided to submit the changes. Clicking the Submit button invokes another servlet to process the modifications and persist any data modifications.
                public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
                {
HttpSession session =request.getSession(false);
                if(session== null)
  handleError();
else
                {
  Employee emp =(Employee)session.getValue("employee");
  if(emp != null)
  {
    session.invalidate();
   }
  //send a response
}
          The preceding example demonstrates how to procure an existing session from the request object. The false parameter in the getSession() method specifies not to create a new session if one is not located in the request object. If so, a null is returned. The getValue() method return type is Object, so the value must be cast to the appropriate type before the value is usable.

Wednesday, June 22, 2011

a


// my first program in C++
#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}

// my first program in C++
This is a comment line. All lines beginning with two slash signs (//) are considered comments and do not
have any effect on the behavior of the program. The programmer can use them to include short
explanations or observations within the source code itself. In this case, the line is a brief description of
what our program is.

#include <iostream>
Lines beginning with a hash sign (#) are directives for the preprocessor. They are not regular code lines
with expressions but indications for the compiler's preprocessor. In this case the directive #include
<iostream> tells the preprocessor to include the iostream standard file. This specific file (iostream)
includes the declarations of the basic standard input-output library in C++, and it is included because its
functionality is going to be used later in the program.

using namespace std;
All the elements of the standard C++ library are declared within what is called a namespace, the
namespace with the name std. So in order to access its functionality we declare with this expression that
we will be using these entities. This line is very frequent in C++ programs that use the standard library,
and in fact it will be included in most of the source codes included in these tutorials.

int main ()
This line corresponds to the beginning of the definition of the main function. The main function is the point
by where all C++ programs start their execution, independently of its location within the source code. It
does not matter whether there are other functions with other names defined before or after it - the
instructions contained within this function's definition will always be the first ones to be executed in any
C++ program. For that same reason, it is essential that all C++ programs have a main function.
The word main is followed in the code by a pair of parentheses (()). That is because it is a function
declaration: In C++, what differentiates a function declaration from other types of expressions are these
parentheses that follow its name. Optionally, these parentheses may enclose a list of parameters within
them.
Right after these parentheses we can find the body of the main function enclosed in braces ({}). What is
contained within these braces is what the function does when it is executed.

cout << "Hello World!";
This line is a C++ statement. A statement is a simple or compound expression that can actually produce
some effect. In fact, this statement performs the only action that generates a visible effect in our first
program.
cout represents the standard output stream in C++, and the meaning of the entire statement is to insert
a sequence of characters (in this case the Hello World sequence of characters) into the standard output
stream (which usually is the screen).
cout is declared in the iostream standard file within the std namespace, so that's why we needed to
include that specific file and to declare that we were going to use this specific namespace earlier in our
code.
Notice that the statement ends with a semicolon character (;). This character is used to mark the end of
the statement and in fact it must be included at the end of all expression statements in all C++ programs
(one of the most common syntax errors is indeed to forget to include some semicolon after a statement).

return 0;
The return statement causes the main function to finish. return may be followed by a return code (in our
example is followed by the return code 0). A return code of 0 for the main function is generally interpreted
as the program worked as expected without any errors during its execution. This is the most usual way to
end a C++ console program.
You may have noticed that not all the lines of this program perform actions when the code is executed. There were
lines containing only comments (those beginning by //). There were lines with directives for the compiler's
preprocessor (those beginning by #). Then there were lines that began the declaration of a function (in this case,
the main function) and, finally lines with statements (like the insertion into cout), which were all included within
the block delimited by the braces ({}) of the main function.
The program has been structured in different lines in order to be more readable, but in C

;
In C++, the separation between statements is specified with an ending semicolon (;) at the end of each one, so
the separation in different code lines does not matter at all for this purpose. We can write many statements per
line or write a single statement that takes many code lines. The division of code in different lines serves only to
make it more legible and schematic for the humans that may read it.
Let us add an additional instruction to our first program:

Variables. Data Types.
The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write
several lines of code, compile them, and then execute the resulting program just to obtain a simple sentence
written on the screen as result. It certainly would have been much faster to type the output sentence by ourselves.
However, programming is not limited only to printing simple texts on the screen. In order to go a little further on
and to become able to write programs that perform useful tasks that really save us work we need to introduce the
concept of variable.

Identifiers
A valid identifier is a sequence of one or more letters, digits or underscore characters (_). Neither spaces nor
punctuation marks or symbols can be part of an identifier. Only letters, digits and single underscore characters are
valid. In addition, variable identifiers always have to begin with a letter. They can also begin with an underline
character (_ ), but in some cases these may be reserved for compiler specific keywords or external identifiers, as
well as identifiers containing two successive underscore characters anywhere. In no case they can begin with a
digit.

Another rule that you have to consider when inventing your own identifiers is that they cannot match any keyword
of the C++ language nor your compiler's specific ones, which are reserved keywords. The standard reserved
keywords are:

asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default, delete,
do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto,
if, inline, int, long, mutable, namespace, new, operator, private, protected, public, register,
reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template,
this, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void,
volatile, wchar_t, while

Additionally, alternative representations for some operators cannot be used as identifiers since they are reserved
words under some circumstances:

and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq

Fundamental data types
When programming, we store the variables in our computer's memory, but the computer has to know what kind of
data we want to store in them, since it is not going to occupy the same amount of memory to store a simple
number than to store a single letter or a large number, and they are not going to be interpreted the same way.
The memory in our computers is organized in bytes. A byte is the minimum amount of memory that we can
manage in C++. A byte can store a relatively small amount of data: one single character or a small integer
(generally an integer between 0 and 255). In addition, the computer can manipulate more complex data types that
come from grouping several bytes, such as long numbers or non-integer numbers.
char Character or small integer. 1byte
signed: -128 to 127
unsigned: 0 to 255
short int
(short)
Short Integer. 2bytes
signed: -32768 to 32767
unsigned: 0 to 65535
int Integer. 4bytes
signed: -2147483648 to
2147483647
unsigned: 0 to 4294967295
long int (long) Long integer. 4bytes
signed: -2147483648 to
2147483647
unsigned: 0 to 4294967295
bool
Boolean value. It can take one of two values: true
or false.
1byte true or false
float Floating point number. 4bytes +/- 3.4e +/- 38 (~7 digits)
double Double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits)
long double Long double precision floating point number. 8bytes +/- 1.7e +/- 308 (~15 digits)
wchar_t Wide character.
2 or 4
bytes
1 wide character
* The values of the columns Size and Range depend on the system the program is compiled for. The values

Declaration of variables
In order to use a variable in C++, we must first declare it specifying which data type we want it to be. The syntax
to declare a new variable is to write the specifier of the desired data type (like int, bool, float...) followed by a valid
variable identifier. For example:

int a;
float mynumber;
These are two valid declarations of variables. The first one declares a variable of type int with the identifier a. The
second one declares a variable of type float with the identifier mynumber. Once declared, the variables a and
mynumber can be used within the rest of their scope in the program.

// operating with variables
#include <iostream>
using namespace std;
int main ()
{
// declaring variables:
int a, b;
int result;
// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;
// print out the result:
cout << result;
// terminate the program:
return 0;

Scope of variables
All the variables that we intend to use in a program must have been declared with its type specifier in an earlier
point in the code, like we did in the previous code at the beginning of the body of the function main when we
declared that a, b, and result were of type int.
A variable can be either of global or local scope. A global variable is a variable declared in the main body of the
source code, outside all functions, while a local variable is one declared within the body of a function or a block.

Initialization of variables
When declaring a regular local variable, its value is by default undetermined. But you may want a variable to store
a concrete value at the same moment that it is declared. In order to do that, you can initialize the variable. There
are two ways to do this in C++:
The first one, known as c-like, is done by appending an equal sign followed by the value to which the variable will
be initialized:
type identifier = initial_value ;
For example, if we want to declare an int variable called a initialized with a value of 0 at the moment in which it is
declared, we could write:
int a = 0;
The other way to initialize variables, known as constructor initialization, is done by enclosing the initial value
between parentheses (()):

type identifier (initial_value) ;
For example:
int a (0);
Both ways of initializing variables are valid and equivalent in C++.
// initialization of variables
#include <iostream>
using namespace std;
int main ()
{
int a=5; // initial value = 5
int b(2); // initial value = 2
int result; // initial value
undetermined
a = a + 3;
result = a - b;
cout << result;
return 0;
}

Introduction to strings
Variables that can store non-numerical values that are longer than one single character are known as strings.
The C++ language library provides support for strings through the standard string class. This is not a
fundamental type, but it behaves in a similar way as fundamental types do in its most basic usage.
The C++ Language Tuttoriiall
16
© cplusplus.com 2008. All rights reserved
A first difference with fundamental data types is that in order to declare and use objects (variables) of this type we
need to include an additional header file in our source code: <string> and have access to the std namespace
(which we already had in all our previous programs thanks to the using namespace statement).

// my first string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystring = "This is a string";
cout << mystring;
return 0;
}
This is a string
As you may see in the previous example, strings can be initialized with any valid string literal just like numerical
type variables can be initialized to any valid numerical literal. Both initialization formats are valid with strings:
string mystring = "This is a string";
string mystring ("This is a string");

Constants
Constants are expressions with a fixed value.
Literals
Literals are used to express particular values within the source code of a program. We have already used these
previously to give concrete values to variables or to express messages we wanted our programs to print out, for
example, when we wrote:

Integer Numerals
1776
707
-273
They are numerical constants that identify integer decimal values. Notice that to express a numerical constant we
do not have to write quotes (") nor any special character. There is no doubt that it is a constant: whenever we
write 1776 in a program, we will be referring to the value 1776.

Floating Point Numbers
They express numbers with decimals and/or exponents. They can include either a decimal point, an e character
(that expresses "by ten at the Xth height", where X is an integer value that follows the e character), or both a
decimal point and an e character:

Character and string literals
There also exist non-numerical constants, like:
'z'
'p'
"Hello world"
"How do you do?"
The first two expressions represent single character constants, and the following two represent string literals
composed of several characters. Notice that to represent a single character we enclose it between single quotes (')
and to express a string (which generally consists of more than one character) we enclose it between double quotes
(").
When writing both single character and string literals, it is necessary to put the quotation marks surrounding them
to distinguish them from possible variable identifiers or reserved keywords. Notice the difference between these
two expressions:
x
'x'

\n newline
\r carriage return
\t tab
\v vertical tab
\b backspace
\f form feed (page feed)
\a alert (beep)
\' single quote (')
\" double quote (")
\? question mark (?)
\\ backslash (\)

Boolean literals
There are only two valid Boolean values: true and false. These can be expressed in C++ as values of type bool by
using the Boolean literals true and false.
Defined constants (#define)
You can define your own names for constants that you use very often without having to resort to memoryconsuming
variables, simply by using the #define preprocessor directive. Its format is:

Operators
Once we know of the existence of variables and constants, we can begin to operate with them. For that purpose,
C++ integrates operators. Unlike other languages whose operators are mainly keywords, operators in C++ are
mostly made of signs that are not part of the alphabet but are available in all keyboards. This makes C++ code
shorter and more international, since it relies less on English words, but requires a little of learning effort in the
beginning.
You do not have to memorize all the content of this page. Most details are only provided to serve as a later
reference in case you need it.
Assignment (=)
The assignment operator assigns a value to a variable.
a = 5;
This statement assigns the integer value 5 to the variable a. The part at the left of the assignment operator (=) is
known as the lvalue (left value) and the right one as the rvalue (right value). The lvalue has to be a variable
whereas the rvalue can be either a constant, a variable, the result of an operation or any combination of these.
The most important rule when assigning is the right-to-left rule: The assignment operation always takes place from
right to left, and never the other way:
a = b;
This statement assigns to variable a (the lvalue) the value contained in variable b (the rvalue). The value that was
stored until this moment in a is not considered at all in this operation, and in fact that value is lost.
Consider also that we are only assigning the value of b to a at the moment of the assignment operation. Therefore
a later change of b will not affect the new value of a.
For example, let us have a look at the following code - I have included the evolution of the content stored in the
variables as comments:
// assignment operator
#include <iostream>
using namespace std;
int main ()
{
int a, b; // a:?, b:?
a = 10; // a:10, b:?
b = 4; // a:10, b:4
a = b; // a:4, b:4
b = 7; // a:4, b:7
cout << "a:";
cout << a;
cout << " b:";
cout << b;
return 0;
}
a:4 b:7
This code will give us as result that the value contained in a is 4 and the one contained in b is 7. Notice how a was
not affected by the final modification of b, even though we declared a = b earlier (that is because of the right-toleft
rule).

Arithmetic operators ( +, -, *, /, % )
The five arithmetical operations supported by the C++ language are:
+ addition
- subtraction
* multiplication
/ division
% modulo
Operations of addition, subtraction, multiplication and division literally correspond with their respective
mathematical operators. The only one that you might not be so used to see is modulo; whose operator is the
percentage sign (%). Modulo is the operation that gives the remainder of a division of two values. For example, if
we write:

Compound assignment (+=, -=, *=, /=, %=, >>=, <<=, &=,
^=, |=)
When we want to modify the value of a variable by performing an operation on the value currently stored in that
variable we can use compound assignment operators:

Relational and equality operators ( ==, !=, >, <, >=, <= )
In order to evaluate a comparison between two expressions we can use the relational and equality operators. The
result of a relational operation is a Boolean value that can only be true or false, according to its Boolean result.
We may want to compare two expressions, for example, to know if they are equal or if one is greater than the
other is. Here is a list of the relational and equality operators that can be used in C++:

Logical operators ( !, &&, || )
The Operator ! is the C++ operator to perform the Boolean operation NOT, it has only one operand, located at its
right, and the only thing that it does is to inverse the value of it, producing false if its operand is true and true if its
operand is false. Basically, it returns the opposite Boolean value of evaluating its operand. For example:
!(5 == 5) // evaluates to false because the expression at its right (5 == 5) is true.
!(6 <= 4) // evaluates to true because (6 <= 4) would be false.
!true // evaluates to false
!false // evaluates to true.
The logical operators && and || are used when evaluating two expressions to obtain a single relational result. The
operator && corresponds with Boolean logical operation AND. This operation results true if both its two operands
are true, and false otherwise. The following panel shows the result of operator && evaluating the expression a &&
b:
&& OPERATOR
a b a && b
true true true
true false false
false true false
false false false
The operator || correspond

Conditional operator ( ? )
The conditional operator evaluates an expression returning a value if that expression is true and a different one if
the expression is evaluated as false. Its format is:
condition ? result1 : result2
If condition is true the expression will return result1, if it is not it will return result2.
7==5 ? 4 : 3 // returns 3, since 7 is not equal to 5.
7==5+2 ? 4 : 3 // returns 4, since 7 is equal to 5+2.
5>3 ? a : b // returns the value of a, since 5 is greater than 3.
a>b ? a : b // returns whichever is greater, a or b.
// conditional operator
#include <iostream>
using namespace std;
int main ()
{
int a,b,c;
a=2;
b=7;
c = (a>b) ? a : b;
cout << c;
return 0;
}

Comma operator ( , )
The comma operator (,) is used to separate two or more expressions that are included where only one expression
is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is
considered.
For example, the following code:
a = (b=3, b+2);

Basic Input/Output
Until now, the example programs of previous sections provided very little interaction with the user, if any at all.
Using the standard input and output library, we will be able to interact with the user by printing messages on the
screen and getting the user's input from the keyboard.
C++ uses a convenient abstraction called streams to perform input and output operations in sequential media such
as the screen or the keyboard. A stream is an object where a program can either insert or extract characters
to/from it. We do not really need to care about many specifications about the physical media associated with the
stream - we only need to know it will accept or provide characters sequentially.
The standard C++ library includes the header file iostream, where the standard input and output stream objects
are declared.

Standard Output (cout)
By default, the standard output of a program is the screen, and the C++ stream object defined to access it is cout.
cout is used in conjunction with the insertion operator, which is written as << (two "less than" signs).
cout << "Output sentence"; // prints Output sentence on screen
cout << 120; // prints number 120 on screen
cout << x; // prints the content of x on screen

Standard Input (cin).
The standard input device is usually the keyboard. Handling the standard input in C++ is done by applying the
overloaded operator of extraction (>>) on the cin stream. The operator must be followed by the variable that will
store the data that is going to be extracted from the stream. For example:
int age;
cin >> age;
The first statement declares a variable of type int called age, and the second one waits for an input from cin (the
keyboard) in order to store it in this integer variable.

cin and strings
We can use cin to get strings with the extraction operator (>>) as we do with fundamental data type variables:
cin >> mystring;
However, as it has been said, cin extraction stops reading as soon as if finds any blank space character, so in this
case we will be able to get just one word for each extraction. This behavior may or may not be what we want; for
example if we want to get a sentence from the user, this extraction operation would not be useful.
In order to get entire lines, we can use the function getline, which is the more recommendable way to get user
input with cin:

string mystr ("1204");
int myint;
stringstream(mystr) >> myint;
This declares a string object with a value of "1204", and an int object. Then we use stringstream's constructor
to construct an object of this type from the string object. Because we can use stringstream objects as if they
were streams, we can extract an integer from it as we would have done on cin by applying the extractor operator
(>>) on it followed by a variable of type int.
After this piece of code, the variable myint will contain the numerical value 1204.
// stringstreams
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
string mystr;
float price=0;
int quantity=0;
cout << "Enter price: ";
getline (cin,mystr);
stringstream(mystr) >> price;
cout << "Enter quantity: ";
getline (cin,mystr);
stringstream(mystr) >> quantity;
cout << "Total price: " << price*quantity <<
endl;
return 0;
}
Enter price: 22.25
Enter quantity: 7
Total price: 155.75
In this example, we acquire numeric values fr

Control Structures
A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat
code or take decisions. For that purpose, C++ provides control structures that serve to specify what has to be done
by our program, when and under which circumstances.
With the introduction of control structures we are going to have to introduce a new concept: the compoundstatement
or block. A block is a group of statements which are separated by semicolons (;) like all C++
statements, but grouped together in a block enclosed in braces: { }:

Conditional structure: if and else
The if keyword is used to execute a statement or block only if a condition is fulfilled. Its form is:
if (condition) statement
Where condition is the expression that is being evaluated. If this condition is true, statement is executed. If it is
false, statement is ignored (not executed) and the program continues right after this conditional structure.
For example, the following code fragment prints x is 100 only if the value stored in the x variable is indeed 100:
if (x == 100)
cout << "x is 100";

if (x > 0)
cout << "x is positive";
else if (x < 0)
cout << "x is negative";
else
cout << "x is 0";

The while loop
Its format is:
while (expression) statement
and its functionality is simply to repeat statement while the condition set in expression is true.
For example, we are going to make a program to countdown using a while-loop:
// custom countdown using while
#include <iostream>
using namespace std;
int main ()
{
int n;
cout << "Enter the starting number > ";
cin >> n;
while (n>0) {
cout << n << ", ";
--n;
}
cout << "FIRE!\n";
return 0;
}
Enter the starting number > 8
8, 7, 6, 5, 4, 3, 2, 1, FIRE!
When the program starts the user is prompted to insert a starting number for the countdown. Then the while loop
begins, if the value entered by the user fulfills the condition n>0 (that n is greater than zero) the block that follows
the condition will be executed and repeated while the condition (n>0) remains being true.
The whole process of the previous program can be interpreted according to the following script (beginning in
main):


The do-while loop
Its format is:
do statement while (condition);
Its functionality is exactly the same as the while loop, except that condition in the do-while loop is evaluated after
the execution of statement instead of before, granting at least one execution of statement even if condition is
never fulfilled. For example, the following example program echoes any number you enter until you enter 0.
// number echoer
#include <iostream>
using namespace std;
int main ()
{
unsigned long n;
do {
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n";
} while (n != 0);
return 0;
}
Enter number (0 to end): 12345
You entered: 12345
Enter number (0 to end): 160277
You entered: 160277
Enter number (0 to end): 0
You entered: 0
The do-while loop is usually used when the condition that has to determine the end of the loop is determined within
the loop statement itself, like in the previous case, where the user input within the block is what is used to
determine if the loop has to end. In fact if you never enter the value 0 in the previous example you can be
prompted for more numbers forever.

The for loop
Its format is:
for (initialization; condition; increase) statement;
The C++ Language Tuttoriiall
37
© cplusplus.com 2008. All rights reserved
and its main function is to repeat statement while condition remains true, like the while loop. But in addition, the
for loop provides specific locations to contain an initialization statement and an increase statement. So this
loop is specially designed to perform a repetitive action with a counter which is initialized and increased on each
iteration.
It works in the following way:
1. initialization is executed. Generally it is an initial value setting for a counter variable. This is executed
only once.
2. condition is checked. If it is true the loop continues, otherwise the loop ends and statement is skipped
(not executed).
3. statement is executed. As usual, it can be either a single statement or a block enclosed in braces { }.
4. finally, whatever is specified in the increase field is executed and the loop gets back to step 2.
Here is an example of countdown using a for loop:
// countdown using a for loop
#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--) {
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}
Jump statements.
The break statement
Using break we can leave a loop even if the condition for its end is not fulfilled. It can be used to end an infinite
loop, or to force it to end before its natural end. For example, we are going to stop the count down before its
natural end (maybe because of an engine check failure?):
// break loop example
#include <iostream>
using namespace std;
int main ()
{
int n;
for (n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
}
}
return 0;
}
10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!

The continue statement
The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the
statement block had been reached, causing it to jump to the start of the following iteration. For example, we are
going to skip the number 5 in our countdown:
// continue loop example
#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--) {
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!\n";
return 0;
}


Functions (I)
Using functions we can structure our programs in a more modular way, accessing all the potential that structured
programming can offer to us in C++.
A function is a group of statements that is executed when it is called from some point of the program. The
following is its format:
type name ( parameter1, parameter2, ...) { statements }
where:
type is the data type specifier of the data returned by the function.
name is the identifier by which it will be possible to call the function.
parameters (as many as needed): Each parameter consists of a data type specifier followed by an
identifier, like any regular variable declaration (for example: int x) and which acts within the function as
a regular local variable. They allow to pass arguments to the function when it is called. The different
parameters are separated by commas.
statements is the function's body. It is a block of statements surrounded by braces { }.
Here you have the first function example:
// function example
#include <iostream>
using namespace std;
int addition (int a, int b)
{
int r;
r=a+b;
return (r);
}
int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
return 0;
}
The result is 8
In order to examine this code, first of all remember something said at the beginning of this tutorial: a C++
program always begins its execution by the main function. So we will begin there.

Scope of variables
The scope of variables declared within a function or any other inner block is only their own function or their own
block and cannot be used outside of them. For example, in the previous example it would have been impossible to
use the variables a, b or r directly in function main since they were variables local to function addition. Also, it
would have been impossible to use the variable z directly within function addition, since this was a variable local
to the function main.

// function example
#include <iostream>
using namespace std;
int subtraction (int a, int b)
{
int r;
r=a-b;
return (r);
}
int main ()
{
int x=5, y=3, z;
z = subtraction (7,2);
cout << "The first result is " << z << '\n';
cout << "The second result is " << subtraction (7,2) << '\n';
cout << "The third result is " << subtraction (x,y) << '\n';
z= 4 + subtraction (x,y);
cout << "The fourth result is " << z << '\n';
return 0;
}
The first result is 5
The second result is 5
The third result is 2
The fourth result is 6
In this case we have created a function called subtraction. The only thing that this function does is to subtract
both passed parameters and to return the result.

Functions (II)
Arguments passed by value and by reference.
Until now, in all the functions we have seen, the arguments passed to the functions have been passed by value.
This means that when calling a function with parameters, what we have passed to the function were copies of their
values but never the variables themselves. For example, suppose that we called our first function addition using
the following code:
int x=5, y=3, z;
z = addition ( x , y );

// passing parameters by reference
#include <iostream>
using namespace std;
void duplicate (int& a, int& b, int& c)
{
a*=2;
b*=2;
c*=2;
}
int main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" << z;
return 0;
}
x=2, y=6, z=14
The first thing that should call your attention is that in the declaration of duplicate the type of each parameter
was followed by an ampersand sign (&). This ampersand is what specifies that their corresponding arguments are
to be passed by reference instead of by value.

Overloaded functions.
In C++ two different functions can have the same name if their parameter types or number are different. That
means that you can give the same name to more than one function if they have either a different number of
parameters or different types in their parameters. For example:
// overloaded function
#include <iostream>
using namespace std;
int operate (int a, int b)
{
return (a*b);
}
float operate (float a, float b)
{
return (a/b);
}
int main ()
{
int x=5,y=2;
float n=5.0,m=2.0;
cout << operate (x,y);
cout << "\n";
cout << operate (n,m);
cout << "\n";
return 0;
}
10
2.5
In this case we have defined two functions with the same name, operate, but one of them accepts two parameters
of type int and the other one accepts them of type float. The compiler knows which one to call in each case by
examining the types passed as arguments when the function is called. If it is called with two ints as its arguments
it calls to the function that has two int parameters in its prototype and if it is called with two floats it will call to
the one which has two float parameters in its prototype.

inline functions.
The inline specifier indicates the compiler that inline substitution is preferred to the usual function call mechanism
for a specific function. This does not change the behavior of a function itself, but is used to suggest to the compiler
that the code generated by the function body is inserted at each point the function is called, instead of being
inserted only once and perform a regular call to it, which generally involves some additional overhead in running
time.
The format for its declaration is:
inline type name ( arguments ... ) { instructions ... }
and the call is just like the call to any other function. You do not have to include the inline keyword when calling
the function, only in its declaration.

Recursivity.
Recursivity is the property that functions have to be called by themselves. It is useful for many tasks, like sorting
or calculate the factorial of numbers. For example, to obtain the factorial of a number (n!) the mathematical
formula would be:
n! = n * (n-1) * (n-2) * (n-3) ... * 1
more concretely, 5! (factorial of 5) would be:
5! = 5 * 4 * 3 * 2 * 1 = 120
and a recursive function to calculate this in C++ could be:
// factorial calculator
#include <iostream>
using namespace std;
long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
else
return (1);
}
int main ()
{
long number;
cout << "Please type a number: ";
cin >> number;
cout << number << "! = " << factorial (number);
return 0;
}

Please type a number: 9
9! = 362880

Declaring functions.
Until now, we have defined all of the functions before the first appearance of calls to them in the source code.
These calls were generally in function main which we have always left at the end of the source code. If you try to
repeat some of the examples of functions described so far, but placing the function main before any of the other
functions that were called from within it, you will most likely obtain compiling errors. The reason is that to be able
to call a function it must have been declared in some earlier point of the code, like we have done in all our
examples.
But there is an alternative way to avoid writing the whole code of a function before it can be used in main or in
some other function. This can be achieved by declaring just a prototype of the function before it is used, instead of
the entire definition. This declaration is shorter than the entire definition, but significant enough for the compiler to
determine its return type and the types of its parameters.

// declaring functions prototypes
#include <iostream>
using namespace std;
void odd (int a);
void even (int a);
int main ()
{
int i;
do {
cout << "Type a number (0 to exit): ";
cin >> i;
odd (i);
} while (i!=0);
return 0;
}
void odd (int a)
{
if ((a%2)!=0) cout << "Number is odd.\n";
else even (a);
}
void even (int a)
{
if ((a%2)==0) cout << "Number is even.\n";
else odd (a);
}

Arrays
An array is a series of elements of the same type placed in contiguous memory locations that can be individually
referenced by adding an index to a unique identifier.
That means that, for example, we can store 5 values of type int in an array without having to declare 5 different
variables, each one with a different identifier. Instead of that, using an array we can store 5 different values of the
same type, int for example, with a unique identifier.
For example, an array to contain 5 integer values of type int called billy could be represented like this:

Initializing arrays.
When declaring a regular array of local scope (within a function, for example), if we do not specify otherwise, its
elements will not be initialized to any value by default, so their content will be undetermined until we store some
value in them. The elements of global and static arrays, on the other hand, are automatically initialized with their
default values, which for all fundamental types this means they are filled with zeros.

Accessing the values of an array.
In any point of a program in which an array is visible, we can access the value of any of its elements individually as
if it was a normal variable, thus being able to both read and modify its value. The format is as simple as:
name[index]

// arrays example
#include <iostream>
using namespace std;
int billy [] = {16, 2, 77, 40, 12071};
int n, result=0;
int main ()
{
for ( n=0 ; n<5 ; n++ )
{
result += billy[n];
}
cout << result;
return 0;
}

Multidimensional arrays
Multidimensional arrays can be described as "arrays of arrays". For example, a bidimensional array can be
imagined as a bidimensional table made of elements, all of them of a same uniform data type.

Pointers
We have already seen how variables are seen as memory cells that can be accessed using their identifiers. This
way we did not have to care about the physical location of our data within memory, we simply used its identifier
whenever we wanted to refer to our variable.

Declaring variables of pointer types
Due to the ability of a pointer to directly refer to the value that it points to, it becomes necessary to specify in its
declaration which data type a pointer is going to point to. It is not the same thing to point to a char as to point to
an int or a float.
The declaration of pointers follows this format:
type * name;
where type is the data type of the value that the pointer is intended to point to. This type is not the type of the
pointer itself! but the type of the data the pointer points to. For example:
int * number;
char * character;
float * greatnumber;

// example about structures
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
struct movies_t {
string title;
int year;
} mine, yours;
void printmovie (movies_t movie);
int main ()
{
string mystr;
mine.title = "2001 A Space Odyssey";
mine.year = 1968;
cout << "Enter title: ";
getline (cin,yours.title);
cout << "Enter year: ";
getline (cin,mystr);
stringstream(mystr) >> yours.year;
cout << "My favorite movie is:\n ";
printmovie (mine);
cout << "And yours is:\n ";
printmovie (yours);
return 0;
}
void printmovie (movies_t movie)
{
cout << movie.title;
cout << " (" << movie.year << ")\n";
}
Enter title: Alien
Enter year: 1979
My favorite movie is:
2001 A Space Odyssey (1968)
And yours is:
Alien (1979)
The example shows how we can use the members of an object as regular variables. For example, the member
yours.year is a valid variable of type int, and mine.title is a valid variable of type string.

Enumerations create new data types to contain something different that is not limited to the values fundamental
data types may take. Its form is the following:
enum enumeration_name {
value1,
value2,
value3,
.
.
} object_names;
For example, we could create a new type of variable called color to store colors with the following declaration:
enum colors_t {black, blue, green, cyan, red, purple, yellow, white};

Classes (I)
A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and
functions.
An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would be the
variable.
Classes are generally declared using the keyword class, with the following format:
class class_name {
access_specifier_1:
member1;
access_specifier_2:
member2;
...
} object_names;
Where class_name is a valid identifier for the class, object_names is an optional list of names for objects of this
class. The body of the declaration can contain members, that can be either data or function declarations, and
optionally access specifiers.
All is very similar to the declaration on data structures, except that we can now include also functions and
members, but also this new thing called access specifier. An access specifier is one of the following three
keywords: private, public or protected. These specifiers modify the access rights that the members following
them acquire:
private members of a class are accessible only from within other members of the same class or from
their friends.
protected members are accessible from members of their same class and from their friends, but also
from members of their derived classes.
Finally, public members are accessible from anywhere where the object is visible.
By default, all members of a class declared with the class keyword have private access for all its members.
Therefore, any member that is declared before one other class specifier automatically has private access. For
example:
class CRectangle {
int x, y;
public:
void set_values (int,int);
int area (void);
} rect;
Declares a class (i.e., a type) called CRectangle and an object (i.e., a variable) of this class called rect. This class
contains four members: two data members of type int (member x and member y) with private access (because
private is the default access level) and two member functions with public access: set_values() and area(), of
which for now we have only included their declaration, not their definition.

// classes example
#include <iostream>
using namespace std;
class CRectangle {
int x, y;
public:
void set_values (int,int);
int area () {return (x*y);}
};
void CRectangle::set_values (int a, int b) {
x = a;
y = b;
}
int main () {
CRectangle rect;
rect.set_values (3,4);
cout << "area: " << rect.area();
return 0;
}
area: 12
The most important new thing in this code is the operator of scope (::, two colons) included in the definition of
set_values(). It is used to define a member of a class from outside the class definition itself.

// example: one class, two objects
#include <iostream>
using namespace std;
class CRectangle {
int x, y;
public:
void set_values (int,int);
int area () {return (x*y);}
};
void CRectangle::set_values (int a, int b) {
x = a;
y = b;
}
int main () {
CRectangle rect, rectb;
rect.set_values (3,4);
rectb.set_values (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}

Classes (II)
Overloading operators
C++ incorporates the option to use standard operators to perform operations with classes in addition to with
fundamental types. For example:
int a, b, c;
a = b + c;
This is obviously valid code in C++, since the different variables of the addition are all fundamental types.
Nevertheless, it is not so obvious that we could perform an operation similar to the following one:
struct {
string product;
float price;
} a, b, c;
a = b + c;
In fact, this will cause a compilation error, since we have not defined the behavior our class should have with
addition operations. However, thanks to the C++ feature to overload operators, we can design classes able to
perform operations using standard operators. Here is a list of all the operators that can be overloaded:
Overloadable operators
+ - * / = < > += -= *= /= << >>
<<= >>= == != <= >= ++ -- % & ^ ! |
~ &= ^= |= && || %= [] () , ->* -> new
delete new[] delete[]

// vectors: overloading operators example
#include <iostream>
using namespace std;
class CVector {
public:
int x,y;
CVector () {};
CVector (int,int);
CVector operator + (CVector);
};
CVector::CVector (int a, int b) {
x = a;
y = b;
}
CVector CVector::operator+ (CVector param) {
CVector temp;
temp.x = x + param.x;
temp.y = y + param.y;
return (temp);
}
int main () {
CVector a (3,1);
CVector b (1,2);
CVector c;
c = a + b;
cout << c.x << "," << c.y;
return 0;
}

Friendship and inheritance
Friend functions
In principle, private and protected members of a class cannot be accessed from outside the same class in which
they are declared. However, this rule does not affect friends.
Friends are functions or classes declared as such.
If we want to declare an external function as friend of a class, thus allowing this function to have access to the
private and protected members of this class, we do it by declaring a prototype of this external function within the
class, and preceding it with the keyword friend:

// friend functions
#include <iostream>
using namespace std;
class CRectangle {
int width, height;
public:
void set_values (int, int);
int area () {return (width * height);}
friend CRectangle duplicate (CRectangle);
};
void CRectangle::set_values (int a, int b) {
width = a;
height = b;
}
CRectangle duplicate (CRectangle rectparam)
{
CRectangle rectres;
rectres.width = rectparam.width*2;
rectres.height = rectparam.height*2;
return (rectres);
}
int main () {
CRectangle rect, rectb;
rect.set_values (2,3);
rectb = duplicate (rect);
cout << rectb.area();
return 0;
}
24
The duplicate function is a friend of CRectangle. From within that function we have been able to access the
members width and height of different objects of type CRectangle, which are private members. Notice that
neither in the declaration of duplicate() nor in its later use in main() have we considered duplicate a member
of class CRectangle. It isn't! It simply has access to its private and protected members without being a member.

Friend classes
Just as we have the possibility to define a friend function, we can also define a class as friend of another one,
granting that first class access to the protected and private members of the second one.

// friend class
#include <iostream>
using namespace std;
class CSquare;
class CRectangle {
int width, height;
public:
int area ()
{return (width * height);}
void convert (CSquare a);
};
class CSquare {
private:
int side;
public:
void set_side (int a)
{side=a;}
friend class CRectangle;
};
void CRectangle::convert (CSquare a) {
width = a.side;
height = a.side;
}
int main () {
CSquare sqr;
CRectangle rect;
sqr.set_side(4);
rect.convert(sqr);
cout << rect.area();
return 0;
}
16
In this example, we have declared CRectangle as a friend of CSquare so that CRectangle member functions could
have access to the protected and private members of CSquare, more concretely to CSquare::side, which describes
the side width of the square.
You may also see something ne

What is inherited from the base class?
In principle, a derived class inherits every member of a base class except:
its constructor and its destructor
its operator=() members
its friends
Although the constructors and destructors of the base class are not inherited themselves, its default constructor
(i.e., its constructor with no parameters) and its destructor are always called when a new object of a derived class
is created or destroyed.
If the base class has no default constructor or you want that an overloaded constructor is called when a new
derived object is created, you can specify it in each constructor definition of the derived class:
derived_constructor_name (parameters) : base_constructor_name (parameters) {...}
For example:
The C++ Language Tuttoriiall
105
© cplusplus.com 2008. All rights reserved
// constructors and derived classes
#include <iostream>
using namespace std;
class mother {
public:
mother ()
{ cout << "mother: no parameters\n"; }
mother (int a)
{ cout << "mother: int parameter\n"; }
};
class daughter : public mother {
public:
daughter (int a)
{ cout << "daughter: int parameter\n\n"; }
};
class son : public mother {
public:
son (int a) : mother (a)
{ cout << "son: int parameter\n\n"; }
};
int main () {
daughter cynthia (0);
son daniel(0);
return 0;
}
mother: no parameters
daughter: int parameter
mother: int parameter
son: int parameter
Notice the difference between which mother's constructor is called when a new daughter object is created and
which when it is a son object. The difference is because the constructor declaration of daughter and son:
daughter (int a) // nothing specified: call default
son (int a) : mother (a) // constructor specified: call this
Multiple inheritance
In C++ it is perfectly possible that a class inherits members from more than one class. This is done by simply
separating the different base classes with commas in the derived class declaration. For example, if we had a
specific class to print on screen (COutput) and we wanted our classes CRectangle and CTriangle to also inherit its
members in addition to those of CPolygon we could write:
class CRectangle: public CPolygon, public COutput;
class CTriangle: public CPolygon, public COutput;
here is the complete example:

// multiple inheritance
#include <iostream>
using namespace std;
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b;}
};
class COutput {
public:
void output (int i);
};
void COutput::output (int i) {
cout << i << endl;
}
class CRectangle: public CPolygon, public COutput {
public:
int area ()
{ return (width * height); }
};
class CTriangle: public CPolygon, public COutput {
public:
int area ()
{ return (width * height / 2); }
};
int main () {
CRectangle rect;
CTriangle trgl;
rect.set_values (4,5);
trgl.set_values (4,5);
rect.output (rect.area());
trgl.output (trgl.area());
return 0;
}
20
10

Polymorphism
Before getting into this section, it is recommended that you have a proper understanding of pointers and class
inheritance. If any of the following statements seem strange to you, you should review the indicated sections:
Statement: Explained in:
int a::b(c) {}; Classes
a->b Data Structures
class a: public b; Friendship and inheritance
Pointers to base class
One of the key features of derived classes is that a pointer to a derived class is type-compatible with a pointer to
its base class. Polymorphism is the art of taking advantage of this simple but powerful and versatile feature, that
brings Object Oriented Methodologies to its full potential.
We are going to start by rewriting our program about the rectangle and the triangle of the previous section taking
into consideration this pointer compatibility property:

// pointers to base class
#include <iostream>
using namespace std;
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
};
class CRectangle: public CPolygon {
public:
int area ()
{ return (width * height); }
};
class CTriangle: public CPolygon {
public:
int area ()
{ return (width * height / 2); }
};
int main () {
CRectangle rect;
CTriangle trgl;
CPolygon * ppoly1 = &rect;
CPolygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout << rect.area() << endl;
cout << trgl.area() << endl;
return 0;
}
20
10
In function main, we create two pointers that point to objects of class CPolygon (ppoly1 and ppoly2). Then we
assign references to rect and trgl to these pointers, and because both are objects of classes derived from
CPolygon, both are valid assignment operations.

Templates
Function templates
Function templates are special functions that can operate with generic types. This allows us to create a function
template whose functionality can be adapted to more than one type or class without repeating the entire code for
each type.
In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that
can be used to pass a type as argument: just like regular function parameters can be used to pass values to a
function, template parameters allow to pass also types to a function. These function templates can use these
parameters as if they were any other regular type.
The format for declaring function templates with type parameters is:
template <class identifier> function_declaration;
template <typename identifier> function_declaration;
The only difference between both prototypes is the use of either the keyword class or the keyword typename. Its
use is indistinct, since both expressions have exactly the same meaning and behave exactly the same way.
For example, to create a template function that returns the greater one of two objects we could use:
template <class myType>
myType GetMax (myType a, myType b) {
return (a>b?a:b);
}
Here we have created a template function with myType as its template parameter. This template parameter
represents a type that has not yet been specified, but that can be used in the template function as if it were a
regular type. As you can see, the function template GetMax returns the greater of two parameters of this stillundefined
type.
To use this function template we use the follow

// function template II
#include <iostream>
using namespace std;
template <class T>
T GetMax (T a, T b) {
return (a>b?a:b);
}
int main () {
int i=5, j=6, k;
long l=10, m=5, n;
k=GetMax(i,j);
n=GetMax(l,m);
cout << k << endl;
cout << n << endl;
return 0;
}
6
10

Class templates
We also have the possibility to write class templates, so that a class can have members that use template
parameters as types. For example:
template <class T>
class mypair {
T values [2];
public:
mypair (T first, T second)
{
values[0]=first; values[1]=second;
}
};
The class that we have just defined serves to store two elements of any valid type. For example, if we wanted to
declare an object of this class to store two integer values of type int with the values 115 and 36 we would write:
mypair<int> myobject (115, 36);

// class templates
#include <iostream>
using namespace std;
template <class T>
class mypair {
T a, b;
public:
mypair (T first, T second)
{a=first; b=second;}
T getmax ();
};
template <class T>
T mypair<T>::getmax ()
{
T retval;
retval = a>b? a : b;
return retval;
}
int main () {
mypair <int> myobject (100, 75);
cout << myobject.getmax();
return 0;
}

dynamic_cast
dynamic_cast can be used only with pointers and references to objects. Its purpose is to ensure that the result of
the type conversion is a valid complete object of the requested class.
Therefore, dynamic_cast is always successful when we cast a class to one of its base classes:

// dynamic_cast
#include <iostream>
#include <exception>
using namespace std;
class CBase { virtual void dummy() {} };
class CDerived: public CBase { int a; };
int main () {
try {
CBase * pba = new CDerived;
CBase * pbb = new CBase;
CDerived * pd;
pd = dynamic_cast<CDerived*>(pba);
if (pd==0) cout << "Null pointer on first type-cast" << endl;
pd = dynamic_cast<CDerived*>(pbb);
if (pd==0) cout << "Null pointer on second type-cast" << endl;
} catch (exception& e) {cout << "Exception: " << e.what();}
return 0;
}
Null pointer on second typecast

static_cast
static_cast can perform conversions between pointers to related classes, not only from the derived class to its
base, but also from a base class to its derived. This ensures that at least the classes are compatible if the proper
object is converted, but no safety check is performed during runtime to check if the object being converted is in
fact a full object of the destination type. Therefore, it is up to the programmer to ensure that the conversion is
safe. On the other side, the overhead of the type-safety checks of dynamic_cast is avoided.
class CBase {};
class CDerived: public CBase {};
CBase * a = new CBase;
CDerived * b = static_cast<CDerived*>(a);

Preprocessor directives
Preprocessor directives are lines included in the code of our programs that are not program statements but
directives for the preprocessor. These lines are always preceded by a hash sign (#). The preprocessor is executed
before the actual compilation of code begins, therefore the preprocessor digests all these directives before any
code is generated by the statements.
These preprocessor directives extend only across a single line of code. As soon as a newline character is found, the
preprocessor directive is considered to end. No semicolon (;) is expected at the end of a preprocessor directive.
The only way a preprocessor directive can extend through more than one line is by preceding the newline character
at the end of the line by a backslash (\).
macro definitions (#define, #undef)
To define preprocessor macros we can use #define. Its format is:
#define identifier replacement
When the preprocessor encounters this directive, it replaces any occurrence of identifier in the rest of the code
by replacement. This replacement can be an expression, a statement, a block or simply anything. The
preprocessor does not understand C++, it simply replaces any occurrence of identifier by replacement.


Input/Output with files
C++ provides the following classes to perform output and input of characters to/from files:
ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.
These classes are derived directly or indirectly from the classes istream, and ostream. We have already used
objects whose types were these classes: cin is an object of class istream and cout is an object of class ostream.
Therfore, we have already been using classes that are related to our file streams. And in fact, we can use our file
streams the same way we are already used to use cin and cout, with the only difference that we have to associate
these streams with physical files. Let's see an example:

// basic file operations
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
[file example.txt]
Writing this to a file
This code creates a file called example.txt and inserts a sentence into it in the same way we are used to do with
cout, but using the file stream myfile instead.

Open a file
The first operation generally performed on an object of one of these classes is to associate it to a real file. This
procedure is known as to open a file. An open file is represented within a program by a stream object (an
instantiation of one of these classes, in the previous example this was myfile) and any input or output operation
performed on this stream object will be applied to the physical file associated to it.

open (filename, mode);