Java Notes2014

118
NOTES SUBJECT: INTERNET AND JAVA PROGRAMMING SUBJECT CODE: NMCA-314 BRANCH: MCA SEM:3 rd SESSION: 2014-15 Evaluation scheme: Subjec t Code Name of Subject Periods Evaluation Scheme Subject Total Credit L T P CT TA TOTAL ESC NMCA- 314 Internet And Java Programmin g 3 1 0 30 20 50 100 150 Aditya Pratap Singh Mani Dwivedi MCA Department AKGEC,GZB.

description

covers all the java basics in simple language

Transcript of Java Notes2014

NOTES

SUBJECT: INTERNET AND JAVA PROGRAMMINGSUBJECT CODE: NMCA-314BRANCH: MCASEM:3rd SESSION: 2014-15

Evaluation scheme:Subject CodeName of SubjectPeriodsEvaluation SchemeSubject TotalCredit

LTPCTTATOTALESC

NMCA-314Internet And Java Programming310302050100150

Aditya Pratap SinghMani DwivediMCA Department

AKGEC,GZB.

INDEX

Unit 1

Internet

1.1 Internet

1.2 Internet Service Provider

1.3 Electronic Mail1.4 TCP/IP Protocol Suite

1.5 File Transfer Protocol (FTP)

1.6 Voice And Video Conferencing

Unit -2

Core Java

2.1 Introduction

2.2 Operators

2.3 Datatypes

2.4 Control Statements

2.5 Classes, Objects And Methods

2.6 Inheritance

2.7 Interfaces

2.8 Packages

2.9 Exception-Handling2.10 Multithreading

2.11 Input/Output

2.12 String Handling

2.13 Networking

2.14 Applets

2.15 Event Handling

2.16 Introduction To Awt And Graphics

2.17 Layout Managers

2.18 Awt Controls

Unit-3

Java Swing3.1 Swing3.2 Swing Components3.3 JDBCIntroduction3.4 JDBC Architecture

3.5 JDBC Drivers

3.6 Steps To Get Connect To Database

Unit-4

Java Beans4.1 Java Bean4.2 Application Builder Tool4.3 The Bean Developer Kit (BDK)4.4 Introspection4.5 Properties4.6 The Java Beans Api4.7 Persistence4.8 Steps To Create A Javabean4.9 Introduction To EJB4.10 Remote Method InvocationUnit-5

Java Servlets

5.1 Java Servlets

5.2 Servlet Life Cycle

5.3 The Java Servlet API5.4 Cookies

5.5 Session Tracking5.6 Servlet Debugging5.7 Java Server Pages (JSP)

Unit 1 ( INTERNET)1.1 INTERNET

The Internet is a worldwide system of computer networks - a network of networks in which users at any one computer can, if they have permission, get information from any other computer (and sometimes talk directly to users at other computers). It was conceived by the Advanced Research Projects Agency (ARPA) of the U.S. government in 1969 and was first known as the ARPANET. The original aim was to create a network that would allow users of a research computer at one university to be able to "talk to" research computers at other universities. A side benefit of ARPANet's design was that, because messages could be routed or rerouted in more than one direction, the network could continue to function even if parts of it were destroyed in the event of a military attack or other disaster.

Today, the Internet is a public, cooperative, and self-sustaining facility accessible to hundreds of millions of people worldwide. Physically, the Internet uses a portion of the total resources of the currently existing public telecommunication networks. Technically, what distinguishes the Internet is its use of a set of protocols called TCP/IP (for Transmission Control Protocol/Internet Protocol). Two recent adaptations of Internet technology, the intranet and the extranet, also make use of the TCP/IP protocol.

Common methods of home access include dial-up, landline broadband (over coaxial cable, fiber optic or copper wires), Wi-Fi, satellite and 3G technology cell phones.

IP Addresses: An Internet Protocol (IP) address is a numerical identification (logical address) that is assigned to devices participating in a computer network utilizing the Internet Protocol for communication between its nodes. Although IP addresses are stored as binary numbers, they are often displayed in more human-readable notations, such as 192.168.100.1 (for IPv4), and 2001:db8:0:1234:0:567:1:1 (for IPv6). The role of the IP address has been characterized as follows: "A name indicates what we seek. An address indicates where it is. A route indicates how to get there."

Originally, an IP address was defined as a 32-bit number and this system, now named Internet Protocol Version 4 (IPv4), is still in use today. However, due to the enormous growth of the Internet and the resulting depletion of the address space, a new addressing system (IPv6), using 128 bits for the address, had to be developed. IPv6 is now being deployed across the world; in many places it coexists with the old standard and is transmitted over the same hardware and network links.

The Internet Protocol also is responsible for routing data packets between networks, and IP addresses specify the locations of the source and destination nodes in the topology of the routing system. For this purpose, some of the bits in an IP address are used to designate a sub network. (In CIDR notation, the number of bits used for the subnet follows the IP address. E.g. 192.168.100.1/16) An IP address can be private, for use on a LAN, or public, for use on the Internet or other WAN.

Figure: IP address format

1.1.1 Working of web browsers with these addresses

A web browser is a software application which enables a user to display and interact with text, images, videos, music and other information typically located on a Web page at a website on the World Wide Web or a local area network. Text and images on a Web page can contain hyperlinks to other Web pages at the same or different website. Web browsers allow a user for quick and easy access information provided on many Web pages at many websites by traversing these links. Some of the Web browsers currently available for personal computers include Mozilla Firefox, Safari, Konqueror, Opera, Flock, Internet Explorer, Epiphany and AOL Explorer. Web browsers are the most commonly used type of HTTP user agent. Although browsers are typically used to access the World Wide Web, they can also be used to access information provided by Web servers in private networks or content in file systems.

They work with addresses in following way:

When we give a name of webpage to open

The web browser send it to the attached DNS server

If its lookup table has the corresponding ip, it returns or forward it to the next DNS server

When browser get corresponding ip for the name provided to try to download the index page or the mentioned page

When it gets downloaded then browser interprets the code and displays it.

1.2 Internet Service Provider

It is a company which primarily offers their customers to access to the Internet using dial-up or other means of data telecommunication. ISPs may provide Internet e-mail accounts to users which allow them to communicate with one another by sending and receiving electronic messages through their ISPs' servers. ISPs may provide other services such as remotely storing data files on behalf of their customers, as well as other services unique to each particular ISP.

For home users and small businesses, the most popular options include dial-up, DSL (typically Asymmetric Digital Subscriber Line, ADSL), broadband wireless, cable modem, fiber to the premises (FTTH), and Integrated Services Digital Network (ISDN) (typically basic rate interface (BRI).

For customers with more demanding requirements, such as medium-to-large businesses, or other ISPs, DSL (often SHDSL or ADSL), Ethernet, Metro Ethernet, Gigabit Ethernet, Frame Relay, ISDN (BRI or PRI), ATM, satellite Internet access and synchronous optical networking (SONET) are more likely to be used.

With the increasing popularity of downloading music and online video and the general demand for faster page loads, higher bandwidth connections are becoming more popular.

Typical home user connection

DSL

Broadband wireless access

Cable modem

FTTH

ISDN

Typical business type connection

DSL

SHDSL

Ethernet technologies

When using a dial-up or ISDN connection method, the ISP cannot determine the caller's physical location to more detail than using the number transmitted using an appropriate form of Caller ID; it is entirely possible to e.g. connect to an ISP located in Mexico from the U.S. Other means of connection such as cable or DSL require a fixed registered connection node, usually associated at the ISP with a physical address.

Related services

Broadband Internet access

Fixed wireless access

Cable

Triple play

Internet hosting service

Web hosting service

E-mail hosting service

DNS hosting service

Dynamic DNS1.3 ELECTRONIC MAIL

One of the most popular Internet services is electronic mail (e-mail). The designers of the Internet probably never imagined the popularity of this application program. Its architecture consists of several components that we discuss in this chapter. At the beginning of the Internet era, the messages sent by electronic mail were short and consisted of text only; they let people exchange quick memos. Today, electronic mail is much more complex. It allows a message to include text, audio, and video. It also allows one message to be sent to one or more recipients.

An e-mail system including the three main components: user agent, message transfer agent, and message access agent. User AgentThe first component of an electronic mail system is the user agent (VA). It provides service to the user to make the process of sending and receiving a message easier.

1.3.1 Services Provided by a User Agent

A user agent is a software package (program) that composes, reads, replies to, and forwards messages. It also handles mailboxes. Composing Messages A user agent helps the user compose the e-mail message to be sent out. Most user agents provide a template on the screen to be filled in by the user. Some even have a built-in editor that can do spell checking, grammar checking.

1.3.2 User Agent Types

There are two types of user agents: command-driven and GUI-based. Command-Driven Command-driven user agents belong to the early days of electronic mail. They are still present as the underlying user agents in servers. A command-driven user agent normally accepts a one-character command from the keyboard to perform its task. For example, a user can type the character r, at the command prompt, to reply to the sender of the message, or type the character R to reply to the sender and all recipients. Some examples of command-driven user agents are mail, pine, and elm.

1.4 TCP/IP Protocol SuiteThe Internet Protocol suite (commonly TCP/IP) is the set of communications protocols used for the Internet and other similar networks. It is named from two of the most important protocols in it: the Transmission Control Protocol (TCP) and the Internet Protocol (IP), which were the first two networking protocols defined in this standard. Today's IP networking represents a synthesis of several developments that began to evolve in the 1960s and 1970s, namely the Internet and LANs (Local Area Networks), which, together with the invention of the World Wide Web by Sir Tim Berners-Lee in 1989, have revolutionized computing.

The Internet Protocol suite like many protocol suites can be viewed as a set of layers. Each layer solves a set of problems involving the transmission of data, and provides a well-defined service to the upper layer protocols based on using services from some lower layers. Upper layers are logically closer to the user and deal with more abstract data, relying on lower layer protocols to translate data into forms that can eventually be physically transmitted. The TCP/IP model consists of four layers.

From lowest to highest, these are the Link Layer, the Internet Layer, the Transport Layer, and the Application Layer.

The main differences between the OSI architecture and that of TCP/IP relate to the layers above the transport layer (layer 4) and those at the network layer (layer 3). OSI has both, the session layer and the presentation layer, whereas TCP/IP combines both into an application layer. The requirement for a connectionless protocol also required TCP/IP to combine OSIs physical layer and data link layer into a network level.

1.4.1 Physical Layer

The physical layer may be either ethernet, SDH-DCC, or some timeslot of a PDH signal. Either OSI protocols and TCP/IP protocols build on the same physical layer standards, thus there is no difference between OSI and TCP/IP in this aspect.

1.4.2 Data Link Layer

The purpose of the data link layer is to provide error free data transmission even on noisy links. This is achieved by framing of data and retransmission of every frame until it is acknowledged from the far end, using flow control mechanisms. Error detection is done by means of error detection codes. In the internet world there is no real data link layer protocol, but the subnet protocol which has quite many similarities. The subnet protocol consists of the IMP-IMP protocol which aims to provide a reliable connection between neighbored IMPs. For ethernet based networks e.g. LANs (Local Area Network), the data link protocol LLC (Logical Link Control) is equally used in OSI and TCP/IP networks.

1.4.3 Network Layer

The network layer provides routing capabilities between source and destination system. TCP divides messages in datagrams of up to 64k length. Each datagram consists of a header and a text part. Besides some other information, the header contains the source and the destination address of the datagram. IP routes these datagrams through the network using e.g. the protocol OSPF (Open Shortest Path First) or RIP (Route Information Protocol) for path calculation purposes. The service provided by IP is not reliable. Datagrams may be received in the wrong order or they may even get lost in the network.

1.4.4 Transport Layer

The transport layer provides a reliable end-to-end connection between source and destination system on top of the network layer. It builds an integral part of the whole OSI layering principle and of the internet protocol.

The OSI transport layer protocol (TP4) and the internet tranport protocol (TCP) have many similarities but also some remarkable differences. Both protocols are built to provide a reliable connection oriented end-to-end transport service on top of an unreliable network service. The network service may loose packets, store them, deliver them in the wrong order or even duplicate packets. Both protocols have to be able to deal with the most severe problems e.g. a subnetwork stores valid packets and sends them at a later date. TP4 and TCP have a connect, transfer and a disconnect phase. The principles of doing this are also quite similar.

1.5 FILE TRANSFER PROTOCOL (FTP)It allows for upload and download of files. Anonymous FTP -No username or password required. Uploading will most likely require a username and password. Some files are compressed into an archive using a program like WinZip, so the files need to be expanded or extracted after downloading.

Self-extracting is an executable that is double-clicked to begin file extraction.

If not self-extracting, will need a compatible program to extract files.

FTP uses the services of TCP. It needs two TCP connections. The well-known port 21 is used for the control connection and the well-known port 20 for the data connection.

1.6 VOICE AND VIDEO CONFERENCINGVideoconferencing is an interactive tool that incorporates audio, video, and computing, and communications technologies to allow people in different locations to electronically collaborate face-to-face, in real time, and share all types of information including data, documents, sound and picture. In essence videoconferencing removes the barrier of distance that separates us.

Video conferencing in its most basic form is the transmission of image (video) and speech (audio) back and forth between two or more physically separate locations.

1.6.1 Common standards in use today

H.320 : Designed for room-to-room videoconferencing over high-speed phone lines

H.323: Family of standards designed for desktop videoconferencing and just simple audio conferencing over Internet

MPEG-2: Designed for faster connections such as LAN or privately owned WANs

The other components required for a VTC system include:

Video input : video camera or webcam

Video output: computer monitor , television or projector

Audio input: microphones

Audio output: usually loudspeakers associated with the display device or telephone

Data transfer: analog or digital telephone network, LAN or Internet

Codec - "compressor/de-compressor - makes the audio/video data "small enough" to be practical for sending over expensive network connections. A codec takes analog signals, compresses and digitizes them, and transmits the signals over digital phone lines.

The Supporting System and the Network Connection1.6.2 Various Uses:

Presentations

Virtual meetings

Videoconference-based learning

JIT (just in time) events

Recruitment/search committees

General meetings

1.6.3 Additional Uses:

Project coordination

Informal work sessions

Alumni relations

Question and answer sessions

1.6.4 Benefits of Videoconferencing:

Can improve work quality

Increase productivity

Reduce costs

Improves communication

Groups can meet more frequently

Critical meetings can be convened in less time

More faculty and staff can be involved

Unit -2 (CORE JAVA)2.1 INTRODUCTION Java is a general-purpose, high-level programming language. The features of Java: Java program is both compiled and interpreted.

Write once, run anywhere

Java is a software-only platform running on top of other, hardware-based platforms.

Java Virtual Machine (Java VM)

The Java Application Programming Interface (JAVA API)

2.1.1 Java Features

(1) Simple: It fixes some clumsy features of C++. There is no use of pointers. Java has Automatic garbage collection. It has rich pre-defined class library http://java.sun.com/j2se/1.4.2/docs/api/

(2) Object oriented: Focus on the data (objects) and methods manipulating the data. All functions are associated with objects. Almost all datatypes are objects (files, strings, etc.). it has potentially better code organization and reuse.(3)Interpreted: Java compiler generate byte-codes, not native machine code. This compiled byte-codes are platform-independent. Java bytecodes are translated on the fly to machine readable instructions in runtime (Java Virtual Machine).(4)Portable: Same application runs on all platforms. The sizes of the primitive data types are always the same. The libraries define portable interfaces

(5)Reliable: There is extensive compile-time and runtime error checking. No pointers but real arrays. Memory corruptions or unauthorized memory accesses are impossible. Automatic garbage collection tracks objects usage over time.(6)Secure: Its usage in networked environments requires more security. Memory allocation model is a major defense. Here access restrictions are forced (private, public).(7)Multithreaded: Multiple concurrent threads of executions can run simultaneously. It utilizes a sophisticated set of synchronization primitives (based on monitors and condition variables paradigm) to achieve this

(8)Dynamic: Java is designed to adapt to evolving environment. Libraries can freely add new methods and instance variables without any effect on their clients. Interfaces promote flexibility and reusability in code by specifying a set of methods an object can perform, but leaves open how these methods should be implemented. It can check the class type in runtime.2.1.2 ByteCode: Java compilation produces bytecode which is an Intermediate code readable by the VM and transferable across the Internet as applets. VM interprets BC into instructions. ByteCode produced on any platform may be executed on any other platform which supports a VM.2.1.3 JVM: Acts as an interpreter for the bytecode, which takes the bytecodes as input and executes as if it was a physical process executing machine code. JVM is a component of the Java system that interprets and executes the instructions in our class files. Each instance of the JVM has one method area, one heap, and one or more stacks - one for each thread. When JVM loads a class file, it puts its information in the method area As the program runs, all objects instantiated are stored in the heap The stack area is used to store activation records as a program runs

Create a Java Source Filepublic class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello World!"); }

}

Compile and Run

Compile:javac HelloWorld.java

One file named HelloWorld.class is created if the compilation is succeeds.

Run:java HelloWorld

2.2 OPERATORS

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

1. Arithmetic Operators: Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. E.g. +,-,*,/ ,%, ++, -.

2. Relational Operators: There are following relational operators supported by Java language ( ==, !=, =, < ,>.3. Bitwise Operators: Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte. Bitwise operator works on bits and performs bit-by-bit operation.

4. Logical Operators: The following table lists the logical operators: &&, ||, !.

5. Assignment Operators: There are following assignment operators supported by Java language: +=, =, *=, /+, -=,%=.6. Misc Operators: Conditional Operator ( ? : ):Conditional operator is also known as the ternary operator.This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. instanceof Operator:This operator is used only for object reference variables. The operator checks whether the object is of a particular type(class type or interface type).

2.3 DATATYPES

There are eight primitive data types supported by Java. Primitive data types are predefined by the language and named by a keyword. Let us now look into detail about the eight primitive data types.

byte:Byte data type is an 8-bit signed two's complement integer.

Minimum value is -128 (-2^7)

Maximum value is 127 (inclusive)(2^7 -1)

Default value is 0

Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an int.

Example: byte a = 100 , byte b = -50

short:Short data type is a 16-bit signed two's complement integer.

Minimum value is -32,768 (-2^15)

Maximum value is 32,767 (inclusive) (2^15 -1)

Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an int

Default value is 0.

Example: short s = 10000, short r = -20000

int:Int data type is a 32-bit signed two's complement integer.

Minimum value is - 2,147,483,648.(-2^31)

Maximum value is 2,147,483,647(inclusive).(2^31 -1)

Int is generally used as the default data type for integral values unless there is a concern about memory.

The default value is 0.

Example: int a = 100000, int b = -200000

long:Long data type is a 64-bit signed two's complement integer.

Minimum value is -9,223,372,036,854,775,808.(-2^63)

Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)

This type is used when a wider range than int is needed.

Default value is 0L.

Example: long a = 100000L, int b = -200000L

float:Float data type is a single-precision 32-bit IEEE 754 floating point.

Float is mainly used to save memory in large arrays of floating point numbers.

Default value is 0.0f.

Float data type is never used for precise values such as currency.

Example: float f1 = 234.5f

double:double data type is a double-precision 64-bit IEEE 754 floating point.

This data type is generally used as the default data type for decimal values, generally the default choice.

Double data type should never be used for precise values such as currency.

Default value is 0.0d.

Example: double d1 = 123.4

boolean:boolean data type represents one bit of information.

There are only two possible values: true and false.

This data type is used for simple flags that track true/false conditions.

Default value is false.

Example: boolean one = true

char:char data type is a single 16-bit Unicode character.

Minimum value is '\u0000' (or 0).

Maximum value is '\uffff' (or 65,535 inclusive).

Char data type is used to store any character.

Example: char letterA ='A'

2.4 CONTROL STATEMENTS

The statements inside your source files are generally executed from top to bottom, in the order that they appear.Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program toconditionallyexecute particular blocks of code.ava contains the following types of control statements:

1- Selection Statements2- Repetition Statements3- Branching Statements2.4.1 Selection statements:If Statement:This is a control statement to execute a single statement or a block of code, when the given condition is true and if it is false then it skipsifblock and rest code of program is executed .

Syntax:if(conditional_expression){ ; ...; ...;}If-else Statement:The"if-else"statementis an extension of if statement that provides another option when 'if' statement evaluates to "false" i.e. else block is executed if"if"statement is false.

Syntax:if(conditional_expression){ ; ...; ...; } else{ ; ....; ....; }Switch Statement: This is an easier implementation to the if-else statements. The keyword"switch"is followed by an expression that should evaluates to byte, short, char or int primitive data types ,only. In a switch block there can be one or more labeled cases. The expression that creates labels for the case must be unique. The switch expression is matched with each case label. Only the matched case is executed ,if no case matches then the default statement (if present) is executed.

Syntax:switch(control_expression){ case expression 1: ; case expression 2: ; ... ... case expression n: ; default: ; }//end switch

2.4.2 Repetition Statements:while loop statements:This is a looping or repeating statement. It executes a block of code or statements till the given condition is true. The expression must be evaluated to a boolean value. It continues testing the condition and executes the block of code. When the expression results to false control comes out of loop.

Syntax:while(expression){ ; ...; ...; }

do-while loop statements:This is another looping statement that tests the given condition past so you can say that the do-while looping statement is a past-test loop statement.First thedoblock statements are executed then the condition given inwhilestatement is checked. So in this case, even the condition is false in the first attempt, do block of code is executed at least once.

Syntax:do{ ; ...; ...; }while (expression);

for loop statements:This is also a loop statement that provides a compact way to iterate over a range of values. From a user point of view, this is reliable because it executes the statements within this block repeatedly till the specified conditions is true .

Syntax: for (initialization; condition; increment or decrement){ ; ...; ...; }initialization:The loop is started with the value specified.condition:It evaluates to either 'true' or 'false'. If it is false then the loop is terminated.increment or decrement:After each iteration, value increments or decrements.

2.4.3 Branching Statements:Break statements:The break statement is a branching statement that contains two forms: labeled and unlabeled. The break statement is used for breaking the execution of a loop (while, do-while and for) . It also terminates the switch statements.

Syntax:break; // breaks the innermost loop or switch statement. break label; // breaks the outermost loop in a series of nested loops.

Continue statements:This is a branching statement that are used in the looping statements (while, do-while and for) to skip the current iteration of the loop and resume the next iteration .

Syntax:continue;

Return statements:It is a special branching statement that transfers the control to the caller of the method. This statement is used to return a value to the caller method and terminates execution of method. This has two forms: one that returns a value and the other that can not return. the returned value type must match the return type of method.

Syntax:return; return values;

return; //This returns nothing. So this can be used when method is declared with void return type.return expression; //It returns the value evaluated from the expression.

2.5 CLASSES, OBJECTS AND METHODS2.5.1 Class Class is a collection of objects of same type. It provides a convenient way for packing together a group of related data items and functions. A class is declared by using a keyword class.

class classname

{

Field declarations;

Methods declarations:

}

A class can contain any of the following variable types.

1.Local variables:Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.

2.Instance variables:Instance variables are variables within a class but outside any method. These variables are instantiated when the class is loaded. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.

3.Class variables:Class variables are variables declared with in a class, outside any method, with the static keyword. It can be tedious to initialize all of the variables in a class each time an instance is created. Because the requirement for initialization is so common, Java allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of a constructor.2.5.2 Creating and declaring objectsObtaining objects of a class in two steps

Declare a variable of class type, it does not define an object, instead it is simply a variable that can refer to an object.

Rectangle rect1; // declare

Declaration creates a physical copy of that object and assign it to that variable and returns reference to it.

rect1=new Rectangle(); // instantiation

2.5.3 Accessing class membersWe can access the instance variables and the methods with the use of concerned objects and dot operator.

Obj.varaiable=value;

Obj.method(parameter list);

2.5.4 Constructors

A constructor initializes an object immediately upon creation. It has the same name as the class in which it resides and is syntactically similar to a method. Once defined, the constructor is automatically called immediately after the object is created, before the new operator completes.

Constructors look a little strange because they have no return type, not even void. This is because the implicit return type of a class' constructor is the class type itself. It is the constructor's job to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object immediately.

Example

class Box {

double width;

double height;

double depth;

// This is the constructor for Box.

Box() {

System.out.println("Constructing Box");

width = 10;

height = 10;

depth = 10;

}

// compute and return volume

double volume() { return width * height * depth; }

}

class BoxDemo6 {

public static void main(String args[]) {

// declare, allocate, and initialize Box objects

Box mybox1 = new Box();

Box mybox2 = new Box();

double vol;

// get volume of first box

vol = mybox1.volume();

System.out.println("Volume is " + vol);

// get volume of second box

vol = mybox2.volume();

System.out.println("Volume is " + vol);

} }

When this program is run, it generates the following results:

Constructing Box

Constructing Box

Volume is 1000.0

Volume is 1000.0

2.5.5 this Keyword:Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines this keyword. this can be used inside any method to refer to the current object. That is, this is always a reference to the object on which the method was invoked. You can use this anywhere a reference to an object of the current class' type is permitted.

To better understand what this refers to, consider the following version of Box( ):

// A redundant use of this.

Box(double w, double h, double d) {

this.width = w;

this.height = h;

this.depth = d;

}

This version of Box ( ) operates exactly like the earlier version. The use of this is redundant, but perfectly correct. Inside Box( ), this will always refer to the invoking object.

2.5.6 Instance Variable Hiding

As you know, it is illegal in Java to declare two local variables with the same name inside the same or enclosing scopes. Interestingly, you can have local variables, including formal parameters to methods, which overlap with the names of the class' instance variables. However, when a local variable has the same name as an instance variable, the local variable hides the instance variable. This is why width, height, and depth were not used as the names of the parameters to the Box ( ) constructor inside the Box class.

If they had been, then width would have referred to the formal parameter, hiding the instance variable width. While it is usually easier to simply use different names, there is another way around this situation. Because this lets you refer directly to the object, you can use it to resolve any name space collisions that might occur between instance variables and local variables. For example, here is another version of Box( ), which uses width, height, and depth for parameter names and then uses this to access the instance variables by the same name:

// Use this to resolve name-space collisions.

Box(double width, double height, double depth) {

this.width = width;

this.height = height;

this.depth = depth;

}

2.6 INHERITANCE

Inheritance is a fundamental Object Oriented concept. The mechanism of driving a new class from old one is called inheritance. A class that is derived from another class is called subclass (derived class or extended class or child class). The class from which the subclasses is derived is called superclass (base class or parent class). A class can be defined as a "subclass" of another class. The subclass inherits all data attributes of its superclass. The subclass inherits all methods of its superclass. The subclass can: Add new functionality Use inherited functionality Override inherited functionalityIf a base class has private members, those members are not accessible to the derived class. Protected members are public to derived classes but private to the rest of the program. When you define an object of derived class, the compiler executes the constructor function of the base class followed by the constructor function of the derived class.

Example:

class Superclass {

public void superMeth()

{ System.out.println(Superclass);

}

class Subclass extends Superclass {

public void subMeth()

{ System.out.println(Subclass);

}

}

class Inherit{

public static void main( String v[])

{

Superclass s1=new Superclass();

s1.superMeth();

Subclass s2=new Subclass();

s2.superMeth();

s2.subMeth();

}

}

2.6.1 Types of Inheritance Single inheritance (only one superclass).

Hierarchial inheritance(one superclass, many subclasses).

Multiple inheritance (several superclasses)

Multilevel inheritance( derived from a derived class).

Note: Java doesnot directly implement multiple inheritance. It is implemented using interfaces. 2.6.2 Method OverridingSubclasses inherit all methods from their superclass. Sometimes, the implementation of the method in the superclass does not provide the functionality required by the subclass. In these cases, the method must be overridden. To override a method, provide an implementation in the subclass. The method in the subclass MUST have the exact same signature as the method it is overriding. When an overridden method is called from within a subclass, it will always refer to that method defined by the subclass. 2.6.3 Using super

There will be times when you will want to create a superclass that keeps the details of its implementation to itself (that is, that keeps its data members private). In this case, there would be no way for a subclass to directly access or initialize these variables on its own. Since encapsulation is a primary attribute of OOP, it is not surprising that Java provides a solution to this problem. Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword super. super has two general forms. The first calls the superclass' constructor. The second is used to access a member of the superclass that has been hidden by a member of a Subclass.

2.6.4 Dynamic Method Dispatch

Method overriding forms the basis for one of Java's most powerful concepts: dynamic method dispatch. Dynamic method dispatch is the mechanism by which a call to an overridden function is resolved at run time, rather than compile time. Dynamic method dispatch is important because this is how Java implements run-time polymorphism. Let's begin by restating an important principle: a superclass reference variable can refer to a subclass object. Java uses this fact to resolve calls to overridden methods at run time. Here is how. When an overridden method is called through a superclass reference, Java determines which version of that method to execute based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time. When different types of objects are referred to, different versions of an overridden method will be called. In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed. Therefore, if a superclass contains a method that is overridden by a subclass, then when different types of objects are referred to through a superclass reference variable, different versions of the method are executed. Here is an example that illustrates dynamic method dispatch:

// Dynamic Method Dispatch

class A {

void callme() {

System.out.println("Inside A's callme method");

}

}

class B extends A {

// override callme()

void callme() {

System.out.println("Inside B's callme method");

}

}

class C extends A {

// override callme()

void callme() {

System.out.println("Inside C's callme method");

}

}

class Dispatch {

public static void main(String args[]) {

A a = new A(); // object of type A

B b = new B(); // object of type B

C c = new C(); // object of type C

A r; // obtain a reference of type A

r = a; // r refers to an A object

r.callme(); // calls A's version of callme

r = b; // r refers to a B object

r.callme(); // calls B's version of callme

r = c; // r refers to a C object

r.callme(); // calls C's version of callme

}

}

The output from the program is shown here:

Inside A's callme method

Inside B's callme method

Inside C's callme method

2.6.5 Abstract

Abstract method is created by specifying abstract modifier. An abstract method contains no body. A subclass must override it- it can simply use the version defined in the superclass. It cannot be applied to static methods or to constructors. A class that contains one or more abstract methods must also be declared as abstract. We can also declare concrete methods in an abstract class. There were no abstract variables. Objects of an abstract class cannot be created, but reference can be created.

E.g. Base ref=new first();

Though the reference of abstract class, only methods of the abstract class implemented in the derived class called.

Example:

abstract class A{

abstract void show();

}

Class B extends A

{

void show()

{ System.out.println(Bs implementation);

}

}

class AbstractDemo{

public static void main( String v[])B b=new B();

b.show;

}

}

2.7 INTERFACES

An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements. Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.

An interface is similar to a class in the following ways:

An interface can contain any number of methods.

An interface is written in a file with a.javaextension, with the name of the interface matching the name of the file.

The bytecode of an interface appears in a.classfile.

Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name.

However, an interface is different from a class in several ways, including:

You cannot instantiate an interface.

An interface does not contain any constructors.

All of the methods in an interface are abstract.

An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.

An interface is not extended by a class; it is implemented by a class.

An interface can extend multiple interfaces.

2.7.1 Declaring Interfaces:

Theinterfacekeyword is used to declare an interface. Here is a simple example to declare an interface:

accessmodifier interface name

{

ret-type meth_name1(param-list);

ret-type meth_name2(param-list);

type final-variablename1=value;

type final-variablename2=value;

}

2.7.2 Implementing Interfaces:

When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract.

A class uses theimplementskeyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.

When implementation interfaces there are several rules:

1. A class can implement more than one interface at a time.

2. A class can extend only one class, but implement many interfaces.

3. An interface can extend another interface, similarly to the way that a class can extend another class.

2.7.3 Extending Interfaces:

An interface can extend another interface, similarly to the way that a class can extend another class.Theextendskeyword is used to extend an interface, and the child interface inherits the methods of the parent interface.

2.8 PACKAGES

A package is a grouping of related types providing access protection and name space management. Packages are used in Java in-order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier etc.

2.8.1 Creating a package:

When creating a package, you should choose a name for the package and put a package statement with that name at the top of every source file that contains the classes, interfaces that you want to include in the package. The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.

Example:

package mypack;

public class demo1

{

public void show()

{

System.out.println(helloo in package);

}

}

2.8.2 The import Keyword:

If a class wants to use another class in the same package, the package name does not need to be used. Classes in the same package find each other without any special syntax.

Example:

import mypack.demo1;

class Main

{public static void main( String ar[])

{demo1 d= new demo1();

d.show();

}}

2.9 Exception-Handling

A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed. Exceptions can be generated by the Java run-time system, or they can be manually generated by your code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. Manually generated exceptions are typically used to report some error condition to the caller of a method.

Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. Briefly, here is how they work. 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 runtime 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 before a method returns is put in a finally block.

This is the general form of an exception-handling block:

try {

// block of code to monitor for errors

}

catch (ExceptionType1 exOb) {

// exception handler for ExceptionType1

}

catch (ExceptionType2 exOb) {

// exception handler for ExceptionType2

}

// ...

finally {

// block of code to be executed before try block ends

}

Here, ExceptionType is the type of exception that has occurred.Example:

class Excep1

{

public static void main(String ar[])

{

try

{

throw new ArithmeticException("hello from exception");

}

catch(ArithmeticException e)

{

System.out.println("Exception Caught:"+e);

System.out.println(e.getMessage());

}

catch(Exception e)

{

System.out.println("Exception rethrown");

}

}

}

2.9.1 Creating Your Own Exception Subclasses

Although Java's built-in exceptions handle most common errors, you will probably want to create your own exception types to handle situations specific to your applications. This is quite easy to do: just define a subclass of Exception (which is, of course, a subclass of Throwable). Your subclasses don't need to actually implement anythingit is their existence in the type system that allows you to use them as exceptions. The Exception class does not define any methods of its own. It does, of course, inherit those methods provided by Throwable. Thus, all exceptions, including those that you create, have the methods defined by Throwable available to them.

Example:

class MyException extends Exception

{

int n;

MyException(int a)

{

n=a;

}

public String toString()

{

return"myexception thrown with n="+n;

}

}

class Excep2

{

static void check(int x) throws MyException

{

System.out.println("check called x="+x);

if(x