Vous êtes sur la page 1sur 71

WELCOME

TO KGISL

JAVA

What is JAVA?
A high level Programming Language. Java was developed by a group of people at Sun

Microsystems, Inc. in 1991.

Original need for the language. Redefined need. Difference with the Native language C .

Why JAVA?
4

Object Oriented

Simple & Secure


Architecture Neutral Portable & Robust

Interpreted
High Performance Distributed

Write Once; Run Anywhere, any time, forever

Dynamic
Multi-threaded AWT & Event Handling

Heart of JAVA

Installing JAVA
Download the Java Development Kit (JDK) for your

platform. (Its free)


Run the .exe file to install java on your machine.

(or) Follow the instructions given.

Setting Path

Start Control Panel System Advanced Click on Environment Variables, under System Variables, find PATH, and click on it. In the Edit windows, modify PATH by adding the location of the class to the value for PATH. If you do not have the item PATH, you may select to add a new variable and add PATH as the name and the location of the class as the value. Close the window. (Or) In command prompt set classpath=%path%;.; (Or) set path=location of class;

Compilation & Execution


To Compile
javac

xxx.java

To Execute
java

xxx

Language Fundamentals
Tokens In a Java program, all characters are grouped into symbols called tokens.

tokens identifier

| keyword | separator | operator | literal | comment

Elements

Identifiers: names the programmer chooses Keywords: names already in the programming language Separators (also known as punctuators): punctuation characters and paired-delimiters Operators: symbols that operate on arguments and produce results

Literals (specified by their type)


Numeric: int,float and double Logical: boolean Textual: char and String Reference: null

Comments Line // Block /*

*/

Data Types

There are two data types available in Java:

Primitive Data Types


Reference/Object Data Types

Operator

An operator is a symbol (+,-,*,/) that directs the computer to perform certain mathematical or logical manipulations and is usually used to manipulate data and variables

Types
1.

2.
3. 4.

5.
6. 7.

8.

Arithmetic operators Relational operators Logical operators Assignment operators Increment and decrement operators Conditional operators Bitwise operators Special operators

Control Statements
Selection Statements if, if-else, if-else-if ladder, nested if-else switch-case Iteration Statements while do-while for Nested loops Jump Statements break continue return

First JAVA Program


public class First { public static void main(String args[]) { System.out.println(Java is my passion); } }

What all are Object?


Tangible Things Roles

Incidents
Interactions Specifications

as a car, printer, ... as employee, boss, ... as flight, overflow, ... as contract, sale, ... as colour, shape,

KGiSL - iTech

What is Object?
an object represents an

An object is like a black box. The internal details are hidden.

individual, identifiable item, unit, or entity, either real or abstract, with a well-defined role in the problem domain. Or An "object" is anything to which a concept applies. Etc.

Classes
The general form of a class definition is shown here:
class ClassName { type instance-variable1; // ... type instance-variableN; type methodName1(parameter-list) { // body of method } // ... type methodNameN(parameter-list) { // body of method } }

Elements of Classes
variables. The code is contained within methods. Collectively, the methods and variables defined within a class are called members of the class. Example: class Vehicle { int passengers; // number of passengers int fuelcap; // fuel capacity in gallons int mpg; // fuel consumption in miles per gallon // Display the range. void range() { System.out.println("Range is " + fuelcap * mpg); }
The data, or variables, defined within a class are called instance

Creating Objects
Vehicle minivan; /* declare reference to

object */ minivan = new Vehicle(); /* allocate a Vehicle object */ (or)


Vehicle minivan = new Vehicle(); /*

create a Vehicle object called minivan*/ minivan.fuelcap= 16; /* Accessing the member of the Vehicle class */

Example
class Vehicle { int passengers; // number of passengers int fuelcap; // fuel capacity in gallons int mpg; // fuel consumption in miles per gallon Vehicle(int p, int f, int m) { passengers = p; fuelcap = f; mpg = m; } // Display the range. void range() { System.out.println("Range is " + fuelcap * mpg); } }

class AddMeth { public static void main(String args[]) { Vehicle minivan = new Vehicle(); Vehicle sportscar = new Vehicle(2,14,12); // assign values to fields in minivan minivan.passengers = 7; minivan.fuelcap = 16; minivan.mpg = 21; System.out.print("Minivan can carry " + minivan.passengers +". "); minivan.range(); // display range of minivan System.out.print("Sportscar can carry " + sportscar.passengers +". "); sportscar.range(); // display range of sportscar. } }

static keyword
class StaticDemo { int x; // a normal instance variable static int y; // a static variable } class SDemo { public static void main(String args[]) { StaticDemo ob1 = new StaticDemo(); StaticDemo ob2 = new StaticDemo(); ob1.x = 10; ob2.x = 20; System.out.println("Of course, ob1.x and ob2.x " + "are independent."); System.out.println("ob1.x: " + ob1.x + "\nob2.x: " + ob2.x);

/* Each object shares one copy of


a static variable. */ System.out.println("The static variable y is shared.");

ob1.y = 19;
System.out.println("ob1.y: " + ob1.y + "\nob2.y: " + ob2.y); System.out.println("The static variable y can be" + " accessed through its class."); StaticDemo.y = 11; /* Can refer to y through class name */ System.out.println("StaticDemo.y: " + StaticDemo.y + "\nob1.y: " + ob1.y + "\nob2.y: " + ob2.y); } }

Array Variables
Declaration type var-name[ ]; //E.g: int arr[ ]; Memory Allocation array-var = new type[size]; // arr=new int[5]; Types: Single and Multi-Dimensional Array Jagged Array- Different column sized array Alternative Array Declaration int a[ ] = new int[5]; int[ ] a = new int[5];

Using Command Line Arguments


A command-line argument is the information that directly

follows the programs name on the command line when it is executed. They are stored as strings in the String array passed to main( ). Example:
class CommandLine { public static void main(String args[]) { for(int i=0; i<args.length; i++) System.out.println("args["+i+"]:"+ args[i]); } }

Try executing this program, as shown here: java CommandLine this is a test 100 -1

Inheritance
Using inheritance, you can create a general class

that defines traits common to a set of related items. This class can then be inherited by other, more specific classes, each adding those things that are unique to it. A class that is inherited is called a superclass. The class that does the inheriting is called a subclass.

Types of Inheritance
Single Inheritance
A

Multi Level Inheritance


A B

Hierarchal Inheritance
A B D E B E

Multiple Inheritance
A B C A C F

Hybrid Inheritance
D

Polymorphism
Overloading In Java it is possible to define two or more methods within the same class that share the same name, as long as their return type and parameter declarations(signature) are different.

Overriding In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass.

Abstract methods
30

An abstract method is created by specifying the abstract type modifier. An abstract method contains no body and is, therefore, not implemented by the superclass. Thus, a subclass must override it The abstract modifier can be used only on normal methods It cannot be applied to static methods or to constructors. To declare an abstract method, use this general form:
abstract type name(parameter-list); Ex: abstract void moveTo(int deltaX, int deltaY);

Abstract class
31

Any class that contains one or more abstract methods

must also be declared abstract.


To declare a class abstract, you simply use the abstract

keyword in front of the class keyword at the beginning of the class declaration.
An abstract class cannot be directly instantiated, but can

be inherited.
Any subclass of an abstract class must either implement

all of the abstract methods in the superclass, or be itself declared abstract.

String Class
String is probably the most commonly used

class in Javas class library. Every string that created is actually an object of type String. Even string constants are actually String objects.
String myString = "this is a test";

Java defines one operator for String objects: +.


String myString = "I" + " like " + "Java.";

Packages
Packages are containers for classes that are used to keep the

class name space compartmentalized.

The package is both a naming and a visibility control

mechanism.

You can define classes inside a package that are not accessible by

code outside that package.

You can also define class members that are only exposed to other

members of the same package.

This is the general form of the package statement:

package pkg;

Visibility Level
34

Private
Same class Yes

No Modifier
Yes

Protected Public
Yes Yes

Same package subclass


Same package non-subclass Different package subclass

No
No No

Yes
Yes No

Yes
Yes Yes

Yes
Yes Yes

Different package non-subclass

No

No

No

Yes

Note: A class has only two possible access levels default and public.

Interfaces
one interface, multiple methods
Defines what a class must do but not how it will do it. Using the keyword interface, you can fully abstract a

class interface from its implementation. Once it is defined, any number of classes can implement an interface. Also, one class can implement any number of interfaces.

Java I/O
Java does provide strong, flexible support for I/O as it

relates to files and networks. Javas I/O system is cohesive and consistent. Java programs perform I/O through streams. A stream is an abstraction that either produces or consumes information. Input stream can abstract many different kinds of input: from a disk file, a keyboard, or a network socket. Output stream may refer to the console, a disk file, or a network connection. Java implements streams within class hierarchies defined in the java.io package.

Types of Streams
37

Java 2 defines two types of streams


Byte

Streams Character Streams

Byte Streams
38

Byte streams provide a convenient means for handling

input and output of bytes.


Byte streams are defined by using two class hierarchies. At the top are two abstract classes: InputStream and

OutputStream.
The abstract classes InputStream and OutputStream

define several key methods that the other stream classes implement.
Two of the most important are read( ) and write( ).

Character Streams
39

Character streams provide a convenient means for

handling input and output of characters.


Character streams are defined by using two class

hierarchies.
At the top are two abstract classes, Reader and Writer. The abstract classes Reader and Writer define several

key methods that the other stream classes implement.


Two of the most important methods are read( ) and

write( ).

The Predefined Streams


40

System Class Stream Variables in, out, err System.out refers to the standard output stream.

System.in refers to standard input stream.


System.err refers to the standard error stream. System.in is an object of type InputStream;

System.out and System.err are objects of type PrintStream.

Console Input Using Character Streams


41

The best class for reading console input is

BufferedReader, which supports a buffered input stream.


Use InputStreamReader, which converts bytes to

characters.
To obtain an InputStreamReader object, use the constructor

shown here:

InputStreamReader(InputStream inputStream)

Since System.in refers to an object of type InputStream,

it can be used for inputStream.


To construct a BufferedReader use the constructor shown

here:

BufferedReader(Reader inputReader)

Exception Handling
An exception is an error that occurs at run time. Exception handling subsystem streamlines error

handling by allowing your program to define a block of code, called an exception handler, that is executed automatically when an error occurs.

Another reason that exception handling is important

is that Java defines standard exceptions for common program errors.

Fundamentals
try:

catch:

Program statements that you want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch) and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed upon exiting from a try block is put in a finally block.

throw:

throws:

finally:

Example
// Demonstrate exception handling. class ExcDemo { public static void main(String args[]) { int nums[] = new int[4]; try { System.out.println("Before exception is generated."); // Generate an index out-of-bounds exception. nums[7] = 10; System.out.println("won't displayed"); } catch(ArrayIndexOutOfBoundsException exc){ // catch the exception System.out.println(Array out of range!"); } System.out.println("After catch statement."); } }

Uncaught Exception
// Let JVM handle the error. class NotHandled { public static void main(String args[]) { int nums[] = new int[4]; System.out.println("Before exception."); //generate an index out-of-bounds exception nums[7] = 10; } } OUTPUT: Before exception. Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7 at NotHandled.main(NotHandled.java:9)

Multithreading
A multithreaded program contains two or more parts

that can run concurrently.


Each part of such a program is called a thread, and

each thread defines a separate path of execution.


There are two distinct types of multitasking: process-

based and thread-based.


Processes are heavyweight where as threads are

lightweight.
Multithreading enables to write very efficient programs

because it lets to utilize the idle time that is present in most programs.

Thread Model
Threads exist in several states.

A thread can be running.


It can be ready to run as soon as it gets CPU time. A running thread can be suspended. A suspended thread can then be resumed. A thread can be blocked when waiting for a

resource.
At any time, a thread can be terminated.

The main Thread


When a Java program starts up, main thread

which is created automatically, begins running immediately.


It is the thread from which other child threads will

be spawned.
It must be the last thread to finish execution. It can be controlled through a Thread object. To get the reference were having the following

method static Thread currentThread( )

Example
// Controlling the main Thread. class CurrentThreadDemo { public static void main(String args[]) { Thread t = Thread.currentThread(); //Prints thread name, priority, name of the group System.out.println("Current thread: " + t); t.setName("My Thread"); //change the thread name System.out.println("After name change: " + t); try { for(int n = 5; n > 0; n--) { System.out.println(n); Thread.sleep(1000); //suspends thread } } catch (InterruptedException e) { System.out.println("Main thread interrupted"); } } }

Type Wrappers
Primitive types, rather than objects, are used for these quantities

for the sake of performance.


The primitive types are not part of the object hierarchy, and they

do not inherit Object.


Java provides type wrappers, which are classes that

encapsulate a primitive type within an object.


The type wrappers are Double, Float, Long, Integer, Short,

Byte, Character, and Boolean, which are packaged in java.lang.


All of the numeric type wrappers inherit the abstract class

Number.
Number declares methods that return the value of an object in

each of the different numeric types.

Numeric Wrappers
Byte Byte(byte num) Byte(String str) throws NumberFormatException Short Short(short num) Short(String str) throws NumberFormatException Integer Integer(int num) Integer(String str) throws NumberFormatException Long Long(long num) Long(String str) throws NumberFormatException

Float

Float(double num) Float(float num) Float(String str) throws NumberFormatException Double(double num) Double(String str) throws NumberFormatException

Double

Constants: MIN_VALUE - Minimum value MAX_VALUE - Maximum value

Converting Numbers to/from Strings


Following methods will convert String object to

numeric types.

parseByte() parseShort() parseInt() parseLong()...

Following methods will convert numeric values to

String object.

toString() toBinaryString() toHexString() toOctalString()...

Character Wrapper
The constructor for Character is

Character(char ch)
static static static static static static static static static boolean isDigit(char ch) boolean isLetter(char ch) boolean isLetterOrDigit(char ch) boolean isLowerCase(char ch) boolean isUpperCase(char ch) boolean isWhitespace(char ch) char toLowerCase(char ch) char toUpperCase(char ch) char toTitleCase(char ch)

Some methods in this class are


Boolean Wrapper
Boolean is a very thin wrapper

It contains the constants TRUE and FALSE


Boolean defines these constructors: Boolean(boolean boolValue) Boolean(String boolString) This class has some methods like toString(), equals(), booleanValue() and valueOf()

Database Connectivity
Steps :
1)

Loading the Driver into application

2)

Getting the connection


Getting the Permission Executing Sql statements

3)

4)

Class.forName("oracle.jdbc.driver.OracleDriver");

Connection co = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1: 1521:XE",uname",pwd");


Statement st=co.createStatement(); String query="create table emp(name varchar(15),city varchar(20))"; st.executeUpdate(query); //(or)ResultSet rs = st.executeQuery(query) for select query co.close();

COLLECTIONS

APPLET/SWINGS

EVENT HANDLING

NETWORKING

J2EE

N-Tier J2EE Architecture

Web Tier

EJB Tier

J2EE Platform Architecture


B2B Applications
Existing Applications

B2C Applications

Web Services

Wireless Applications

Application Server

Enterprise Information Systems

Servlet
Its a Java program.

Handle the request from the client and send the

response. Its a thread based program. Types:


Generic Servlet Protocol Independent HTTP Servlet Protocol Dependent

Servlet API: javax.servlet.*; javax.servlet.http.*;

JSP
Itll handle the request and response with the client.

Static and Dynamic contents are combined.


Objects are implicit. Contents: JSP Directives JSP Action Tags JSP Scripting Directives: Page Directive Include Directive Taglib Directive

Session Management

Maintaining the clients state.


Types:

1. Hidden Form Fields 2. URL Rewriting 3. Cookies 4. Session

RMI

EJB

AJAX

HIBERNATE

Vous aimerez peut-être aussi