Complete Reference - Java
Java Language
Software Development using Java
INTRODUCING SWINGS
JAVA BEANS
click to edit
INTRODUCTION
ADVANTAGES
write once run anywhere paradigm
The properties, events, and methods of a Bean that are exposed to another application
can be controlled
The configuration settings of a Bean can be saved in persistent storage and restored
at a later time.
A Bean may register to receive events from other objects and can generate events
that are sent to other objects.
[click to edit]
histroy and evolution of java
operators
control statments
inheritance
exception handling
multithreaded programing
applets
java is related to c++,which is direct descedant of c.
- from c java derives its syntax
*java was concevied by JAMES GOSLING,PATRICK NAUGHTON,CHRIS WARTH,ED FRANK and MIKE SHERIDAN at sun microsystem in 1991.
*this language was initially was called as "OAK" but was renamed as "JAVA" IN 1995.
THE JAVA BEANS API
Property descriptor
Event set descriptor
Method descriptor
Introspector
INTROSPECTION
Design patterns for simple properties
Design patterns for events
Methods and design patterns
Using Bean Info Interface
Persistence
customizers
ORIGIN
THE SWING PACKAGES
KEY FEATURES
COMPONENTS ARE LIGHTWEIGHT
SUPPORTS A PLUGGABLE LOOK AND FEEL
EVENT HANDLING
SWING APPLET
PAINTING IN SWING
COMPONENTS AND CONTAINERS
COMPONENTS
JLIST
JFRAME
JAPPLET
JDIALOG
CONTAINERS
JFRAME
JAPPLET
JDIALOG
JWINDOW
EXPLORING SWINGS
JLABEL
Icon GetIcon()
String GetText()
ImageIcon
SWING BUTTONS
RADIO BUTTONS
JTOGGLEBUTTON
CHECKBOXES
JBUTTON
JTABBEDPANE
JSCROLLPANE
JLIST
JCOMBOBOX
TREES
JTABLE
SERVELETS
BACKGROUND
LIFECYCLE
SESSION TRACKING
USING COOKIES
HADNLING HTTP REQUEST AND RESPONSE
HTTP GET REQUEST
HTTP POST REQUEST
JAVA.SERVELET.HTTP PACKAGE
SERVELET API
JAVAX.SERVELET PACKAGE
SERVELET EXAMPLE
CREATE AND COMPILE SERVELET CODE
START TOMCAT
START A WEB BROWSER AND REQUEST THE SERVELET
JAVA LIBRARY
STRING HANDLING
exploring java language
string constructors
string length
special string operations
string literals
string concatination
string concatination with other data types
string conversition and toString()
character extraction
string comparision
searching atrings
modifying a string
data conversition using valueOf()
changing the case of characters within a string
additional string methods
string buffers
string builder
primitive type wrappers
void
process
runtime
process builder
system
object
using clone() and the cloneable interface
class
classloader
math
strictmath
compiler
thread,threadgroup and runnable
threadlocal and inheritable threadl ocal
package
runtime permission
throwable
security manager
stacktraceelement
Enum
the char sequence interfact
the comparable interfact
the appendable interface
java.util part-1: the collections frame work
overview
recent changes
the collection interfaces
the collection classes
the random access interface
accessing a collection via an iterator
storing user defined classes in collections
working with maps
comparators
the collection algorithms
arrays
why generic collections?
the legacy classes and interfaces
parting thoughts on collections
java.util part 2:more utility classes
string tokenizer
bitset
date
calender
georgian calender
timezone
simple time zone
locale
random
observable
timer and timer task
currency
formatter
scanner
the resource bundle, list resource bundle and property resource bundle classes
miscellaneous utility classes and interfaces
java.utl sub packages
input/output :exploring java.io
the java I/o classes and interfaces
file
the closable and flushable interfaces
the stream classes
the byte streams
the character streams
the console class
serialization
using stream i/o
stream benifits
NETWORKING
basics
the networking classes and interfaces
inet address
inet4 address and inet6 address
TCP/IP client sockets
URL
URL connection
HttpURL connection
the URI class
cookies
TCP/IP server sockets
datagrams
THE APPLET CLASS
two types of applets
applet basics
applet architecture
an applet skeleton
simple applet display methods
requesting and repaintinmg
using the status window
the HTML applet tag
passing parameters to applets
applet context and show document
the audio clip interface
the applet stub interface
outputting to the console
EVENT HANDLING
two event handling mechanisms
the delegation event model
event clases
source of events
event listener interfaces
using the deligation event model
adapter classes
inner classes
INTRODUCTION TO AWT
AWT classes
window fundamentals
working and frame windows
creating a frame window in an applet
creating a windowed program
displaying information within a window
working with graphics
Working with colour
setting the paint mode
Working with fonts
managing text output using fontmatrics
centering text
multiline text alignment
Using AWT controls,layout managers and menus
control fundamentals
labels
using buttons
appying check boxes
checkbox group
choice controls
using lists
managing scroll bars
using a text area
using a text field
understanding layout managers
menu bars and menus
dialog boxes
file dialogue
handling events by extending AWT components
images
the concurency utilities
NIO,regular expressions and other packages
file formats
image fundamentals: creating,loading and displaying
image observer
double buffering
media tracker
image consumer
image producer
image filter
cell animation
the concurent API packages
using synchronization objects
using an executor
the concurent collections
the time unit enumeration
locks
atomic operations
the core java API packages
NIO
regular expresion processing
reflection
remote method invocation
text formatting
1) Shreyas
2) Krishna B
3) Sanjeev
4) Vivek
5) kanika
6) Chaitanya
7) Priyanka
Logical Operator
Relational Operator
Bitwise operator
Arithmaetic operator
Java provides a rich operator enviraonment.
most of the operators are divided into following 4 groups
Operator Result
- Addition
– Subtraction (also unary minus) - Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
–= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
– – Decrement
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
Shift right
Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
= Shift right assignment
= Shift right zero fill assignment
<<= Shift left assignment
Operator Result
== Equal to
!= Not equal to
Greater than
< Less than
= Greater than or equal to
<= Less than or equal to
Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
Methods and classes
Class fundamental
Introducing Methods
Simple class
Declaring Object
Assigning Object reference
Adding method to the box class
Constructor
This key word
Finalise the methods
Thread State:Life Cycle of Thread
Life cycle of the applet
Supercl;ass
Subclass
Method overriding
In the terminology of java a class that is inherited is called "super class"
A class that does the inheriting is callled the "Sub class"
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
click to edit
packages and interfaces
Using Extension
Access Protection
Extension are .jar file stored within the ext directory
Accessing a package
Defining a package
when you are compiling a program that uses
the packages,depends on where you have put it
Understanding packages
Adding Classes From a Package to Your program
Package pkg;
package My package
Interface can be Extended
Partial Implementation
Accessing Implementation through interface References
Packages are implicit in the organization
of the standard classes as well as your own program
One interface can inherit another by use of the keyword Extends
Defining an Interface
Implementing Interface
one or more classes can implement that interface
An interface is define much like a class.
click to edit
New State
Runnable State
Running State
Dead State
Blocked
Different states implementing
multiple-Threds
Sleeping
Waiting for notification
sleep()
Selection statement
Iteration Statements
final void wait()
Blocked on I/O
Blocked for joint completion
Blocked for lock acquisition
If statements
The main Thread
Switch statements
Nested if statements
Else if ladder
Nested switch statements
Every java program has one thread,even
if do not create any thread.this thread is called main Thread.
While
Do-while
For statements
Creating a thread
implement the runnable interface
extends the thread class,itself
Using Multiple threads in a program
Using is Alive() and join()
Synchronizing Threads
Communicating Between threads
Data types Variables
Arrays
Suspending and Resuming threads
Int
Float point
One dimensional Array
Multi dimensional array
Short
Integer long
Byte
Overriding update()
Initialization
Float
Double
Starting
Stopping
Destroying
Painting
The Applet Class
Including an Applet on a Web Page
The HTML APPLET Tag
Passing Parameters to Applets
Graphical User Interface in Java
Java exception handling is
managed by 5 keywords
Throw
Catch
Finally
Try
Model-View-Controller Architecture
Creating a Window
Component and Containers
Window and Frame Component
Window Panes
IO and File Stream
Byte Stream
Input Stream
Output stream
Character Stream Classes
Reader
A simple property has a single value. It can be identified by the following design patterns,
where N is the name of the property and T is its type:
public T getN( )
public void setN(T arg)
Writer
streaming character input
Streaming character output
streaming byte input
Persistence is the ability to save the current state of a Bean, including the values of a Bean’s
properties and instance variables, to nonvolatile storage and to retrieve them at a later time.
The object serialization capabilities provided by the Java class libraries are used to provide
persistence for Beans.
int Available()
A Bean developer can provide a customizer that helps another developer configure the Bean
The BeanInfo interface enables you to explicitly control what
information is available. The BeanInfo interface defines several methods, including these:
PropertyDescriptor[ ] getPropertyDescriptors( )
EventSetDescriptor[ ] getEventSetDescriptors( )
MethodDescriptor[ ] getMethodDescriptors( )
void close()
mark(int num bytes)
design patterns implicitly determine what information is
available to the user of a Bean
streaming by output
Beans use the delegation event model . Beans can
generate events and send them to other objects. These can be identified by the following
design patterns, where T is the type of the event:
public void addTListener(TListener eventListener)
public void addTListener(TListener eventListener)
throws java.util.TooManyListenersException
public void removeTListener(TListener eventListener)
Void close()
void flush()
void write(int b)
void write(byte buffer[])
The MethodDescriptor class represents a Bean method. To obtain the name of the method,
call getName( ). You can obtain information about the method by calling getMethod( ),
shown here:
Method getMethod( )
An object of type Method that describes the method is returned.
The EventSetDescriptor class represents a Bean event. It supports several methods that
obtain the methods that a Bean uses to add or remove event listeners, and to otherwise manage
events. For example, to obtain the method used to add listeners, call getAddListenerMethod( ).
To obtain the method used to remove listeners, call getRemoveListenerMethod( ). To obtain
the type of a listener, call getListenerType( ). You can obtain the name of an event by calling
getName( ).
The PropertyDescriptor class describes a Bean property. It supports several methods that
manage and describe properties. For example, you can determine if a property is bound by
calling isBound( ). To determine if a property is constrained, call isConstrained( ). You can
obtain the name of property by calling getName( ).
The Introspector class provides several static methods that support introspection. Of most
interest is getBeanInfo( ). This method returns a BeanInfo object that can be used to obtain
information about the Bean. The getBeanInfo( ) method has several forms, including the
one shown here:
static BeanInfo getBeanInfo(Class<?> bean) throws IntrospectionException
The returned object contains information about the Bean specified by bean.
abstract void close()
void mark(int num Chars)
JLabel is Swing’s easiest-to-use component. It creates a label and was introduced in the
preceding chapter. Here, we will look at JLabel a bit more closely. JLabel can be used to
display text and/or an icon. It is a passive component in that it does not respond to user
input. JLabel defines several constructors. Here are three of them:
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)
int read()
Radio buttons are a group of mutually exclusive
buttons, in which only one button can be selected at
any one time.
abstract void close()
The JCheckBox class provides the functionality of a check box. Its immediate superclass is
JToggleButton, which provides support for two-state buttons, as just described. JCheckBox
defines several constructors. The one used here is
JCheckBox(String str
Toggle buttons are objects of the JToggleButton
class. JToggleButton implements AbstractButton.
In addition to creating standard toggle buttons,
JToggleButton is a superclass for two other Swing
components that also represent two-state controls.
These are JCheckBox and JRadioButton, which are
described later in this chapter. Thus, JToggleButton
defines the basic functionality of all two-state
components.
abstract void flush()
void write(int ch)
The JButton class provides the functionality of a push button. You have already seen a
simple form of it in the preceding chapter. JButton allows an icon, a string, or both to be
associated with the push button. Three of its constructors are shown here:
JButton(Icon icon)
JButton(String str)
JButton(String str, Icon icon)
viod write(char buffer[]
void write(String str)
Swing provides a combo box (a combination of a text field and a drop-down list) through
the JComboBox class. A combo box normally displays one entry, but it will also display a
drop-down list that allows a user to select a different entry.
The JComboBox constructor used by
the example is shown here:
JComboBox(Object[ ] items)
Atree is a component that presents a hierarchical view of data. The user has the ability to
expand or collapse individual subtrees in this display. Trees are implemented in Swing by
the JTree class. A sampling of its constructors is shown here:
JTree(Object obj[ ])
JTree(Vector<?> v)
JTree(TreeNode tn)
In Swing, the basic list class is called JList. It supports the selection of one or more items
from a list. Although the list often consists of strings, it is possible to create a list of just
about any object that can be displayed
JScrollPane is a lightweight container that automatically handles the scrolling of another
component.
The component to be scrolled is specified by comp. Scroll bars are automatically displayed
when the content of the pane exceeds the dimensions of the viewport.Here are the steps to follow to use a scroll pane:
- Create the component to be scrolled.
- Create an instance of JScrollPane, passing to it the object to scroll.
- Add the scroll pane to the content pane.
JTabbedPane encapsulates a tabbed pane. It manages a set of components by linking them
with tabs. Selecting a tab causes the component associated with that tab to come to the
forefront. Tabbed panes are very common in the modern GUI. JTabbedPane defines three constructors. We will use its default constructor, which
creates an empty control with the tabs positioned across the top of the pane. The other two
constructors let you specify the location of the tabs, which can be along any of the four
sides. JTabbedPane uses the SingleSelectionModel model.
JTable is a component that displays rows and columns of data. You can drag the cursor
on column boundaries to resize columns.
Depending on its configuration, it is also possible to select a row, column, or cell within the
table, and to change the data within a cell
JTable supplies several constructors. The one used here is
JTable(Object data[ ][ ], Object colHeads[ ])
Three methods are central to the life cycle of a servlet. These are init( ), service( ), and destroy( ).
They are implemented by every servlet and are invoked at specific times by the server. Let
us consider a typical user scenario to understand when these methods are called.
To begin, create a file named HelloServlet.java that contains the following program:
import java.io.;
import javax.servlet.;
public class HelloServlet extends GenericServlet {
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
Start Tomcat as explained earlier. Tomcat must be running before you try to execute a servlet.
Start a Web Browser and Request the Servlet
Start a web browser and enter the URL shown here:
http://localhost:8080/servlets-examples/servlet/HelloServlet
Alternatively, you may enter the URL shown here:
http://127.0.0.1:8080/servlets-examples/servlet/HelloServlet
This can be done because 127.0.0.1 is defined as the IP address of the local machine.
You will observe the output of the servlet in the browser display area. It will contain the
string Hello! in bold type.
The javax.servlet package contains a number of interfaces and classes that establish the
framework in which servlets operate. The following table summarizes the core interfaces
that are provided in this package. The most significant of these is Servlet. All servlets must
implement this interface or extend a class that implements the interface. The ServletRequest
and ServletResponse interfaces are also very important.
Two packages contain the classes and interfaces that are required to build servlets. These are
javax.servlet and javax.servlet.http. They constitute the Servlet API. Keep in mind that these
packages are not part of the Java core packages.
Here we will develop a servlet that handles an HTTP GET request. The servlet is invoked when
a form on a web page is submitted. The example contains two files. A web page is defined
in ColorGet.htm, and a servlet is defined in ColorGetServlet.java. The HTML source code
for ColorGet.htm is shown in the following listing. It defines a form that contains a select
element and a submit button
Here we will develop a servlet that handles an HTTP POST request. The servlet is invoked
when a form on a web page is submitted. The example contains two files. A web page is
defined in ColorPost.htm, and a servlet is defined in ColorPostServlet.java.
The HTML source code for ColorPost.htm is shown in the following listing. It is identical
to ColorGet.htm except that the method parameter for the form tag explicitly specifies that
the POST method should be used, and the action parameter for the form tag specifies a
different servlet.
A session can be created via the getSession( ) method of HttpServletRequest. An
HttpSession object is returned. This object can store a set of bindings that associate names with
objects. The setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( )
methods of HttpSession manage these bindings. It is important to note that session state is
shared among all the servlets that are associated with a particular client.
The HTML source code for AddCookie.htm is shown in the following listing. This page
contains a text field in which a value can be entered. There is also a submit button on the
page.
The javax.servlet.http package contains a number of interfaces and classes that are commonly
used by servlet developers. You will see that its functionality makes it easy to build servlets
that work with HTTP requests and responses.
The main package is javax.swing. This package must be imported into any program
that uses Swing. It contains the classes that implement the basic Swing components, such as
push buttons, labels, and check boxes.
The preceding example showed the basic form of a Swing program, but it left out one
important part: event handling. Because JLabel does not take input from the user, it does
not generate events, so no event handling was needed. However, the other Swing components
do respond to user input and the events generated by those interactions need to be handled.
Events can also be generated in ways not directly related to user input. For example, an
event is generated when a timer goes off. Whatever the case, event handling is a large part
of any Swing-based application
The second type of program that commonly uses Swing is the applet. Swing-based applets
are similar to AWT-based applets, but with an important difference: A Swing applet extends
JApplet rather than Applet. JApplet is derived from Applet. Thus, JApplet includes all of
the functionality found in Applet and adds support for Swing. JApplet is a top-level Swing
container, which means that it is not derived from JComponent. Because JApplet is a
top-level container, it includes the various panes described earlier. This means that all
components are added to JApplet
In general, Swing components are derived from the JComponent class. (The only exceptions
to this are the four top-level containers, described in the next section.) JComponent provides
the functionality that is common to all components. For example, JComponent supports the
pluggable look and feel. JComponent inherits the AWT classes Container and Component.
Thus, a Swing component is built on and compatible with an AWT component.
Swing defines two types of containers. The first are top-level containers: JFrame, JApplet,
JWindow, and JDialog. These containers do not inherit JComponent. They do, however,
inherit the AWT classes Component and Container. Unlike Swing’s other components,
which are lightweight, the top-level containers are heavyweight. This makes the top-level
containers a special case in the Swing component library.
The String class supports several constructors. To create an empty String, you call the default constructor.
click to edit