Java Unit 4
Java Unit 4
As shown in the above figure, a thread is executed inside the process. There is
context-switching between the threads. There can be multiple processes inside
the OS, and one process can have multiple threads.
Note: At a time one thread is executed only.
Thread Class
Java provides Thread class to achieve thread programming.
A Thread class has several methods and constructors which allow us to perform
various operations on a thread. The Thread class extends the Object class.
The Object class implements the Runnable interface. The thread class has the
following constructors that are used to perform various operations.
Methods of Thread Class
In java.lang.Thread class, several constructors have been declared for different purposes.
Some of them are:
Thread(): no-argument constructor.
Thread (String name): takes a string as an argument.
Thread(Runnable r): takes reference (r) of a Runnable object as an argument.
Thread(*Runnable r, String r): takes reference (r) of a Runnable object as well as a
string as arguments.
Note: We have two more methods of the Thread class but they are now deprecated.
1. public void suspend(): which is used to suspend the current thread.
2. public void resume(): which is used to resume the currently suspended thread.
Creating Thread
A thread is created either by "creating or implementing" the Runnable Interface or by
extending the Thread class.
These are the only two ways through which we can create a thread.
Runnable Interface(run() method)
The Runnable interface is required to be implemented by that class whose instances
are intended to be executed by a thread. The runnable interface gives us
the run() method to perform an action for the thread.
start() method
The method is used for starting a thread that we have newly created. It starts a new
thread with a new callstack. After executing the start() method, the thread changes
the state from New to Runnable. It executes the run() method when the thread gets
the correct time to execute it.
Running Threads
We can use the Runnable interface or Thread class method use for the Implementation of
thread in java.
a. Using the Thread Class Method for the Implementation:
Output:
3. Running state: Running means Processor (CPU) has allocated time slot
to thread for its execution.
When thread scheduler selects a thread from the runnable state for
execution, it goes into running state. Look at the above figure.
In running state, processor gives its time to the thread for execution and
executes its run method.
This is the state where thread performs its actual functions. A thread can
come into running state only from runnable state.
A running thread may give up its control in any one of the following
situations and can enter into the blocked state.
a) When sleep() method is invoked on a thread to sleep for specified time
period, the thread is out of queue during this time period.
The thread again reenters into the runnable state as soon as this time
period is elapsed.
b) When a thread is suspended using suspend() method for some time in
order to satisfy some conditions.
A suspended thread can be revived by using resume() method.
c) When wait() method is called on a thread to wait for some time.
The thread in wait state can be run again using notify() or notifyAll()
method.
5. Dead state: A thread dies or moves into dead state automatically when
its run() method completes the execution of statements.
That is, a thread is terminated or dead when a thread comes out of run()
method. A thread can also be dead when the stop() method is called.
During the life cycle of thread in Java, a thread moves from one state to
another state in a variety of ways.
This is because in multithreading environment, when multiple threads are
executing, only one thread can use CPU at a time.
All other threads live in some other states, either waiting for their turn on
CPU or waiting for satisfying some conditions.
Therefore, a thread is always in any of the five states.
Lab program 17:-Create three threads
import java.lang.Thread;
import java.io.*;
class A extends Thread
{
Public void run()
{
try
{
for (int i = 1; i <= 5; i++)
{ sleep(1000); // The main thread sleeps for the 1000 milliseconds, which is 1 sec
// whenever the loop runs displaying the value of the variable
System.out.println(“GOOD MORNING”);
}
}
catch(InterruptException e)
{
System.out.println(“Thread interrupted”);
}
System.out.println(“Exit From Thread A”);
}
}
class B extends Thread
{
Public void run()
{
try
{
for (int j = 1; j <= 5; j++)
{ sleep(2000);
System.out.println(“HELLO”);
}
}
catch(InterruptException e)
{
System.out.println(“Thread interrupted”);
}
System.out.println(“Exit From Thread B”);
}}
class C extends Thread
{
Public void run()
{
try{
for (int k = 1; k<= 5; k++)
{ sleep(3000);
System.out.println(“WELCOME”);
}
}
catch(InterruptException e)
{
System.out.println(“Thread interrupted”);
}
System.out.println(“Exit From Thread C”);
}}
public class ThreadMethods
{
// main method
public static void main(String args[])
{
A threadA =new A();
B theadB=new B();
C threadC=new C();
System.out.println(“Start Thread A”);
threadA.start();
System.out.println(“Start Thread B”);
threadB.start();
System.out.println(“Start Thread C”);
threadC.start();
System.out.println(“End of main Thread”);
}
}
Deadlock in Java
Deadlock in Java is a part of multithreading.
Deadlock can occur in a situation when a thread is waiting for an object lock, that is
acquired by another thread and second thread is waiting for an object lock that is
acquired by first thread.
Since, both threads are waiting for each other to release the lock, the condition is
called deadlock.
synchronized (resource2) {
System.out.println("Thread 1: locked resource 2");
}
}
}
};
synchronized (resource1) {
System.out.println("Thread 2: locked resource 1");
}
}
}
};
t1.start();
t2.start();
}
}
Output:
Thread 1: locked resource 1
Thread 2: locked resource 2
ThreadGroup Example
File: ThreadGroupDemo.java
public class ThreadGroupDemo implements Runnable{
public void run() {
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
ThreadGroupDemo runnable = new ThreadGroupDemo();
ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");
}
}
Output:
one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]
// 1st Thread
// Displaying the priority of the thread
// using the getPriority() method
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
// 2nd Thread
// Display the priority of the thread
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
// 3rd Thread
// // Display the priority of the thread
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
// 6
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
// 3
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
// 9
System.out.println("Priority of the thread th3 is : " + th3.getPriority());
// Main thread
// Displaying name of the currently executing thread
System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName());
System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
We know that a thread with high priority will get preference over lower priority threads
when it comes to the execution of threads.
However, there can be other scenarios where two threads can have the same priority.
All of the processing, in order to look after the threads, is done by the Java thread
scheduler.
Synchronization in Java
Synchronization in Java is the capability to control the access of multiple threads to
any shared resource.
Java Synchronization is better option where we want to allow only one thread to
access the shared resource.
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing
data. It can be achieved by using the following three ways:
1. By Using Synchronized Method
2. By Using Synchronized Block
3. By Using Static Synchronization
TestSynchronization1.java
class Table{
void printTable(int n){ //method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}
Output:
5
100
10
200
15
300
20
400
25
500
}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}
Problem
To make sure that the producer won’t try to add data into the buffer if it’s
full and that the consumer won’t try to remove data from an empty buffer.
Solution
The producer is to either go to sleep or discard data if the buffer is full.
The next time the consumer removes an item from the buffer, it notifies the
producer, who starts to fill the buffer again.
In the same way, the consumer can go to sleep if it finds the buffer to be
empty. The next time the producer puts data into the buffer, it wakes up
the sleeping consumer.
{
wait();
}
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");
}
this.n =
n; va
lueSet = true;
System.out.println("Put: " +
n); notify();
}
}
}
}
}
class prog5q
{
public static void main(String args[])
{
Q q = new
Q(); new
Producer(q); new
Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
Output:
There are several File Operations like creating a new File, getting information
about File, writing into a File, reading from a File and deleting a File.
Before understanding the File operations, it is required that we should have knowledge
of Stream and File methods.
Stream
A series of data is referred to as a stream.
In Java, Stream is classified into two types, i.e., Byte Stream and Character Stream.
Byte Stream
Byte Stream is mainly involved with byte data. A file handling process with a byte
stream is a process in which an input is provided and executed with the byte data.
Character Stream
Character Stream is mainly involved with character data. A file handling process with
a character stream is a process in which an input is provided and executed with the
character data.
2. createNewFile() Boolean The createNewFile() method is used to create a new empty file.
3. canWrite() Boolean The canWrite() method is used to check whether we can write the
data into the file or not.
4. exists() Boolean The exists() method is used to check whether the specified file is
present or not.
6. getName() String The getName() method is used to find the file name.
8. length() Long The length() method is used to get the size of the file in bytes.
9. list() String[] The list() method is used to get an array of the files available in the
directory.
10. mkdir() Boolean The mkdir() method is used for creating a new directory.
File Operations
We can perform the following operation on a file:
o Create a File
o Get File Information
o Write to a File
o Read from a File
o Delete a File
Create a File
Create a File operation is performed to create a new file. We use
the createNewFile() method of file. The createNewFile() method returns true when
it successfully creates a new file and returns false when the file already exists.
CreateFile.java
Output:
In the above code, we import the File and IOException class for performing file operation and
handling errors, respectively. We create the f0 object of the File class and specify the location
of the directory where we want to create a file. In the try block, we call
the createNewFile() method through the f0 object to create a new file in the specified
location. If the method returns false, it will jump to the else section. If there is any error, it gets
handled in the catch block.
Write to a File
The next operation which we can perform on a file is "writing into a file".
In order to write data into a file, we will use the FileWriter class and its write() method
together.
We need to close the stream using the close() method to retrieve the allocated
resources.
Let's take an example to understand how we can write data into a file.
WriteToFile.java
// Importing the FileWriter class
import java.io.FileWriter;
class WriteToFile {
public static void main(String[] args) {
try {
FileWriter fwrite = new FileWriter("D:FileOperationExample.txt");
// writing the content into the FileOperationExample.txt file
fwrite.write("A named location used to store related information is referred to as a File.")
;
Output:
I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast.
The java.io package contains all the classes required for input and output operations.
We can perform file handling in Java by Java I/O API.
Stream
A stream is a sequence of data.
In Java, a stream is composed of bytes.
It's called a stream because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically.
All these streams are attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
OutputStream vs InputStream
OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an
array, peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket.
OutputStream class
OutputStream class is an abstract class.
It is the superclass of all classes representing an output stream of bytes.
An output stream accepts output bytes and sends them to some sink.
1) public void write(int) throws IOException is used to write a byte to the current output
stream.
2) public void write(byte[]) throws IOException is used to write an array of byte to the current
output stream.
3) public void flush() throws IOException flushes the current output stream.
4) public void close() throws IOException is used to close the current output stream.
InputStream class
InputStream class is an abstract class.
It is the superclass of all classes representing an input stream of bytes.
Method Description
1) public abstract int read() throws IOException reads the next byte of data from the input stream.
It returns -1 at the end of the file.
2) public int available() throws IOException returns an estimate of the number of bytes that
can be read from the current input stream.
3) public void close() throws IOException is used to close the current input stream.
protected void finalize() It is used to clean up the connection with the file output stream.
void write(byte[] ary) It is used to write ary.length bytes from the byte array to the file
output stream.
void write(byte[] ary, int off, It is used to write len bytes from the byte array starting at offset off to
int len) the file output stream.
void write(int b) It is used to write the specified byte to the file output stream.
FileChannel getChannel() It is used to return the file channel object associated with the file
output stream.
FileDescriptor getFD() It is used to return the file descriptor associated with the stream.
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Output:
Success...
The content of a text file testout.txt is set with the data A.
testout.txt
A
Method Description
int available() It is used to return the estimated number of bytes that can be
read from the input stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the input
stream.
int read(byte[] b, int off, int len) It is used to read up to len bytes of data from the input stream.
long skip(long x) It is used to skip over and discards x bytes of data from the
input stream.
protected void finalize() It is used to ensure that the close method is call when there is no
more reference to the file input stream.
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Output:
Welcome to javaTpoint
Constructor Description
BufferedOutputStream(OutputStream os) It creates the new buffered output stream which is used for
writing the data to the specified output stream.
BufferedOutputStream(OutputStream os, It creates the new buffered output stream which is used for
int size) writing the data to the specified output stream with a
specified buffer size.
Java BufferedOutputStream class methods
Method Description
void write(int b) It writes the specified byte to the buffered output stream.
void write(byte[] b, int It write the bytes from the specified byte-input stream into a specified
off, int len) byte array, starting with the given offset
Constructor Description
Method Description
int available() It returns an estimate number of bytes that can be read from the
input stream without blocking by the next invocation method for
the input stream.
int read() It read the next byte of data from the input stream.
int read(byte[] b, int off, int ln) It read the bytes from the specified byte-input stream into a
specified byte array, starting with the given offset.
void close() It closes the input stream and releases any of the system resources
associated with the stream.
void reset() It repositions the stream at a position the mark method was last
called on this input stream.
void mark(int readlimit) It sees the general contract of the mark method for the input stream.
long skip(long x) It skips over and discards x bytes of data from the input stream.
boolean markSupported() It tests for the input stream to support the mark and reset methods.
import java.io.*;
public class BufferedInputStreamExample{
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
BufferedInputStream bin=new BufferedInputStream(fin);
int i;
while((i=bin.read())!=-1){
System.out.print((char)i);
}
bin.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Here, we are assuming that you have following data in "testout.txt" file:
javaTpoint
Output:
javaTpoint
int size() It is used to return the number of bytes written to the data
output stream.
void write(int b) It is used to write the specified byte to the underlying output
stream.
void write(byte[] b, int off, int len) It is used to write len bytes of data to the output stream.
void writeUTF(String str) It is used to write a string to the output stream using UTF-
8 encoding in portable manner.
In this example, we are writing the data to a text file testout.txt using DataOutputStream class.
import java.io.*;
public class OutputExample {
public static void main(String[] args) throws IOException {
FileOutputStream file = new FileOutputStream(D:\\testout.txt);
DataOutputStream data = new DataOutputStream(file);
data.writeInt(65);
data.flush();
data.close();
System.out.println("Succcess...");
}
}
Output:
Succcess...
testout.txt:
A
Java DataInputStream Class
Java DataInputStream class allows an application to read primitive data from the input stream
in a machine-independent way.
Java application generally uses the data output stream to write data that can later be read by a
data input stream.
Method Description
int read(byte[] b) It is used to read the number of bytes from the input stream.
int read(byte[] b, int off, int len) It is used to read len bytes of data from the input stream.
int readInt() It is used to read input bytes and return an int value.
byte readByte() It is used to read and return the one input byte.
char readChar() It is used to read two input bytes and returns a char value.
double readDouble() It is used to read eight input bytes and returns a double value.
boolean readBoolean() It is used to read one input byte and return true if byte is non zero,
false if byte is zero.
int skipBytes(int x) It is used to skip over x bytes of data from the input stream.
String readUTF() It is used to read a string that has been encoded using the UTF-8
format.
void readFully(byte[] b) It is used to read bytes from the input stream and store them into
the buffer array.
void readFully(byte[] b, int off,
It is used to read len bytes from the input stream.
int len)
package com.javatpoint;
import java.io.*;
public class DataStreamExample {
public static void main(String[] args) throws IOException {
InputStream input = new FileInputStream("D:\\testout.txt");
DataInputStream inst = new DataInputStream(input);
int count = input.available();
byte[] ary = new byte[count];
inst.read(ary);
for (byte bt : ary) {
char k = (char) bt;
System.out.print(k+"-");
}
}
}
Here, we are assuming that you have following data in "testout.txt" file:
JAVA
Output:
J-A-V-A
Java - RandomAccessFile
This class is used for reading and writing to random access file.
A random access file behaves like a large array of bytes.
There is a cursor implied to the array called file pointer, by moving the cursor we do the read
write operations.
If end-of-file is reached before the desired number of byte has been read than EOFException
is thrown. It is a type of IOException.
Constructor
Constructor Description
RandomAccessFile(File file, String mode) Creates a random access file stream to read from,
and optionally to write to, the file specified by the
File argument.
RandomAccessFile(String name, String mode) Creates a random access file stream to read from,
and optionally to write to, a file with the specified
name.
void close() It closes this random access file stream and releases
any system resources associated with the stream.
void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.
void writeDouble(double v) It converts the double argument to a long using the
doubleToLongBits method in class Double, and then
writes that long value to the file as an eight-byte
quantity, high byte first.
void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.
Example
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample {
static final String FILEPATH ="myFile.TXT";
public static void main(String[] args) {
try {
System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
writeToFile(FILEPATH, "I love my country and my people", 31);
} catch (IOException e) {
e.printStackTrace();
}
}
private static byte[] readFromFile(String filePath, int position, int size)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(position);
byte[] bytes = new byte[size];
file.read(bytes);
file.close();
return bytes;
}
private static void writeToFile(String filePath, String data, int position)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
file.seek(position);
file.write(data.getBytes());
file.close();
}
}
The myFile.TXT contains text "This class is used for reading and writing to random access
file."
after running the program it will contains
This class is used for reading I love my country and my peoplele.
Applets
Applet program
An applet is a special program that we can embedded in
a web page such that the applet gains control over a certain
part of the displayed page.
It is differ from application program
Applets are created from classes
An applet do not have main as an entry. Instead have
several methods to control specific aspects of applet
execution.
Java.awt.Component
Java.awt.Container
Java.awt.Panel
Java.applet.Applet
About Java.awt.Component
• java.lang.Object
• java.awt.Component
• public abstract class Component extends Object implements
ImageObserver, MenuContainer, Serializable
• A component is an object having a graphical representation that
can be displayed on the screen and that can interact with the
user.
• Examples of components are the buttons, checkboxes, and
scrollbars of a typical graphical user interface.
About Java.awt.Container
• java.lang.Object
• java.awt.Component
java.awt.Container
About Java.awt.Panel
• java.lang.Object
• java.awt.Component
java.awt.Container
• java.awt.Panel
• public class Panel extends Container implements Accessible
• Panel is the simplest container class.
• A panel provides space in which an application can attach any
other component, including other panels.
• The default layout manager for a panel is the FlowLayout layout
manager.
Java.applet.Applet
• java.lang.Object
• java.awt.Component
java.awt.Container
java.awt.Panel
o java.applet.Applet
public class Applet extends Panel
o An applet is a small program
that is intended not to be run on its own,
but rather to be embedded inside another
application.
o The Applet class must be the superclass of any applet
that is to be embedded in a Web page or viewed by the
Java Applet Viewer. The Applet class provides a
standard interface between applets and their
environment.
Example - 1
impor
t
java.a
wt.*;
impor
t
java.a
pplet.
*;
public class myapplet extends Applet
{
public void paint(Graphics g)
drawString("Welcome to applet",30,30);
--------------------------------
Html file
<html>
<head>
<body>
<applet code = "myapplet.class"
width=200 height=100> abcd
</applet>
</body>
</head>
drawString("Welcome toapplet",30,30);
}
}
/*
<applet code = "myapplet.class" width = 200 height = 100>
<
/
a
p
p
l
e
t
>
*
/
• Save the above program with myapplet.java
• Compile it using javac myapplet.java
• Run using appletviewer myapplet.java
Architecture of an Applet
All but the most trivial applets override a set of methods that
provides the basic mechanism by which the browser or
applet viewer interfaces to the applet and controls its
execution. Four of these methods—init( ), start( ), stop( ),
and destroy( )—are defined by Applet. Another, paint( ), is
defined by the AWT Component class.
// An Appletskeleton.
import java.awt.*;
import java.applet.*;
/*
</applet> */
{ // Called first.
// initialization
{ // suspends execution
Although this skeleton does not do anything, it can be compiled and run.
When run, it generates the following window when viewed with an applet
viewer:
Applet Initialization and Termination
init( )
The init( ) method is the first method to be called.
This is where you should initialize variables.
This method is called only once during the run time of your applet.
start( )
The start( ) method is called after init( ).
It is also called to restart an applet after it has been stopped.
Whereas init( ) is called once—the first time an applet is
loaded—start( ) is called each time an applet’s HTML document
is displayed onscreen.
So, if a user leaves a web page and comes back, the applet
resumes execution at start( ).
paint( )
The paint( ) method is called each time your applet’s output
must be redrawn. This situation can occur for several reasons.
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.
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.
stop( )
The stop( ) method is called when a web browser leaves the
HTML document containing the applet—when it goes to another
page, for example.
When stop( ) is called, the applet is probably running.
You should use stop( ) to suspend threads that don’t need to
run when the applet is not visible.
You can restart them when start( ) is called if the user returns
to the page.
destroy( )
The destroy( ) method is called when the environment
determines that your applet needs to be removed completely
from memory.
At this point, you should free up any resources the applet may
be using.
The stop( ) method is always called before destroy( ).
Overriding update( )
In some situations, applet may need to override another
method defined by theAWT, called update( ).
This method is called when your applet has requested that a
portion of its window be redrawn.
The default version of update( ) first fills an applet with the
default background color and then calls paint( ).
If you fill the background using a different color in paint( ),
the user will experience a flash of the default background
each time update( ) is called—that is, whenever the window
is repainted.
One way to avoid this problem is to override the update( )
method so that it performs all necessary display activities.
Then have paint( ) simply call update( ).
Thus, for some applications, the applet skeleton will override
paint( ) and update( ), as shown here:
o Color.black
o Color.magenta
o Color.blue
o Color.orange
o Color.cyan
o Color.pink
o Color.darkGra
o Color.red
o Color.gray
o Color.white
o Color.green
o Color.yellow
o Color.lightGray
For example, this sets the background color to green and the text color to
red:
setBackground(Color.green);
setForeground(Color.red);
We has to set the foreground and background colors is in the
init( ) method o we can change these colors during execution
of program also
The default foreground color is black.
o The default background color is light gray.
o we can obtain the current settings for the background and
foreground colors by calling getBackground( ) and
getForeground( ), respectively.
Program
/* A simple applet that sets the foreground and background colors and outputs a
string. */
import java.awt.*;
import java.applet.*;
/*
</applet> */
public class Sample extends Applet{
String msg;
This applet creates a thread that scrolls the message contained in msg right to left
across the applet's window.
*/
import java.awt.*;
import java.applet.*;
/*
</applet>
*/
{ setBackground(Color.cyan);
setForeground(Color.red);
// Start thread
{ t = new Thread(this);
{ char ch;
// Display banner
for( ; ; )
try { repaint();
Thread.sleep(250);
ch = msg.charAt(0);
msg += ch;
if(stopFlag) break;
} catch(InterruptedException e) {}
{ stopFlag = true;
t = null;
import java.awt.*;
import java.applet.*;
/*
</applet>
*/
{ setBackground(Color.cyan);
}
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels
HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
...
</APPLET>
CODEBASE
CODEBASE is an optional attribute that specifies the base URL of
the applet code, which is the directory that will be searched for the
applet’s executable class file (specified by the CODE tag).
The HTML document’s URL directory is used as the CODEBASE if
this attribute is not specified.
The CODEBASE does not have to be on the host from which the
HTML document was read.
CODE
CODE is a required attribute that gives the name of the file
containing your applet’s compiled .class file.
This file is relative to the code base URL of the applet, which is the
directory that the HTML file was in or the directory indicated by
CODEBASE if set.
ALT
The ALT tag is an optional attribute used to specify a short text
message that should be displayed if the browser understands the
APPLET tag but can’t currently run Java applets.
This is distinct from the alternate HTML you provide for browsers
that don’t support applets.
NAME
NAME is an optional attribute used to specify a name for the applet
instance. Applets must be named in order for other applets on the
same page to find them by name and communicate with them.
To obtain an applet by name, use getApplet( ), which is defined by
the AppletContext interface.
<p>
</applet>
Passing Parameters to Applets:
// Use Parameters
import java.awt.*;
import java.applet.*;
/*
</applet>
*/
String fontName;
int fontSize;
float leading;
boolean active;
{ String param;
fontName = getParameter("fontName");
if(fontName == null)
param = getParameter("fontSize");
try {
fontSize = Integer.parseInt(param);
else
fontSize = 0;
} catch(NumberFormatException e) {
fontSize = -1;
param = getParameter("leading");
leading = Float.valueOf(param).floatValue();
else
leading = 0;
} catch(NumberFormatException e)
{ leading = -1; }
param = getParameter("accountEnabled");
if(param != null)
active = Boolean.valueOf(param).booleanValue();
// Display parameters.