Detailed Report On JAVA



Java is a programming language originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform.
Java is a high-level object-oriented programming language developed by Sun Microsystems.It was only developed keeping in mind the consumer electronics and communication equipments. It came into existence as a part of web application, web services and a platform independent programming language in 1990s.
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.
It promised "Write Once, Run Anywhere" (WORA), providing no-cost run-times on popular platforms.

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.

Downloading  and  Installation
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.

Syntax for the Object : 
class_name object_name = new class_name();

To work with OOP, you should be able to identify three key characteristics of objects:
• The object’s behavior—What can you do with this object, or what methods can you apply to it?
• The object’s state—How does the object react when you apply those methods?
• The object’s identity—How is the object distinguished from others that may have the same behavior and state?

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.

public class class_name
{
            returntype method_name()
            {
                        //statements;
            }
}

4.Inheritance

ü  When one class inherits from another , it is called Inheritance.
ü  The class which is inherited is called superclass  and the class which inherits is called
subclass.
ü  So we can say that subclass extends  superclass  but subclass can add new methods and instance variables of its own and it can override the methods of superclass.

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.
ü  So , by implementing many interfaces in a same class , we can use the concept of multiple inheritance.
ü  All the methods in an interface are public.
To make a class implement an interface , we carry out 2 steps:
1.Declare that class intends to implement the given interface.
2.Supply definition for all methods in the interface.

Defining an Interface:
access modifier  interface  name{
returntype  method1(parameter list);
returntype method2(parameter list);
}

Implementing an interface:
access modifier  class  classname  implements  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.

ü  An abstract class has no use , no value , no purpose in life unless it is extended.
ü  An abstract class means that nobody can ever make a new instance of that class.

Syntax:

            abstract public class canine extends Animal
            {
                        Public void roam()
                        {
                        }
            }

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

public class overloads{
            String uniqueID;
            public int addNums(int a,int b){
                        return a+b;
            }
            public  double addNums(double a , double b){
                        return a+b;
            }
}
Overriding

ü  An instance method in a subclass with the same signature and returntypes as an instance method in the superclass overrides the siperclass’s method.
ü  The overriding method has same name , numer  and types of parameters and return types as the method it overrides.
ü  If a subclass defines a method with same signature as a class method in the superclass , the method in subclass hides the one in superclass.

public class Animal {
            public static void testClassMethod() {
                        System.out.println(“The class method in Animal”);
            }
            public  void testInstanceMethod() {
                        System.out.println(“The instance method in Animal”);
            }
}

Public class Cat extends Animal{
            Public static void testClassMethod(){
                        System.out.println(“The Class Method in Cat”);
            }
            Public void testInstanceMethod(){
                        System.out.println(“The Instance method in Cat.”);
            }

            Public static void main(String args[]){
                        Cat  mycat= new Cat();
                        Animal  myanimal= mycat();
                        Animal.testClassMethod();
                        Myanimal.testInsatnceMethod();
            }
}


The cat class overrides the instance method in Animal.

The Output from this program is as follows:

                        The class method in Animal.
                        The instance method in Cat.

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:

public class Employee
{
private float salary;
public float getSalary()
{
return salary;
}
public void setSalary(float salary)
{
this.salary = salary;

Constructor

A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. For example, Bicycle has one constructor:

public Bicycle(int startCadence, int startSpeed, int startGear) {
               gear = startGear;
               cadence = startCadence;
               speed = startSpeed;
}

To create a new Bicycle object called myBike, a constructor is called by the new operator:

Bicycle myBike = new Bicycle(30, 0, 8);

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.

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

ü  Multithreaded programs extend the idea of multitasking.
ü  Individual programs will appear to do multiple tasks at the same time . Each task is called a thread.
ü  Programs that can run more than one thread at once are said to be multithreaded.
ü  Process speed can be increased by using threads because the thread can stop or suspend a specific running process and start or resume the suspended processes.

Example:

public class Threads{
  public static void main(String[] args){
    Thread th = new Thread();
    System.out.println("Numbers are printing line by line after 5 seconds : ");
    try{
      for(int i = 1;i <= 10;i++)
      {
        System.out.println(i);
        th.sleep(5000);
      }
    }
    catch(InterruptedException e){
      System.out.println("Thread interrupted!");
      e.printStackTrace();
    }
  }
}

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.

A Java applet can have any or all of the following advantages:

ü  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.

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. It helps us to connect to a data source, like a database.
2. It helps us in sending queries and updating statements to the database and
3. Retrieving and processing  the results received from the database in terms of answering to your query.

How to use JDBC?

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.

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 :

ü  Read explicit data sent by client(form data).
ü  Read implicit data sent by client(request header).
ü  Generate the results.
ü  Send the explicit data back to client.
ü  Send the implicit data back to client.

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.

POSTs are a good way to get input from HTML forms.

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");
}
}

 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:

<%@ taglib prefix=”tags” tagdir=”/WEB-INF/tags” %>
<html>
<head>
<title>Presenting JSP 2.0</title>
</head>
<body>
<h1>My First JSP 2.0 Template</h1>
<hr>
<p>I am so excited, I want to scream “<tags:helloWorld/> <tags:helloWorld/>
<tags:helloWorld/>”</p>
</body>
</html>

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... %>

ü  Scriptlets are arbitrary Java code segments. They appear as follows:
            <% ... Java code 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 ... %>

No comments:

Post a Comment

leave your opinion