Você está na página 1de 60

Introduction

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. 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 the year 1991 they make 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
Simple Object Oriented Robust Secure Portable Interpreted High Performance Multithreaded Dynamic

Versions Of Java

250 classes Slow Lots of bugs Applets

500 little faster more capable very popular

2300 much faster powerful J2EE,J2SE,J2ME

3500 more powerful easy known as Tiger

How to download JDK


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

Installation

Microsoft Windows 2000 [Version 5.00.2195] (C) Copyright 1985-2000 Microsoft Corp. C:\Documents and Settings\Administrator>java Usage: java [-options] class [args...] (to execute a class) or java [-options] -jar jarfile [args...] (to execute a jar file) where options include: -client to select the "client" VM -server to select the "server" VM -hotspot is a synonym for the "client" VM [deprecated] The default VM is client. -cp <class search path of directories and zip/jar files> -classpath <class search path of directories and zip/jar files> A ; separated list of directories, JAR archives, and ZIP archives to search for class files. -D<name>=<value> set a system property -verbose[:class|gc|jni] enable verbose output -version print product version and exit -version:<value> require the specified version to run -showversion print product version and continue -jre-restrict-search | -jre-no-restrict-search include/exclude user private JREs in the version search -? -help print this help message -X print help on non-standard options -ea[:<packagename>...|:<classname>] -enableassertions[:<packagename>...|:<classname>] enable assertions -da[:<packagename>...|:<classname>] -disableassertions[:<packagename>...|:<classname>] disable assertions -esa | -enablesystemassertions enable system assertions -dsa | -disablesystemassertions disable system assertions -agentlib:<libname>[=<options>] load native agent library <libname>, e.g. -agentlib:hprof see also, -agentlib:jdwp=help and -agentlib:hprof=help -agentpath:<pathname>[=<options>] load native agent library by full pathname -javaagent:<jarpath>[=<options>] load Java programming language agent, see java.lang.instrument

Open the dos prompt and type javac on the console, it should show this output:

C:\Documents and Settings\Administrator>

Simple Java Program

Oops Concepts
Class Object Methods Inheritance Abstraction Polymorphism Encapsulation

Class,Object & Methods

Anatomy Of Class

Object
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. For example, You might use the Button class to make dozens of different buttons and each button might have its own color , size , shape , label etc. Syntax for the Object : class_name object_name = new class_name();

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.

Example

Program

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 } }

Abstraction
The process of abstraction in Java is used to hide certain details and only show the essential features of the object 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:

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.

Overloading Example

Overriding
An instance method in a subclass with the same signature and returntypes as an instance method in the superclass overrides the superclasss 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.

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

Encapsulation

Constructor

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.

try-catch-finally

Example

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 ; } }
C:\java>java UseOfThisOperator The area of a Rectangle is : 30

" + area)

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 lin e 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(); } } }

Thread States
New Runnable Blocked Waiting Timed waiting Terminated

Applet
It is another type of Java program that used within a web page to add many new features to a web browser.
These are small program used in the programming of instant messaging, chat service, solving some complex calculation and for many other purposes.

Example

JDBC
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) 2) 3) 4) 5) 6) 7) Load the JDBC driver Define the connection url Establish the connection Create a statement object Execute a query or update Process the result Close the connection

Example
package coreservlets; import java.sql.*; 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); 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
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"); } }

JSP
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>

Output

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

Você também pode gostar