Java Seminar Report
Java Seminar Report
On
JAVA
TECHNOLOGY
Submitted To:
Submitted By:
Mr. Rajesh Nishima
Girdhar
(CSE-235/06)
Nitu
(CSE-237/06)
Contents
Introduction to Java
Features of Java
Versions of Java
Downloading and Installation
Simple Java Program
Oops Concepts
Class
Object
Methods
Inheritance
Abstraction
Polymorphism
Encapsulation
Constructors
Exception Handling
This Keyword
Multithreading
Applet
JDBC(Java Database Connectivity)
Servlets
JSP(Java Server Pages)
Introduction to Java
Earlier, C++ was widely used to write object oriented programming languages , however,it was
not a platform independent and needed to be recompiled for each different CPUs. A team of Sun
Microsystems in the guidance of James Goslings decided to develop an advanced programming
language for the betterment of consumer electronic devices. In the year 1991 they make a
platform independent software and named it Oak. But later due to some patent conflicts , it was
renamed as Java and in 1995 the Java 1.0 was officially released to the world.
Features Of Java
1. Simple
We wanted to build a system that could be programmed easily without a lot of esoteric
training and which leveraged today’s standard practice. So even though we found that C++ was
unsuitable, we designed Java as closely to C++ as possible in order to make the system more
comprehensible. Java omits many rarely used, poorly understood, confusing features of C++ that,
in our experience, bring more grief than benefit.
2. Object Oriented
Simply stated, object-oriented design is a technique for programming that focuses on the data (=
objects) and on the interfaces to that object. To make an analogy with carpentry, an “object-
oriented” carpenter would be mostly concerned with the chair he was building, and secondarily
with the tools used to make it; a “non-objectoriented”carpenter would think primarily of his tools.
The object-oriented facilities of Java are essentially those of C++.
3. Robust
Java is intended for writing programs that must be reliable in a variety of ways. Java puts a lot of
emphasis on early checking for possible problems, later dynamic (runtime) checking, and
eliminating situations that are error-prone. . . . The single biggest difference between Java and
C/C++ is that Java has a pointer model that eliminatesthe possibility of overwriting memory and
corrupting data.
4. Secure
Java is intended to be used in networked/distributed environments. Toward that end, a lot of
emphasis has been placed on security. Java enables the construction of virus-free, tamper-free
systems.
5. Portable
Unlike C and C++, there are no “implementation-dependent” aspects of the specification. The
sizes of the primitive data types are specified, as is the behavior of arithmetic on them.
6. Interpreted
The Java interpreter can execute Java bytecodes directly on any machine to which the interpreter
has been ported. Since linking is a more incremental and lightweight process, the development
process can be much more rapid and exploratory.
7. High Performance
While the performance of interpreted bytecodes is usually more than adequate, there are
situations where higher performance is required. The bytecodes can be translated on the fly (at
runtime) into machine code for the particular CPU the application is running on.
8. Multithreaded
[The] benefits of multithreading are better interactive responsiveness and real-time behavior.
9. Dynamic
In a number of ways, Java is a more dynamic language than C or C++. It was designed to adapt to
an evolving environment. Libraries can freely add new methods and instance variables without
any effect on their clients. In Java, finding out runtime type information is straightforward.
Versions Of Java
JDK is a software development program provided by sun Microsystems. Java Development Kit
or JDK comes in Various version and can be downloaded free from the sun Microsystems.
Acronyms:
JDK Java Development Kit
JVM Java virtual machine
Download JDk:
You can download JDK from www.javasoft.com/j2se
Simple Java Program
Oops Concepts
1.Classes
A class is the template or blueprint from which objects are made. Thinking about classes as
cookie cutters. Objects are the cookies themselves. When you construct an object from a class,
you are said to have created an instance of the class.
General form of a class :
A class is declared by use of the class keyword. The classes can get much more complex.The
general form of a class definition is shown as
class class_name
{
type instance-variable1;
type instance-variable2;
type method-name(parameter-list){
//body of method
}
}
2.Objects
Objects are the basic run time entity or in other words object is a instance of a class . An
object is a software bundle of variables and related methods of the special class.
Each object made from a class can have its values for the instance variables of that class.
3. Methods
A class has one or more methods .Methods must be de clared inside the class.Within the curly
braces of a method, write the instructions for how that method should be performed. Method code
is basically a set of statements , and you can think of a method kind of like a function or
procedure.
4.Inheritance
Example :
Interface
Interfaces are similar to classes but they lack instance variables and their methods are
declared without any body.
Any number of classes can implement an interface, also one class can implement any
number of interfaces.
Defining an Interface:
Implementing an interface:
returntype method1(){
//body
returntype method2(){
// body
5.Abstraction
The process of abstraction in Java is used to hide certain details and only show the essential
features of the object. Through the process of abstraction, a programmer hides all but the
relevant data about an object in order to reduce complexity and increase efficiency. In the
same way that abstraction sometimes works in art, the object that remains is a
representation of the original, with unwanted detail omitted. The resulting object itself
can be referred to as an abstraction, meaning a named entity made up of selected
attributes and behavior specific to a particular usage of the originating entity.
Syntax:
6.Polymorphism
It describes the ability of the object in belonging to different types with specific behavior
of each type.
It can be done by two ways:
Overloading
Overriding
Overloading
An overloaded method is just a different method that happens to have the same method
name.
An overloaded method is NOT the same as an overridden method.
The returntype can be different.
The number of parameters can be different.
Datatype of parameters can also be different.
Example
7.Encapsulation
Encapsulation is the concept of hiding the implementation details of a class and allowing access
to the class through a public interface. For this, we need to declare the instance variables of the
class as private or protected.
The client code should access only the public methods rather than accessing the data directly.
Also, the methods should follow the Java Bean's naming convention of set and get.
Encapsulation makes it easy to maintain and modify code. The client code is not affected when
the internal implementation of the code changes as long as the public method signatures are
unchanged. For instance:
To create a new Bicycle object called myBike, a constructor is called by the new operator:
new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields.
Exception Handling
An exception arises in code at runtime.
Exception are a clean way to manage abnormal states.
Exception : mild error which you can handle.
Error: serious errorà cause termination.
An Exception is thrown and then caught.
Exception, that means exceptional errors. Actually exceptions are used for handling errors in
programs that occurs during the program execution. During the program execution if any error
occurs and you want to print your own message or the system message about the error then you
write the part of the program which generate the error in the try{} block and catch the errors
using catch() block. Exception turns the direction of normal flow of the program control and send
to the related catch() block. Error that occurs during the program execution generate a specific
object which has the information about the errors occurred in the program.
How to handle Exceptions?
This keyword
When we declare the name of instance variable and local variables same , This keyword
helps us to avoid name conflicts.
In the example, this.length and this.breadth refers to the instance variable length and
breadth while length and breadth refers to the arguments passed in the method
Example
class Rectangle{
int length,breadth;
void show(int length,int breadth){
this.length=length;
this.breadth=breadth;
}
int calculate(){
return(length*breadth);
}
}
public class UseOfThisOperator{
public static void main(String[] args){
Rectangle rectangle=new Rectangle();
rectangle.show(5,6);
int area = rectangle.calculate();
System.out.println("The area of a Rectangle is : " + area);
}
}
Output:
C:\java>java UseOfThisOperator
The area of a Rectangle is : 30
Multithreading
Example:
Output:
1
2
3
4
5
6
7
8
9
10
Applet
A Java applet is an applet delivered to the users in the form of Java bytecode. Java
applets can run in a Web browser using a Java Virtual Machine (JVM), or
in Sun's AppletViewer, a stand-alone tool for testing applets. Java applets were
introduced in the first version of the Java language in 1995.
Applets are also used to create onlinegame collections that allow players to compete
against live opponents in real-time.
It is simple to make it work on Linux, Windows and Mac OS i.e. to make it cross
platform. Applets are supported by most web browsers
Applets also improve with use: after a first applet is run, the JVM is already running and
starts quickly (JVM will need to restart each time the browser starts fresh).
It can move the work from the server to the client, making a web solution more scalable
with the number of users/clients
The applet naturally supports the changing user state like figure positions on the
chessboard.
Example:
Java Database Connectivity
JDBC is Java application programming interface that allows the Java programmers to access
database management system from Java code. It was developed byJavaSoft, a subsidiary of Sun
Microsystems.
In short JDBC helps the programmers to write java applications that manage these three
programming activities:
1. Load the JDBC driver. To load a driver, you specify the classname of the database driver in
the Class.forName method. By doing so, you automatically create a driver instance and register it
with the JDBC driver manager.
2. Define the connection URL. In JDBC, a connection URL specifies the server host, port, and
database name with which to establish a connection.
3. Establish the connection. With the connection URL, username, and password, a network
connection to the database can be established. Once the connection is established, database
queries can be performed until the connection is closed.
4. Create a Statement object. Creating a Statement object enables you to send queries and
commands to the database.
5. Execute a query or update. Given a Statement object, you can send SQL statements to the
database by using the execute, executeQuery, executeUpdate, or executeBatch methods.
6. Process the results. When a database query is executed, a ResultSet is returned. The ResultSet
represents a set of rows and columns that you can process by calls to next and various getXxx
methods.
7. Close the connection. When you are finished performing queries and processing results, you
should close the connection, releasing resources to the database.
Example:
package coreservlets;
import java.sql.*;
/** A JDBC example that connects to the MicroSoft Access sample
* Northwind database, issues a simple SQL query to the
* employee table, and prints the results.
*/
public class NorthwindTest {
public static void main(String[] args) {
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String url = "jdbc:odbc:Northwind";
String username = ""; // No username/password required
String password = ""; // for desktop access to MS Access.
showEmployeeTable(driver, url, username, password);
}
/** Query the employee table and print the first and
* last names.
*/
public static void showEmployeeTable(String driver,
String url,
String username,
String password) {
try {
// Load database driver if it's not already loaded.
Class.forName(driver);
// Establish network connection to database.
Connection connection =
DriverManager.getConnection(url, username, password);
System.out.println("Employees\n" + "==========");
// Create a statement for executing queries.
Statement statement = connection.createStatement();
String query =
"SELECT firstname, lastname FROM employees";
// Send query to database and store results.
ResultSet resultSet = statement.executeQuery(query);
// Print results.
while(resultSet.next()) {
System.out.print(resultSet.getString("firstname") + " ");
System.out.println(resultSet.getString("lastname"));
}
connection.close();
}
catch(ClassNotFoundException cnfe) {
System.err.println("Error loading driver: " + cnfe);
}
catch(SQLException sqle) {
System.err.println("Error with connection: " + sqle);
}
}
}
Output:
Listing 17.
Prompt> java coreservlets.NorthwindTest
Employees
==========
Nancy Davolio
Andrew Fuller
Janet Leverling
Margaret Peacock
Steven Buchanan
Michael Suyama
Robert King
Laura Callahan
Anne Dodsworth
Servlet
Servlets are server side components that provide a powerful mechanism for developing server
side programs.
Role of servlet :
Lifecycle of Servlet:
init() – the init() function is called when the servlet is initialized by the server. This often
happens on the first doGet() or doPut() call of the servlet.
destroy() – this function is called when the servlet is being destroyed by the server,
typically when the server process is being stopped.
doGet() – the doGet() function is called when the servlet is called via an HTTP GET.
doPost() – the doPost() function is called when the servlet is called via an HTTP POST.
Example:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
Output:
Java Server Pages
JavaServer Pages (JSP) is a Java-based technology that is run on a server to facilitate the
processing of Web-based requests. Many of the Web sites that you visit daily may be
using JSP to format and display the data that you see.
Specifically, JSP provides the following benefits:
❑ A templating mechanism whereby Java-based logic can be embedded within HTML
pages
❑ Automatic detection and recompilation whenever the JSP is changed
Unlike servlets, JSPs are not written in the Java programming language (although some
JSPs may contain embedded Java coding). Instead, they are text-based templates.
JSP runs on server like apache tomcat.
Example:
Output:
Scripting Elements In JSP:
Scripting elements are embedded code, typically in the Java programming language, within a JSP
page.
There are three different types of scripting elements:
❑ Declarations
❑ Scriptlets
❑ Expressions
Declarations are Java code that is used to declare variables and methods. They appear as
follows:
<%! ... Java declaration goes here... %>
Expressions are Java expressions that yield a resulting value. When the JSP is executed,
this value is converted to a text string and printed at the location of the scripting element.
Expression scripting elements appear as:
<%= ... Java expression goes here ... %>