Anda di halaman 1dari 34

Influence Objective-C, Ada 83, UCSD Pascal, C++, C#, Eiffel, Smalltalk,

d by Mesa, Modula-3, Generic Java

Influence Ada 2005, C#, Clojure, D,ECMAScript, Groovy, J#,PHP, Scala, JavaScript,P
d ython, BeanShell

OS Cross-platform (multi-platform)

License GNU General Public License / Java Community Process

Website http://java.sun.com

Java is a programming language originally developed by James Gosling at Sun


Microsystems and released in 1995 as a core component of Sun Microsystems' Java
platform. The language derives much of its syntax from C and C++ but has a
simpler object model and fewer low-level facilities. Java applications are
typically compiled to bytecode (class file) that can run on any Java Virtual
Machine (JVM) regardless of computer architecture.

The original and reference implementation Java compilers, virtual machines, and class
libraries were developed by Sun from 1995. As of May 2007, in compliance with the
specifications of the Java Community Process, Sun relicensed most of their Java
technologies under the GNU General Public License. Others have also developed
alternative implementations of these Sun technologies, such as the GNU Compiler for
Java and GNU Classpath.

(1.1) What Is Java..?


Java is great programming language for the development of enterprise grade
applications. This programming Language is evolved from a language named Oak. Oak
was developed in the early nineties at Sun Microsystems as a platform-independent
language aimed at allowing entertainment appliances such as video game consoles and
VCRs to communicate . Oak was first slated to appear in television set-top boxes
designed to provide video-on-demand services. Oak was unsuccessful so in 1995 Sun
changed the name to Java and modified the language to take advantage of the
burgeoning World Wide Web.

Java is an object-oriented language, and this is very similar to C++. Java


Programming Language is simplified to eliminate language features that cause common
programming errors. Java source code files are compiled into a format called bytecode,
which can then be executed by a Java interpreter.

(1.2) Basics of Java Technology:

This section provides an overview of Java technology as programming language and a


platform. Java technology is a simple, secure, robust, complete object oriented and
platform independent high level programming language. It is also portable, high
performance, multithreaded and networksavy that enable it in constructing software that
can run along in small machines. The whole technology is based on the concept of Java
Virtual Machine (JVM) that acts as a translators of byte code into machine language. In
other words JVM converts the java byte codes into platform specific machine language.
Understanding
Java technology is high-level, object-oriented, very robust programming language. Java
is platform independent programming language and you can run your compiled code on
any operating system without recompiling your source code. Java technology is based
on the concept of a single Java virtual machine (JVM) -- a translator between the
language and the underlying software and hardware. All implementations of the
programming language must emulate the JVM, enabling Java programs to run on any
system that has a version of the JVM.

If you want to start java programming then you need to use a text editor to create and
edit the source code. By using the Java complier, you can change the source code into
bytecode. .

(1.3)Importance

This high-level powerful programming language provides a powerful software platform


as the JVM installed on different platform understand the same byte code. This is ideal
for server side web programming and runs in a secured manner over internet. It enhance
the computing power of the users by taking merely from desktop to the resource of the
web. It contains JVM and Java Application Programming Interface (API) that are kinds
of readymade software components, and for using any component, the need is just to
import a related package in your program use the functionality. It offers development
tools that can be used in compiling, running, debugging and documenting the
application, making the Java programming fun and easy. The automatic garbage
collection mechanism helps in avoiding memory leaks and its coding takes less
development time than other programming languages like C++.

(1.4)Different Editions of Java Technology

a) Java SE - Java SE or Java Standard Edition provides tools and API's that you can
use to create server applications, desktop applications, and even applets. These
programs developed using Java SE can be run on almost every popular operating
system, including Linux, Macintosh, Solaris, and Windows.

b) JEE - Based on the foundation framework of the standard edition, Java Enterprise
Edition helps in web application service, component model and enterprise class service
oriented architecture (SOA).

c) JME - Java Micro Edition or JME for short is an accumulation of Java APIs that are
used for the development of software for devices like mobile phones, PDAs, TV set-
top boxes, game programming. The platform of micro edition generally consists of an
easy user interface, a robust security model and a wide variety of built-in networks for
running Java based application.

(1.5) Components of each edition

(a) JSE Components

JavaBeans - It is the component architecture for J2SE platform and one can develop
and assemble these software programs for better web application. It is a reusable
software component that can be manipulated visually in a builder tool. This software
assists visual builder tools in using reflection, introspection, and also analyze and
customize JavaBeans.

Java Foundation Classes (JFC) - It is a part of Java class libraries based on the Java
platform used for developing graphical user interface (GUI). JFC helps in 2D graphics,
imaging, text formatting and printing with the help of Abstract Window Toolkit
(AWT), Swing and Java2D. With the help of input method framework, the JFC
technology assists in preparing application that can be accessible to all users around
the world in different languages. Drag and Drop is another feature of JFC that supports
data transfers between different Java applications.

JavaHelp - It is a platform independent and a feature oriented software system that


offers developer an automated help component. JavaHelp 2.0 API is useful while
building online documentation and presenting online information to the application
users.

Java Web Start - It is framework in the Java platform that assists in starting
Application software directly from the internet by using a web browser. As we know
Java applet can run in a browser but in case of Java Web Start, it doesn't run inside and
solve many complex problems associated with Java plugins and JVM. It also provide
many classes that in turn provides various services and allow better access to
resources. Version 1.0 was introduced in the year 2001. Now with the release of J2SE
1.4, Java Web Start is included with Java Runtime Environment and does need any
separate installation.

Java Database Connectivity (JDBC) - JDBC API is a part of Java Standard Edition
that helps in accessing data from a SQL based database. Besides, it also process the
result and allows in using the programming language with "Write Once, Run
Anywhere" feature. Some of its key features are like full access to metadata, no special
installation and database identification.

Java Media Framework (JMF) - Its an advanced API that allows Java developers to
process and add audio-video source to Java application and applets. It is useful for
multimedia developers to capture, playback, transcode different media formats.

(b) JEE - Components:

Enterprise JavaBeans (EJB) - This technology is a server side component of Java


platform used for the construction of enterprise application. It is one of the Java APIs
attached with the enterprise edition. By using Java technology, EJB helps in quick
development of small, distributed, transactional and secure application.
JavaMail - This JavaMail API technology allows to build mails and messaging
application in a platform independent and protocol independent framework. It is both a
part of JSE and JEE platform. Thus, JavaMail uses an extensible platform for
transferring all kinds of Multimedia Internet Mail Extension (MIME).

Java Message Service (JMS) - Developed under Java community process, JMS
technology is used for sending messages between users. Basically, it is an enterprising
messaging tool used for building enterprising application. The JMS API is a
combination of Java technology and enterprising messaging that provides facilities for
building small message based application. It functions under two models: Point-to-
Point and Publishing & Subscribing model.

JavaServer Pages (JSP) - The JSP technology enables web developers in developing
and maintaining web content pages in formats like HTML and XML. With the help of
JSP, it becomes very easy to build server and platform independent web based
application. This uses HTML and XML tags that offers logical solution for the content.
This separately user interface and content development from each other, which allows
the designer to change page layout without changing the content.

Java Servlets - This enables a developer in adding content to a web server by using
Java platform. This provides the mechanism for enhancing the functionality of web
server. In short, servlets provides platform independent and component based web
based application without the performance limiting of CGI program.

(c) JME - Components:

Connected Limited Device Configuration (CLDC) - It is one of the configurations


of Java Micro Edition. 'Configuration' describes minimal features of a complete Java.
The CLDC specifies the capabilities of JVM, the base set of API for resource limited
devices like pager and mobile phones. There are two version of CLDC: version 1.0
was released in 2000 and came to be known as Java Specification Request (JSR)30.
Later version 1.1 or JSR 139 but 1.0 is more widely used. The Connected Limited
Device Configuration and the Mobile Information Device Profile (MIDP) together
provides solid Java platform for developing application to run on less processing
power devices.

Mobile Information Device Profile (MIDP) - This is another configuration of Java


Micro Edition and coupled with CLDC, it provides a farm Java Runtime Environment
for various mobile devices and other personal digital assistance (PDA). With the help
of MIDP, developers can develop application once and then redistribute them into
various mobile information devices in a very small period of time. Its principal
functions include the user interface, network connectivity data storage and overall
application process management. There are two versions of MIDP: one is MIDP 2.0 or
JSR 118 and the second one is the MIDP 1.0 or JSR 37.

Connected Device Configuration (CDC) - Developed under the Java Community


Process (JCP), it is a standard framework of Java technology used for building and
delivering application that can be shared in a wide range of networks and devices
ranging from pagers, mobile phones, set top box and other PDA devices. It is in two
versions: the JSR 36 (CDC 1.0) and the latest one is the JSR 218 (CDC 1.1).

CHAPTER-2
History

Duke, the Java mascot

James Gosling initiated the Java language project in June 1991 for use in one of his
many set-top box projects. The language, initially called Oak after an oak tree that stood
outside Gosling's office, also went by the name Green and ended up later renamed
as Java, from a list of random words. Gosling aimed to implement a virtual machine and
a language that had a familiar C/C++ style of notation.

Sun released the first public implementation as Java 1.0 in 1995. It promised "Write
Once, Run Anywhere" (WORA), providing no-cost run-times on popular platforms.
Fairly secure and featuring configurable security, it allowed network- and file-access
restrictions. Major web browsers soon incorporated the ability to run Java applets within
web pages, and Java quickly became popular. With the advent of Java 2 (released initially
as J2SE 1.2 in December 1998), new versions had multiple configurations built for
different types of platforms. For example, J2EE targeted enterprise applications and the
greatly stripped-down version J2ME for mobile applications. J2SE designated the
Standard Edition. In 2006, for marketing purposes, Sun renamed new J2 versions as Java
EE, Java ME, and Java SE, respectively.

In 1997, Sun Microsystems approached the ISO/IEC JTC1 standards body and later
the Ecma International to formalize Java, but it soon withdrew from the process. Java
remains a de facto standard, controlled through the Java Community Process. At one
time, Sun made most of its Java implementations available without charge, despite
their proprietary software status. Sun generated revenue from Java through the selling of
licenses for specialized products such as the Java Enterprise System. Sun distinguishes
between its Software Development Kit (SDK) and Runtime Environment (JRE) (a subset
of the SDK); the primary distinction involves the JRE's lack of the compiler, utility
programs, and header files.

(2.1)Primary Goals:

There were five primary goals in the creation of the Java language:

• It should use the object-oriented programming methodology.


• It should allow the same program to be executed on multiple operating systems.
• It should contain built-in support for using computer networks
• It should design to executed code from remote sources securely.
• It should easy to use by selecting what were considered the good parts of other
object-oriented languages.

JAVA BYTE CODE HELPS IN MAKING THE PROGRAM “WRITE ONCE, RUN
ANYWHERE”. THE PROGRAM CAN BE COMPILED INTO BYTE CODE BY ANY
PLATFORM THAT IS HAVING THE JAVA COMPILER; THE COMPILED JAVA
BYTE CODE PROGRAM IS READY TO RUN ON ANY MACHINE HAVING THE
JAVA VIRTUAL MACHINE (JVM). JVM IS AN INTERPRETER FOR BYTE
CODE.

CHAPTER-3
Uses

3.1)What is the use of java?

Introduction.

Java technology is a high-level programming and a platform independent language. Java


is designed to work in the distributed environment on the Internet. Java has a GUI
features that provides you better "look and feel" over the C++ language, moreover it is
easier to use than C++ and works on the concept of object-oriented programming
model. Java enable us to play online games, video, audio, chat with people around the
world, Banking Application, view 3D image and Shopping Cart. Java find its extensive
use in the intranet applications and other e-business solutions that are the grassroots of
corporate computing. Java , regarded as the most well described and planned language
to develop an applications for the Web.

Java is a well known technology which allows you for software designed and written
only once for an "virtual machine" to run on a different computers, supports various
Operating System like Windows PCs, Macintoshes, and Unix computers. On the web
aspect, Java is popular on web servers, used by many of the largest interactive websites.
Java is used to create standalone applications which may run on a single computer or in
distributed network. It is also be used to create a small application program based on
applet, which is further used for Web page. Applets make easy and possible to interact
with the Web page.

Java Preferred Over Other Languages


The Java is a high-level programming language that can be supported by all of the
following features:

Architecture
Simple
neutral
Object
Portable
oriented
High
Distributed
performance
Multithreaded Robust
Dynamic Secure
Java has advantages over other languages and environments that make it suitable for
just about any programming task.

3.2)The advantages of Java are as follows:

• Java is simple, easy to design , easy to write, and therefore easy to compile,
debug, and learn than any other programming languages.
• Java is object-oriented, that is used to build modular programs and reusable code
in other application.
• Java is platform-independent and flexible in nature. The most significant feature
of Java is to run a program easily from one computer system to another.
• Java works on distributed environment. It is designed to work on distributed
computing , Any network programs in Java is same as sending and receiving data
to and from a file.
• Java is secure. The Java language, compiler, interpreter and runtime environment
are securable .
• Java is robust. Robust means reliability. Java emphasis on checking for possible
errors, as Java compilers are able to detect many error problem in program during
the execution of respective program code.
• Java supports multithreaded. Multithreaded is the path of execution for a program
to perform several tasks simultaneously within a program. The java come with
the concept of Multithreaded Program. In other languages, operating system-
specific procedures have to be called in order to work on multithreading.

Java Technology Works

Java is a high-level programming language and powerful software platform. On full


implementation of the Java platform gives you the following features:

• JDK Tools: The JDK tools provide compiling, Interpreter, running, monitoring,
debugging, and documenting your applications. The main tools used are the
Javac compiler, the java launcher, and the javadoc documentation tool.
• Application Programming Interface (API): The API provides the core
functionality of the Java programming language. It gives a wide collection of
useful classes, which is further used in your own applications. It provides basic
objects and interface to networking and security, to XML generation and database
access, and much more.
• Deployment Technologies: The JDK software provides two type of deployment
technology such as the Java Web Start software and Java Plug-In software for
deploying your applications to end users.
• Graphical User Interface Toolkits: The Swing and Java 2D toolkits provide us
the feature of Graphical User Interfaces (GUIs).
• Integrated Libraries: Integrated with various libraries such as the Java IDL API,
JDBC API, Java Naming and Directory Interface TM ("J.N.D.I.") API, Java RMI,
and Java Remote Method Invocation over Internet Inter-ORB Protocol
Technology (Java RMI-IIOP Technology) enable database to access and changes
of remote objects.

Java Technology Changes Our Life


• Easy to Start: Since Java programming language is completely based on object-
oriented language, it's easy very simple and easy to learn, especially for
programmers already known with C or C++.
• Easy to write code: As compared to program metrics (class counts, method
counts, and so on) tell us that a program written in the Java programming
language can be four times smaller as compare to the same program written in C+
+.
• Write better code: The Java programming language encourages good coding
practices, and manages automatic garbage collection which helps you avoid
memory leaks. Based on the concept of object orientation, its Java Beans
component architecture, and wide-range, easily extendible, flexibility and API
can reuse existing, tested code and introduce fewer bugs.
• Develop programs and Time Safer: The Java programming language is easier
and simpler than C++, as such, manages your development time upto twice as
fast when writing in it. The programs will also require fewer lines of code.
• Platform Independencies: The program keep portable and platform independent
by avoiding the use of libraries written in other languages.
• Write Once and Used in any Java Platform : Any Source code of Program are
written in the Java programming language, that is compiled into machine-
independent byte codes and run consistently on any platform of java.
• Distribute software makes work easy : Using Java Web Start software, users
will be able to launch own applications with a single click on mouse. An
automatic version check initially weather users are always up to date with the
latest version of your software. If an update is available for it, the Java Web Start
software will automatically update their installation.

The API and Java Virtual Machine insulate the program from
hardware.
Java work on platform-independent environment, the Java platform is bit slower than
native code. However, new changes in compiler and virtual machine brings
performance close to that of native code without posing any threatening to portability
security.

All source code is written in text files (Notepad Editor) save with the .java extension
in the Java programming language.

The source files are compiled into .class files by the java compiler. A .class file
contains byte codes — the machine language of the Java Virtual Machine (JVM).
The java launcher tool runs your application with an instance of the Java Virtual
Machine.
Schematic Flow of Java Software Development Life Cycle

JVM works on different Operating System . The .class files(bytecode) capable of


running on various Operating System. There are some virtual machines, such as the
Java Hotspots virtual machine that boost up your application performance at runtime .
This include various tasks such as Efficiency of Programme and recompiling (to native
code) which is frequently used sections of code.

Java JVM, the same application is capable to run on multiple platform


CHAPTER-5

Syntax

Syntax
The syntax of Java is largely derived from C++. Unlike C++, which combines the syntax
for structured, generic, and object-oriented programming, Java was built almost
exclusively as an object oriented language. All code is written inside a class and
everything is an object, with the exception of the intrinsic data types (ordinal and real
numbers, boolean values, and characters), which are not classes for performance reasons.

Java suppresses several features (such as operator overloading and multiple inheritance)
for classes in order to simplify the language and to prevent possible errors and anti-
pattern design.

Java uses the same commenting methods as C++. There are two different styles of
comment: a single line style marked with two forward slashes, and a multiple line style
opened with a forward slash asterisk (/*) and closed with an asterisk forward slash (*/).

Example:

//This is an example of a single line comment using two forward slashes


/* This is an example of a multiple line comment using the forward slash
and asterisk. This type of comment can be used to hold a lot of information
but it is very important to remember to close the comment. */
Examples:

Hello world

The traditional Hello world program can be written in Java as:

/*
* Outputs "Hello, world!" and then exits
*/

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, world!");
}
}

By convention, source files are named after the public class they contain, appending the
suffix .java, for example, HelloWorld.java. It must first be compiled into bytecode, using
a Java compiler, producing a file named HelloWorld.class. Only then can it be executed,
or 'launched'. The java source file may only contain one public class but can contain
multiple classes with less than public access and any number of public inner classes.

A class that is declared private may be stored in any .java file. The compiler will
generate a class file for each class defined in the source file. The name of the class file is
the name of the class, with.class appended. For class file generation, anonymous
classes are treated as if their name was the concatenation of the name of their enclosing
class, a $, and an integer.

The keyword public denotes that a method can be called from code in other classes, or
that a class may be used by classes outside the class hierarchy. The class hierarchy is
related to the name of the directory in which the .java file is.

The keyword static in front of a method indicates a static method, which is associated
only with the class and not with any specific instance of that class. Only static methods
can be invoked without a reference to an object. Static methods cannot access any
method variables that are not static.

The keyword void indicates that the main method does not return any value to the caller.
If a Java program is to exit with an error code, it must call System.exit() explicitly.

The method name "main" is not a keyword in the Java language. It is simply the name of
the method the Java launcher calls to pass control to the program. Java classes that run in
managed environments such as applets and Enterprise JavaBean do not use or need
a main() method. A java program may contain multiple classes that have main methods,
which means that the VM needs to be explicitly told which class to launch from.

The main method must accept an array of String objects. By convention, it is referenced
as args although any other legal identifier name can be used. Since Java 5, the main
method can also usevariable arguments, in the form of public static void main(String...
args), allowing the main method to be invoked with an arbitrary number
of String arguments. The effect of this alternate declaration is semantically identical
(the args parameter is still an array of String objects), but allows an alternate syntax for
creating and passing the array.

The Java launcher launches Java by loading a given class (specified on the command line
or as an attribute in a JAR) and starting its public static void main(String[]) method.
Stand-alone programs must declare this method explicitly. The String[] args parameter is
an array of String objects containing any arguments passed to the class. The parameters
to main are often passed by means of acommand line.

Printing is part of a Java standard library: The System class defines a public static field
called out. The out object is an instance of the PrintStream class and provides many
methods for printing data to standard out, including println(String) which also appends a
new line to the passed string.

The string "Hello, world!" is automatically converted to a String object by the compiler.
A more comprehensive example

// OddEven.java
import javax.swing.JOptionPane;

public class OddEven {


// "input" is the number that the user gives to the computer
private int input; // a whole number("int" means integer)

/*
* This is the constructor method. It gets called when an object of the OddEven type
* is being created.
*/
public OddEven() {
//Code not shown
}

// This is the main method. It gets called when this class is run through a Java
interpreter.
public static void main(String[] args) {
/*
* This line of code creates a new instance of this class called "number" (also known
as an
* Object) and initializes it by calling the constructor. The next line of code calls
* the "showDialog()" method, which brings up a prompt to ask you for a number
*/
OddEven number = new OddEven();
number.showDialog();
}

public void showDialog() {


/*
* "try" makes sure nothing goes wrong. If something does,
* the interpreter skips to "catch" to see what it should do.
*/
try {
/*
* The code below brings up a JOptionPane, which is a dialog box
* The String returned by the "showInputDialog()" method is converted into
* an integer, making the program treat it as a number instead of a word.
* After that, this method calls a second method, calculate() that will
* display either "Even" or "Odd."
*/
input = new Integer(JOptionPane.showInputDialog("Please Enter A Number"));
calculate();
} catch (NumberFormatException e) {
/*
* Getting in the catch block means that there was a problem with the format of
* the number. Probably some letters were typed in instead of a number.
*/
System.err.println("ERROR: Invalid input. Please type in a numerical value.");
}
}

/*
* When this gets called, it sends a message to the interpreter.
* The interpreter usually shows it on the command prompt (For Windows users)
* or the terminal (For Linux users).(Assuming it's open)
*/
private void calculate() {
if (input % 2 == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
}
}

The import statement imports the JOptionPane class from the javax.swing package.

• The OddEven class declares a single private field of type int named input.
Every instance of the OddEven class has its own copy of the input field. The
private declaration means that no other class can access (read or write)
the input field.
• OddEven() is a public constructor. Constructors have the same name as the
enclosing class they are declared in, and unlike a method, have no return type. A
constructor is used to initialize an objectthat is a newly created instance of the
class.
• The calculate() method is declared without the static keyword. This means that
the method is invoked using a specific instance of the OddEven class.
(The reference used to invoke the method is passed as an undeclared parameter of
type OddEven named this.) The method tests the expression input % 2 == 0 using
the if keyword to see if the remainder of dividing the input field belonging to the
instance of the class by two is zero. If this expression is true, then it prints Even;
if this expression is false it prints Odd. (The input field can be equivalently
accessed as this.input, which explicitly uses the undeclared this parameter.)
• OddEven number = new OddEven(); declares a local object reference variable
in the main method named number. This variable can hold a reference to an object
of type OddEven. The declaration initializesnumber by first creating an instance
of the OddEven class, using the new keyword and the OddEven() constructor, and
then assigning this instance to the variable.
• The statement number.showDialog(); calls the calculate method. The instance
of OddEven object referenced by the number local variable is used to invoke the
method and passed as the undeclared thisparameter to the calculate method.
• input = new Integer(JOptionPane.showInputDialog("Please Enter A
Number")); is a statement that converts the type of String to the primitive data
type int by taking advantage of the primitive wrapper class Integer.
CHAPTER-8

Exceptions in Java

(8.1) Introduction

Exception is a run-time error which arises during the execution of java program. The
term exception in java stands for an exceptional event. It can be defined as abnormal
event that arises during the execution and normal flow of program. The exceptional
event can also be error in the program.

Errors in Java are of two type-

1.Compile-time Errors- Compile -time Error are those error which occurs when you
don't follow the Syntax of the code or do wrong in writing a code of the Programming
language. The Compiler detect the Syntax error in the code of the Programming
language during its execution. For example in normal java coding ,you need your
every statement to be terminated with semicolon(;).if you don't follow the rule, this
will give you Compile-time error.

2.Run -time Error- Run-time error are the error which arises during the execution of a
program. For example. The program runs out of the memory, result in Run-time error.

(8.2) Why Exceptions Occur-

An Exception is Run-time error that arises during the normal execution of Java
program. In case of Run-time error, if you divide a number by zero or unable to open a
file which does not exist, an exception is raised. In java exception are handled by Run-
time System or user-defined code. A run-time error throws an exception.

Error handling plays a important role while developing an application. Following are
the situation in which run-time error arises-
1. Search a file which does not exist.
2. Dividing a number by zero.
3. Allocating Memory error.
4. Problem in accessing Network Connectivity.

(8.3) What is Exception Class

Object Class is the base class of the exception hierarchy.. Object class is the super
class of Throwable class.Throwable class is the super class of all the exceptional class
and error class. In java you can throw exception Object which are derived from
throwable class. The following Syntax for declaring a throwable class .

Throwable()

The Syntax represent a constructor of throwable class with no arguments.

In the same way we can declare a constructor of Throwable class with a userdefined
Parameter.

Throwable(String Parameter)

Parameter can be message that may be userdefined included in Throwable class.

(8.4) Exception Class

1. ClassNot Found Exception- Exception arises when a class is being reffered,but no


such definition of class name is being found.
2. Runtime Exception- handles the Exception arises during the runtime execution of
the program.
3. Illegal Access Exception-This Exception is thrown when method is not found.
(8.5) Exception Hierarchy

(8.6) Built-in Exceptions

1.Checked Exception- These exception are the objects of the Exception class and its
subclasses. It don't include the Run time Exception. These exception occurs due to
invalid user input, problem in the network connectivity database connection). This also
arises when we forget to import the packages. For Example
java.sql.sqlexception,java.io.ioexception.The Exception problem can be overcome by
implementing Try-Catch block which u see in Example in exception.
2.Unchecked Exception- These exception are the run-time errors that arises due to
incorrect arguments passed to the public method written by the programmer. The
Compiler never checks the Unchecked exception during the program compilation. For
example, Dividing any number by zero is an unchecked exception.

CHAPTER-9

Special Classes

Special classes

(9.1) Applet
Java applets are programs that are embedded in other applications, typically in a Web
page displayed in a Web browser.

// Hello.java
import javax.swing.JApplet;
import java.awt.Graphics;

public class Hello extends JApplet {


public void paintComponent(Graphics g) {
g.drawString("Hello, world!", 65, 95);
}
}

The import statements direct the Java compiler to include


the javax.swing.JApplet and java.awt.Graphics classes in the compilation. The import
statement allows these classes to be referenced in the source code using the simple class
name (i.e. JApplet) instead of the fully qualified class name (i.e. javax.swing.JApplet).

The Hello class extends (subclasses) the JApplet (Java Applet) class; the JApplet class
provides the framework for the host application to display and control the lifecycle of the
applet. The JApplet class is a JComponent (Java Graphical Component) which provides
the applet with the capability to display a graphical user interface (GUI) and respond to
user events.

The Hello class overrides the paintComponent(Graphics) method inherited from


the Container superclass to provide the code to display the applet. The paint() method is
passed a Graphics object that contains the graphic context used to display the applet.
The paintComponent() method calls the graphic context drawString(String, int,
int) method to display the "Hello, world!" string at a pixeloffset of (65, 95) from the
upper-left corner in the applet's display.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"


"http://www.w3.org/TR/html4/strict.dtd">
<!-- Hello.html -->
<html>
<head>
<title>Hello World Applet</title>
</head>
<body>
<applet code="Hello" width="200" height="200">
</applet>
</body>
</html>

An applet is placed in an HTML document using the <applet> HTML element.


The applet tag has three attributes set: code="Hello" specifies the name of
the JApplet class and width="200" height="200"sets the pixel width and height of the
applet. Applets may also be embedded in HTML using either
the object or embed element[23], although support for these elements by Web browsers is
inconsistent.[24] However, the applet tag is deprecated, so the object tag is preferred where
supported.

The host application, typically a Web browser, instantiates the Hello applet and creates
an AppletContext for the applet. Once the applet has initialized itself, it is added to the
AWT display hierarchy. The paint method is called by the AWT event dispatching
thread whenever the display needs the applet to draw itself.

(9.2) Servlet
Java Servlet technology provides Web developers with a simple, consistent mechanism
for extending the functionality of a Web server and for accessing existing business
systems. Servlets are server-side Java EE components that generate responses
(typically HTML pages) to requests (typically HTTP requests) from clients. A servlet can
almost be thought of as an applet that runs on the server side—without a face.

// Hello.java
import java.io.*;
import javax.servlet.*;

public class Hello extends GenericServlet {


public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
final PrintWriter pw = response.getWriter();
pw.println("Hello, world!");
pw.close();
}
}

The import statements direct the Java compiler to include all of the public classes
and interfaces from the java.io and javax.servlet packages in the compilation.

The Hello class extends the GenericServlet class; the GenericServlet class provides the
interface for the server to forward requests to the servlet and control the servlet's
lifecycle.
The Hello class overrides the service(ServletRequest, ServletResponse) method defined
by the Servlet interface to provide the code for the service request handler.
The service() method is passed aServletRequest object that contains the request from the
client and a ServletResponse object used to create the response returned to the client.
The service() method declares that
it throws theexceptions ServletException and IOException if a problem prevents it from
responding to the request.

The setContentType(String) method in the response object is called to set


the MIME content type of the returned data to "text/html". The getWriter() method in
the response returns a PrintWriterobject that is used to write the data that is sent to the
client. The println(String) method is called to write the "Hello, world!" string to the
response and then the close() method is called to close the print writer, which causes the
data that has been written to the stream to be returned to the client.

JavaServer Page

JavaServer Pages (JSPs) are server-side Java EE components that generate responses,
typically HTML pages, to HTTP requests from clients. JSPs embed Java code in an
HTML page by using the special delimiters <% and %>. A JSP is compiled to a
Java servlet, a Java application in its own right, the first time it is accessed. After that, the
generated servlet creates the response.

Swing application

Swing is a graphical user interface library for the Java SE platform. It is possible to
specify a different look and feel through the pluggable look and feel system of Swing.
Clones of Windows, GTK+ andMotif are supplied by Sun. Apple also provides
an Aqua look and feel for Mac OS X. Where prior implementations of these looks and
feels may have been considered lacking, Swing in Java SE 6 addresses this problem by
using more native GUI widget drawing routines of the underlying platforms.
This example Swing application creates a single window with "Hello, world!" inside:

// Hello.java (Java SE 5)
import java.awt.BorderLayout;
import javax.swing.*;

public class Hello extends JFrame {


public Hello() {
super("hello");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
add(new JLabel("Hello, world!"));
pack();
}

public static void main(String[] args) {


new Hello().setVisible(true);
}
}

The first import statement directs the Java compiler to include the BorderLayout class
from the java.awt package in the compilation; the second import includes all of the
public classes and interfaces from the javax.swing package.

The Hello class extends the JFrame class; the JFrame class implements a window with
a title bar and a close control.

The Hello() constructor initializes the frame by first calling the superclass constructor,
passing the parameter "hello", which is used as the window's title. It then calls
thesetDefaultCloseOperation(int) method inherited from JFrame to set the default
operation when the close control on the title bar is selected
to WindowConstants.EXIT_ON_CLOSE — this causes the JFrameto be disposed of
when the frame is closed (as opposed to merely hidden), which allows the JVM to exit
and the program to terminate. Next, the layout of the frame is set to a BorderLayout; this
tells Swing how to arrange the components that will be added to the frame. A JLabel is
created for the string "Hello, world!" and the add(Component) method inherited from
the Container superclass is called to add the label to the frame. The pack() method
inherited from the Window superclass is called to size the window and lay out its
contents, in the manner indicated by the BorderLayout.

The main() method is called by the JVM when the program starts. It instantiates a
new Hello frame and causes it to be displayed by calling the setVisible(boolean) method
inherited from theComponent superclass with the boolean parameter true. Once the
frame is displayed, exiting the main method does not cause the program to terminate
because the AWT event dispatching threadremains active until all of the Swing top-level
windows have been disposed.

(9.3) Generics
In 2004 generics were added to the Java language, as part of J2SE 5.0. Prior to the
introduction of generics, each variable declaration had to be of a specific type. For
container classes, for example, this is a problem because there is no easy way to create a
container that accepts only specific types of objects. Either the container operates on all
subtypes of a class or interface, usually Object, or a different container class has to be
created for each contained class. Generics allow compile-time type checking without
having to create a large number of container classes, each containing almost identical
code.
CHAPTER-10

Class Libraries

Class libraries

• Java libraries are the compiled bytecodes of source code developed by the JRE
implementor to support application development in Java. Examples of these
libraries are:

a. The core libraries, which include:


i. Collection libraries that implement data structures such
as lists, dictionaries, trees and sets
ii. XML Processing (Parsing, Transforming, Validating) libraries
iii. Security
iv. Internationalization and localization libraries
b. The integration libraries, which allow the application writer to
communicate with external systems. These libraries include:
i. The Java Database Connectivity (JDBC) API for database access
ii. Java Naming and Directory Interface (JNDI) for lookup and
discovery
iii. RMI and CORBA for distributed application development
iv. JMX for managing and monitoring applications
c. User interface libraries, which include:
i. The (heavyweight, or native) Abstract Window Toolkit (AWT),
which provides GUI components, the means for laying out those
components and the means for handling events from those
components
ii. The (lightweight) Swing libraries, which are built on AWT but
provide (non-native) implementations of the AWT widgetry
iii. APIs for audio capture, processing, and playback

• A platform dependent implementation of Java Virtual Machine (JVM) that is the


means by which the byte codes of the Java libraries and third party applications
are executed
• Plugins, which enable applets to be run in Web browsers
• Java Web Start, which allows Java applications to be efficiently distributed
to end-users across the Internet
• Licensing and documentation.

Anda mungkin juga menyukai