tag:blogger.com,1999:blog-87110087214612989732024-02-21T00:23:01.084-08:00My Java CampThis blog of My Java Camp provides Java Tutorials and practical guides for students and programmers who want to use the Java programming language to create applications.Anonymoushttp://www.blogger.com/profile/11915327317555464700noreply@blogger.comBlogger3125tag:blogger.com,1999:blog-8711008721461298973.post-75509731968209557402011-01-03T03:36:00.000-08:002011-01-03T03:38:41.549-08:00Java Servlets<h1 style="margin: auto 0in; text-align: justify; text-justify: inter-ideograph;"><span style="color: #990000; font-size: 14pt;">What is Java Servlets?</span></h1><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><span style="font-size: 11.5pt;">Servlets are server side components that provide a powerful mechanism for developing server side programs. Servlets provide component-based, platform-independent methods for building Web-based applications, without the performance limitations of CGI programs. Unlike proprietary server extension mechanisms (such as the Netscape Server API or Apache modules), servlets are server as well as platform-independent. This leaves you free to select a "best of breed" strategy for your servers, platforms, and tools. Using servlets web developers can create fast and efficient server side application which can run on any servlet enabled web server. Servlets run entirely inside the Java Virtual Machine. Since the Servlet runs at server side so it does not checks the browser for compatibility. Servlets can access the entire family of Java APIs, including the JDBC API to access enterprise databases. Servlets can also access a library of HTTP-specific calls, receive all the benefits of the mature java language including portability, performance, reusability, and crash protection. Today servlets are the popular choice for building interactive web applications. Third-party servlet containers are available for Apache Web Server, Microsoft IIS, and others. Servlet containers are usually the components of web and application servers, such as BEA WebLogic Application Server, IBM WebSphere, Sun Java System Web Server, Sun Java System Application Server and others.</span></div><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><span style="font-size: 11.5pt;">Servlets are not designed for a specific protocols. It is different thing that they are most commonly used with the HTTP protocols Servlets uses the classes in the java packages javax.servlet and javax.servlet.http. Servlets provides a way of creating the sophisticated server side extensions in a server as they follow the standard framework and use the highly portable java language.</span></div><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><span style="font-size: 11.5pt;">HTTP Servlet typically used to:</span></div><ul type="disc"><li class="MsoNormal" style="margin: 0in 0in 0pt; mso-list: l1 level1 lfo1; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto; tab-stops: list .5in; text-align: justify; text-justify: inter-ideograph;"><span style="font-size: 11.5pt;">Priovide dynamic content like getting the results of a database query and returning to the client.</span></li>
<li class="MsoNormal" style="margin: 0in 0in 0pt; mso-list: l1 level1 lfo1; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto; tab-stops: list .5in; text-align: justify; text-justify: inter-ideograph;"><span style="font-size: 11.5pt;">Process and/or store the data submitted by the HTML.</span></li>
<li class="MsoNormal" style="margin: 0in 0in 0pt; mso-list: l1 level1 lfo1; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto; tab-stops: list .5in; text-align: justify; text-justify: inter-ideograph;"><span style="font-size: 11.5pt;">Manage information about the state of a stateless HTTP. e.g. an online shopping car manages request for multiple concurrent customers.</span></li>
</ul><h1 style="margin: auto 0in; text-align: justify; text-justify: inter-ideograph;"><span style="color: #990000; font-size: 14pt;">Methods of Servlets</span></h1><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><span style="font-size: 11.5pt;">A Generic servlet contains the following five methods:</span></div><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><b><span style="font-size: 11.5pt;"><span style="color: #20124d;">init()</span><i><br />
</i></span></b><span style="font-size: 11.5pt;"><br />
<b>public void init(ServletConfig config) throws ServletException</b></span></div><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><span style="font-size: 11.5pt;">The<span class="apple-converted-space"> </span><b>init() method</b><span class="apple-converted-space"> </span>is called only once by the servlet container throughout the life of a servlet. By this init() method the servlet get to know that it has been placed into service. </span></div><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><span style="font-size: 11.5pt;">The servlet cannot be put into the service if</span></div><ul type="disc"><li class="MsoNormal" style="margin: 0in 0in 0pt; mso-list: l0 level1 lfo2; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto; tab-stops: list .5in; text-align: justify; text-justify: inter-ideograph;"><span style="font-size: 11.5pt;"> The init() method does not return within a fix time set by the web server. </span></li>
<li class="MsoNormal" style="margin: 0in 0in 0pt; mso-list: l0 level1 lfo2; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto; tab-stops: list .5in; text-align: justify; text-justify: inter-ideograph;"><span style="font-size: 11.5pt;"> It throws a ServletException</span></li>
</ul><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><span style="font-size: 11.5pt;">Parameters - The init() method takes<span class="apple-converted-space"><b> </b></span>a<span class="apple-converted-space"><b> </b></span><b>ServletConfig</b><span class="apple-converted-space"> </span>object that contains the initialization parameters and servlet's configuration and throws a<span class="apple-converted-space"> </span><b>ServletException</b><span class="apple-converted-space"> </span>if an exception has occurred.<br />
<br />
<b><span style="color: #20124d;">service()</span><i><br />
</i></b><br />
<b>public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException</b><br />
<br />
Once the servlet starts getting the requests, the service() method is called by the servlet container to respond. The servlet services the client's request with the help of two objects. These two objects<span class="apple-converted-space"> </span><b>javax.servlet.ServletRequest<span class="apple-converted-space"> </span></b>and <span class="apple-converted-space"> </span><b>javax.servlet.ServletResponse<span class="apple-converted-space"> </span></b>are passed by the servlet container.<br />
<br />
The status code of the response always should be set for a servlet that throws or sends an error.<br />
<br />
Parameters - <span class="apple-converted-space"><b> </b></span>The service() method takes<span class="apple-converted-space"><b> </b></span><b>the ServletRequest<span class="apple-converted-space"> </span></b>object that contains the client's request and the object<span class="apple-converted-space"><b> </b></span><b>ServletResponse</b><span class="apple-converted-space"> </span>contains the servlet's response. The service() method throws<span class="apple-converted-space"> </span><b>ServletException and IOExceptions<span class="apple-converted-space"> </span></b>exception.<br />
</span></div><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><b><span style="font-size: 11.5pt;"><span style="color: #20124d;">getServletConfig()</span><i><br />
</i></span></b><span style="font-size: 11.5pt;"><br />
<b>public ServletConfig getServletConfig()</b> </span></div><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><span style="font-size: 11.5pt;">This method contains parameters for initialization and startup of the servlet and returns a<b>ServletConfig object.<span class="apple-converted-space"> </span></b>This object is then passed to the init method. When this interface is implemented then it stores<span class="apple-converted-space"> </span><b>the ServletConfig object<span class="apple-converted-space"> </span></b>in order to return it. It is done by the generic class which implements this inetrface.</span></div><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><span style="font-size: 11.5pt;">Returns - the ServletConfig object</span></div><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><b><span style="font-size: 11.5pt;"><span style="color: #20124d;">getServletInfo()</span><i><br />
</i></span></b><span style="font-size: 11.5pt;"><br />
<b>public String getServletInfo()</b> </span></div><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><span style="font-size: 11.5pt;">The information about the servlet is returned by this method like version, author etc. This method returns a string which should be in the form of plain text and not any kind of markup. </span></div><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><span style="font-size: 11.5pt;"> Returns - a string that contains the information about the servlet</span></div><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><b><span style="font-size: 11.5pt;"><span style="color: #20124d;">destroy()</span><i><br />
</i></span></b><span style="font-size: 11.5pt;"><br />
<b>public void destroy()</b> </span></div><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><span style="font-size: 11.5pt;">This method is called when we need to close the servlet. That is before removing a servlet instance from service, the servlet container calls the destroy() method. Once the servlet container calls the destroy() method, no service methods will be then called . That is after the exit of all the threads running in the servlet, the destroy() method is called. Hence, the servlet gets a chance to clean up all the resources like memory, threads etc which are being held. </span></div><h1 style="margin: auto 0in; text-align: justify; text-justify: inter-ideograph;"><span style="color: #990000; font-size: 14pt;">Life cycle of Servlet</span></h1><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><span style="font-size: 11.5pt;">The life cycle of a servlet can be categorized into four parts:</span></div><ol type="1"><li class="MsoNormal" style="margin: 0in 0in 0pt; mso-list: l2 level1 lfo3; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto; tab-stops: list .5in; text-align: justify; text-justify: inter-ideograph;"><b><span style="font-size: 11.5pt;">Loading and Inatantiation:<span class="apple-converted-space"> </span></span></b><span style="font-size: 11.5pt;">The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute <load-on-startup> of web.xml file. If the attribute <load-on-startup> has a positive value then the servlet is load with loading of the container otherwise it load when the first request comes for service. After loading of the servlet, the container creates the instances of the servlet.</span></li>
<li class="MsoNormal" style="margin: 0in 0in 0pt; mso-list: l2 level1 lfo3; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto; tab-stops: list .5in; text-align: justify; text-justify: inter-ideograph;"><b><span style="font-size: 11.5pt;">Initialization:<span class="apple-converted-space"> </span></span></b><span style="font-size: 11.5pt;">After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet.<br />
<br />
The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet.</span></li>
<li class="MsoNormal" style="margin: 0in 0in 0pt; mso-list: l2 level1 lfo3; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto; tab-stops: list .5in; text-align: justify; text-justify: inter-ideograph;"><b><span style="font-size: 11.5pt;">Servicing the Request:</span></b><span class="apple-converted-space"><span style="font-size: 11.5pt;"> </span></span><span style="font-size: 11.5pt;">After successfully completing the initialization process, the servlet will be available for service. Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object.</span></li>
<li class="MsoNormal" style="margin: 0in 0in 0pt; mso-list: l2 level1 lfo3; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto; tab-stops: list .5in; text-align: justify; text-justify: inter-ideograph;"><b><span style="font-size: 11.5pt;">Destroying the Servlet:<span class="apple-converted-space"> </span></span></b><span style="font-size: 11.5pt;">If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any request for service and the servlet releases all the resources associated with it. Java Virtual Machine claims for the memory associated with the resources for garbage collection.</span></li>
</ol><div class="MsoNormal" style="margin: 0in 0in 0pt; mso-list: l2 level1 lfo3; mso-margin-bottom-alt: auto; mso-margin-top-alt: auto; tab-stops: list .5in; text-align: justify; text-justify: inter-ideograph;"><br />
</div> <br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjvLeCLo2ablkgDbOs1W84Xc77cre-L9efEswJyGmbpSBuCHVE63Qz7F3S5hYD2duxA1krxgRvZ-1qO1D3MbOsPbP2eFh4cw9gg0YndeQ8ZBErohFTHl6CtV9ZLSJ1lHAHWVjfcsORaiZLV/s1600/ser1.bmp" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" height="320" n4="true" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjvLeCLo2ablkgDbOs1W84Xc77cre-L9efEswJyGmbpSBuCHVE63Qz7F3S5hYD2duxA1krxgRvZ-1qO1D3MbOsPbP2eFh4cw9gg0YndeQ8ZBErohFTHl6CtV9ZLSJ1lHAHWVjfcsORaiZLV/s320/ser1.bmp" width="312" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;"><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><b><span style="font-size: 11.5pt;"> Life Cycle of a Servlet</span></b><span style="font-size: 11.5pt;"> </span></div></td></tr>
</tbody></table> <br />
<h1 style="margin: auto 0in;"><span style="color: #990000; font-size: 14pt;">Advantages of Java Servlets</span></h1><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><b><span style="font-size: 11.5pt;">Portability</span></b><span style="font-size: 11.5pt;">As we know that the servlets are written in java and follow well known standardized APIs so they are highly portable across operating systems and server implementations. We can develop a servlet on Windows machine running the tomcat server or any other server and later we can deploy that servlet effortlessly on any other operating system like Unix server running on the iPlanet/Netscape Application server. So servlets are<span class="apple-converted-space"> </span><b>write once, run anywhere (WORA)</b>program.</span></div><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><b><span style="font-size: 11.5pt;">Powerful</span></b><span style="font-size: 11.5pt;">We can do several things with the servlets which were difficult or even impossible to do with CGI, for example the servlets can talk directly to the web server while the CGI programs can't do. Servlets can share data among each other, they even make the database connection pools easy to implement. They can maintain the session by using the session tracking mechanism which helps them to maintain information from request to request. It can do many other things which are difficult to implement in the CGI programs.</span></div><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><b><span style="font-size: 11.5pt;">Efficiency</span></b><span style="font-size: 11.5pt;">As compared to CGI the servlets invocation is highly efficient. When the servlet get loaded in the server, it remains in the server's memory as a single object instance. However with servlets there are N threads but only a single copy of the servlet class. Multiple concurrent requests are handled by separate threads so we can say that the servlets are highly scalable. </span></div><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><b><span style="font-size: 11.5pt;">Safety</span></b><span style="font-size: 11.5pt;">As servlets are written in java, servlets inherit the strong type safety of java language. Java's automatic garbage collection and a lack of pointers means that servlets are generally safe from memory management problems. In servlets we can easily handle the errors due to Java's exception handling mechanism. If any exception occurs then it will throw an exception.</span></div><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><b><span style="font-size: 11.5pt;">Integration</span></b><span style="font-size: 11.5pt;"><br />
Servlets are tightly integrated with the server. Servlet can use the server to translate the file paths, perform logging, check authorization, and MIME type mapping etc.</span></div><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><b><span style="font-size: 11.5pt;">Extensibility</span></b><span style="font-size: 11.5pt;">The servlet API is designed in such a way that it can be easily extensible. As it stands today, the servlet API support Http Servlets, but in later date it can be extended for another type of servlets.</span></div><div style="margin: 6pt; text-align: justify; text-justify: inter-ideograph;"><b><span style="font-size: 11.5pt;">Inexpensive</span></b><span style="font-size: 11.5pt;">There are number of free web servers available for personal use or for commercial purpose. Web servers are relatively expensive. So by using the free available web servers you can add servlet support to it.</span></div><div class="separator" style="border-bottom: medium none; border-left: medium none; border-right: medium none; border-top: medium none; clear: both; text-align: center;"><br />
</div>Anonymoushttp://www.blogger.com/profile/11915327317555464700noreply@blogger.com1tag:blogger.com,1999:blog-8711008721461298973.post-44037175167234905202010-10-26T02:39:00.000-07:002010-12-21T21:30:25.173-08:00Fundemantals<span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;">Source code of the java program is first written in plain text files ending with the <code>.java</code> extension. When you compile the java program Those source files are then converted into <code>.class</code> files by the <code>javac</code> compiler. A <code>.class</code> file does not contain code that is native to your processor; it instead contains <i>bytecodes</i> <br />
<br />
<img align="bottom" alt="Figure showing MyProgram.java, compiler, MyProgram.class, Java VM, and My Program running on a computer." height="83" src="http://download.oracle.com/javase/tutorial/figures/getStarted/g1.gif" width="482" /><br />
Java VM is available on many different operating systems, the same <code>.class</code> files are capable of running on Microsoft Windows, the Solaris <sup>TM</sup> Operating System (Solaris OS), Linux, or Mac OS.</span></span><br />
<br />
<span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><span style="font-family: GillSans-Bold;"><span style="color: #990000;"><b>Identifiers and Keywords</b><br />
<br />
<span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"></span></span></span></span></span></span><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;">The rules the compiler uses to determine whether a name is legal.</span></span> <span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"></span></span> <br />
<ul><li><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><div align="left">Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). Identifiers cannot start with a number!</div></span></span></li>
<li><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><div align="left">After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers.</div></span></span></span></span></li>
<li><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><div align="left">In practice, there is no limit to the number of characters an identifier can contain.</div></span></span></span></span></span></span></li>
<li><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;">You can't use a Java keyword as an identifier.</span></span></span></span></span></span></span></span></li>
<li><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;">Identifiers in Java are case-sensitive; </span></span><span style="font-family: Courier; font-size: xx-small;"><span style="font-family: Courier; font-size: xx-small;">foo </span></span><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;">and </span></span><span style="font-family: Courier; font-size: xx-small;"><span style="font-family: Courier; font-size: xx-small;">FOO </span></span><span style="font-family: Goudy; font-size: small;"><span style="font-family: Goudy; font-size: small;">are two different identifiers</span></span></span></span></span></span></span></span></span></span></li>
</ul><b><span style="color: #990000;">Examples:</span></b><br />
The following identifiers are legal <br />
<br />
<div align="left">int _a; //starting with underscore</div><div align="left">int $c; //starting with $ sign</div><div align="left">int ______2_w; //starting with underscore</div><div align="left">int _$; //starting with underscore</div>int this_is_a_very_detailed_name_for_an_identifier; // starting with a letter<br />
<br />
The following identifiers are illegal<br />
<br />
<span style="font-family: Courier; font-size: xx-small;"><span style="font-family: Courier; font-size: xx-small;"></span></span>int :b; // starting letter is not valid<br />
<div align="left"></div><div align="left">int -d; // starting letter is not valid</div><div align="left">int e#; // special charactor # is not legal</div><div align="left">int .f; // starting (.) is not valid</div><div align="left">int 7g; //starting with number not allowed.</div><br />
<span style="font-family: Courier; font-size: xx-small;"><span style="font-family: Courier; font-size: xx-small;"></span></span><b><span style="color: #990000;">Java Keywords</span></b><br />
<br />
You cannot use any of the following as identifiers in your programs<br />
<br />
<pre><table style="height: 301px; width: 455px;"><tbody>
<tr><td>abstract</td><td> continue</td><td> for </td><td> new </td></tr>
<tr><td>switch </td><td> assert*** </td><td> default</td><td> goto* </td></tr>
<tr><td>package </td><td> synchronized </td><td> boolean </td><td> do </td></tr>
<tr><td>if</td><td> private </td><td> this </td><td> break </td></tr>
<tr><td>double </td><td> implements </td><td> protected </td><td> throw </td></tr>
<tr><td>byte </td><td> else </td><td> import </td><td> public </td></tr>
<tr><td>case </td><td> enum**** </td><td> instanceof </td><td> return </td></tr>
<tr><td>transient </td><td> catch </td><td> extends </td><td> int </td></tr>
<tr><td>short </td><td> try </td><td> char </td><td> final </td></tr>
<tr><td>interface </td><td> static </td><td> void </td><td> throws </td></tr>
<tr><td>class </td><td> finally </td><td> long </td><td> strictfp** </td></tr>
<tr><td>volatile </td><td> const* </td><td> float </td><td> native </td></tr>
<tr><td>super </td><td> while </td><td></td><td></td></tr>
</tbody></table></pre><br />
<pre>* not used </pre>** added in 1.2 *** added in 1.4 **** added in 5.0 <br />
<div align="left"></div><br />
<div class="FigureCaption">Through the Java VM, the same application is capable of running on multiple platforms.<br />
<br />
<img align="bottom" alt="Figure showing source code, compiler, and Java VM's for Win32, Solaris OS/Linux, and Mac OS" height="332" src="http://download.oracle.com/javase/tutorial/figures/getStarted/helloWorld.gif" width="346" /></div><br />
<div align="left"><span style="color: #990000;"><b>Legal Identifiers</b> </span><br />
<br />
<div align="left">Technically, legal identifiers must be composed of only Unicode characters, numbers, currency symbols, and connecting characters (like underscores).</div></div><br />
<div style="text-align: justify;">All the Java components —classes, variables, and methods—need names. In Java these names are called </div><div style="text-align: justify;">there are rules for what constitutes a legal Java identifier.</div><div style="text-align: justify;"><br />
</div>Anonymoushttp://www.blogger.com/profile/11915327317555464700noreply@blogger.com1tag:blogger.com,1999:blog-8711008721461298973.post-68808541152747463482010-09-13T21:49:00.000-07:002010-12-07T02:33:51.146-08:00Review Questions<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg0pBBgj6bFXZJRk6trCMvCHXbRBvMac6y3R05VcbWorCCld5pLHSBBtfOJiOBKhXE4xMxEIShLrwtt0dhtnUJZ0q9X0754LiITGt1nGjcBr6-zI6y5G_f2nXx6nwBQsUS8EEZ7Qnq3yuov/s1600/untitledmod.bmp"><img alt="" border="0" id="BLOGGER_PHOTO_ID_5516634477794218674" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg0pBBgj6bFXZJRk6trCMvCHXbRBvMac6y3R05VcbWorCCld5pLHSBBtfOJiOBKhXE4xMxEIShLrwtt0dhtnUJZ0q9X0754LiITGt1nGjcBr6-zI6y5G_f2nXx6nwBQsUS8EEZ7Qnq3yuov/s320/untitledmod.bmp" style="cursor: hand; display: block; height: 156px; margin: 0px auto 10px; text-align: center; width: 237px;" /></a><br />
<div></div><br />
<ol><li>Write a java program to display your name on the command prompt</li>
<li>Write a java program to display numbers from 1-10 using a for loop</li>
<li>Write a java program to display numbers for a given range on the command prompt<br />
eg. Java NumDemo 12 30<br />
will display numbers starting from 12 to 30 </li>
<li>write a java program to sort and display a given number series as user arguments, and also display the maximum and the minimum in the series. </li>
<li>Write a java program to find the mean and the median of a given number series as user arguments: (use two methods to find the two attributes and invoke them inside the main method)</li>
<li>Write a java program to find the mode of a given number series as user arguments.</li>
<li>Identify what are the java keywords from the followings<br />
a. abstract b. boolean c. interface d.public e. method f. subclasses</li>
<li>Which one of these lists contains only Java programming language keywords? (Choose one.)<br />
A. class, if, void, long, Int, continue<br />
B. goto, instanceof, native, finally, default, throws<br />
C. try, virtual, throw, final, volatile, transient<br />
D. strictfp, constant, super, implements, do<br />
E. byte, break, assert, switch, include</li>
<li>Which three are legal array declarations? (Choose three.)<br />
A. int [] myScores [];<br />
B. char [] myChars;<br />
C. int [6] myScores;<br />
D. Dog myDogs [];<br />
E. Dog myDogs [7];</li>
<li>Which will legally declare, construct, and initialize an array? (Choose one.)<br />
A. int [] myList = {“1”, “2”, “3”};<br />
B. int [] myList = (5, 8, 2);<br />
C. int myList [] [] = {4,9,7,0};<br />
D. int myList [] = {4, 3, 7};<br />
E. int [] myList = [3, 5, 6];<br />
F. int myList [] = {4; 6; 5};</li>
<li>What is the output of the following program</li>
</ol><pre>public class CharDemo{
public static void main(String arg[]){
char a = 'A';
char b = (char)(a+1);
System.out.println(a+b);
System.out.println("a+b is "+a+b);
int x = 75;
char y = (char)x;
char half = '\u00AC';
System.out.println("Y is "+y+"and half is"+half);
}
}
</pre><br />
<strong>Wrte your answers in the comments area and submit</strong><br />
<ol></ol><strong>Sample solutions</strong> <br />
<br />
<pre>1. public class NameDisplay{
public static void main(String[] arg){
System.out.println("Chaminda Wijesinghe");
}
}
</pre><br />
Write the above program on a notepad and <br />
Save the above program using the file name NameDisplay.java and filetype All Files<br />
Open command prompt and compile the program using "Javac NameDisplay.java"<br />
Run the program using "Java DisplayName"<br />
<br />
<pre>2. public class NumberDisplay{
public static void main(String[] arg){
for(int i=1;i<=10;i++){
System.out.println(""+i);
} // end of for loop
} //end of main method
} // end of the class
3. public class NumberDisplay2{
public static void main(String[] arg){
int i = Integer.parseInt(arg[0]);
int j = Integer.parseInt(arg[1]);
for(int x=i; x<=j; x++){
System.out.println(""+x);
}
}
}
</pre><strong><span style="font-size: large;">Sample Java Programms</span></strong><br />
<br />
<strong><span style="font-size: large;">A program to display prime Numbers</span></strong><br />
<br />
public class prime{<br />
private static boolean checkprime(int num)<br />
{<br />
boolean done = false;<br />
<br />
for(int i=2;i<num;i++)<br />
{<br />
if(num%i!=0)<br />
done=true;<br />
else<br />
return false;<br />
}<br />
return done;<br />
}<br />
public static void main(String[] arg)<br />
{<br />
for(int i=2;i<=100;i++)<br />
{<br />
if(checkprime(i))<br />
{<br />
System.out.println("prime "+i);<br />
}<br />
}<br />
}<br />
}<br />
<strong><span style="font-size: large;">A program to implement a Calculator</span></strong><br />
<br />
import java.awt.*;<br />
import java.awt.event.*;<br />
import java.applet.*;<br />
public class CalculatorApplet extends Applet implements ActionListener<br />
{<br />
private Button keysArray[];<br />
private Panel keyPad;<br />
private TextField lcdField;<br />
private double result;<br />
private boolean first;<br />
private boolean foundKey;<br />
static boolean clearText;<br />
private int prevOperator;<br />
public void init()<br />
{<br />
lcdField = new TextField(20);<br />
keyPad = new Panel ();<br />
keysArray = new Button[17];<br />
result = 0.0;<br />
prevOperator = 0;<br />
first = true;<br />
clearText = true;<br />
//Set frame layout manager setLayout(new BorderLayout());<br />
lcdField.setEditable(false);<br />
//Create buttons<br />
for (int i = 0; i <=9; i++)<br />
keysArray[i] = new Button(String.valueOf(i));<br />
keysArray[10] = new Button("/");<br />
keysArray[11] = new Button("*");<br />
keysArray[12] = new Button("-");<br />
keysArray[13] = new Button("+");<br />
keysArray[14] = new Button("=");<br />
keysArray[15] = new Button(".");<br />
keysArray[16] = new Button("CLR");<br />
<br />
//Set panel layout manager<br />
keyPad.setLayout(new GridLayout (4,4));<br />
//Add button to keyPad panel<br />
for (int i = 7; i <=10; i++) //adds Button 7,8,9, and divide to Panel<br />
keyPad.add(keysArray[i]);<br />
for (int i = 4; i <6; i++) //adds buttons 4,5,6 to Panel<br />
keyPad.add(keysArray[i]);<br />
keyPad.add(keysArray[11]); //adds multiply button to Panel<br />
for (int i = 1; i <= 3;i++) //adds buttons 1,2 and 3 to Panel<br />
keyPad.add(keysArray[i]);<br />
keyPad.add(keysArray[12]);//adds minus button to Panel<br />
keyPad.add(keysArray[0]); //adds 0 key to Panel<br />
for (int i = 15; i >=13; i--)<br />
keyPad.add(keysArray[i]); //adds decimal point, equal, and addition keys Panel<br />
add(lcdField, BorderLayout.NORTH); //adds text field to top of Frame<br />
add(keyPad, BorderLayout.CENTER); //adds Panel to center of Frame<br />
add(keysArray[16], BorderLayout.EAST); //adds Clear key to right side of applet<br />
for(int i = 0; i < keysArray.length; i++)<br />
keysArray[i].addActionListener(this);<br />
}<br />
public void actionPerformed(ActionEvent e)<br />
{<br />
foundKey = false;<br />
//Search for the key pressed<br />
for (int i = 0; i < keysArray.length && !foundKey; i++)<br />
if(e.getSource() == keysArray[i]) //key match found<br />
{<br />
foundKey = true;<br />
switch(i)<br />
{<br />
case 0: case 1: case 2: case 3: case 4: //number buttons<br />
case 5: case 6: case 7: case 8: case 9: //0-9<br />
case 15:<br />
if (clearText)<br />
{<br />
lcdField.setText("");<br />
clearText = false;<br />
}<br />
lcdField.setText(lcdField.getText() +<br />
keysArray[i].getLabel());<br />
break;<br />
case 10:// divide button<br />
case 11:// multiply button<br />
case 12:// minus button<br />
case 13:// plus button<br />
case 14:// equal button<br />
clearText = true;<br />
if (first) // First operand<br />
{<br />
if(lcdField.getText().length()==0)<br />
result = 0.0;<br />
else<br />
result = Double.valueOf(lcdField.getText()).doubleValue();<br />
first = false;<br />
prevOperator = i; //save previous operator<br />
}<br />
else //second operand already enter, so calculator total<br />
{<br />
switch(prevOperator)<br />
{<br />
case 10: //divide Button<br />
result /= Double.valueOf(lcdField.getText()).<br />
doubleValue();<br />
break;<br />
case 11: //multiply Button<br />
result *= Double.valueOf(lcdField.getText()).<br />
doubleValue();<br />
break;<br />
case 12: //minus button<br />
result -= Double.valueOf(lcdField.getText()).<br />
doubleValue();<br />
break;<br />
case 13: //plus button<br />
result += Double.valueOf(lcdField.getText()).<br />
doubleValue();<br />
break;<br />
}<br />
lcdField.setText(Double.toString(result));<br />
if (i==14)//equal button<br />
first = true;<br />
else<br />
prevOperator = i; //save previous opetator<br />
}<br />
break;<br />
case 16://Clear button<br />
clearText = true;<br />
first = true;<br />
lcdField.setText("");<br />
result = 0.0;<br />
prevOperator = 0;<br />
break;<br />
}<br />
}<br />
}<br />
}<br />
<strong><span style="font-size: large;">A program to display Candidate's preferencial votes as a Histogram</span></strong><br />
import javax.swing.*;<br />
public class Histogram<br />
{<br />
public static void main( String args[] )<br />
{<br />
int n[] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };<br />
String output = "";<br />
<br />
output += "Canidate No\tVotes\tHistogram";<br />
<br />
for ( int i = 0; i < n.length; i++ )<br />
{<br />
output += "\n" + i + "\t" + n[ i ] + "\t";<br />
<br />
for ( int j = 1; j <= n[ i ]; j++ ) // print a bar<br />
output += "*";<br />
}<br />
<br />
JTextArea outputArea = new JTextArea( 11, 30 );<br />
outputArea.setText( output );<br />
<br />
JOptionPane.showMessageDialog( null, outputArea,"Histogram Printing Program",JOptionPane.INFORMATION_MESSAGE );<br />
<br />
System.exit( 0 );<br />
}<br />
}<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<a href="http://www.blogger.com/" name="answers"></a><br />
<ol></ol><br />
<ol></ol><br />
<ol></ol>Anonymoushttp://www.blogger.com/profile/11915327317555464700noreply@blogger.com9