Unit 1
Unit 1
Chapter-1
Introducing Applet
1.1 Applet Basics
Applets are small programs that are designed for transmission over the Internet and run
within a browser. Because Java‘s virtual machine is in charge of executing all Java
programs, including applets, applets offer a secure way to dynamically download and execute
programs over the Web.
There are two general varieties of applets: those based on the Abstract Window Toolkit (AWT)
and those based on Swing. Both the AWT and Swing support the creation of a graphical user
interface (GUI). The AWT is the original GUI toolkit and Swing is Java‘s lightweight
alternative. It is important to understand, however, that Swing-based applets are built upon
the same basic architecture as AWT-based applets. Furthermore, Swing is built on top of the
AWT. Therefore, the information and techniques presented here describe the foundation of
applet programming and most of it applies to both types of applets.
/ / A Minimal AWT-based applet.
import java.awt.*;
import java.applet.*;
public class SimpleApplet extends Applet {
public void paint (Graphics g) {
g.drawString (―Java makes applets easy. ―, 20, 20);
}
}
This applet begins with two import statements. The first imports the Abstract Window Toolkit
classes. Applets interact with the user (either directly or indirectly) through the AWT, not
through the console-based I/O classes. The AWT contains support for a window- based,
graphical user interface. The next import statement imports the applet package. This package
contains the class Applet. Every applet that you create must be a subclass (either directly
or indirectly) of Applet. The next line in the program declares the class SimpleApplet.
This class must be declared as public because it will be accessed by outside code. Inside
SimpleApplet, paint( ) is declared. This method is defined by the AWT Component class
(which is a superclass of Applet) and is overridden by the applet. paint( ) is called each
time the applet must redisplay its output. This can occur for several reasons. For example, the
window in which the applet is running can be overwritten by another window and then
uncovered. Or the applet window can be minimized and then restored. paint( ) is also called
when the applet begins execution. Whatever the cause, whenever the applet must redraw its
output, paint( ) is called. 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.
Inside paint( ), there is a call to drawString( ), which is a member of the Graphics class.
This
method outputs a string beginning at the specified X, Y location. It has the following general
form:
void drawString(String message, int x, int y)
Here, message is the string to be output beginning at x, y. In a Java window, the upper-left
corner is location 0,0. The call to drawString( ) in the applet causes the message to be displayed
beginning at location 20,20.
The applet does not have a main( ) method. Unlike the standalone application program, applets
do not begin execution at main( ). In fact, most applets don‘t even have a main( ) method.
Instead, an applet begins execution when the name of its class is passed to a browser or other
applet-enabled program.
Compiling applet program is similar to stand alone application program. However, running
SimpleApplet involves a different process. There are two ways in which you can run an applet:
inside a browser or with a special development tool that displays applets. The tool provided
with the standard Java JDK is called appletviewer use it to run the applets. We can also run
them in your browser, but the appletviewer is much easier to use during development.
One way to execute an applet (in either a Web browser or the appletviewer) is to write a
short HTML text file that contains a tag that loads the applet. Currently, Oracle recommends
using the APPLET tag for this purpose.
<applet code = ―simple applet ― width=200 height=60>
</applet>
The width and height statements specify the dimensions of the display area used by the applet.
To execute SimpleApplet with an applet viewer, you will execute this HTML file. For example,
if the preceding HTML file is called StartApp.html, then the following command line will
run SimpleApplet:
C:\> appletviewer StartApp.html
Import java.awt.*;
Import java.applet.*;
…………..
…………..
An applet is said to be dead when it is removed from memory. This occurs by invoking the
destroy() method when we quit the browser. Destroying stage occurs only once in the applet‘s
life cycle.
public void destroy()
{
…………
…………
…………
}
Display State
Applet moves to the display state whenever it has to perform some output operations on the
screen. This happens immediately after the applet enters into the running state. The paint()
method is called to accomplish this task.
public void paint(Graphics g)
{
………
……..(Display statements)
}
Similarly, we can change the text to be displayed by an applet by supplying new text to the
applet through a <PARAM .... >tag as shown below:
<PARAM NAME = text VALUE = ‖I love Java ―>
This will produce output as Hello Applet. if we remove <param> tag from HTML file will
produce output as Hello Java.
CHAPTER 2
MANAGING INPUT/OUTPUT FILES IN JAVA
2.1 Introduction
A file is a collection of related records placed in a particular area on the disk. A record is
composed of several fields and a field is a group of characters. Characters in java are Unicode
characters composed of two bytes, each byte containing eight binary digits, 1 or 0.
Storing and managing data using files is known as file processing which includes tasks such
as creating files, updating files and manipulation of data.
InputStream and OutputStream are designed for byte streams. Reader and Writer are
designed for character streams. The byte stream classes and the character stream classes form
separate hierarchies. In general, you should use the character stream classes when working
with characters or strings, and use the byte stream classes when working with bytes or other
binary objects.
InputStream
InputStream is an abstract class that defines Java‘s model of streaming byte input. It
implements the Closeable interface. Most of the methods in this class will throw an
IOException on error conditions. (The exceptions are mark( ) and markSupported( ).) Table
19-1 shows the methods in InputStream.
OutputStream
OutputStream is an abstract class that defines streaming byte output. It implements the
Closeable and Flushable interfaces. Most of the methods in this class return void and throw
an IOException in the case of errors. (The exceptions are mark( ) and markSupported( ).)
The below table gives a brief description of all the methods provided by the InputStream
class
Method Description
1. Read() Reads a byte from the input stream
2. Read(byte b[]) Reads an array of bytes into b
3. Read(byte b[], int n, int m) Reads m bytes into b starting from nth byte
4. Available() Gives number of bytes availale in the input
5. Skip(n) skips over n bytes from the input stream
6. Reset() Goes back to the beginning of the stream
7. Close closes the input stream
There are two kinds of Character Stream classes - Reader classes and Writer classes.
Reader Classes - These classes are subclasses of an abstract class, Reader and they are
used to read characters from a source(file, memory or console).
Writer Classes - These classes are subclasses of an abstract class, Writer and they used
to write characters to a destination(file, memory or console).
Reader
Reader class and its subclasses are used to read characters from source.
Reader class is a base class of all the classes that are used to read characters from a file,
memory or console. Reader is an abstract class and hence we can't instantiate it but we can use
its subclasses for reading characters from the input stream. We will discuss subclasses of
Reader class with their code, in the next few articles.
Methods Description
Int read() This method reads a character from the input
stream
Int read(char[], This method reads a chunk of characters from
ch) the input stream and store them in its char array,
ch.
close() This method closes this output stream and also
frees any system resources connected with it.
Writer
Writer class and its subclasses are used to write characters to a file, memory or console. Writer
is an abstract class and hence we can't create its object but we can use its subclasses for writing
characters to the output stream. We will discuss subclasses of Writer with their code in the next
few articles.
Hierarchy of Writer classes
Methods of writer classes
Methods of Writer class provide support for writing characters to the output stream. As this is
an abstract class. Hence, some undefined abstract methods are defined in ths subclasses of
Output Stream.
Methods Description
abstract void This method flushes the output steam by forcing out buffered
flush() bytes to be written out.
void write(int c) This method writes a characters(contained in an int) to the
output stream.
void write(char[] This method writes a whole char array(arr) to the output
arr) stream.
abstract void This method closes this output stream and also frees any
close() resources connected with this output stream.
Each i/o statement or group of i/o statements must have an exception handler around it as
shown below.
try
{
……
……//I/O statements
}
Catch(IOException e)
{
…….
……//message output statement
}
Data type is to decide the type of file stream classes to be used for handling the data. We should
decide whether the data to be handled is in the form of characters, bytes or primitive type.
The purpose of using a file must also be decided before using it. For example, we should know
whether the file is created for reading only, or writing only, or both the operations.
For using a file, it must be opened first. This is done by creating a file stream and then linking
it to the filename. A file stream can be defined using the classes of Reader/InputStream for
reading data and Writer/OutputStream for writing data.
Common Stream Classes used for I/O Operations
Characters
Read Write
CharArrayReader CharArrayWriter
FileReader FileWriter
PipedReader PipedWriter
Bytes
Read Write
ByteArrayInputstream ByteArrayOutputStream
FileInputStream FileOutputStream
PipedInputStream PipedOutputStream
FileInputStream fis;
try
{
// Assign the filename to the file stream object
fis=new FileInputStream(―test.dat‖);
……
}
Catch(IOException e){}
The indirect approach uses a file object that has been initialized with the desired filename.
This is illustrated by the following code.
fis “test.dat”
import java.io.*;
class ReadBytes
{
Public static void main(String args[])
{
FileInputStream infile=null;
int b;
try
{
infile=new FileInputStream(args[0]);
while((b=infile.read())!=-1)
{
System.out.println((char)b);
}
infile.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
A. display()
B. paint()
C. displayApplet()
D. PrintApplet()
Answer: Option B
A. display()
B. print()
C. drawString()
D. transient()
Answer: Option C
4. Which of these is used to perform all input & output operations in Java?
A. streams
B. Variables
C. classes
D. Methods
Answer: Option A
A. Integer stream
B. Short stream
C. Byte stream
D. Long stream
Answer: Option C
6. Which of these classes are used by Byte streams for input and output operation?
A. InputStream
B. InputOutputStream
C. Reader
D. All of the mentioned
Answer: Option A
7. Which of these classes are used by character streams for input and output operations?
A. InputStream
B. Writer
C. ReadStream
D. InputOutputStream
Answer: Option B
A. IOException
B. InterruptedException
C. SystemException
D. SystemInputException
Answer: Option A
9. Which of these packages contain classes and interfaces used for input & output
operations of a program?
A. java.util
B. java.lang
C. java.io
D. All of the mentioned
Answer: Option C
A. String
B. StringReader
C. Writer
D. File
Answer: Option A
11. Which of these class is not related to input and output stream in terms of functioning?
A. File
B. Writer
C. InputStream
D. Reader
Answer: Option A
12. The ................................ package contains a large number of stream classes that provide
capabilities for processing all types of data.
A) java.awt
B) java.io
C) java.util
D) java.net
Answer: Option B
16. The .................................... class provides the capacity to read primitive data types from
an input stream.
A) pushbackInputStream
B) DataInputStream
C) BufferedInputStream
D) PipeInputStream
Answer: Option B
17. DataInput is
A) an abstract class defined in java.io
B) a class we can use to read primitive data types
C) an interface that defines methods to open files
D) an interface that defines methods to read primitives data types
Answer: Option D
19. An applet can play an audio file represented by the AudioClip interface in the java,
applet package Causes the audio clip to replay continually in which method?
A. Public Void Play()
B. Public Void Loop()
C. Public Void Stop()
D. None Of The Above
Answer: Option B
20. What invokes immediately after the start() method and also any time the applet needs
to repaint itself in the browser?
A. Stop()
B. Init()
C. Paint()
D. Destroy()
Answer: Option C
21. Which method is called only once during the run time of your applet?
A. stop()
B. paint()
C. init()
D. destroy()
Answer: Option C
22. When an applet is terminated which of the following sequence of methods calls take
place?
A. stop(),paint(),destroy()
B. destroy(),stop(),paint()
C. destroy(),stop()
D. stop(),destroy()
Answer: Option D
23. Which is a special type of program that is embedded in the webpage to generate the
dynamic content?
A. Package
B. Applet
C. Browser
D. None Of The Above
Answer: Option B