Wednesday, 10 July 2013

Servlet Tutorials


Java : Servlet Tutorials

Java : Servlet Tutorials


  1. History of  Web applicationEarlier in client- server computing, each application had its own client program and it worked as a user interface and need to be installed on each user's personal computer.
       
  2. Introduction to Web ServerWeb Server is a computer on the World Wide Web that stores Html documents that can be retrieved via a Web browser. It is a computer that delivers web pages.
      
  3. What is a ContainerContainer are nothing but a Java application which controls servlets. Tomcat is one of the example of a container. It is the container which calls the servlet's methods like doPost() and doGet().
       
  4. Overview of ServletsWhat is servlet?  Methods of Servlet
    Life Cycle of Servlet
    Features of Servlet 2.4

    Features of Servlet 2.5
    Features of Servlet 3.0

    Advantages of Java Servlets
    Advantages of Servlets over CGI
    Servlet 3.0 Complete Tutorial

  5. Quick get to Servlet
    Servlets overview
    Introduction to Server Side programming 
    Introduction to Java Servlets 
    Installing Configuring and Running Servlets    
        
  6. How to run a Servlet?Install the tomcat server in a directory in which you want to install and set the classpath.for the variable JAVA_HOME in the environment variable.
        
  7. Writing Hello WorldWe should start understanding the servlets from the beginning. Lets start by making one program which will just print the "Hello World" on the browser. Each time the user visits this page it will display "Hello World" to the user.
      
  8. Displaying Date in ServletIn this example we are going to show how we can display a current date and time on our browser. It is very easy to display it on our browser by using the Date class of the java.utilpackage.
         
  9. Simple Counter In ServletIn this example we are going to know how we can make a program on counter which will keep track how many times the servlet has been accessed.
        
  10. A Holistic counter in ServletIn this program we are going to make a such a servlet which will count the number it has been accessed and the number of threads created by the server.
       
  11. Counter in Init() MethodIn this program we are going to make a such a servlet which will count and displays the number of times it has been accessed and by reading the init parameter to know from where the counting will begin.
      
  12. Snooping the serverTo display the name of the server you are using use the method getServerName() of theServletRequest interface. To display the server port number use the method getServerPort().
       
  13. Snooping HeadersIn this program we are going to going to make a servlet which will retrieve all the Http request header.
      
  14. Dice RollerWe are going to make one program on the dice roller in which the number in the dice will be selected randomly.
       
  15. Getting Init Parameter NamesWhenever the container makes a servlet it always reads it deployment descriptor file i.e. web.xml. Container creates name/value pairs for the ServletConfig object.  Once the parameters are in ServletConfig they will never be read again by the Container.
        
  16. Passing Parameter Using Html FormThis is a very simple example in which we are going to display the name on the browser which we have entered from the Html page.
       
  17. Multiple values for a single parameterIn our program it may be that we may have multiples values for a single parameter like in checkboxes.
      
  18. Time Updater in Servlet
    In this program we are going to make one program on servlet which will keep on updating the time in every second and the result will be displayed to you.
       
  19. Send Redirect in Servlet 
    In this example we are going to make one html in which we will submit the user name and his password. The controller will check if the password entered by the user is correct or not.
        
  20. Session Tracking
    As we know that the Http is a stateless protocol, means that it can't persist the information. It always treats each request as a new request. In Http client makes a connection to the server, sends the request., gets the response, and closes the connection.
           
  21. To Determine whether the Session is New or Old
    In this program we are going to make one servlet on session in which we will check whether the session is new or old.
       
  22. Pre- Existing Session
    In this example we are going to find out whether the session is pre- existing or not.
          
  23. Session Last Accessed Time Example
    This example illustrates to find current  access time of session  and last access time of session. Sessions are used to maintain state and user identity across multiple page requests.
      
  24. Get Session Id
    In this example we are going to make a program in which we will find the session id which was generated by the container.
      
  25. Display session value Using Servlet
    Sometime while developing web application it is necessary to interact with the different values of the Session object. In this example we will explore the different values of the Session object and then learn how to use it in our programming code.
       
  26. Hit Counter Servlet Example
    This example illustrates about counting how many times the servlet is accessed. When first time servlet (CounterServlet) runs then session is created and value of the counter will be zero and after again accessing of servlet  the counter value will be increased by one.
      
    Connection with the Database
         
  27. Inserting Data In Database table using Statement
    In this program we are going to insert the data in the database from our java program in the table stored in the database.
             
  28. Retrieving Data from the table using StatementIn this program we are going to fetch the data from the database in the table from our java program.
        
  29. Inserting data from the HTML page to the databaseIn this program we are going to make program in which we are going to insert the values in the database table from the html form.
         
  30. Retrieving Data from the table using PreparedStatement
    In this program we are going to fetch the data from the database in the table from our java program using PreparedStatement
     
  31. Getting Columns Names using Servlets
    Consider a situation where there is a need to know about the name of the columns without touching our database. As we are the programmers so why we need to worry about the database.
      
  32. Getting Number of ColumnsConsider a situation where there is a need to know about the number of columns in the table without touching our database. As we are the programmers so why we should worry about the database.
       
  33. Getting Number of RowsConsider a situation where we want to know about the number of rows in the particular database table without touching our database.
    We want to find out the number of rows without going touching our back- end.
      
  34. Deleting Rows From Table
    Consider a situation where we have entered some wrong data and in later situation it starts giving problem to the organization.
       
  35. Deleting All Rows From the database Table
    Consider a situation where we have entered some wrong data and in later situation it starts giving problem to an organization or may become useless after sometime . Rather than go through with that data its better to delete that data.
         
  36. How to add a column in a table
    Consider a situation where the requirement of the client gets changed and you have asked to modify the structure of the table. In reality it is the work of the database administrator but as a Java programmer you should know how you can modify the structure of the table.
         
  37. How to delete a table in mysql
    Consider a situation where we need to delete a table from a database.
      
  38. changing column name
    consider a scenario where we have a table and it consists some data and a situation arises where there is a need to change the name of the column.  
      
  39. insert into statement in sql using servlets
    In this tutorial we are going to learn how we can insert a value from a html form in the table stored in the database.  
                 
  40. join tables mysql using servlets
    In this program we are going to join the two table by using the servlets and the result will be displayed in the browser.
            
  41. Natural Left Join using servlets
    In this program we are going to join the two table by using the servlets and the result will be displayed in the browser. This join will be natural left join.
       
  42. Natural Right Join using servlets
    In this program we are going to join the two table by using the servlets and the result will be displayed in the browser. This join will be natural right join.
               
  43. Difference between Servlet 2.4 and Servlet 2.5
    In this tutorial you will know  the difference between Servlet 2.4 and Servlet 2.5
           
        
  44. Get And Post Method of HttpThe Get is one the simplest Http method. Its main job is to ask the server for the resource. The Post method is more powerful request. By using Post we can request as well as send some data to the server.
           
  45. Servlets Links
    Servlets are the Java platform technology of choice for extending and enhancing Web servers. Servlets provide a component-based, platform-independent method for building Web-based applications, without the performance limitations of CGI programs. And unlike proprietary server extension mechanisms (such as the Netscape Server API or Apache modules), servlets are server- and platform-independent.
        
  46. Select Color
    In this program we are going to selected the various color and on the basis of the selection the output will be displayed to the user.
                  
  47. sendRedirect
    In send Redirect whenever the client makes any request it goes to the container, there the container decides whether the concerned servlet can handle the request or not.
           
  48. Send Redirect in Servlet
    When we want that someone else should handle the response of our servlet, then there we should use sendRedirect() method.
         
  49. Random RedirectorIn this program we are going to make such a servlet which will be responsible to select a site randomly from the list of sites you have entered. Note that the selection of the site will be randomly.
            
  50. Servlet ContextServletContext is a interface which helps us to communicate with the servlet container. There is only one ServletContext for the entire web application and the components of the web application can share it.    
      
  51. Servlet Context ListenerServContextListener is a interface which contains two methods: public void contextInitialized(ServletContextEvent event) andpublic void contextDestroyed(ServletContextEvent event).
      
  52. ServletContextListener example
    ServletContextListener is notified when the context is initialized. It will be notified when the context is destroyed. It closes the database connection.
           
  53. ServletContextAttributeListener
    The listener ServletContextAttributeListener is an interface and extends thejava.util.EventListener class. This listener come into existence when this interface receives notifications of changes to the attribute list on the servlet context of a web application.
         
  54. HttpSessionListener
    HttpSessionListener is an interface which extends java.util.EventListener class. The main purpose of this listener is to notify whenever there is a change in the list of active sessions in a web application..
         
  55. HttpSessionListener example
    Before going into the details of the SessionListener we should firstly know about the sessions. Whenever a client makes a request for any resources to the server, the server receives the request and processes the request and sends back the response.
      
  56. HttpSessionAttributeListener
    The listener HttpSessionAttributeListener is an interface and extends thejava.util.EventListener class. This listener will be called by the container whenever there there will be change to the attribute list on the servlet session of a web application.
     
  57. HttpSessionAttributeListener Example
    This listener is used when we want to know when a attribute has been added in a session, when a attribute has been removed and when it is replaced by another attribute.
       
  58. httpsessionbindinglistener
    HttpSessionBindingListener is a interface which extends java.util.EventListener interface. The purpose of the this interface is to notify an object when it is bound to or unbound from a session.
        
  59. httpsessionbindinglistener example
    This interface has two methods: valueBound(HttpSessionBindingEvent event) andvalueUnBound(HttpSessionBindingEvent event).
         
  60. ServletRequestAttributeListener
    This listener is used when we want to know when a attribute has been added in a request, when a attribute has been removed and when it is replaced by another attribute.
        
      
  61. Inserting Image in a database TableConsider a case where we want that along with the name of the person and its information, his image should also come with all these things.
      
  62. Insert  Image into Database Using Servlet
    This example illustrate the process of inserting image into database table using Servlet. This type of program is useful in social networking or HR application where it is necessary to save the uploaded photograph of the user. 
     
  63. Retrieve image from database using Servlet
    In this example we will show you how to develop a Servlet that connects to the MySQL database and retrieves the image from the table. After completing this tutorial you will be able to develop program for your java based applications that retrieves the image from database.
            
      
  64. say hello in spanishIn this program we are going to display "hello" in spanish along with the date.
      
  65. Accessing Date In ServletIn this example, we are going to show how we can display a creation date of the session and last accessed date or time and id on our browser. It is very easy to display it on our browser by using the Date class of the java.util package.
      
  66. Post Message In servletIn this example, we are going to implement posting massage to servlet. In the following program, you will learn how to post massage.
         
  67. Show Parameter In ServletIn this section, you will learn how to send and put all parameter names into the table. The following program uses two methods, which is described below.
     
  68. Get Parameter Name From Servlet Request
    This example illustrates about how to get parameter from jsp page in your servlet. In the jsp (parameter.jsp) page we have taken three input fields having name as firstname, lastname and middle name..
     
  69. How to connect to MySql Database from Servlet?
    In this example we will show you how to connect to MySQL database and perform select operation. You will learn the JDBC steps necessary to connect to the MySQL Database and execute the query.
      
  70. Servlet Error Message based on user input
    In this example user is presented with a screen to enter the name. If the entered name exists in the database its displays the sucess message otherwise it displays the error message. So, you can use Servlet to check the user input against database and display the message to the user.
     
  71. Quintessential ServletQuintessential servlet is not any special kind of servlet. It is just a proper and appropriate way to write a servlet. This quintessential servlet means that servlet is having accurate way of code written for an organizations servlet.
     
  72. Logging Filter Servlet ExampleThis example illustrates how one can write Logging Filter servlet to provide control over log file. You can have additional controls over these log files and these all are available to use by implementing "Filter" class.
     
  73. Context Log Example Using ServletThis example illustrates about how to use of Context Log in servlet. Context Log is used to write specified message to server log file when servlet is called. In the following JSP page(message.jsp) we have simply taken a text area where user give his/her message and post the form.
     
  74. Response Filter Servlet ExampleThis Example shows how to use of response filter in  Java Servlet. Filter reads own initial parameters and adds its value to the response. Use the init-param child element of the filter element to declare the initialization parameter and its value.
     
  75. IP Filter ExampleThe filter provides a basic security  mechanism for a firewall to determining what traffic passes through the firewall based on IP address details. This protects the secure network from outsiders.
      
  76. Working with Tomcat ServerApache Tomcat is a famous Servlet container developed at  Apache Software  Foundation. This software is released under under the Apache Software License.
      
  77. Use of Cookie in ServletThe cookie class provides an easy way  for servlet to read, create, and manipulate HTTP-style cookies, which allows  servlets to store small amount of data.
      
  78. Send a Response Status in servletAll Response status is defined in HttpServletResponse Class. You can then use constants (response.SC_OK,response.SC_NOT_FOUND etc..) values to return process status to the browser.
           
  79. Read Cookies from ServletsThe Cookie Class provides an easy way to read Cookies. You can use getCookies() method to retrieve all the cookies in your servlet program.
          
  80. Send Cookies in Servlets
    This section illustrates you how to send cookie in servlets.
     Cookies are small bits of  information that a Web server sends to a browser and that the browser returns unchanged after visiting the same page.
          
  81. How to read text file in ServletsIn this example we will use the input stream to read the text from the disk file. The InputStreamReader class is used to read the file in servlets program.
      
  82. Check if parameter exists in servlets requestIn this example we will see how to check is parameter exists in servlets request. In this example given below we have used method getParamaterNames() of the ServletRequest interface  to find all the parameters name in the clients request.
           
  83. Accept Language and Accept Charset in ServletsAccept Language and Accept Char set provides a servlets to determine the language in which it will speak to the clients. A browser sends the user's language to the server using the Accept .
          
  84. Multiple Drop Down Menu UsingIn this Example we can Add and Update the Details of Employee using Servlet. We create four file employee.jsp, viewdata.jsp, EmployeeAdd.java and viewdata.java.
         
  85. Refresh a Web Page Using In ServletIn this simplified example we develop an application to Refresh a web Page using Servlet. We create two file timer.html and timer.java.
      
  86. How to get client's address in a servlet
    This is detailed java code to get client's address in a servlet. In this example we have used method getremoteAddr() of the ServletRequest interface which returns IP address of the client in the string format.
       
  87. Search from Database In ServletIn this section, we have developed an Employee Search application. We created three filesearch.jsp, viewSearch.jsp and Search.java.
     
  88. Header Information available from the client in ServletWhen a HTTP client sends a request, generally GET or POST method is specified. It can send a number of headers.
     
  89. ServletContextListener with Timer
    In this section, you will learn how to use timer with ServletContextListener to run code snippet after every 1 minute immediate after the application run. In the below eaxmple, we are usingServletContextListener with timer to run code after every 1 min. ServletContextListener  immediately starts after code execution. And the Timer class of java.util.Timer is used inside contextInitialized() function, which runs the code after every 1 minute.

jsp database connection

[tutorial] Database Connection in JSP




have I told you that I am both a Programming teacher in Vocational High School and Lecturer in one of college in town. So, now in vocational high school we are in the second semester this year and based on the teaching subject that shared among the teachers, I -again- assigned to teach Java Server Page. I am a Web-Based-Application freak and I love web Programming. Web Programming allow me make the Program and designed the page at the same time. but I am more like a PHP Girl rather than a Java Woman, and I don’t want to cheat him… I don’t know, it isn’t like I hate Java, I just not so get along with him…. sorry Mr. Java.
But if the boss said that I have to teach it, so be it. When the First semester of the third class was learn about the basic of JSP, now this semester I will connect their application with the Database.
Application you might need :
  1. Netbeans ( I used Netbeans IDE 7.2.1 )
  2. XAMPP ( I used XAMPP 1.7.3 )
    note here that, if you found tomcat in this version of XAMPP, just leave it alone. we won’t disturb him. we need this XAMPP just for their MySQL Database. maybe you wondering why didn’t I install another version of GUI MySQL. The reason is, this XAMPP and every application inside is package that I used for all of my PHP application.
  3. Browser ( it’s obvious )
  4. Mysql Connector for Java you can download here
I assume you already started the mysql database and already installed all of the application above. Fasten your seat belt Ladies and Gentlemen, we’ll go for a ride….
  1. Start your netbeans application
  2. Make your new Project, Click File-New Project
    Pict 1
    Pict 1
  3. Choose Java Web-Web Application when ‘New Project’ Windows appear then click Next.
    Pict 2
    Pict 2
  4. Fill the name of your new Project and define the place where you want to place your project. Click Next
    Pict 3
    Pict 3
  5. the Next Page is Server setting, just leave them alone if you don’t have another web server you want to use. I use the default setting and just click next to the next page.
    Pict 4
    Pict 4
  6. Just Click finish in this Page
    Pict 5
    Pict 5
  7. When it’s done, Look at the up left panel of your workspace, click the ‘+’ symbol near your project name, then right click on a library tree, Click ‘Add JAR/Folder…’ button
    Pict 6
    Pict 6
  8. When the windows is open, locate your ‘mysql connector’ Library you donwload and click ‘Open’
    Pict 7
    Pict 7
    Your left panel will be like like this, after you add the mysql connector
    Pict 8
    Pict 8
  9. Then you need to make the connection in order to connect to the database you wish. so, Click ‘Service’ tab menu
    Pict 9
    Pict 9
  10. Right Click on ‘Database’ tree menu and choose ‘New Connection…’
    Pict 10
    Pict 10
  11. In the first Page of ‘New Connection Wizard’ you have to define the driver you will use. I choose ‘Mysql (Connector / J driver)’ then click next
    Pict 11
    Pict 11
  12. Fill the Host name, username and password of your database then click ‘Test Connection’ button.
    Pict 12
    Pict 12
    when the ‘connection succeeded’ information has been appear, means that you can click the Finish button
    Pict 13
    Pict 13
  13. back to your Database tree menu, several database name will appear according to your current database. Right click on the database you will use, choose ‘Connect’
    Pict 15
    Pict 15
  14.  and the last part is, Write the code. I used the following syntax to view the record from my ‘siswa’ table from database ‘osis’
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<%@ page import=”java.sql.*” %>
<%@ page import=”java.io.*” %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>JSP Page</title>
</head>
<body>
<%
try {
String Host = “jdbc:mysql://localhost:3306/osis”;
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
Class.forName(“com.mysql.jdbc.Driver”);
connection = DriverManager.getConnection(Host, “root”, “”);
statement = connection.createStatement();
String Data = “select * from pil”;
rs = statement.executeQuery(Data);
%>
<TABLE border=”1″>
<tr  width=”10″ bgcolor=”#9979″>
<td>Kode</td>
<td>Nama</td>
<td>Count</td></tr>
<%
while (rs.next()) {
%>
<TR>
<TD><%=rs.getString(“kd”)%></TD>
<TD><%=rs.getString(“nama”)%></TD>
<TD><%=rs.getString(“count”)%></TD>
</TR>
<%   }    %>
</table>
<%
rs.close();
statement.close();
connection.close();
} catch (Exception ex) {
out.println(“Can’t connect to database.”);
}
%>
<h1>Hello World!</h1></body>
</html>

jsp information

This section will help you in to understand What is JSP ?, What are the features of JSP ?, What is a JSP page ?, Why use JSP?, Life cycle of JSP, Versions of JSP, Implicit objects in JSP, JSP scriptlets, JSP directives, Actions in JSP. 







JSP Tutorial


In this section you will learn about the JSP.
This section will help you in to understand What is JSP What are the features of JSP ?, What is a JSP page ?, Why use JSP?, Life cycle of JSPVersions of JSPImplicit objects in JSPJSP Scriptlets, JSP directivesActions in JSP.
JSP is an acronym for JavaServer Pages. JSP is a technology that facilitate web developer to build web applications using both static and dynamic content. In a JSP page a web developer can write HTML code along with the Java Code. Java codes are written on the JSP page within JSP tag <% %>, codes written inside these tags are executed inside the Java Servlet technology.


Features of JSP technology are as follows :
  • In JSP developers can insert java code directly into jsp file, due to which the web application's development as well as its maintenance becomes very simple and easy.
  • JSP pages are a text based documents where processing of a request and constructing of its response is described.
  • JSP supports the expression language using which server-side objects can be accessed.
What is a JSP Page ?
A JSP page is a text document which may contain the static data and dynamic contents. Static data can be in any text based format for example HTML, XML, SVG, WML whereas, dynamic contents can be constructed using JSP elements. File extension of a source file of JSP page is .jsp and the file extension of source file of fragment JSP page is .jspf. In a JSP page JSP elements can be used in either of the following two ways first way is using the Standard syntax and the second is using XML syntax.
Why use JSP?
In comparison to Servlet there are various advantages of using JSP.
  • JSP allows to use all the dynamic capabilities of Java Servlet technology as well as it provides the implicit objects, predefined JSP tags, the support of expression language.
  • In a JSP page business and presentation logic can be separated.
  • Re-deploy of project is not required if a JSP page is modified.
  • In JSP pages build process is performed automatically.
There is a Life cycle of JSP page which follows the following phases :
  • Translation & Compilation
  • Class loading (JSP page's Servlet class loading)
  • Instantiation (Instance of the Servlet class is instantiated)
  • Initialization (Instance of the Servlet is initializes by invoking jspInit method)
  • _jspService method is invoked by the container to pass request and response objects.
  • jspDestroy method is called by the container to destroy the JSP page's Servlet.
There are nine(9) Implicit objects in JSP these are as follows :
  • request
  • response
  • out
  • session
  • application
  • config
  • pageContext
  • page
  • exception
JSP supports three types of scriptlet elements these are as follows :
  • scriptlet tag : <% %> called scriptlet tag. Java code is written within the scriptlet in JSP page.
  • expression tag : <%=  %> called expression tag. Code written within the expression tag is written to the output stream.
  • declaration tag : <%!  %> called declaration tag. Within declaration tag fields and methods is to be declared.
JSP directives
JSP supports three types of directive elements these are as follows :
  • page directive : page directive is used to provide the information to JSP page
  • include directive : include directive is used to include a file in the JSP page.
  • taglib directive : taglib directive is used to use the custom tags in the JSP pages.
Action tags or elements in JSP are defined for performing a specific tasks. There are various of actions tags are defined in JSP these are as follows:
  • jsp:include
  • jsp:param
  • jsp:forward
  • jsp:plugin
  • jsp:fallback
  • jsp:setProperty
  • jsp:getProperty
  • jsp:useBean

java information



  • 1. JAVA TUTORIAL Write Once, Run Anywhere
  • 2. JAVA - GENERAL Java is: platform independent programming language similar to C++ in syntax similar to Smalltalk in mental paradigm Pros: also ubiquitous to net Cons: interpreted, and still under development (moving target)
  • 3. JAVA - GENERAL Java has some interesting features: automatic type checking, automatic garbage collection, simplifies pointers; no directly accessible pointer to memory, simplified network access, multi-threading!


  • 4. HOW IT WORKS…! Compile-time Environment Compile-time Environment Java Bytecodes move locally or through network Java Source (.java) Java Compiler Java Bytecode (.class ) Runtime System Class Loader Bytecode Verifier Java Class Libraries Operating System Hardware Java Virtual machine Java Interpreter Just in Time Compiler

  • 5. HOW IT WORKS…! Java is independent only for one reason: Only depends on the Java Virtual Machine (JVM), code is compiled to bytecode , which is interpreted by the resident JVM, JIT (just in time) compilers attempt to increase speed.












6. JAVA - SECURITY Pointer denial - reduces chances of virulent programs corrupting host, Applets even more restricted - May not run local executables, Read or write to local file system, Communicate with any server other than the originating server.




  • 7. OBJECT-ORIENTED Java supports OOD Polymorphism Inheritance Encapsulation Java programs contain nothing but definitions and instantiations of classes Everything is encapsulated in a class!



  • 8. JAVA ADVANTAGES Portable - Write Once, Run Anywhere Security has been well thought through Robust memory management Designed for network programming Multi-threaded (multiple simultaneous tasks) Dynamic & extensible (loads of libraries) Classes stored in separate files Loaded only when needed
  • 9. BASIC JAVA SYNTAX




  • 10. PRIMITIVE TYPES AND VARIABLES boolean, char, byte, short, int, long, float, double etc. These basic (or primitive) types are the only types that are not objects (due to performance issues). This means that you don’t use the new operator to create a primitive variable. Declaring primitive variables: float initVal; int retVal, index = 2; double gamma = 1.2, brightness boolean valueOk = false;
  • 11. INITIALISATION If no value is assigned prior to use, then the compiler will give an error Java sets primitive variables to zero or false in the case of a boolean variable All object references are initially set to null An array of anything is an object Set to null on declaration Elements to zero false or null on creation
  • 12. DECLARATIONS int index = 1.2; // compiler error boolean retOk = 1; // compiler error double fiveFourths = 5 / 4; // no error! float ratio = 5.8f; // correct double fiveFourths = 5.0 / 4.0; // correct 1.2f is a float value accurate to 7 decimal places. 1.2 is a double value accurate to 15 decimal places.
  • 13. ASSIGNMENT All Java assignments are right associative int a = 1, b = 2, c = 5 a = b = c System.out.print( “ a= “ + a + “b= “ + b + “c= “ + c) What is the value of a, b & c Done right to left: a = (b = c);
  • 14. BASIC MATHEMATICAL OPERATORS * / % + - are the mathematical operators * / % have a higher precedence than + or - double myVal = a + b % d – c * d / b; Is the same as: double myVal = (a + (b % d)) – ((c * d) / b);
  • 15. STATEMENTS & BLOCKS A simple statement is a command terminated by a semi-colon: name = “Fred”; A block is a compound statement enclosed in curly brackets: { name1 = “Fred”; name2 = “Bill”; } Blocks may contain other blocks
  • 16. FLOW OF CONTROL Java executes one statement after the other in the order they are written Many Java statements are flow control statements: Alternation: if, if else, switch Looping: for, while, do while Escapes: break, continue, return


  • 17. IF – THE CONDITIONAL STATEMENT The if statement evaluates an expression and if that evaluation is true then the specified action is taken if ( x < 10 ) x = 10; If the value of x is less than 10, make x equal to 10 It could have been written: if ( x < 10 ) x = 10; Or, alternatively: if ( x < 10 ) { x = 10; }


  • 18. RELATIONAL OPERATORS == Equal (careful) != Not equal >= Greater than or equal <= Less than or equal > Greater than < Less than
  • 19. IF… ELSE The if … else statement evaluates an expression and performs one action if that evaluation is true or a different action if it is false. if (x != oldx) { System.out.print(“x was changed”); } else { System.out.print(“x is unchanged”); }
  • 20. NESTED IF … ELSE if ( myVal > 100 ) { if ( remainderOn == true) { myVal = mVal % 100; } else { myVal = myVal / 100.0; } } else { System.out.print(“myVal is in range”); }
  • 21. ELSE IF Useful for choosing between alternatives: if ( n == 1 ) { // execute code block #1 } else if ( j == 2 ) { // execute code block #2 } else { // if all previous tests have failed, execute code block #3 }
  • 22. A WARNING… WRONG! if( i == j ) if ( j == k ) System.out.print( “ i equals k”); else System.out.print( “ i is not equal to j”); CORRECT! if( i == j ) { if ( j == k ) System.out.print( “ i equals k”); } else System.out.print(“i is not equal to j”); // Correct!
  • 23. THE SWITCH STATEMENT switch ( n ) { case 1: // execute code block #1 break; case 2: // execute code block #2 break; default: // if all previous tests fail then //execute code block #4 break; }
  • 24. THE FOR LOOP Loop n times for ( i = 0; i < n; n++ ) { // this code body will execute n times // ifrom 0 to n-1 } Nested for: for ( j = 0; j < 10; j++ ) { for ( i = 0; i < 20; i++ ){ // this code body will execute 200 times } }
  • 25. WHILE LOOPS while(response == 1) { System.out.print( “ID =” + userID[n]); n++; response = readInt( “Enter “); } What is the minimum number of times the loop is executed? What is the maximum number of times?
  • 26. DO {… } WHILE LOOPS do { System.out.print( “ID =” + userID[n] ); n++; response = readInt( “Enter ” ); }while (response == 1); What is the minimum number of times the loop is executed? What is the maximum number of times?
  • 27. BREAK A break statement causes an exit from the innermost containing while , do , for or switch statement. for ( int i = 0; i < maxID, i++ ) { if ( userID[i] == targetID ) { index = i; break; } } // program jumps here after break
  • 28. CONTINUE Can only be used with while, do or for. The continue statement causes the innermost loop to start the next iteration immediately for ( int i = 0; i < maxID; i++ ) { if ( userID[i] != -1 ) continue; System.out.print( “UserID ” + i + “ :” + userID); }
  • 29. ARRAYS Am array is a list of similar things An array has a fixed: name type length These must be declared when the array is created. Arrays sizes cannot be changed during the execution of the code
  • 30. myArray has room for 8 elements the elements are accessed by their index in Java, array indices start at 0 3 6 3 1 6 3 4 1 myArray = 0 1 2 3 4 5 6 7
  • 31. DECLARING ARRAYS int myArray[]; declares myArray to be an array of integers myArray = new int[8]; sets up 8 integer-sized spaces in memory, labelled myArray[0] to myArray[7] int myArray[] = new int[8]; combines the two statements in one line


  • 32. ASSIGNING VALUES refer to the array elements by index to store values in them. myArray[0] = 3; myArray[1] = 6; myArray[2] = 3; ... can create and initialise in one step: int myArray[] = {3, 6, 3, 1, 6, 3, 4, 1};
  • 33. ITERATING THROUGH ARRAYS for loops are useful when dealing with arrays: for (int i = 0; i < myArray.length; i++) { myArray[i] = getsomevalue(); }
  • 34. ARRAYS OF OBJECTS So far we have looked at an array of primitive types. integers could also use doubles, floats, characters… Often want to have an array of objects Students, Books, Loans …… Need to follow 3 steps.
  • 35. DECLARING THE ARRAY 1. Declare the array private Student studentList[]; this declares studentList 2 .Create the array studentList = new Student[10]; this sets up 10 spaces in memory that can hold references to Student objects 3. Create Student objects and add them to the array: studentList[0] = new Student(&quot;Cathy&quot;, &quot;Computing&quot;);
  • 36. JAVA METHODS & CLASSES
  • 37. CLASSES ARE OBJECT DEFINITIONS OOP - object oriented programming code built from objects Java these are called classes Each class definition is coded in a separate .java file Name of the object must match the class/object name



  • 38. THE THREE PRINCIPLES OF OOP Encapsulation Objects hide their functions ( methods ) and data ( instance variables ) Inheritance Each subclass inherits all variables of its superclass Polymorphism Interface same despite different data types car auto- matic manual Super class Subclasses draw() draw()
  • 39. SIMPLE CLASS AND METHOD Class Fruit { int grams ; int cals_per_gram ; int total_calories () { return( grams * cals_per_gram ); } }
  • 40. METHODS A method is a named sequence of code that can be invoked by other Java code. A method takes some parameters, performs some computations and then optionally returns a value (or object). Methods can be used as part of an expression statement. public float convertCelsius(float tempC) { return( ((tempC * 9.0f) / 5.0f) + 32.0 ); }
  • 41. METHOD SIGNATURES A method signature specifies: The name of the method. The type and name of each parameter. The type of the value (or object) returned by the method. The checked exceptions thrown by the method. Various method modifiers. modifiers type name ( parameter list ) [throws exceptions ] public float convertCelsius (float tCelsius ) {} public boolean setUserInfo ( int i, int j, String name ) throws IndexOutOfBoundsException {}



  • 42. PUBLIC/PRIVATE Methods/data may be declared public or private meaning they may or may not be accessed by code in other classes … Good practice: keep data private keep most methods private well-defined interface between classes - helps to eliminate errors
  • 43. USING OBJECTS Here, code in one class creates an instance of another class and does something with it … Fruit plum=new Fruit(); int cals; cals = plum.total_calories(); Dot operator allows you to access (public) data/methods inside Fruit class
  • 44. CONSTRUCTORS The line plum = new Fruit(); invokes a constructor method with which you can set the initial data of an object You may choose several different type of constructor with different argument lists eg Fruit(), Fruit(a) ...
  • 45. OVERLOADING Can have several versions of a method in class with different types/numbers of arguments Fruit() {grams=50;} Fruit(a,b) { grams=a; cals_per_gram=b;} By looking at arguments Java decides which version to use
  • 46. JAVA DEVELOPMENT KIT javac - The Java Compiler java - The Java Interpreter jdb - The Java Debugger appletviewer -Tool to run the applets javap - to print the Java bytecodes javaprof - Java profiler javadoc - documentation generator javah - creates C header files
  • 47. STREAM MANIPULATION
  • 48. STREAMS AND I/O basic classes for file IO FileInputStream , for reading from a file FileOutputStream , for writing to a file Example: Open a file &quot;myfile.txt&quot; for reading FileInputStream fis = new FileInputStream(&quot;myfile.txt&quot;); Open a file &quot;outfile.txt&quot; for writing FileOutputStream fos = new FileOutputStream (&quot;myfile.txt&quot;);
  • 49. DISPLAY FILE CONTENTS import java.io.*; public class FileToOut1 { public static void main(String args[]) { try { FileInputStream infile = new FileInputStream(&quot;testfile.txt&quot;); byte buffer[] = new byte[50]; int nBytesRead; do { nBytesRead = infile.read(buffer); System.out.write(buffer, 0, nBytesRead); } while (nBytesRead == buffer.length); } catch (FileNotFoundException e) { System.err.println(&quot;File not found&quot;); } catch (IOException e) { System.err.println(&quot;Read failed&quot;); } } }
  • 50. FILTERS Once a stream (e.g., file) has been opened, we can attach filters Filters make reading/writing more efficient Most popular filters: For basic types: DataInputStream , DataOutputStream For objects: ObjectInputStream , ObjectOutputStream
  • 51. WRITING DATA TO A FILE USING FILTERS import java.io.*; public class GenerateData { public static void main(String args[]) { try { FileOutputStream fos = new FileOutputStream(&quot;stuff.dat&quot;); DataOutputStream dos = new DataOutputStream(fos); dos.writeInt(2); dos.writeDouble(2.7182818284590451); dos.writeDouble(3.1415926535); dos.close(); fos.close(); } catch (FileNotFoundException e) { System.err.println(&quot;File not found&quot;); } catch (IOException e) { System.err.println(&quot;Read or write failed&quot;); } } }
  • 52. READING DATA FROM A FILE USING FILTERS import java.io.*; public class ReadData { public static void main(String args[]) { try { FileInputStream fis = new FileInputStream(&quot;stuff.dat&quot;); DataInputStream dis = new DataInputStream(fis); int n = dis.readInt(); System.out.println(n); for( int i = 0; i < n; i++ ) { System.out.println(dis.readDouble()); } dis.close(); fis.close(); } catch (FileNotFoundException e) { System.err.println(&quot;File not found&quot;); } catch (IOException e) { System.err.println(&quot;Read or write failed&quot;); } } }
  • 53. OBJECT SERIALIZATION Write objects to a file, instead of writing primitive types. Use the ObjectInputStream , ObjectOutputStream classes, the same way that filters are used.
  • 54. WRITE AN OBJECT TO A FILE import java.io.*; import java.util.*; public class WriteDate { public WriteDate () { Date d = new Date(); try { FileOutputStream f = new FileOutputStream(&quot;date.ser&quot;); ObjectOutputStream s = new ObjectOutputStream (f); s.writeObject (d); s.close (); } catch (IOException e) { e.printStackTrace(); } public static void main (String args[]) { new WriteDate (); } }
  • 55. READ AN OBJECT FROM A FILE import java.util.*; public class ReadDate { public ReadDate () { Date d = null; ObjectInputStream s = null; try { FileInputStream f = new FileInputStream (&quot;date.ser&quot;); s = new ObjectInputStream (f); } catch (IOException e) { e.printStackTrace(); } try { d = (Date) s.readObject (); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InvalidClassException e) { e.printStackTrace(); } catch (StreamCorruptedException e) { e.printStackTrace(); } catch (OptionalDataException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println (&quot;Date serialized at: &quot;+ d); } public static void main (String args[]) { new ReadDate (); } }