Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 28

Unit III Applet Programming:

A Java applet is an applet delivered to users in the form of Java bytecode. Java applets can run in a Web browser using a Java Virtual Machine (JVM), or in Sun's AppletViewer, a stand-alone tool for testing applets. Java applets were introduced in the first version of the Java language in 1995, and are written in programming languages that compile to Java bytecode, usually in Java, but also in other [8] [9] [10] languages such as Jython, JRuby, or Eiffel (via SmartEiffel). Java applets run at very fast speeds comparable to, but generally slower than, other compiled [11] languages such as C++, but until approximately 2011 many times faster than JavaScript. In addition they can use 3D hardware acceleration that is available from Java. This makes applets well suited for non-trivial, computation intensive visualizations. As browsers have gained support for native hardware accelerated graphics in the form of Canvas and WebGL, as well as Just in Time compiled JavaScript, the speed difference has become less noticeable. Since Java's bytecode is cross-platform or platform independent, Java applets can be executed by browsers for many platforms, includingMicrosoft Windows, Unix, Mac OS and Linux. It is also trivial to run a Java applet as an application with very little extra code. This has the advantage of running a Java applet in offline mode without the need for any Internet browser software and also directly from theintegrated development environment (IDE).

Overview
Applets are used to provide interactive features to web applications that cannot be provided by HTML alone. They can capture mouse input and also have controls like buttons or check boxes. In response to the user action an applet can change the provided graphic content. This makes applets well suitable for demonstration, visualization and teaching. There are online applet collections for [12] [3] studying various subjects, from physics to heart physiology. Applets are also used to create online game collections that allow players to compete against live opponents in real-time. An applet can also be a text area only, providing, for instance, a cross platform command-line [13] interface to some remote system. If needed, an applet can leave the dedicated area and run as a separate window. However, applets have very little control over web page content outside the applet dedicated area, so they are less useful for improving the site appearance in general (while applets [14] [15] like news tickers or WYSIWYG editors are also known). Applets can also play media in formats [16] that are not natively supported by the browser HTML pages may embed parameters that are passed to the applet. Hence the same applet may appear differently depending on the parameters that were passed. As applets have been available before CSS, they were also widely used for trivial effects like [17] navigation buttons. This use is criticized and declining. [edit]Technical

information

Java applets are executed in a sandbox by most web browsers, preventing them from accessing local data like clipboard or file system. The code of the applet is downloaded from a web server and the

browser either embeds the applet into a web page or opens a new window showing the applet's user interface. A Java applet extends the class java.applet.Applet, or in the case of a Swing applet, javax.swing.JApplet. The class must override methods from the applet class to set up a user interface inside itself (Applet is a descendant of Panel which is a descendant ofContainer. As applet inherits from container, it has largely the same user interface possibilities as an ordinary Java application, including regions with user specific visualization. The first implementations involved downloading an applet class by class. While classes are small files, there are frequently a lot of them, so applets got a reputation as slow loading components. However, since jars were introduced, an applet is usually delivered as a single file that has a size similar to a large image file (hundreds of kilobytes to several megabytes). The domain from where the applet executable has been downloaded is the only domain to which the usual (unsigned) applet is allowed to communicate. This domain can be different from the domain where the surrounding HTML document is hosted. Java system libraries and runtimes are backwards compatible, allowing to write code that runs both on current and on future versions of the Java virtual machine. [edit]Similar

technologies

Many Java developers, blogs and magazines are recommending that the Java Web Start technology [18][19] be used in place of Applets. Java Web Start also allows to launch unmodified applet code, only it then runs in a separate window (not inside the invoking browser). A Java Servlet is sometimes informally compared to be "like" a server-side applet, but it is different in its language, functions, and in each of the characteristics described here about applets. [edit]Embedding

into a web page

The applet can be displayed on the web page by making use of the deprecated applet HTML [20] [21] [22] element, or the recommended objectelement. Embed element can be used with Mozilla family browsers (embed was deprecated in HTML 4 but is included in HTML 5). This specifies the applet's source and location. Object and embed tags can also download and install Java virtual machine (if required) or at least lead to the plugin page. Applet and object tags also support loading of the serialized applets that start in some particular (rather than initial) state. Tags also specify the message that shows up in place of the applet if the browser cannot run it due any reason. However, despite object being officially a recommended tag, as of 2010, the support of the object tag was not yet consistent among browsers and Sun kept recommending the [23] older applet tag for deploying in multibrowser environments, as it remained the only tag consistently supported by the most popular browsers. To support multiple browsers, the object tag currently requires JavaScript (that recognizes the browser and adjusts the tag), usage of additional browser-specific tags or delivering adapted output from the server side. Deprecating applet tag has been criticized. Oracle now provides a maintained JavaScript code platform workarounds
[24] [25]

to launch applets with cross

Advantages
A Java applet can have any or all of the following advantages:
[28]

It is simple to make it work on Linux, Microsoft Windows and Mac OS X i.e. to make it cross platform. Applets are supported by most web browsers. The same applet can work on "all" installed versions of Java at the same time, rather than just the latest plug-in version only. However, if an applet requires a later version of theJava Runtime Environment (JRE) the client will be forced to wait during the large download. Most web browsers cache applets so will be quick to load when returning to a web page. Applets also improve with use: after a first applet is run, the JVM is already running and starts quickly (the JVM will need to restart each time the browser starts afresh). It should be noted that JRE versions 1.5 and greater stop the JVM and restart it when the browser navigates from one HTML page containing an applet to another containing an applet. It can move the work from the server to the client, making a web solution more scalable with the number of users/clients. If a standalone program (like Google Earth) talks to a web server, that server normally needs to support all prior versions for users which have not kept their client software updated. In contrast, a properly configured browser loads (and caches) the latest applet version, so there is no need to support legacy versions. The applet naturally supports the changing user state, such as figure positions on the chessboard. Developers can develop and debug an applet direct simply by creating a main routine (either in the applet's class or in a separate class) and calling init() and start() on the applet, thus allowing for development in their favorite Java SE development environment. All one has to do after that is re-test the applet in the AppletViewer program or a web browser to ensure it conforms to security restrictions. An untrusted applet has no access to the local machine and can only access the server it came from. This makes such an applet much safer to run than a standalone executable that it could replace. However, a signed applet can have full access to the machine it is running on if the user agrees. Java applets are fast - and can even have similar performance to native installed software.

[edit]Disadvantages A Java applet may have any of the following disadvantages: It requires the Java plug-in. Some browsers, notably mobile browsers running Apple iOS or Android do not run Java applets [29][30] at all. Some organizations only allow software installed by the administrators. As a result, some users can only view applets that are important enough to justify contacting the administrator to request installation of the Java plug-in. As with any client-side scripting, security restrictions may make it difficult or even impossible for an untrusted applet to achieve the desired goals. However, simply editing the java.policy file in

the JAVA JRE installation, one can grant access to the local filesystem or system clipboard for example, or to other network sources other than the network source that served the applet to the browser. Some applets require a specific JRE. This is discouraged.
[31]

If an applet requires a newer JRE than available on the system, or a specific JRE, the user running it the first time will need to wait for the large JRE download to complete. Java automatic installation or update may fail if a proxy server is used to access the web. This makes applets with specific requirements impossible to run unless Java is manually updated. The Java automatic updater that is part of a Java installation also may be complex to configure if it must work through a proxy. Unlike the older applet tag, the object tag needs workarounds to write a cross-browser HTML document. There is no standard to make the content of applets available to screen readers. Therefore, applets can harm the accessibility of a web site to users with special needs.

Local & Remote Applets:

Local and Remote Applets


One of Java's major strengths is that you can use the language to create dynamic content for your Web pages. That is, thanks to Java applets, your Web pages are no longer limited to the tricks you can perform with HTML. Now your Web pages can do just about anything you want them to. All you need to do is write the appropriate applets. But writing Java applets is only half the story. How your Web page's users obtain and run the applets is equally as important. It's up to you to not only write the applet (or use someone else's applet), but also to provide users access to the applet. Basically, your Web pages can contain two types of applets: local and remote. In this section, you learn the difference between these applet types, which are named after the location at which they are stored. Local Applets A local applet is one that is stored on your own computer system (Figure 3.1). When your Web page must find a local applet, it doesn't need to retrieve information from the Internet-in fact, your browser doesn't even need to be connected to the Internet at that time. As you can see in Listing 3.1, a local applet is specified by a path name and a file name. Figure 3.1 : Local applets are stored on and loaded from your computer system. Listing 3.1 LST3_1.TXT: Specifying a Local Applet.
<applet codebase="tictactoe" code="TicTacToe.class" width=120

height=120> </applet>

In Listing 3.1, the codebase attribute specifies a path name on your system for the local applet, whereas the code attribute specifies the name of the byte-code file that contains the applet's code. The path specified in the codebase attribute is relative to the folder containing the HTML document that references the applet. (See the "Optional Attributes for Applets" section of Chapter 2for more information.) Remote Applets A remote applet is one that is located on another computer system (Figure 3.2). This computer system may be located in the building next door or it may be on the other side of the world-it makes no difference to your Java-compatible browser. No matter where the remote applet is located, it's downloaded onto your computer via the Internet. Your browser must, of course, be connected to the Internet at the time it needs to display the remote applet. Figure 3.2 : Remote applets are stored on another system and are down-loaded onto your computer via the Internet. To reference a remote applet in your Web page, you must know the applet's URL (where it's located on the Web) and any attributes and parameters that you need to supply in order to display the applet correctly. If you didn't write the applet, you'll need to find the document that describes the applet's attributes and parameters. This document is usually written by the applet's author. Listing 3.2 shows how to compose an HTML <applet> tag that accesses a remote applet. Listing 3.2 LST3_2.TXT: Specifiying a Remote Applet.
<applet codebase="http://www.myconnect.com/applets/" code="TicTacToe.class" width=120 height=120> </applet>

The only difference between Listing 3.1 and Listing 3.2 is the value of the codebase attribute. In the first case, codebase specifies a local folder, and in the second case, it specifies the URL at which the applet is located.

Applet & Application:

Applications, in short, are computer programs that you write that run on your computer. You start from scratch, and you write the whole program; you have full control. Applications start by you typing onto the screen java NameOfClass. The Java software on your computer looks for the class that has the same name (in this case NameOfClass), looks to see if it has a main method. If it does it starts from the main method, and continues until either the program finishes, or is terminated by the user (i.e., by pressing control C). Applets on the other hand are programs that you write, and put inside your web page. When someone opens up your web page, he automatically downloads any applet that you have on your web page, just like an image. But by an applet, you can't always control how much of the screen the applet takes up. The applet is shown with the web page on the browser. Let's say that the user has an applet that is running on the browser, and he opens up a different window over your applet. Your applet is going to have to know how to stop in middle of what it is doing, and restart when the user goes back to your applet. Let's say the user resizes the browser window, then your applet is going to have to know how to redraw itself. That is a lot of work. The good news is that you do not have to do the work. When you extend the Applet class (for now all that means is you write extends applet after the name of the class), the browser does most of the work for you. The browser supplies the "main" method, and around 200 methods that deal with the window resizing, starting, stopping, etc. The browser is like a container that has its own Java machine, and all that it needs is for you to fill in mainly two spots; what do you want the applet to do when it starts and downloads the applet for the first time, and what do you want for the applet to do when it needs to redraw itself every time. For example, let's say that your applet comes with an image picture. You want to tell the browser to download the image only once, and save it temporarily, while the user is on your site. However, you want the browser to redraw the picture every time something blocks it. Therefore, there are two spots available, one where you tell it that when the user starts the applet the first time download the picture, and the second for when you want the applet to redraw the picture. If you told it to download the picture every time it needed to be redrawn your applet would take forever, and if you told it to draw the picture only once then if the user opened another window on top of it and takes it off, your picture would not be redrawn. Therefore there are two main spots to fill, and the browser does the rest of the work. Because the browser runs its own Java software (which has to be this way, because the user might not have any of its own Java software elsewhere), you have to follow the rules of the browser that it is running on. Some browsers, especially the old ones, are unable to run Swing (advanced graphics), and therefore if you care you would choose to use only the simple graphics that all browsers use. See the Downloading Browsers section. Another difference is that for security reasons applets are sometimes restricted in creating it's own network connections, looking into your files, etc.

Or in other words

Applets as previously described, are the small programs while applications are larger programs. Applets don't have the main method while in an application execution starts with the main method. Applets can run in our browser's window or in an appletviewer. To run the applet in an appletviewer will be an advantage for debugging. Applets are designed for the client site programming purpose while the applications don't have such type of criteria. Applet are the powerful tools because it covers half of the java language picture. Java applets are the best way of creating the programs in java. There are a less number of java programmers that have the hands on experience on java applications. This is not the deficiency of java applications but the global utilization of internet. It doesn't mean that the java applications don't have the place. Both (Applets and the java applications) have the same importance at their own places. Applications are also the platform independent as well as byte oriented just like the applets. Applets are designed just for handling the client site problems. while the java applications are designed to work with the client as well as server. Applications are designed to exists in a secure area. while the applets are typically used. Applications and applets have much of the similarity such as both have most of the same features and share the same resources. Applets are created by extending the java.applet.Applet class while the java applications start execution from the main method. Applications are not too small to embed into a html page so that the user can view the application in your browser. On the other hand applet have the accessibility criteria of the resources. The key feature is that while they have so many differences but both can perform the same purpose. Review of Java Applets: You have previously learned about the java applets. To create an applet just create a class that extends the java.applet.Applet class and inherit all the features available in the parent class. The following programs make all the things clear. import java.awt.*; import java.applet.*;

class Myclass extends Applet { public void init() { /* All the variables, methods and images initialize here will be called only once because this method is called only once when the applet is first initializes */ } public void start() { /* The components needed to be initialize more than once

in your applet are written here or if the reader switches back and forth in the applets. This method can be called more than once.*/ }

public void stop() { /* This method is the counterpart to start(). The code, used to stop the execution is written here*/ }

public void destroy() { /* This method contains the code that result in to release the resources to the applet before it is finished. This method is called only once. */ } public void paint(Graphics g) { /* Write the code in this method to draw, write, or color things on the applet pane are */ } }

In the above applet you have seen that there are five methods. In which two ( init() and destroy ) are called only once while remaining three (start() , stop() , and paint() ) can be called any number of times as per the requirements. The major difference between the two (applet and application) is that java applications are designed to work under the homogenous and more secure areas. On contrary to that, java applets are designed to run the heterogeneous and probably unsecured environment. Internet has imposed several restrictions on it. Applets are not capable of reading and writing the user's file system. This means that the applet neither can access nor place anything locally. To illustrate this lets take an example.. Many Window based C applications uses the .INF file as the initialization file to store the information about the application and any user preferences in 16-bit Windows or the Registry in 32-bit Windows. While in case of current applet it is not possible. One more thing to point here is that applets are unable to use the native methods, run any program on the user system or load shared libraries. The major security concern here is that the local shared libraries and the native methods may results in the loophole in the java security model.

Applets are not capable of communicating the server than one from which they are originating. There are the cases in which an encryption key is used for the verification purpose for a particular applet to a server. But accessing a remote server is not possible. The conclusion is that the java applets provides a wide variety of formats for program execution and a very tight security model on the open environment as on the Internet. Introduction to Java Application : Java applications have the majority of differences with the java applets. If we talk at the source code level, then we don't extend any class of the standard java library that means we are not restricted to use the already defined method or to override them for the execution of the program. Instead we make set of classes that contains the various parts of the program and attach the main method with these classes for the execution of the code written in these classes. The following program illustrate the structure of the java application. public class MyClass { /* Various methods and variable used by the class MyClass are written here */ class myClass { /* This contains the body of the class myClass */ } public static void main(String args[]) { /* The application starts it's actual execution from this place. **/ } }

The main method here is nothing but the system method used to invoke the application. The code that results an action should locate in the main method. Therefore this method is more than the other method in any java application. If we don't specify the main method in our application, then on running the application will through an exception like this one: In the class MyClass: void main(String args[]) is undefined But at higher level major concern is that in a typical java application security model, an application can access the user's file system and can use native methods. On properly configuring the user's environment and the java application it will allow access to all kind of stuff from the Internet. In most of the cases it is seen that the java application seems like a typical C/C++ application. Now we are going to create plenty of applications to exemplify some of the methods and features of a specific Java application. All of them are console based Java applications because here we are not going to cover the AWT.

Applet Life Cycle:


When you run the Applet you will find that when an applet begins, the AWT calls the following methods, in this sequence:1) Init() 2) Start() 3) Paint() And, when an applet is terminated, the following sequence of method calls takes place: 1) Stop() 2) Destroy()

init()

when the applet is first loaded, init()method is very first method to be called . It is called

exactly once in an applet's life. This is where we should initialize variables, read PARAM tags, start dowloading any other images or media files or setup the user inerface. Many applets have init() method but it is not compulsory to overide.

start()

Start() method is called just after init() method. It is called at least once in an applet's life.

start( ) is called each time an applets HTML document is displayed onscreen. So, if a user leaves a web page and comes back, the applet resumes execution at start( ). Many applets have start() method but it is not compulsory to overide.

paint() Applet needs to draw the AWT window for displaying output (strings and figures). For this
paint() method is called. The paint( ) method is called each time your applets output must be redrawn. For example, the window in which the applet is running may be overwritten by another window and then uncovered. Or the applet window may be minimized and then restored. The paint( ) method has one parameter of type Graphics. This parameter will contain the graphics

context, which describes the graphics environment in which the applet is running. This context is used whenever output to the applet is required.

stop()

Stop() method is complement of start() method. The stop() method is called at least once in

an applet's life, when the browser leaves the page in which the applet is embedded.

destroy()

The destroy() method is called exactly once in an applet's life, just before the browser

unloads the applet. This frees up any resources the applet may be using. The stop( ) method is always called before destroy( ). This method can be said as a complement of the init() method.

creating an executable applet :


Executable applet is nothing but the .class file of the applet, which is obtained by compiling the source code of the applet. Compiling an applet is exactly the same as compiling an application. Therefore, we can use the Java compiler to compile the applet. Assume that we have created a file called HelloJava.java for our applet. Here are the steps required for compiling the HelloJava applet. 1. Move to the directory containing command: javacHelloJava.java the source code and type the following

2. The compiled output file called HelloJava.class is placed in the same directory as the source. 3. If any error message is received, then we must check for errors, correct them and compile the applet again.

In Other words

These optional steps describe how to create an applet client that runs in a Web browser. Complete all steps under "Creating the application" before running the applet: 1. 2. 3. 4. 5. Verify that your browser can run JDK 1.2 applets. Prepare your EAServer installation to run applets. Write the applet code. Create an HTML page to run the applet. Run the applet.

Applet Tag :
Applets are embedded in HTML documents with the <APPLET> tag. The <APPLET> tag resembles the HTML <IMG> image tag.[1] It contains attributes that identify the applet to be displayed and, optionally, give the Web browser hints about how it should be displayed. The standard image tag sizing and alignment attributes, such as height and width, can be used inside the applet tag. Unlike images, however, applets have both an opening <APPLET> and a closing </APPLET> tag. Sandwiched between these can be any number of <param> tags that contain application-specific parameters to be passed to the applet itself: [1] If you are not familiar with HTML or other markup languages, you may want to refer to HTML: The Definitive Guide, from O'Reilly & Associates, for a complete reference on HTML and structured Web documents.
<applet attribute [ attribute ] ... [<param parameter >] [<param parameter >] ... </applet> >

3.4.1 Attributes Attributes are name=value pairs that are interpreted by a Web browser or appletviewer. (Many HTML tags besides <APPLET> have attributes.) Attributes of the <APPLET> tag specify general features that apply to all applets, such as size and alignment. The definition of the <APPLET> tag lists a fixed set of recognized attributes; specifying an incorrect or nonexistent attribute should be considered an HTML error.

Three attributes are required in the <APPLET> tag. Two of these attributes specify the space the applet occupies on the screen: not surprisingly, they're named width and height. The third required attribute may be either code or object; you must supply one of these attributes, and you can't specify both. The code attribute specifies the class file from which the applet is loaded; the object attribute specifies a serialized representation of an applet. Most often, you'll use the code attribute; the tools for creating serialized applets aren't quite there yet. (Serializing an applet, or any Java class, means saving it, perhaps after customizing it, for use later. You can use appletviewer to create serialized applets, but that feature isn't really useful yet. Serialized applets will become interesting when the next generation of integrated development environments for Java are available.) The following is an HTML fragment for a hypothetical, simple clock applet that takes no parameters and requires no special HTML layout:
<applet code=AnalogClock width=100 height=100></applet>

The HTML file that contains this <APPLET> tag must be stored in the same directory as the AnalogClock.class class file. The applet tag is not sensitive to spacing, so the above is therefore equivalent to:
<applet code=AnalogClock width=100 height=100> </applet>

You can use whatever form seems appropriate. 3.4.2 Parameters Parameters are analogous to command-line arguments; they provide a way to pass information to an applet. Each <param> tag contains a name and a value that are passed as strings to the applet:
<param name = parameter_name value = parameter_value>

Parameters provide a means of embedding application-specific data and configuration information within an HTML document.[2] Our AnalogClock applet, for example, might accept a parameter that selects between local and universal time: [2] If you are wondering why the applet's parameters are specified in yet another type of tag, here's the reason. In the original alpha release of Java, applet parameters were included inside of a single <app> tag along with formatting

attributes. However, this format was not SGML-compliant, so the <param> tag was added.
<applet code=AnalogClock width=100 height=100> <param name=zone value=GMT> </applet>

Presumably, this AnalogClock applet is designed to look for a parameter named zone with a possible value of GMT. Parameter names and values can be quoted to contain spaces and other special characters. We could therefore be more verbose and use a parameter value like the following:
<param name=zone value="Greenwich Mean Time">

The parameters a given applet expects are determined by the developer of that applet. There is no fixed set of parameter names or values; it's up to the applet to interpret the parameter name/value pairs that are passed to it. Any number of parameters can be specified, and the applet may choose to use or ignore them as it sees fit. The applet might also consider parameters to be either optional or required and act accordingly.

i/o Basics:
I/O Fundamentals The Java language provides a simple model for input and output (I/O). All I/O is performed by writing to and reading from streams of data. The data may exist in a file or an array, be piped from another stream, or even come from a port on another computer. The flexibility of this model makes it a powerful abstraction of any required input and output. One of the key issues regarding Java I/O is providing file support for all Javaenabled platforms. The Java file I/O classes must restrict themselves to a reasonable, "least common denominator" of file-system functionality. Provided functionality is restricted to only those general features that can be used on any modern platform. For example, you won't find ways to work with OS/2's "extended attributes", or "sync" a file in UNIX. All classes referred to in this module are located in the java.io package (unless otherwise stated.) Notes A few notes on the content and examples in this module: This module refers to some methods and classes that are only available in the Java 2 SDK, standard edition v1.2 (formerly known as "JDK 1.2"). Methods and classes such as these are marked "(since 1.2)" We discuss the most commonly used methods in these classes, not necessarily all available methods. See the javadocs for a list of all methods in each class. All examples will require exception handling to catch IOException. This

exception handling is omitted in many examples for clarity, and discussed at the end of the module. If an example is a complete class listing, the exception handling will be present.

UNIT IV

String handeling:
A String is a sequence of characters. In many other languages a string is treated as a character array. But in Java a string is treated as an object. After creating a string object you can not change it. So that is why it is said that a string is immutable. Java provides three string classes named String, StringBuffer and StringBuilder. The reason for three class is to reduce the problem of the mutability of the StringBuffer and StringBuilder classes; both are mutable. But in your mind you might ask why not remove the String class. The reason is that an immutable String can be implemented more efficiently. The StringBuffer and StringBuilder classes have the same methods with one difference and that's synchronization. A StringBuffer is synchronized (which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized (which implies it isn't thread safe). So, if you aren't going to use threading then use the StringBuilder class as it wll be more efficient than StringBuffer due to the absence of synchronization. In this article we describe the String class and its methods. String class The String class has several constructors (near about 13) and several methods (near about more than 60) so it's not possible to describe all of them but the important constructors and methods are described in this article. Constructor summary String() String(Char chars[]) String(String strobj) String(byte[] bytes) Initializes a newly created String object so that it represents an empty character sequence. Allocates a new String so that it represents the sequence of characters currently contained in the character array argument. Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Constructs a new String by decoding the specified array of bytes using the platform's default charset.

Method Summary Return Type char int int Name Description

charAt(int index) Returns the char value at the specified index. compareTo(String Compares two strings lexicographically. anotherString) compareToIgnoreCase( String Compares two strings lexicographically, ignoring case

String int string int char[] String Static String

str) concat(String str) indexOf(int ch) replace(char oldchar, char newchar) length() toCharArray() trim() valueOf(Object obj)

differences. Concatenates the specified string to the end of this string. Returns the index within this string of the first occurrence of the specified character Returns a new string resulting from replacing all occurrences ofoldChar in this string with newChar. Returns the length of this string. Converts this string to a new character array. Returns a copy of the string, with leading and trailing whitespace omitted. Returns the string representation of the Object argument.

Other words
The String class is defined in the java .lang package and hence is implicitly available to all the programs in Java. The String class is declared as final, which means that it cannot be subclassed. It extends the Object class and implements the Serializable, Comparable, and CharSequence interfaces. Java implements strings as objects of type String. A string is a sequence of characters. Unlike most of the other languages, Java treats a string as a single value rather than as an array of characters.

The String objects are immutable, i.e., once an object of the String class is created, the string it contains cannot be changed. In other words, once a String object is created, the characters that comprise the string cannot be changed. Whenever any operation is performed on a String object, a new String object will be created while the original contents of the object will remain unchanged. However, at any time, a variable declared as a String reference can be changed to point to some other String object.

Other words

String represents a sequence of characters. It has fixed length of character sequence. Once a string object has been created than we can't change the character that comprise that string. It is immutable. This allows String to be shared. String object can be instantiated like any other object String s=new String();

This creates an empty string by calling default constructor. char c[]={'a','b','d'}; String s=new String(c);

In this case string s points to the character array "abd". StringBuffer This represents growable and writeable character sequence. It is mutable in nature. StringBuffer are safe to be used by multiple thread as they are sunchronized but this brings performance penalty. It defines 3-constructor:

StringBuffer(); //initial capacity of 16 characters StringBuffer(int size); //The initial size StringBuffer(String str); The following table describes the various important string search methods.

int indexOf(int ch)

Returns the first occurrence of the specified character.

int lastIndexOf(int ch)

Returns last occurrence of the specified character.

boolean contains(CharSequence s)

Returns true if the string contains the specified character sequence.

String replace(char oldChar,char newChar)

Returns a new string resulting from replacing all occurrences of oldChar in th string with newChar.

String substring(int startIndex)

return a subtring,and startindex specifies the index at which substring will begin.

String trim()

This will removed the leading and trailing whitespace

String concat(String str)

It will append the string str at the end.

StringBuilder StringBuilder class is introduced in Java 5.0 version. This class is an alternative to the existing StringBuffer class. If you look into the operations of the both the classes, there is no difference. The only difference between StringBuilder and StringBuffer is that StringBuilder class is not synchronized so it gives better performance. Whenever there are no threading issues, its

preferable to use StringBuilder. StringBuffer class can be replaced by StringBuilder with a simple search and replace with no compilation issue.

Event handeling:
No matter what the programming language or paradigm you are using, chances are that you will eventually run into a situation where your program will have to wait for an external event to happen. Perhaps your program must wait for some user input, or perhaps it must wait for data to be delivered over the network. Or perhaps something else. In any case, the program must wait for something to happen that is beyond the program's control: the program cannot make that event happen. In this situation there are two general options for making a program wait for an external event to happen. The first of these is called polling and means you write a little loop of the for "while the event has not happened, check again". Polling is very simple to build and very straightforward. But it is also very wasteful: it means a program takes up processor time in order to do absolutely nothing but wait. This is usually considered too much of a drawback for programs that have to do a lot of waiting. Programs that have a lot of waiting moments (for example, programs that have a graphical user interface and often have to wait for long periods of time until the user does something) usually fare much better when they use the other mechanism: event-driven programming. In event-driven programming a program that must wait, simply goes to sleep. It no longer takes up processor time, might even be unloaded from memory and generally leaves the computer available to do useful things. But the program doesn't completely go away; instead, it makes a deal with the computer or the operating system. A deal sort of like this: Okay Mr. Operating System, since I have to wait for an event to happen, I'll go away and let you do useful work in the meantime. But in return, you have to let me know when my event has happened and let me come back to deal with it. Event-driven programming usually has a pretty large impact on the design of a program. Usually, a program has to be broken up into separate pieces to do event-drive programming (one piece for general processing and one or more others to deal with events that occur). Event-driven programming in Java is more complicated than non-event driven but it makes far more efficient use of the hardware and sometimes (like when developing a graphical user interface) dividing your code up into eventdriven blocks actually fits very naturally with your program's structure. In this module we examine the basis of the Java Platform's facilities for event-driven programming and we look at some typical examples of how that basis has been used throughout the platform.

[edit]The Java Platform Event Model


[edit]Introduction
One of the most interesting things about support for event-driven programming on the Java platform is that there is none, as such. Or, depending on your point of view, there are many different individual pieces of the platform that offer their own support for event-driven programming.

The reason that the Java platform doesn't offer one general implementation of event-driven programming is linked to the origins of the support that the platform does offer. Back in 1996 the Java programming language was just getting started in the world and was still trying to gain a foothold and conquer a place for itself in software development. Part of this early development concentrated on software development tooling like IDEs. One of the trends in software development around that time was for reusable software components geared towards user interfaces: components that would encapsulate some sort of interesting, reusable functionality into a single package that could be handled as a single entity rather than as a loose collection of individual classes. Sun Microsystems tried to get on the component bandwagon by introducing what they called a JavaBean, a software component not only geared towards the UI but that could also be configured easily from an IDE. In order to make this happen Sun came up with a large specification of JavaBeans (the JavaBeans Spec) dealing mostly with naming conventions (to make the components easy to handle from an IDE). But Sun also realized at the same time that a UI-centric component would need support for an eventdriven way of connecting events in the component to business logic that would have to be written by the individual developer. So the JavaBeans Spec also included a small specification for an event Model for the Java platform. When they started working on this Event Model, the Sun engineers were faced with a choice: try to come up with a huge specification to encompass all possible uses of an event model, or just specify an abstract, generic framework that could be expanded for individual use in specific situations. They chose the latter option and so, love it or hate it, the Java Platform has no generic support for eventdriven programming other than this general Event Model framework.

Java Event Handling


By S. Nageswara Rao, Corporate Trainer on May 22, 2011

In AWT components, we came to know every component (except Panel and Label) generates events when interacted by the user like clicking over a button or pressing enter key etc. Listeners handle the events. Let us know the style (or design pattern) Java follows to handle the events. The event handling involves four types of classes. 1. Event Sources 2. Event classes 3. Event Listeners 4. Event Adapters 1. Event Sources

Event sources are components, subclasses ofjava.awt.Component, capable to generate events. The event source can be a button, TextField or a Frame etc. 2. Event classes Almost every event source generates an event and is named by some Java class. For example, the button generates ActionEvent and Checkbox generates ItemEvent. All events listed injava.awt.event package. Following list gives a few components and their listeners.
Component Event it generates

Button, TextField, List, Menu Frame Checkbox, Choice, List Scrollbar Mouse (hardware) Keyboard (hardware)

ActionEvent WindowEvent ItemEvent AdjustmentEvent MouseEvent KeyEvent

The events generated by hardware components (like MouseEvent and KeyEvent) are known as low-level events and the events generated by software components (like Button, List) are known as semantic events. 3. Event Listeners The events generated by the GUI components are handled by a special group of classes known as "listeners". Listener is an interface. Every component has its own listener, say, AdjustmentListener handles the events of scrollbar Some listeners handle the events of a few components. For example, ActionListener handles the events of Button, TextField, List and Menus. Listeners are from java.awt.eventpackage. More description on listeners and list of listeners is available at Java AWT Listeners. 4. Event Adapters When a listener includes many abstract methods to override, the coding becomes heavy to the programmer. For example, to close the frame, you override seven abstract methods of WindowListener, in which, infact you are using only one method. To avoid this heavy coding, the designers come with another group of classes known as "adapters". Adapters are abstract classes defined

in java.awt.event package. Every listener that has more than one abstract method has got a corresponding adapter class.

AWT : working with windows grphics and text:


The Abstract Window Toolkit (AWT) was introduced inChapter 19because it providessupport for applets. This chapter begins its in-depth examination. The AWT containsnumerous classes and methods that allow you to create and manage windows. A fulldescription of the AWT would easily fill an entire book. Therefore, it is not possible todescribe in detail every method, instance variable, or class contained in the AWT.However, this and the following two chapters explain all the techniques needed toeffectively use the AWT when creating your own applets or stand-alone programs. Fromthere, you will be able to explore other parts of the AWT on your own.

In this chapter, you will learn how to create and manage windows, manage fonts, outputtext, and utilize graphics.Chapter 22describes the various controls, such as scroll barsand push buttons, supported by the AWT. It also explains further aspects of Java's event-handling mechanism.Chapter 23examines the AWT's imaging subsystem andanimation.

Although the main purpose of the AWT is to support applet windows, it can also be usedto create stand-alone windows that run in a GUI environment, such as Windows. Most of the examples are contained in applets, so to run them, you need to use an applet viewer or a Javacompatible Web browser. A few examples will demonstrate the creation of standalone, windowed programs

The AWT classes are contained in the java.awt package. It is one of Java's largestpackages. Fortunately, because it is logically organized in a top-down, hierarchicalfashion, it is easier to understand and use than you might at first believe. Although the basic structure of the AWT has been the same since Java 1.0, some of theoriginal methods were deprecated and replaced by new ones when Java 1.1 wasreleased. For backward-compatibility, Java 2 still supports all the original 1.0 methods.However, because these methods are not for use with new code, this book does notdescribe them.

Window Fundamentals

The AWT defines windows according to a class hierarchy that adds functionality andspecificity with each level. The two most common windows are those derived from Panel ,which is used by applets, and those derived from Frame , which creates a standardwindow. Much of the functionality of these windows is derived from their parent classes.Thus, a description of the class hierarchies relating to these two classes is fundamentalto their understanding. Figure 21-1 shows the class hierarchy for Panel and Frame . Let'slook at each of these classes now.

Component

At the top of the AWT hierarchy is the Component class.Component is an abstractclass that encapsulates all of the attributes of a visual component. All user interfaceelements that are displayed on the screen and that interact with the user are subclasses of Component. It defines over a hundred public methods that are responsible for managing events, such as mouse and keyboard input, positioning and sizing the window,and repainting. (You already used many of these methods when you created applets inChapters 19and20.) A Component object is responsible for remembering the currentforeground and background colors and the currently selected text font.

Figure 21.1: the class hierarchy for Panel and Frame Container The Container class is a subclass of Component. It has additional methods that allowother Component objects to be nested within it. Other Container objects can be storedinside of a Container (since they are themselves instances of Component). This makesfor a multileveled containment system. A container is responsible for laying out (that is,positioning) any components that it contains. It does this through the use of variouslayout managers, which you will learn about inChapter 22.

Panel The Panel class is a concrete subclass of Container . It doesn't add any new methods; itsimply implements Container . APanelmay be thought of as a recursively nestable,concrete screen component. Panel is the superclass for Applet. When screen output isdirected to an applet, it is drawn on the surface of a Panel object. In essence, a Panel isa window that does not contain a title bar, menu bar, or border. This is why you don't seethese items when an applet is run inside a browser. When you run an applet using anapplet viewer, the applet viewer provides the title and border. Other components can be added to a Panel object by its add( ) method (inherited from Container). Once these components have been added, you can position and resize themmanually using the setLocation( ),setSize( ), or setBounds( )methods defined by Component . Window TheWindow class creates a top-level window. A top-level window is not contained withinany other object; it sits directly on the desktop. Generally, you won't create Window objects directly. Instead, you will use a subclass of Windowcalled Frame, describednext. Frame Frame encapsulates what is commonly thought of as a "window." It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners. If you create a Frame object from within an applet, it will contain a warning message, such as "Warning:Applet Window," to the user that an applet window has been created. This messagewarns users that the window they see

was started by an applet and not by softwarerunning on their computer. (An applet that could masquerade as a host-based applicationcould be used to obtain passwords and other sensitive information without the user'sknowledge.) When a Frame window is created by a program rather than an applet, anormal window is created.

Canvas

- 471 Although it is not part of the hierarchy for applet or frame windows, there is one other typeof window that you will find valuable: Canvas. Canvas encapsulates a blank window uponwhich you can draw. You will see an example of Canvas later in this book

CONTROLS
WebLogic Workshop provides Java controls that make it easy for you to encapsulate business logic and to access enterprise resources such as databases, legacy applications, and web services. There are three different types of Java Controls: built-in Java controls, portal controls, and custom Java controls. Built-in controls provide easy access to enterprise resources. For example, the Database control makes it easy to connect to a database and perform operations on the data using simple SQL statements, whereas the EJB control enables you to easily access an EJB. Built-in controls provide simple properties and methods for customizing their behavior, and in many cases you can add methods and callbacks to further customize the control. A portal control is a kind of built-in Java control specific to the portal environment. If you are building a portal, you can use portal controls to expose tracking and personalization functions in multi-page portlets. You can also build your own custom Java control from scratch. Custom Java controls are especially powerful when used to encapsulate business logic in reusable components. It can act as the nerve center of a piece of functionality, implementing the desired overall behavior and delegating subtasks to built-in Java controls (and/or other custom Java controls). This use of a custom Java control ensures modularity and encapsulation. Web services, JSP pages, or other custom Java controls can simply use the custom Java control to obtain the desired functionality, and changes that may become necessary can be implemented in one software component instead of many. If you are connecting to an enterprise resource that exposes a standards-based, J2EE, or Web Services interface, you can create a custom Java control to directly connect to that application. However, if you are connecting to an external resource that is proprietary or does not expose standard J2EE APIs, you may need to use a JCA (Java Connector Architecture) adaptor and an Application View control rather than a Java control to connect to that resource. JCA adaptors and the Application View control are available through WebLogic Integration. For more information on using JCA adaptors and the Application View control, see Overview: Application Integration.

LAYOUT MANAGERS

Layout Managers in JavaTM technology Basics of Layout Managers Java technology uses Layout Managers to define the location and size of Graphical User Interface components. Java technology does not encourage programmers to use absolute location and size of components. Java technology instead places components based on specified Layout Manager. A Layout Manager implements a layout policy that defines constraints between components in a container.

Types of Layout Managers Java technology provides the following Layout Managers, each of which implements the LayoutManager interface.

FlowLayout GridLayout BorderLayout GridBagLayout CardLayout

The FlowLayout is the default Layout Manager for Panel, and hence the Applet class. The BorderLayout is the default Layout Manager for Window class and its subclasses (Frame and Dialog). Setting Layout Managers The following method defined in the Container class can be used for setting layout managers.
void setLayout(LayoutManager mgr);

So for example to set FlowLayout as the Layout Manager for a container C, the following can be used C.setLayout(new FlowLayout());

The add method defined in the Container class can be used for adding components to a container. The following are the prototypes of the add method Component add(Component comp); Component add(Component comp, int index); void add(Component comp, Object constraints, int index); void add(Component comp, Object constraint);

The order in which components are added to a container effects the placement of components. Also a component added to a container can itself be a container that holds other components. FlowLayout Manager FlowLayout places component in rows from left to right. Components towards the end of row are written on next row, if there is not enough space in the current row. The FlowLayout honors the specified size of a component. The size of a component never changes regardless of size of container. The following constructors of FlowLayout are provided by AWT FlowLayout();

FlowLayout(int alignment); FlowLayout(int alignment, int hor_gap, int ver_gap);

Alignment can take values of constants - LEFT, CENTER and RIGHT. The default alignment for the components in a row is center. Default horizontal and vertical gaps are 5 pixels. GridLayout Manager A GridLayout Manager places the components in a rectangular grid. Each component's position is identified by a column and row. All the cells in the grid have same size and width. Each component is stretched to the cell size. So a GridLayout ignores the Component's preferred size. The GridLayout class provides the following constructors.
GridLayout(); GridLayout(int rows, int columns); GridLayout(int rows, int columns, int hor_gap, int ver_gap);

This creates a row*col grid layout with the specified horizontal and vertical gaps. In the constructor, either rows or cols can be zero, but not both. The first constructor is equivalent to one row with any number of components. The default gap between components is zero pixels. BorderLayout Manager A BorderLayout Manager divides the window into five regions - North, East, West, South and Center. A component can be explicitly added to one of the regions using the add() method of the Container class. Any space left over by the component in North, East, South and West is occupied by the component in Center. Only the last component added to a region is shown, and not all regions need to be occupied by a component. So a container that uses BorderLayout may have up-to 5 components. The BorderLayout class defines the following constructors BorderLayout(); BorderLayout(int hor_gap, int ver_gap);

As illustrated below, components can be added to the container using add() method defined in the Container class.
Component add(Component comp); void add(Component comp, Object constraints);

Here constraints can be NORTH, SOUTH, EAST, WEST and CENTER. These constants correspond to strings "North", "South", East", "West", and

"Center" respectively. They describe the region where the component should be placed. The default region is CENTER. GridBagLayout GridBagLayout is the most advanced LayoutManager in Java technology. Refer to The Java AWT: GridBagLayout for an excellent coverage of GridBagLayout. Typically the Certification exam includes one question on GridBagLayout.

You might also like