Java Notes
Java Notes
Java Notes
*Introduction of java:-
Java is great programming language for the development of enterprise grade applications.
This programming Language is evolved from a language named Oak. Oak was developed in the
early nineties at Sun Microsystems as a platform-independent language aimed at allowing
entertainment appliances such as video game consoles and VCRs to communicate. Oak was
first slated to appear in television set-top boxes designed to provide video-on-demand services.
Oak was unsuccessful so in 1995 Sun changed the name to Java and modified the language to
take advantage of the growing World Wide Web.
Java is an object-oriented language, and this is very similar to C++. Java Programming
Language is simplified to eliminate language features that cause common programming errors.
Java source code files are compiled into a format called byte code, which can then be executed
by a Java interpreter.
*Features of java:-
• Platform Independence
The Write-Once-Run-Anywhere ideal has not been achieved (tuning for different
platforms usually required), but closer than with other languages.
• Object Oriented
o Object oriented throughout - no coding outside of class definitions, including
main().
o An extensive class library available in the core language packages.
• Compiler/Interpreter Combo
o Code is compiled to bytecodes that are interpreted by a Java virtual machines
(JVM) .
o This provides portability to any machine for which a virtual machine has been
written.
o The two steps of compilation and interpretation allow for extensive code checking
and improved security.
• Robust
o Exception handling built-in, strong type checking (that is, all data must be
declared an explicit type), local variables must be initialized.
• Security
o No memory pointers
o Programs run inside the virtual machine sandbox.
o Array index limit checking
o Code pathologies reduced by
bytecode verifier - checks classes after loading
class loader - confines objects to unique namespaces. Prevents loading a
hacked "java.lang.SecurityManager" class, for example.
security manager - determines what resources a class can access such as
reading and writing to the local disk.
• Dynamic Binding
o The linking of data and methods to where they are located, is done at run-time.
o New classes can be loaded while a program is running. Linking is done on the fly.
• Even if libraries are recompiled, there is no need to recompile code that uses classes in
those libraries.
• Good Performance
o Interpretation of bytecodes slowed performance in early versions, but advanced
virtual machines with adaptive and just-in-time compilation and other techniques
now typically provide performance up to 50% to 100% the speed of C++
programs.
• Threading
o Lightweight processes, called threads, can easily be spun off to perform
multiprocessing.
o Can take advantage of multiprocessors where available
o Great for multimedia displays.
• Built-in Networking
o Java was designed with networking in mind and comes with many classes to
develop sophisticated Internet communications.
Features such as eliminating memory pointers and by checking array limits greatly help to
remove program bugs. The garbage collector relieves programmers of the big job of memory
management. These and the other features can lead to a big speedup in program development
compared to C/C++ programming.
JDK is a software development program provided by sun Microsystems. Java Development Kit
or JDK comes in various versions and can be downloaded free from the sun Microsystems.
JVM compiler, debugger and other tools are used with JDK for developing java based
application & java applets. So make sure that your JVM compiler & JDK versions are same.
JDK also known as Java 2 Platform That comes in three editions J2ME, J2SE & J2EE.
Bin directory - The bin directory provides all inessential tools for developing and testing the
program through the help of command provided by Java compiler.
Include directory - It contains all header files like for 'C' programming language that enables
you to combine C code into a Java program.
Jre directory- when you run any java program then you have compile it by the help of java
interpreter or java Runtime environment(JRE).The SDK uses the internal adaption of JRE, which
containing in the jre root directory.
Lib directory- this is most important important directory for development tools that contains
libraries and it’s supported files.
Docs Directory-It is the last directory of software development kit that assistes you to store the
java documents. The docs directory is an optional directory
Complex Data
Structures, unions Structures, unions, classes Classes
Types
Operator
N/A Yes No
Overloading
Automatic Yes, with warnings Yes, with warnings if loss Not at all if loss could occur;
coercions if loss could occur could occur must cast explicitly
true and false are defined constants of the language and are not the same as True and
False, TRUE and FALSE, zero and nonzero, 1 and 0 or any other numeric value.
Booleans may not be cast into any other type of variable nor may any other variable be
cast into a Boolean.
Byte
short
int
long
float
Like all numeric types floats may be cast into other numeric types (byte, short, long, int,
double). When lossy casts to integer types are done (e.g. float to short) the fractional part
is truncated and the conversion is done modulo the length of the smaller type.
double
8 bytes IEEE 754. Covers a range from 4.94065645841246544e-324d to
1.79769313486231570e+308d (positive or negative).
char
Variables
instance Variables (Non-Static Fields) Technically speaking, objects store their individual
states in "non-static fields", that is, fields declared without the static keyword. Non-static fields
are also known as instance variables because their values are unique to each instance of a class
(to each object, in other words); the currentSpeed of one bicycle is independent from the
currentSpeed of another.
Class Variables (Static Fields) a class variable is any field declared with the static modifier;
this tells the compiler that there is exactly one copy of this variable in existence; regardless of
how many times the class has been instantiated. A field defining the number of gears for a
particular kind of bicycle could be marked as static since conceptually the same number of gears
will apply to all instances. The code static int numGears = 6; would create such a static field.
Additionally, the keyword final could be added to indicate that the number of gears will never
change.
Local Variables Similar to how an object stores its state in fields, a method will often store its
temporary state in local variables. The syntax for declaring a local variable is similar to
declaring a field (for example, int count = 0;). There is no special keyword designating a variable
as local; that determination comes entirely from the location in which the variable is declared —
which is between the opening and closing braces of a method. As such, local variables are only
visible to the methods in which they are declared; they are not accessible from the rest of the
class.
Constants in java
Even though Java does not have a constant type, you can achieve the same effect by declaring
and initializing variables that are static, public, and final. After the variables have been
initialized, their value cannot be changed. You can then access the constant value using the name
of the variable joined to the name of its class with a period.
class Constants02{
public static void main(String[] args){
System.out.println("pi = " + Constants.pi);
System.out.println("e = " + Constants.e);
}//end main
}//end class Constants02
//=======================================================//
class Constants{
public static final double pi = 3.14159;
public static final double e = 2.71828;
}//end class Constants
*Operators:
Assignment
Arithmetic
Relational
Logical
With the knowledge you now have of the basics of the Java programming language, you can
learn to write your own classes. In this lesson, you will find information about defining your own
classes, including declaring member variables, methods, and constructors.
You will learn to use your classes to create objects, and how to use the objects you create.
This lesson also covers nesting classes within other classes, enumerations, and annotations.
Classes
This section shows you the anatomy of a class, and how to declare fields, methods, and
constructors.
Objects
This section covers creating and using objects. You will learn how to instantiate an object, and,
once instantiated, how to use the dot operator to access the object's instance variables and
methods.
More on Classes
This section covers more aspects of classes that depend on using object references and the dot
operator that you learned about in the preceding section: returning values from methods, the this
keyword, class vs. instance members, and access control.
Nested Classes
Static nested classes, inner classes, anonymous inner classes, and local classes are covered.
Constructors
When you create a new instance (a new object) of a class using the new keyword, a constructor
for that class is called. Constructors are used to initialize the instance variables (fields) of an
object. Constructors are similar to methods, but with some important differences.
• Constructor name is class name. A constructors must have the same name as the class
its in.
• Default constructor. If you don't define a constructor for a class, a default parameter
less constructor is automatically created by the compiler. The default constructor calls
the default parent constructor (super()) and initializes all instance variables to default
value (zero for numeric types, null for object references, and false for Booleans).
• Default constructor is created only if there are no constructors. If you define any
constructor for your class, no default constructor is automatically created.
• Differences between methods and constructors.
o There is no return type given in a constructor signature (header). The value is this
object itself so there is no need to indicate a return value.
o There is no return statement in the body of the constructor.
o The first line of a constructor must either be a call on another constructor in the
same class (using this), or a call on the superclass constructor (using super). If the
first line is neither of these, the compiler automatically inserts a call to the
parameter less super class constructor.
These differences in syntax between a constructor and method are sometimes hard to see
when looking at the source. It would have been better to have had a keyword to clearly
mark constructors as some languages do.
• This (...) - Calls another constructor in same class. Often a constructor with few
parameters will call a constructor with more parameters, giving default values for the
missing parameters. Use this to call other constructors in the same class.
• Super (...). Use super to call a constructor in a parent class. Calling the constructor for
the super class must be the first statement in the body of a constructor. If you are satisfied
with the default constructor in the super class, there is no need to make a call to it
because it will be supplied automatically.
Garbage collection
Since objects are dynamically allocated by using the new operator, you might be
wondering how such objects are destroyed and their memory released for later reallocation.
In some languages, such as C++, dynamically allocated objects must be manually released
by use of a delete operator.
Java takes a different approach; it handles deallocation for you automatically. The
technique that accomplishes this is called garbage collection. It works like this: when no
references to an object to an object exist, that object is assumed to be no longer needed, and
the memory occupied by the object can be reclaimed. There is no explicit need to destroy
objects as in C++. Garbage collection only occurs sporadically (if at all) during the
execution of your program. It will not occur simply because one or more objects exist that
are no longer used. Furthermore, different java run-time implementations will take varying
approaches to garbage collection, but for the most part, you should not have to think about it
while writing your programs
To add a finalizer to a class, you simply define the finalize() method. The
java run time calls that method whenever it is about to recycle an object of that class. Inside
the finalize() method you will specify those actions that must be performed before an object
is destroyed. The garbage collector runs periodically, checking for objects that are no longer
referenced by any running state or indirectly through other referenced objects. Right before
an asset is freed, the java run time calls the finalize() method on the object.
Here, the keyword protected is a specifier that prevents access to finalize() by code
defined outside its class.
demo(int i)
{
id=i;
}
public static void main(String ar[])
{
System.runFinalizersOnExit(true);
demo d=null;
for(int i=1;i<5;i++)
d=new demo(i);
}
public void finalize()throws Throwable
{
System.out.println("finalizr"+id);
super.finalize();
}
}
Class sample1
Session 2:
class aa
static int b;
System.out.println("x="+x);
System.out.println("x="+b);
System.out.println("x="+a);
static
System.out.println("static block");
b=a*4;
aa a1=new aa();
a1.show(20);
}
}
Java compilar
To commence with Java programming, we must know the significance of Java Compiler.
When we write any program in a text editor like Notepad, we use Java compiler to compile it. A
Java Compiler javac is a programmer set of programs which translates java source
code intojava byte code.
The output from a Java compiler comes in the form of Java class files (with .class
extension). The code contained in files end with the .java extension. The file name must be the
same as the class name, asclassname.java. When the javac compiles the source file defined in
a .java files, it generates bytecode for the java source file and saves in a class file with a .class
extension.
The most commonly used Java compiler is javac, included in JDK from Sun Microsystems.
Following figure shows the working of the Java compiler:
Once the byte code is generated it can be run on any platform using Java Interpreter (JVM). It
interprets byte code (.class file) and converts into machine specific binary code. Then JVM
runs the binary code on the host machine.
Java debugger
Java Debugger
Java debugger helps in finding and the fixing of bugs in Java language programs. The Java
debugger is denoted as jdb. It works like a command-line debugger for Java classes.
jdb session
The way to start the jdb session is to have jdb launch a newJVM (Java virtual machine) with
the main class. Then the application of the main class is debugged by substituting the
command jdb in command-line. For instance, if the main class of the application is
TempClass, the following command is used to debug it:
jdb TempClass
There is another way to use jdb i.e.to attach jdb to Java VM which is already running.
There are few options which are used to debug a VM with jdb. These are:
option purpose
The following command will run the TempClass application to which the jdb will connect
afterwords.
% java -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n
TempClass
Now the jdb will be attached to the VM in this way: % jdb -attach 8000
You can go through the basic jdb commands that the Java debugger supports.
cont
Ihis command Continues the execution of the debugged application after a breakpoint,
exception, or step.
run
Use run command to start the execution after starting jdb, and setting any necessary
breakpoints, use run command to start the execution . When jdb launches the debugged
application then only this command is available.
print
This command is used to display Java objects and primitive values. The actual value is printed
for the variables or fields of primitive types. For objects, a short description is printed.
In simple terms, an applet runs under the control of a browser, whereas an application runs stand-
alone, with the support of a virtual machine. As such, an applet is subjected to more stringent
security restrictions in terms of file and network access, whereas an application can have free
reign over these resources.
Applets are great for creating dynamic and interactive web applications, but the true power of
Java lies in writing full blown applications. With the limitation of disk and network access, it
would be difficult to write commercial applications (though through the user of server based file
systems, not impossible). However, a Java application has full network and local file system
access, and its potential is limited only by the creativity of its developers.
Abstract class:-
Any class that contains one or more abstract methods must also be declared abstract. To
declare a class abstract, you simply use the abstract keyword in front of the class keyword at
the beginning of the class declaration. There can be no objects of an abstract class. That is, an
abstract class cannot be directly instantiated with the new operator. Such objects would be
useless, because an abstract class is not fully defined. Also, you cannot declare abstract
constructors, or abstract static methods. Any subclass of an abstract class must either
implement all of the abstract methods in the super class, or be itself declared abstract.
Here is a simple example of a class with an abstract method, followed by a class which
implements that method:
abstract class bb
void show()
{}
class nn extends bb
void show()
System.out.println("this is n1 class");
class n1
{
public static void main(String ar[])
bb b=new nn();
b.show();
Inner class:-
It is possible to nest a class definition within another class & treat the nested class
has privilege to access all the members of the member of the class enclosing it. A nested class
can either be static or nonstatic a static nested class is one which has static modifier applied.
//inner class
class outclass
int c=3;
class ioclass
{
System.out.println("a="+outclass.a);
System.out.println("a="+outclass.inclass.b);
System.out.println("a="+io.b);
Wrapper class
The java programmers does not look at primitive data types as object for example
numerical, Boolean and character data are treated in the primitive form for sake of
officiency.The java programming language provides wrapper class to manipulate primitive data
elements are wrapped in object created around them Each java primitive data type has a
corresponding wrapper class object encapsulates a single primitive value.
These wrapper classes implement immutable objects.That means that after the primitive
value is initialized in the wrapper object then there is no way to change that value.
Wrapper class
Boolan Bolean
Byte byte
Char char
Short short
Int int
Long long
Float float
Double double
You can construct a wrapper class object by passing the value to wrapped into the
appropriate constructors.
Int pint=420
In p2=wint.intvalue)//unboxing
Wrapper classes are useful when convertry primitive data type because of many wrapper class
methods available
Int x=integer.valu(str).intvalue();
Or
Int x=integer.parseint(str);
If you have to chang the primitive data type to their object equivalents called boxing the
you need to use wrapper classes also to get the primitive data type from the object reference data
type from the object reference called unboxing you need to use wrapper class methods. All of the
boxing and unboxing can clutter up
Session 3:
Interface:-
Interfaces form a contract between the class and the outside world the methods that they
expose. Methods form the object's interface with the outside world; the buttons on the front of
your television set, for example, are the interface between you and the electrical wiring on the
other side of its plastic casing. You press the "power" button to turn the television on and off. an
interface is a group of related methods with empty bodies. Interfaces form a contract between the
class and the outside world.
Interface Bicycle
{
void changeCadence(int newValue);
Package:-
A package is a namespace that organizes a set of related classes and interfaces. Conceptually
you can think of packages as being similar to different folders on your computer. You might
keep HTML pages in one folder, images in another, and scripts or applications in yet another.
Because software written in the Java programming language can be composed of hundreds or
thousands of individual classes, it makes sense to keep things organized by placing related
classes and interfaces into packages.
The Java platform provides an enormous class library (a set of packages) suitable for use in your
own applications. This library is known as the "Application Programming Interface” or “API for
short. Its packages represent the tasks most commonly associated with general-purpose
programming. For example, a String object contains state and behavior for character strings; a
File object allows a programmer to easily create, delete, inspect, compare, or modify a file on the
file system; a Socket object allows for the creation and use of network sockets; various GUI
objects control buttons and checkboxes and anything else related to graphical user interfaces.
There are literally thousands of classes to choose from. This allows you, the programmer, to
focus on the design of your particular application, rather than the infrastructure required to make
it work.
Exception Handling
Basics of exception handling error and abnormal condition arising while executing a program
need to be java handle usually code snippets are written such situation. Java occurs various
classes to handle exception thus making its program robust.
The object class has a sub class called throw able to handle exceptions and error. The throw able
class ha two sub classes.
1. Exception
2.Error:-
Error conditions are normally not trapped by java programs error condition occurring in case of
drastic failure (virtual machine error) which cannot be handle by a program these are generated
to indicate errors generated by run time environment.
The main sub class of exception class is the runtime exception class. An exception is an
abnormal condition which occurs during the execution of program exceptions are is event like
division by zero. Opening of file that does not exist etc. run time exception class generate error
that occurs during the exception of program runtime exception is defined by default for all
program.
Try catch:-
• Comman exception:-
*Program on
arithmetic
exception
class
arithmetic
try
int n=5/0;
System.out.println(“You are trying to devide by zero”);
catch(Arithmetic exception e)
Package java.lang
Provides classes that are fundamental to the design of the Java programming language.
See:
Description
Interface Summary
This interface imposes a total ordering on the objects of each class that
Comparable
implements it.
The Runnable interface should be implemented by any class whose instances are
Runnable
intended to be executed by a thread.
Class Summary
The Boolean class wraps a value of the primitive type boolean in an
Boolean
object.
Byte The Byte class wraps a value of primitive type byte in an object.
Float The Float class wraps a value of primitive type float in an object.
Integer The Integer class wraps a value of the primitive type int in an object.
Long The Long class wraps a value of the primitive type long in an object.
Short The Short class wraps a value of primitive type short in an object.
System The System class contains several useful class fields and methods.
Exception Summary
Error Summary
Provides classes that are fundamental to the design of the Java programming language. The most
important classes are Object, which is the root of the class hierarchy, and Class, instances of
which represent classes at run time.
The class Math provides commonly used mathematical functions such as sine, cosine, and square
root. The classes String and StringBuffer similarly provide commonly used operations on
character strings.
Class Throwable encompasses objects that may be thrown by the throw statement (§14.16).
Subclasses of Throwable represent errors and exceptions.
Package java.util
Contains the collections framework, legacy collection classes, event model, date and time
facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-
number generator, and a bit array).
See:
Description
Interface Summary
EventListener A tagging interface that all event listener interfaces must extend.
An iterator for lists that allows the programmer to traverse the list in either
ListIterator direction, modifies the list during iteration, and obtains the iterator's current
position in the list.
Marker interface used by List implementations to indicate that they support fast
RandomAccess
(generally constant time) random access.
SortedMap A map that further guarantees that it will be in ascending key order, sorted
according to the natural ordering of its keys (see the Comparable interface), or
by a comparator provided at sorted map creation time.
A set that further guarantees that its iterator will traverse the set in ascending
SortedSet element order, sorted according to the natural ordering of its elements (see
Comparable), or by a Comparator provided at sorted set creation time.
Class Summary
EventObject The root class from which all event state objects shall be derived.
This class implements the Map interface with a hash table, using
IdentityHashMap reference-equality in place of object-equality when comparing keys
(and values).
Hash table and linked list implementation of the Map interface, with
LinkedHashMap
predictable iteration order.
Hash table and linked list implementation of the Set interface, with
LinkedHashSet
predictable iteration order.
TimeZone represents a time zone offset, and also figures out daylight
TimeZone
savings.
Exception Summary
System.out.printf("Fred it is\n");
boolean b = Boolean.parseBoolean("false");
} System.out.println(s);
System.out.print().
class Square
{
int size;
Square(int x)
{
size = x;
Array:-
Array: Array is the most important thing in any programming language. By definition, array is
the static memory allocation. It allocates the memory for the same data type in sequence. It
contains multiple values of same types. It also store the values in memory at the fixed size.
Multiple types of arrays are used in any programming language such as: one - dimensional, two -
dimensional or can say multi - dimensional.
Declaration of an array:
int num[]; or int num = new int[2];
Some times user declares an array and it's size simultaneously. You may or may not be define the
size in the declaration time. such as:
int num[] = {50,20,45,82,25,63};
In this program we will see how to declare and implementation. This program illustrates that the
array working way. This program takes the numbers present in the num[] array in unordered list
and prints numbers in ascending order. In this program the sort() function of the java.util.*;
package is using to sort all the numbers present in the num[] array. The Arrays.sort()
automatically sorts the list of number in ascending order by default. This function held the
argument which is the array name num.
import java.util.*;
Vector
Vectors (the java.util.Vector class) are commonly used instead of arrays, because they expand
automatically when new data is added to them. The Java 2 Collections API introduced the
similar ArrayList data structure. ArrayLists are unsynchronized and therefore faster than
Vectors, but less secure in a multithreaded environment. The Vector class was changed in Java 2
to add the additional methods supported by ArrayList. See below for a reasons to use each. The
description below is for the (new) Vector class.
Vectors can hold only Objects and not primitive types (eg, int). If you want to put a primitive
type in a Vector, put it inside an object (eg, to save an integer value use the Integer class or
define your own class). If you use the Integer wrapper, you will not be able to change the integer
value, so it is sometimes useful to define your own class.
To Create a Vector
You must import either import java.util.Vector; or import java.util.*;. Vectors are implemented
with an array, and when that array is full and an additional element is added, a new array must be
allocated. Because it takes time to create a bigger array and copy the elements from the old array
to the new array, it is a little faster to create a Vector with a size that it will commonly be when
full. Of course, if you knew the final size, you could simply use an array. However, for non-
critical sections of code programmers typically don't specify an initial size.
There are many useful methods in the Vector class and its parent classes. Here are some of the
most useful. v is a Vector, i is an int index, o is an Object.
Method Description
v.listIterator() Returns a ListIterator that can be used to go over the Vector. This is a useful
alternative to the for loop.
v.remove(i) Removes the element at position i, and shifts all following elements down.
The array parameter can be any Object subclass (eg, String). This returns the
vector values in that array (or a larger array if necessary). This is useful when
v.toArray(Object[])
you need the generality of a Vector for input, but need the speed of arrays
when processing the data.
When the new Collections API was introduced in Java 2 to provide uniform data structure
classes, the Vector class was updated to implement the List interface. Use the List methods
because they are common to other data structure. If you later decide to use something other than
a Vector (eg, ArrayList, or LinkedList, your other code will not need to change.
Even up thru the first several versions of Java 2 (SDK 1.4), the language had not entirely
changed to use the new Collections methods. For example, the DefaultListModel still uses the
old methods, so if you are using a JList, you will need to use the old method names. There are
hints that they plan to change this, but still and interesting omission.
The following methods have been changed from the old to the new Vector API.
Iterator iterator()
Enumeration elements()
ListIterator listIterator()
Sample program:-
import java.util.Vector;
import java.util.Collections;
import java.io.*;
import java.util.*;
HashTable:-
*Hash Table holds the records according to the unique key value. It stores the non-contiguous
key for several values. Hash Table is created using an algorithm (hashing function) to store the
key and value regarding to the key in the hash bucket. If you want to store the value for the
new key and if that key is already exists in the hash bucket then the situation known as
collision occurs which is the problem in the hash table i.e. maintained by the hashing function.
The drawback is that hash tables require a little bit more memory, and that you can not use the
normal list procedures for working with them.
This program simply asks you for the number of entries which have to entered into the hash
table and takes one-by-one key and it's value as input. It shows all the elements with the
separate key.
Code Description:
Hashtable<Integer, String> hashTable = new Hashtable<Integer, String>():
Above code creates the instance of the Hashtable class. This code is using the type checking
of the elements which will be held by the hash table.
hashTable.put(key, in.readLine()):
Above method puts the values in the hash table regarding to the unique key. This method takes
two arguments in which, one is the key and another one is the value for the separate key.
Map<Integer, String> map = new TreeMap<Integer, String>(hashTable):
Above code creates an instance of the TreeMap for the hash table which name is passed
through the constructor of the TreeMap class. This code creates the Map with the help of the
instance of the TreeMap class. This map has been created in the program for showing several
values and it's separate key present in the hash table. This code has used the type checking.
import java.util.*;
import java.io.*;
import java.util.*;
import java.lang.*;
import java.net.*;
*Properties:-
import java.util.*;
String key;
while (iterator.hasNext()) {
key = iterator.next().toString();
Multithreading allows two parts of the same program to run concurrently. Multitasking is
performing two or more tasks at the same time. Nearly all operating systems are capable of
multitasking by u Process-based multitasking is running two programs concurrently.
Programmers refer to a program as a process. Therefore, you could say that process-based
multitasking is program-based multitasking. Thread-based multitasking is having a program
perform two tasks at the same time. For example, a word processing program can check the
spelling of words in a document while you write the document. This is thread-based
multitasking. A good way to remember the difference between process-based multitasking
and thread-based multitasking is to think of process-based as working with multiple
programs and thread-based as working with parts of one program. The objective of
multitasking is to utilize the idle time of the CPU. Think of the CPU as the engine of your car.
Your engine keeps running regardless of whether the car is moving. Your objective is to keep
your car moving as much as possible so you can get the most miles from a gallon of gas. An
idling engine wastes gas. The same concept applies to the CPU in your computer. You want your
CPU cycles to be processing instructions and data rather than waiting for something to process.
A CPU cycle is somewhat similar to your engine running. It may be hard to believe, but the CPU
idles more than it processes in many desktop computers. Let’s say that you are using a word
processor to write a document. For the most part, the CPU is idle until you enter a character from
the keyboard or move the mouse. Multitasking is designed to use the fraction of a second
between strokes to process instructions from either another program or from a different part of
the same programming one of two multitasking techniques: process-based multitasking and
thread-based multitasking.
Thread:-
You construct threads by using the Thread class and the Runnable interface. This means that
your class must extend the Thread class or implement the Runnable interface. The Thread class
defines the methods you use to manage threads.
Method Description
sleep() Suspends a thread. This method enables you to specify the period
Every Java program has one thread, even if you don’t create any threads. This thread is called the
main thread because it is the thread that executes when you start your program. The main thread
spawns threads that you create. These are called child threads. The main thread is always the last
thread to finish executing because typically the main thread needs to release a resource used by
the program such as network connections.
Programmers can control the main thread by first creating a Thread object and then using method
members of the Thread object to control the main thread. You create a Thread object by calling
the currentThread() method. The currentThread() method returns a reference to the thread. You
then use this reference to control the main thread just like you control any thread, which you’ll
learn how to do in this chapter.
Let’s create a reference to the main thread and then change the name of the thread from main to
Demo Thread. The following program shows how this is done. Here’s what is displayed on the
screen when the program runs:
{
Public static void main (String args[] )
{
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
t.setName("Demo Thread");
System.out.println("Renamed Thread: " + t);
}
}
As you previously learned in this chapter, a thread is automatically created when you execute a
program. The objective of this example is to declare a reference to a thread and then assign that
reference a reference to the main thread. This is done in the first statement of the main () method.
We declare the reference by specifying the name of the class and the name for the reference,
which is done in the following line of code:
Thread t
We acquire a reference to the main thread by calling the currentThread() method member of the
Thread class using the following method call:
Thread.currentThread()
The reference returned by the currentThread() method is then assigned to the reference
previously declared in the opening statement. We then display the thread on the screen:
Thread[main, 5,main]
Information within the square brackets tells us something about the thread. The first appearance
of the word main is the name of the thread. The number 5 is the thread’s priority, which is
normal priority. The priority ranges from 1 to 10, where 1 is the lowest priority and 10 is the
highest. The last occurrence of the word main is the name of the group of threads with which the
thread belongs. A thread group is a data structure used to control the state of a collection of
threads. You don’t need to be concerned about a thread group because the Java run-time
environment handles this.
The setName() method is then called to illustrate how you have control over the main thread of
your program. The setName() method is a method member of the Thread class and is used to
change the name of a thread. This example uses the setName() method to change the main
thread’s name from main to Demo Thread. The thread is once again displayed on the screen to
show that the name has been changed. Here’s what is displayed:
Remember, your program is the main thread, and other portions of your program can also be a
thread. You can designate a portion of your program as a thread by creating your own thread.
The easiest way to do this is to implement the Runnable interface. Implementing the Runnable
interface is an alternative to your class inheriting the Thread class.
An interface describes one or more method members that you must define in your own class in
order to be compliant with the interface. These methods are described by their method name,
argument list, and return value.
The Runnable interface describes the method classes needed to create and interact with a thread.
In order to use the Runnable interface in your class, you must define the methods described by
the Runnable interface.
Fortunately, only you need to define one method described by the Runnable interface—the run()
method. The run() method must be a public method, and it doesn’t require an argument list or
have a return value.
The content of the run() method is the portion of your program that will become the new thread.
Statements outside the run() method are part of the main thread. Statements inside the run()
method are part of the new thread. Both the main thread and the new thread run concurrently
when you start the new thread, which you’ll learn how to do in the next example. The new thread
terminates when the run() method terminates. Control then returns to the statement that called the
run() method.
When you implement the Runnable interface, you’ll need to call the following constructor of the
Thread class. This constructor requires two arguments. The first argument is the instance of the
class that implements the Runnable interface and tells the constructor where the new thread will
be executed. The second argument is the name of the new thread. Here’s the format of the
constructor:
The constructor creates the new thread, but it does not start the thread. You explicitly start the
new thread by calling the start()method. The start() method calls the run() method you defined in
your program. The start() method has no argument list and does not return any values.
The following example illustrates how to create and start a new thread. Here’s what is displayed
when this program runs:
This example begins by defining a class called MyThread, which implements the Runnable
interface. Therefore, we use the keyword implements to implement the Runnable interface. Next,
a reference to a thread is declared. Defining the constructor for the class follows this. The
constructor calls the constructor of the Thread class. Because we are implementing the Runnable
interface, we need to pass the constructor reference to the instance of the class that will execute
the new thread and the name of the new thread. Notice that we use the keyword this as reference
to the instance of the class. The keyword this is a reference to the current instance of the class.
The constructor returns a reference to the new thread, which is assigned to the reference declared
in the first statement in the MyThread class definition. We use this reference to call the start()
method. Remember that the start() method calls the run() method.
Next,we define the run() method. Statements within the run() method become the portion of the
program that executes when the thread executes. There are only two displayed statements in the
run() method. Later in this chapter, we’ll expand the run() method to include more interesting
statements.
Next, we define the program class. The program class explicitly executes the new thread by
creating an instance of the MyThread class. This is done by using the new operator and calling
the constructor of MyThread.
(Page 6 of 10 )
Typically, the main thread is the last thread to finish in a program. However, there isn’t any
guarantee that the main thread won’t finish before a child thread finishes. In the previous
example, we told the main method to sleep until the child threads terminate. However, we
estimated the time it takes for the child threads to complete processing. If our estimate was too
short, a child thread could terminate after the main thread terminates. Therefore, the sleep
technique isn’t the best one to use to guarantee that the main thread terminates last.
Programmers use two other techniques to ensure that the main thread is the last thread to
terminate. These techniques involve calling the isAlive() method and the join() method. Both of
these methods are defined in the Thread class.
The isAlive() method determines whether a thread is still running. If it is, the isAlive() method
returns a Boolean true value; otherwise, a Boolean false is returned. You can use the isAlive()
method to examine whether a child thread continues to run. The join() method works differently
than the isAlive() method. The join() method waits until the child thread terminates and “joins”
the main thread. In addition, you can use the join() method to specify the amount of time you
want to wait for a child thread to terminate.
The following example illustrates how to use the isAlive() method and the join() method in your
program. This example is nearly the same as the previous example. The difference lies in the
main() method of the Demo class definition.
After the threads are declared using the constructor of the MyThread class, the isAlive() method
is called for each thread. The value returned by the isAlive() method is then displayed on the
screen. Next, the join() method is called for each thread. The join() method causes the main
thread to wait for all child threads to complete processing before the main thread terminates.
thread has an assigned priority that is used to let more important threads use resources ahead of
lower-priority resources. Priority is used as a guide for the operating system to determine which
thread gets accesses to a resource such as the CPU. In reality, an operating system takes other
factors into consideration. Typically, programmers have little or no control over those other
factors. Therefore, they establish a priority for their threads without further concern over those
other factors.
A priority is an integer from 1 to 10 inclusive, where 10 is the highest priority, referred to as the
maximum priority, and 1 is the lowest priority, also known as the minimum priority. The normal
priority is 5, which is the default priority for each thread.
In general, a thread with a higher priority bumps a thread with a lower priority from using a
resource. The lower-priority thread pauses until the higher-priority thread is finished using the
resource. Whenever two threads of equal priority need the same resource, the thread that
accesses the resource first has use of the resource. What happens to the second thread depends on
the operating system under which your program is running. Some operating systems force the
second thread to wait until the first thread is finished with the resource. Other operating systems
require the first thread to give the second thread access to the resource after a specified time
period. This is to ensure that one thread doesn’t hog a resource and prevent other threads from
utilizing it.
In the real world, the first thread usually pauses while using the resource because another
resource it needs isn’t available. It is during this pause that the operating system has the first
thread relinquish the resource. The problem is, you don’t know if and when the pause will occur.
It is best to always cause a thread to pause periodically whenever the thread is using a resource
for a long period time. In this way, the thread shares the resource with other threads. You learn
how to pause a thread in the “Suspending and Resuming a Thread” section of this chapter.
You need to keep in mind that there is a downside to periodically pausing a thread. Pausing a
thread diminishes the performance of your program and could cause a backlog for use of the
resource. Therefore, you need to monitor the performance of your program regularly to make
sure you are not experiencing this negative aspect of pausing a thread.
For now let’s focus on something you do have control over—setting the priority of a thread. You
set a thread’s priority by calling the setPriority() method, which is defined in the Thread class.
The setPriority() method requires one parameter, which is the integer representing the level of
priority. You have two ways in which to represent the priority. You can use an integer from 1 to
10, or you can use final variables defined in the Thread class. These variables are
MIN_PRIORITY, MAX_PRIOIRTY, and NORM_PRIOIRTY.
You can determine the priority level of a thread by calling the getPriority() method, which is also
defined in the Thread class. The getPriority() method does not requires an argument, and it
returns the integer representing the level of priority for the thread.
The following example illustrates how to use the setPriority() and getPriority() methods. This
example creates two child threads and sets the priority for each. First, the low-priority thread
starts, followed by the high-priority thread. Here’s what is displayed when you run this program
(notice that the high-priority thread runs ahead of the low-priority thread, even though the low-
priority thread started first):
Synchronizing Threads
A major concern when two or more threads share the same resource is that only one of them can
access the resource at one time. Programmers address this concern by synchronizing threads,
much the same way baseball players take turns being up to bat.
Threads are synchronized in Java through the use of a monitor. Think of a monitor as an object
that enables a thread to access a resource. Only one thread can use a monitor at any one time
period. Programmers say that the thread owns the monitor for that period of time. The monitor is
also called a semaphore.
A thread can own a monitor only if no other thread owns the monitor. If the monitor is available,
a thread can own the monitor and have exclusive access to the resource associated with the
monitor. If the monitor is not available, the thread is suspended until the monitor becomes
available. Programmers say that the thread is waiting for the monitor.
Fortunately, the task of acquiring a monitor for a resource happens behind the scenes in Java.
Java handles all the details for you. You do have to synchronize the threads you create in your
program if more than one thread will use the same resource.
You have two ways in which you can synchronize threads: You can use the synchronized
method or the synchronized statement.
All objects in Java have a monitor. A thread enters a monitor whenever a method modified by
the keyword synchronized is called. The thread that is first to call the synchronized method is
said to be inside the method and therefore owns the method and resources used by the method.
Another thread that calls the synchronized method is suspended until the first thread relinquishes
the synchronized method.
If a synchronized method is an instance method, the synchronized method activates the lock
associated with the instance that called the synchronized method, which is the object known as
this during the execution of the body of the method. If the synchronized method is static, it
activates the lock associated with the class object that defines the synchronized method.
Before you learn how to define a synchronized method in your program, let’s see what might
happen if synchronization is not used in a program. This is the objective of the following
example. This program displays two names within parentheses using two threads. This is a three-
step process, where the opening parenthesis, the name, and the closing parenthesis are displayed
in separate steps.
The example defines three classes: the Parentheses class, the MyThread class, and the Demo
class, which is the program class. The Parentheses class defines one method called display(),
which receives a string in its argument list and displays the string in parentheses on the screen.
The MyThread class defines a thread. In doing so, the constructor of MyThread requires two
arguments. The first argument is a reference to an instance of the Parentheses class. The second
argument is a string containing the name that will be displayed on the screen. The run() method
uses the instance of the Parentheses class to call its display() method, passing the display()
method the name that is to appear on the screen.
The rest of the action happens in the main() method of the Demo class. The first statement
declares an instance of the Parentheses class. The next two classes create two threads. Notice that
both threads use the same instance of the Parentheses class.
Here’s what is displayed when you run this program. It’s probably not what you expected to see.
Each name should be enclosed within its own parentheses. The problem is that the display()
method isn’t synchronized.
{
void display(String s)
{
System.out.print ("(" + s);
try
{
Thread.sleep (1000);
} catch (InterruptedException e)
{
System.out.println ("Interrupted");
}
System.out.println(")");
}
}
class MyThread implements Runnable
{
String s1;
Parentheses p1;
Thread t;
public MyThread (Parentheses p2, String s2) {
p1= p2;
s1= s2;
t = new Thread(this);
t.start();
}
public void run() {
p1.display(s1);
}
}
class Demo
{
public static void main (String args[]) {
Parentheses p3 = new Parentheses();
MyThread name1 = new MyThread(p3, "Bob");
MyThread name2 = new MyThread(p3, "Mary");
try {
name1.t.join();
name2.t.join();
}
catch (InterruptedException e )
{
System.out.println( "Interrupted");
}
}
}
The problem with the previous example is that two threads use the same resource concurrently.
The resource is the display() method defined in the Parentheses class. In order to have one thread
take control of the display() method, we must synchronize the display() method. This is done by
using the keyword synchronized in the header of the display() method, which is illustrated in the
next example.
Here’s what is displayed when you run the next example. This is what you expected to see in the
previous example.
(Bob)
(Mary)
class Parentheses {
synchronized void display(String s) {
System.out.print ("(" + s);
try {
Thread.sleep (1000);
} catch (InterruptedException e) {
System.out.println ("Interrupted");
}
System.out.println(")");
}
}
class MyThread implements Runnable {
String s1;
Parentheses p1;
Thread t;
public MyThread (Parentheses p2, String s2) {
p1= p2;
s1= s2;
t = new Thread(this);
t.start();
}
public void run() {
p1.display(s1);
}
}
class Demo{
public static void main (String args[]) {
Parentheses p3 = new Parentheses();
MyThread name1 = new MyThread(p3, "Bob");
MyThread name2 = new MyThread(p3, "Mary");
try {
name1.t.join();
name2.t.join();
} catch (InterruptedException e ) {
System.out.println( "Interrupted");
}
}
}
There might be times when you need to temporarily stop a thread from processing and then
resume processing, such as when you want to let another thread use the current resource. You
can achieve this objective by defining your own suspend and resume methods, as shown in the
following example.
This example defines a MyThread class. The MyThread class defines three methods: the run()
method, the suspendThread() method, and the resumeThread() method. In addition, the
MyThread class declares the instance variable suspended, whose value is used to indicate
whether or not the thread is suspended.
The run() method contains a for loop that displays the value of the counter variable. Each time
the counter variable is displayed, the thread pauses briefly. It then enters a synchronized
statement to determine whether the value of the suspended instance variable is true. If so, the
wait() method is called, causing the thread to be suspended until the notify() method is called.
The suspendThread() method simply assigns true to the suspended instance variable. The
resumeThread() method assigns false to the suspended instance variable and then calls the
notify() method. This causes the thread that is suspended to resume processing.
The main() method of the Demo class declares an instance of MyThread and then pauses for
about a second before calling the suspendThread() method and displaying an appropriate
message on the screen. It then pauses for about another second before calling the resumeThread()
method and again displaying an appropriate message on the screen.
The thread continues to display the value of the counter variable until the thread is suspended.
The thread continues to display the value of the counter variable once the thread resumes
processing. Here’s what is displayed when you run this program:
Thread: 0
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Thread: Suspended
Thread: Resume
Thread: 5
Thread: 6
Thread: 7
Thread: 8
Thread: 9
Thread exiting.
class MyThread implements Runnable {
String name;
Thread t;
boolean suspended;
MyThread() {
t = new Thread(this, "Thread");
suspended = false ;
t.start();
}
public void run() {
try {
for (int i = 0; i < 10; i++) {
System.out.println("Thread: " + i );
Thread.sleep(200);
synchronized (this) {
while (suspended) {
wait();
}
}
}
} catch (InterruptedException e ) {
System.out.println("Thread: interrupted.");
}
System.out.println("Thread exiting.");
}
void suspendThread() {
suspended = true;
}
synchronized void resumeThread() {
suspended = false;
notify();
}
}
class Demo {
public static void main (String args [] ) {
MyThread t1 = new MyThread();
try{
Thread.sleep(1000);
t1.suspendThread();
System.out.println("Thread: Suspended");
Thread.sleep(1000);
t1.resumeThread();
System.out.println("Thread: Resume");
} catch ( InterruptedException e) {
}
try {
t1.t.join();
} catch ( InterruptedException e) {
System.out.println (
"Main Thread: interrupted");
}
}
}
*Java io package:
The Java Input/output (I/O) is a part of java.io package. The java.io package contains a
relatively large number of classes that support input and output operations. The classes in the
package are primarily abstract classes and stream-oriented that define methods and subclasses
which allow bytes to be read from and written to files or other input and output sources. The
InputStream and OutputStream are central classes in the package which are used for
reading from and writing to byte streams, respectively.
The java.io package can be categories along with its stream classes in a hierarchy structure
shown below:
InputStream:
The InputStream class is used for reading the data such as a byte and array of bytes from an
input source. An input source can be a file, a string, or memory that may contain the data. It
is an abstract class that defines the programming interface for all input streams that are
inherited from it. An input stream is automatically opened when you create it. You cans
explicitly close a stream with the close( ) method, or let it be closed implicitly when the object
is found as a garbage.
The subclasses inherited from the InputStream class can be seen in a hierarchy manner
shown below:
InputStream is inherited from the Object class. Each class of the InputStreams provided by the
java.io package is intended for a different purpose.
OutputStream:
The OutputStream class is a sibling to InputStream that is used for writing byte and array of
bytes to an output source. Similar to input sources, an output source can be anything such as a
file, a string, or memory containing the data. Like an input stream, an output stream is
automatically opened when you create it. You can explicitly close an output stream with the
close( ) method, or let it be closed implicitly when the object is garbage collected.
The classes inherited from the OutputStream class can be seen in a hierarchy structure shown
below:
OutputStream is also inherited from the Object class. Each class of the OutputStreams
provided by the java.io package is intended for a different purpose.
How Files and Streams Work:
Java uses streams to handle I/O operations through which the data is flowed from one
location to another. For example, an InputStream can flow the data from a disk file to the
internal memory and an OutputStream can flow the data from the internal memory to a disk
file. The disk-file may be a text file or a binary file. When we work with a text file, we use a
character stream where one character is treated as per byte on disk. When we work with a
binary file, we use a binary stream.
The working process of the I/O streams can be shown in the given diagram.
Files:-
can read several types of information from files: binary, Java objects, text, zipped files, etc. One
of the most common problems is reading lines of text.
This example reads text files using the classes FileReader, BufferedReader, FileWriter, and
BufferedWriter. It's a main program without a graphical user interface, reading from the console.
To change this to a graphical user interface, use JFileChooser to get a File object instead
console input.
import java.io.*;
GUI interface
javax.swing.JFileChooser creates a standard file dialog and allows you to easily get a File
object for reading or writing. See JFileChooser.
The above program does nothing with the lines of text except write them. Typically, you need to
get values from the lines. There are several useful ways to extract data from the lines.
Stream:-
Streams:
*Streams:-
1.Input stream-
it provides basic input methods for reading data from an input stream.
2.output stream-
*Byte stream:-
This class uses a byte array as it's input source it has two constructors.
1.ByteArrayInputStream(byte ar[]);
Import java.io.*;
class bdemo
String tmp="ashwath";
for(int i=0;i<b.length;i++)
System.out.println(b[i]+"");
for(int i=0;i<=1;i++)
int c;
if(i==0)
System.out.println((char)c);
}
else
System.out.println(character.toUpperCase((char)c));
System.out.println();
*ByteArrayOutputStream:-
1.ByteArrayOutputStream-
2.ByteArrayOutputStream(int)-
import java.io.*;
class bdemo
f.write(b1);
System.out.println("buffer as a string");
System.out.println(f.toString());
byte b2[]=f.toByteArray();
for(int i=0;i<b2.length;i++)
System.out.println(b2[i]+" ");
for(int i=0;i<b2.length;i++)
System.out.println((char)b2[i]);
System.out.println("\n to an outputstream");
System.out.println("see test.txt");
f.writeTo(out);
out.close();
--------------------------------------------------------------------------------------------------
*FileInputStream-
For handling information from a file. fileInputStream class is used this class
helps in reading data from actual disk files. any object at this class can be created using the
keyword new.
*programe to FileInputStream
import java.io.*;
class fileclass
System.out.println("available bytes="+in.available());
in.skip(4);
int n=in.available();
for(int i=0;i<n;i++)
System.out.println((char)in.read());
--------------------------------------------------------------------------------------------------*File
OutputStream-:
for sending information to file we use file output stream class it helps to create a file &
write data into it using methods it has two constructor.
*DataInputStream-
This class is used with the data outstream vicaversa it can be used to read all primitive
data types from the stream.
*programe on dataInputStream
import java.io.*;
class ddemo
String name;
char c;
int i;
long l;
try
System.out.println("enter name");
name=d.readLine();
System.out.println("enter integer");
i=Integer.parseInt(d.readLine());
c=((char)System.in.read());
System.out.println("character is="+c);
catch(Exception e)
{}
*programe
import java.io.*;
class emp
try
for(i=0;i<5;i++)
{
System.out.println("enter empno"+i+1);
name[i]=d.readLine();
System.out.println("enter empcode");
code[i]=Integer.parseInt(d.readLine());
sal[i]=float.parseFloat(d.readLine());
for(int i=0;i<5;i++)
*DataOutputStream
This class is used DataInputStream class. we can write primitive datatype to a stream.
import java.io.*;
class dataclass
d.write int(123);
d.write char('a');
d.write Boolean(true);
d.write Byte(12);
int a=d1.readInt();
System.out.println("integer="+a);
byte b=d1.readByte();
System.out.println("byte is="+b);
Boolean b1=d1.readboolean();
System.out.println("Boolean"+b1);
char c=d1.readChar();
System.out.println("char "+c);
filter stream-
It is used to read data from one stream class we can write an primitive datatype to a stream.
1.FilterInputStream -:
It is abstract class providing an interface for useful functionality to the other input
stream classes.the following classes under the filter input stream.
1.BufferedInputStream
2.DataInputStream
3.PushBackInputStream
2.FilterOutputStream-
1.BufferedoutputStream
2.DataOutputStream
3.PrintStream
1.BufferedInputStream-
It is use to prevent the physical read everytime when more data is readed. this class
accept input by using a buffered array of bytes.
*Constructor
1.BufferedInputStream(InputStream obj);
*BufferedOutputStream:-
*constructor
1.BufferedOutputStream(OutputStream o)
2.BufferedOutputStream(OutputStream,int bufsize);
*Programe of BufferedInputStream
import java.IO.*;
class bufclass
{
String s="ashwath");
byte b1=s.getBytes();
int c;
while((c=buf.read()!=-1)
System.out.println((char)c);
for(int i=0;i<b1.length.i++)
System.out.println("\n"+b1[i]+" ");
3.PushBackInputStream-
It has one byte pushbackBuffer so the last character read can be pushback.
import java.io.*;
class pdemo
String s="dog";
byte b[]=s.getBytes();
int c;
while((c.p.read()!=-1)
{
if(c=p.read())=='0')
System.out.print("\n");
p.unread(c);
else
System.out.print((char)c);
1.PrintStream -;
It is use to produce the formatted output while data output stream handles the storage of
data printStream handles display.
Import java.io.*;
class Psdemo
String s="shreya";
int cno=101;
double sal=30.00;
p.println(s);
p.println(cno);
p.println(sal);
*LineNumberInputStream:-
A LineNumberInputStream is Filter input stream. that counts the number of line terminators
as data is read from the input stream.
*constructor
programe:
Import java.io.*;
class lnum
int m=ar[0].charAt(0);
int ch;
while((ch=l.read())!=-1)
if(ch==m)
{
System.out.println((char)ch+" "+l.getLineNumber());
*StreamTokenizer:-
It help to identify the patient in the input stream it is a responsible for breaking up
the input stream it to tokens. A stream is tokenizer by creating a streamTokenizer with the file
object as its source.The loop invoke the next token which returns the tokenbyte of next token.
1.TT_EOF:-
2.TT_EOL:-
3.TT_word:-
4.TT_NUMBERS:-
*import java.io.*;
class streamdemo
while((tok=s.nextToken())!=StreamTokenizer.TT_EOF)
if(tok==StreamTokenizer.TT_WORD)
System.out.println("word found"+s.sval());
c++;
else if(tok==streamTokenizer.TT_NUMBER);
*filereader:-
Convenience class for reading character files. The constructors of this class assume that the
default character encoding and the default byte-buffer size are appropriate. To specify these
values yourself, construct an InputStreamReader on a FileInputStream.
*constructor:-
1)FileReader(file f)
2)charArrayReader:-
It allows the use of character array as input stream it similar to byte array input
stream.
3)StringReader:-
constructor:-
StringReader(string s)
4)InputStreamReader:-
constructor:-
InputStreamReader(InputStream in)
5)FilterReader:-
constructor:
filterReader(Reader r)
6)BufferdReader:-
It accept a reader object as its parameter and adds a buffered of character it is useful
becuase of its method readline()
constructor:-
BufferedReader(Reader r)
*****************************************************************************
*
*)writer classes:-
The difference betn writer and output stream is that while writers are able to writes
characters outputStreamWriterBytes
1) FilterWriter:-
FileWriter(file f);
2)charArrayWriter:-
constructor:-
charArrayWriter(char ch[])
3)PrintWriter:-
Print formatted representations of objects to a text-output stream. This class implements all of
the print methods found in PrintStream. It does not contain methods for writing raw bytes, for
which a program should use unencoded byte streams.
PrintWriter(outputstream obj);
4)filterWriter:-
filterWriter(Writer w);
5)BufferedWriter:-
Write text to a character-output stream, buffering characters so as to provide for the efficient
writing of single characters, arrays, and strings.
The buffer size may be specified, or the default size may be accepted. The default is large
enough for most purposes.
constructor:-
BufferedWriter(writer w)
6)OutputStreamWriter:-
OutputStreamWriter(OutputStream obj);
*Programes for char stream
Import java.io.*;
String name;
String grade;
String performance;
String rating;
InputStream r;
BufferedReader b;
FileOutputStream f;
public cust()
try
r=new InputStreamReader(System.in);
b=new BufferedReader(r);
System.out.println("customer name");
name=b.readLine();
System.out.println("custmorGrader");
grade=b.readLine();
System.out.ptintln("custmor Performance");
performance =b.readLine();
System.out.println("custmor rating");
rating =b.readLine();
r.close();
b.close();
f=new FileOutputStream("custmor.txt");
String temp=name+";"+grade+";"+performance+";"+rating;
f.write(temp.getBytes());
f.close();
catch(FileNotFoundException fn)
{}
Applet:-
Introduction
In this section you will learn about the different components available in the Java AWT
package for developing user interface for your program.
Following some components of Java AWT are explained :
1. Labels : This is the simplest component of Java Abstract Window Toolkit. This
component is generally used to show the text or string in your application and label never
perform any type of action. Syntax for defining the label only and with justification :
2. Buttons : This is the component of Java Abstract Window Toolkit and is used to trigger
actions and other events required for your application. The syntax of defining the button
is as follows :
3. Check Boxes : This component of Java AWT allows you to create check boxes in your
applications. The syntax of the definition of Checkbox is as follows :
4. Radio Button : This is the special case of the Checkbox component of Java AWT
package. This is used as a group of checkboxes which group name is same. Only one
Checkbox from a Checkbox Group can be selected at a time. Syntax for creating radio
buttons is as follows :
5. Text Area: This is the text container component of Java AWT package. The Text Area
contains plain text. TextArea can be declared as follows:
6. Text Field: This is also the text container component of Java AWT package. This
component contains single line and limited text information. This is declared as follows :
8. In this section, you will learn about the java.awt.*; package available with JDK. AWT
stands for Abstract Windowing Toolkit. It contains all classes to write the program that
interface between the user and different windowing toolkits. You can use the AWT package to
develop user interface objects like buttons, checkboxes, radio buttons and menus etc. This
package provides following interfaces and classes as follows:
Interfaces and Descriptions of AWT Package:
ActionEvent This interface is used for handling
events.
Adjustable This interface takes numeric value to
adjust within the bounded range.
Composite This interface defines methods to
draw a graphical area. It combines a
shape, text, or image etc.
CompositeContext This interface allows the existence of
several context simultaneously for a
single composite object. It handles
the state of the operations.
ItemSelectable This interface is used for
maintaining zero or more selection
for items from the item list.
KeyEventDispatcher The KeyEventDispatcher
implements the current
KeyboardFocusManager and it
receives KeyEvents before
despatching their targets.
KeyEventPostProcessor This interface also implements the
current KeyboardFocusManager.
The KeyboardFocusManager
receives the KeyEvents after that
dispatching their targets.
LayoutManager It defines the interface class and it
has layout containers.
LayoutManager2 This is the interface extends from the
LayoutManager and is subinterface
of that.
MenuContainer This interface has all menu
containers.
Paint This interface is used to color
pattern. It used for the Graphics2D
operations.
PaintContext This interface also used the color
pattern. It provides an important
color for the Graphics2D operation
and uses the ColorModel.
PaintGraphics This interface provides print a
graphics context for a page.
Shape This interface used for represent the
geometric shapes.
Stroke This interface allows the Graphics2D
object and contains the shapes to
outline or stylistic representation of
outline.
Transparency This interface defines the
transparency mode for implementing
classes.
9.
Classes and Descriptions of AWT Package:
AlphaComposite This class implements
the basic alpha
compositing rules. It
combines the source and
destination pixels to
achieve transparency
effects to graphics and
images.
AWTEvent This is a supper class of
all AWT Events.
AWTEventMulticaster This class implements
thread-safe multi-cast
event and it is
despatching for the
AWT event. The AWT
events defined in the
java.awt.event package.
AWTKeyStroke This class used to key
action on the keyboard
or equivalent input
devices.
AWTPermission This class uses for the
AWT permissions.
BasicStroke This class defines the
basic set of rendering
attributes for using
outlines of graphics.
BorderLayout This class uses to
arranging the
components. It has five
components such as:
east, west, north, south
and the center.
BufferCapabilities This class has properties
of buffers.
BufferCapabilities.FlipContents This class has a type-
safe enumeration of
buffer. It contains after
page-flipping.
Button This class used to create
a label button
Convas It represents the blank
rectanglular area on
screen. It can draw or
trap input events from
the user.
CardLayout It is a layout manager
for a comtainer.
Chaeckbox It is a graphical
component. It has two
states. True state that
means "on" or false sate
that means "off".
CheckboxGroup This class to be used
together multiple
checkbox buttons.
CheckboxMenuItem This class represents the
checkbox and also
include the menu.
Choice This class represents
pop-up menu to user's
choice.
Color This class has colors.
The default color is
RGB color. Color
library specify the all
color, it identified by
ColorSpace.
Component This is a graphical
representation to
interacted by user. It
displays on the screen.
ComponentOritentation This class encapsulates
the language-sensitive
orientation. It also used
the order the element of
component or text..
Container A generic AWT
container object has
other AWT components.
ContainerOrderFocusTraversalPolicy It determines the
traversal order based on
the order of child
components in a
container.
Cursor This class represents the
bitmap representation of
the mouse cursor.
DefultFocusTraversalPolicy This class determines
the traversal order on
the order of child
components of
container.
DefultKeyboardFocusManager This class used for
handle the AWT
applecations.
Dialog This is a top label
window. It has title and
border. It can be used
for taking a some input
of users.
Dimension This class describe the
height and width of a
component in a single
object.
DisplayMode This class encapsulates
the bit depth, height,
width and refresh rate of
a GraphicsDevice.
Event This class available only
for the backwards
compatilibility.
EventQueue It is a platform
independent class. It has
both classes underlying
peer class and trusted
application class.
FileDialog This class displays
dialog window. Here
user can be select the
file.
FlowLayout This class arrange the
components and flow
the left to right. It uses
to write lines in a
paragraph.
FocusTraversalPolicy This class defines the
order in which
components traverse
particular focus cycle
root.
Font This class defines fonts
and it uses render text
that is visible.
FontMetrics This class defines font
matrix object.. It
encapsulate the
information and
rendering the paritcular
fonts.
Frame This class defines top-
level window and it
designs the any area of
border.
GradientPaint With the help of
GradientPaint you fill
any shapes.
Graphics This class uses to
drawing all types of
graphics such as: oval,
rectangle etc.
Graphics2D This class controls all
geometry, coordinate
transformation, color
management etc. It
extends form the
Graphics class.
GraphicsConfigTemplate This class contains a
valid
GraphicConfiguration.
GraphicsConfiguration This class describes the
characteristics of
graphics destination
such as printer and
monitor.
GraphicsDevice This class describes the
graphics devices and it
available particular
graphics environment.
GraphicsEnvironment This class is a collection
of GraphicsDevices
object and Font objects.
The GraphicsDevices
objects are screen,
images and printers etc.
GridBagConstraints This class specify the
constraint for
components by using the
GrideBagLayout class.
GridBagLayout This class uses the
layout manager and uses
the vertically and
horizontally
components.
GridLayout This class is a layout
manager. It has
rectangular grid
components.
Image This class is a supper
class of all graphical
images.
ImageCompabilities It has compabilities and
properties of images.
Insets This class represents all
types of border's
container. It includes
borders, blank space and
titles.
JobAttributes This class control the
print job.
JonAttributes.DefaultSelectionType It has default selection
states and extends from
the
java.awt.AttributeValue
package.
JobAttributes.DestinatinType It possible for the job
destinations and extends
form the
java.awt.AttributeValue
package.
JobAttributes.DialogType It displays the user
dialog and extends from
the
java.awt.AttributeValue
package.
JobAttributes.MultipleDocumentHandlingType This class handles the
multiple copy states and
extends form the
java.awt.AttributeValue
package.
JobAttributes.SidesType It uses multi-page
impositions and extends
from the
java.awt.AttributeValue
package.
KeyboardFocusManager This class manage the
current focus owner,
active and focused
windows
Label It is a component which
contains the text in
container.
List This component uses by
the uses and it choose
the list of item.
MediaTracker This class has status of a
number of media
objects. It is a utility
class.
Menu It has pull-down menu
components that
displayed as like menu
bar.
MenuBar This class has the
concept of menu bar and
it also bounded into a
frame.
MenuComponent This is supper class of
all menu related
components.
MenuItem This is a supper class
and it represents the
item of menu.
MenuShortcut This class represents the
handling MenuItem
through help of
keyboard .
PageAttributes It controls the output of
the printed page.
PageAttributes.ColorType It handles the color
states and extends form
the
java.awt.AttributeValue
package.
PageAttributes.MediaType It handles the paper size
and extends from the
java.awt.AttributeValue
package.
PageAttributes.OrientationRequestedType It handles the possible
orientations and extends
from the
java.awt.AttributeValue
package.
PageAttributes.OriginType It handles the origins
and extends from the
java.awt.AttributeValue
package.
PageAttributes.PrintQualityType It handles the print
qualities and extends
from the
java.awt.AttributeValue
package.
Panel This is a simplest
container class. It
includes components
and other panels. It
extends Container and
implements to
Accessible.
Point The point represents the
location of coordinate
(x, y) space. It extends
Point2D.
Polygon It has two dimensional
region and it bounded
by the multiple number
of lines.
PopupMenu It extends the Menu and
specify the positions of
components.
PrintJob This class executes a
print job and extends
from the Object.
Rectangle A rectangle object has
length and width and it
also specify an area in a
coordinate space. It
extends Rectangle2D.
RenderingHints This class contains
rendering hints by using
the Graphics2D class.
RenderingHints.Key This class used to
control the randering
and imaging pipelines.
Robot This class used to
generate the native
system input events and
it automatically test the
java platform
implementations.
Scrollbar This class provide the
user interface
components and also
include the scroll bar.
Which implements the
Adjustable interface.
ScrollPane It includes the horizontal
and vertical scrolling for
a single child
components. The
horizontal and vertical
state represented by the
ScrollPaneAdjustable
objects.
ScrollPaneAdjustable This class represents the
state of horizontal and
vertical scrollbar of
ScrollPane.
SystemColor This class represents the
system's color through
the symbolic
representation color.
The value depends on
the actual value of
RGB.
TextArea It displays multi line
text.
TextComponent This is a supper class of
any component. It
allows to editing the
some text.
TextField It has text component
and It allows to editing a
single line of text.
TexturePaint It provides a way to fill
a shape with a texture
and specify by the
BufferedImage.
Toolkit This is a supper class of
all Abstract Windowing
Toolkit.
Window It is a top-level window.
It has not borders and
menubar. It capable for
generating the window
events like:
WindowOpend,
WindowClosed.
10.
Exceptions and Descriptions of AWT Package:
AWTException This signal displays when an Abstract Windowing Toolkit
exception has occurred.
FontFormatException When the specified font is bad then this exception to be occurred.
It thrown by the createFont method in the Font class.
HeadlessException This exception to be occurs when the codes are not supported by
the keyboard, display and Mouse.
IllegalComponentStateException The AWT has not suitable state for the requesting operation then
it thrown by the IllegalComponentStateException.
AWTError It thrown when the Abstract Windowing Toolkit error has
occurred.
2. Swing Using UIManager. Swing has looked and feel according to user view u can change
look and feel. Applet Does not provide this facility
3.Swing uses for stand-alone Applications, Swing have main method to execute the
program. Applet needs HTML code for Run the Applet
5. Swings have its own Layout...like most popular Box Layout Applet uses Awt
Layouts..Like flowlayout
6. Swings have some Thread rules. Applet doesn’t have any rule.
7. To execute Swing no need any browser By which we can create stand alone application
But Here we have to add container and maintain all action control within frame container.
To execute Applet programs we should need any one browser like Appletviewer, web
browser. Because Applet using browser container to run and all action control within
browser container.
Examples:-
import java.awt.*;
import java.applet.*;
// A Button to click
Button okButton;
TextField nameField;
// necessary to only allow one radio button to be selected at the same time.
CheckboxGroup radioGroup;
Checkbox radio1;
Checkbox radio2;
Checkbox option;
setLayout(null);
okButton.setBounds(20,20,100,30);
nameField.setBounds(20,70,100,40);
radio1.setBounds(20,120,100,30);
radio2.setBounds(140,120,100,30);
option.setBounds(20,170,100,30);
// now that all is set we can add these components to the applet
add(okButton);
add(nameField);
add(radio1);
add(radio2);
add(option);
ActionExample:
import java.awt.*;
import java.applet.*;
Button okButton;
Button wrongButton;
TextField nameField;
CheckboxGroup radioGroup;
Checkbox radio1;
Checkbox radio2;
Checkbox radio3;
setLayout(new FlowLayout());
add(wrongButton);
add(nameField);
add(radio1);
add(radio2);
add(radio3);
okButton.addActionListener(this);
wrongButton.addActionListener(this);
if (radio1.getState()) g.setColor(Color.red);
else g.setColor(Color.green);
// Now that the color is set you can get the text out the TextField
// like this
g.drawString(nameField.getText(),20,100);
// When the button is clicked this method will get automatically called
// This is where you specify all actions.
if (evt.getSource() == okButton)
// That will cause the aplet to get the text out of the textField
repaint();
wrongButton.setLabel("Not here!");
repaint();
ImageExample:-
/*
*/
import java.awt.*;
import java.applet.*;
import java.net.*;
Image my_gif;
URL base;
MediaTracker mt;
mt = new MediaTracker(this);
// Java itself.
try {
base = getDocumentBase();
}
catch (Exception e) {}
my_gif = getImage(base,"4.jpg");
mt.addImage(my_gif,1);
// (in this example don't paint) until the images are fully loaded.
try {
mt.waitForAll();
catch (InterruptedException e) {}
// (image name,x,y,observer);
g.drawImage(my_gif,20,20,this);
g.drawImage(my_gif,20,140,30,40,this);
}
}
Swing:-
The Java Swing provides the multiple platform independent APIs interfaces for interacting
between the users and GUIs components. All Java Swing classes imports form the import
javax.swing.*; package. Java provides an interactive features for design the GUIs toolkit or
components like: labels, buttons, text boxes, checkboxes, combo boxes, panels and sliders etc.
All AWT flexible components can be handled by the Java Swing. The Java Swing supports the
plugging between the look and feel features. The look and feel that means the dramatically
changing in the component like JFrame, JWindow, JDialog etc. for viewing it into the several
types of window.
Here the following APIs interfaces and classes are available:
The following interfaces and it's descriptions to be used by the Java swing.
Interfaces Descriptions
Action This interface performed the action with
the ActionListener where the multiple controls are used for
same purposes.
ButtonModel It defines the state model for the buttons like: radio buttons,
check boxes etc.
CellEditor This interface used by the developer for creating the new
editor and it has the new components implement interfaces.
The CellEditor implements the wrapper based approach.
ComboBoxModel This interface represents the data model in a list model with
the selected items.
ListCellRenderer This interface used for paint the cell in the list with the help
of "rubber stamps" .
ListModel This interface used for JList components method. It gets the
value of each cell of list.
RootPaneContainer This interface uses the RootPane properties and it has the
components like: JFrame, JInternalFrame and JWindow
etc.
UIDefaults.LazyValue This enables one to store an entry in the default table. The
entered value is not constructed until first time is a real
value is created through it
usingLazyValue.createValue() method.
Classes Descriptions
AbstractAction This class handles the any types of action and provides
JFC Action interface.
AbstractButton This class defines the nature of buttons and menu items.
AbstractListModel This class defines the data model which provides the list
with its contents.
ActionMap This class works with InputMap and performs any action
when the key is pressed.
BorderFactory This class extends from Object and creates the Border
instance in the factory.
DefaultListSelectionModel This class used for select the list in a data model.
ImageIcon This class implements the Icon and paints the icons from
the images.
InputVerifier This class helps you when you works with the text fields
through the focus.
JDesktopPane This class extends the JLayeredPane and when you create
the object of JInternalFrame to be maintained in the
JDesktopPane. The JDesktopPane has DesktopManager.
JDialog It extends the Dialog. This class used to create the dialog
window and when you want to create the custom dialog
window with the help ofJOptionPane method.
JLabel This class used to show the small text and image.
JList This class used to create a list where you select the one or
more than objects.
JMenu This class used to create a new menu where you add the
JMenuItems. When you select the item then shows the
popup menu items in the JMenuBar.
JMenuBar It used to create a new menu bar where the JMenu objects
are added.
JMenuItem This class used to create new menu items in the mebus.
JPopupMenu.Separator Here the popup menu and the separator are available.
JScrollBar This class used to create a scroll bar. It provides the view
content area where you show the content to scroll this.
JScrollPane It provides the scrollable view components.
JTabbedPane This class provides the tab component through which you
can switch from one component to another component
regarding to the specific tab button by clicking on that.
KeyStroke This class controls the key events on the keyboard for the
equivalent device.
UIDefaults It extends the Hashtable and you set/get the value with
the help of UIManager.
UIManager This class has track of the current look and feel details.
UIManager.LookAndFeelInfo This is the nested class of UIManager class i.e. used for
getting information about all the look and feels installed
with the softwaredevelopment kit.
The following Exceptions and it's description to be used by the Java swing.
Exception Descriptions
This exception occurred when the look and feel classes are
UnsupportedLookAndFeelException
not supported to user's system.
import java.awt.*;
import javax.swing.*;
public Applet2 () {
super ();
Panel = getContentPane();
Panel.setBackground (Color.cyan);
}
super.paint (g);
Width = getWidth();
Height = getHeight();
g.drawString ("The applet width is " + Width + " Pixels", 10, 30);
g.drawString ("The applet height is " + Height + " Pixels", 10, 50);
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
Frame1 () {
Container Pane;
Handler = new Closer ();
Tag = new JLabel ();
Pane = getContentPane ();
setTitle ("JFrame Example");
setSize (300,120);
Tag.setText ("JLabel");
Pane.add (Tag);
addWindowListener (Handler);
show ();
}
public JPanel1 () {
LayoutManager Layout;
Container Pane;
InputPanel.setLayout (Layout);
Tag.setText ("Diameter ");
Tag.setHorizontalAlignment (JLabel.RIGHT);
Entry.setColumns (8);
Entry.setText ("10");
Entry.setHorizontalAlignment (JTextField.RIGHT);
Entry.addActionListener (this);
InputPanel.add (Tag);
InputPanel.add (Entry);
Pane.add (InputPanel, BorderLayout.NORTH);
Pane.add (Drawing, BorderLayout.CENTER);
}
public CircleCanvas () {
setBackground (Color.yellow);
}
g2 = (Graphics2D) g;
g2.setColor (Color.black);
Width = getWidth ();
Height = getHeight ();
Circle = new Ellipse2D.Double
((double) ((Width - Diameter) / 2),
(double) ((Height - Diameter) / 2),
(double) Diameter, (double)Diameter);
g2.fill (Circle);
}
import java.awt.*;
import javax.swing.*;
public Controls () {
Container Panel;
String [] ListData;
Panel = getContentPane();
Panel.setLayout (Layout);
Panel.setBackground (Color.green);
Panel.add (DemoLabel);
Panel.add (DemoButton);
Panel.add (DemoRadioButton);
Panel.add (DemoCheckBox);
Panel.add (DemoTextField);
Panel.add (DemoPassword);
Panel.add (DemoTextArea);
Panel.add (DemoComboBox);
Panel.add (DemoList);
Panel.add (DemoSlider);
Panel.add (DemoScrollbar);
DemoLabel.setText ("JLabel");
DemoButton.setText ("JButton");
DemoCheckBox.setText ("JCheckbox");
DemoComboBox.addItem ("JComboBox");
DemoComboBox.addItem ("Selection");
DemoList.setListData (ListData);
DemoPassword.setText ("JPasswordField");
DemoRadioButton.setText ("JRadioButton");
DemoTextArea.setText ("JTextArea");
DemoTextField.setText ("JTextField");
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public Button1 () {
/* Instantiation */
Layout = new FlowLayout ();
Panel = getContentPane ();
Button1 = new JButton ("Red Background");
Button2 = new JButton ("Yellow Background");
Button3 = new JButton ();
Command = new JTextField ("ActionCommand", 20);
/* Location */
Panel.setLayout (Layout);
Panel.add (Button1);
Panel.add (Button2);
Panel.add (Button3);
Panel.add (Command);
/* Configuration */
Button1.addActionListener (this);
Button1.setActionCommand ("red");
Button2.setEnabled (false);
Button2.addActionListener (this);
Button3.addActionListener (this);
Command.setEditable (false);
/* Decoration */
Button3.setBackground (Color.black);
Button3.setForeground (Color.white);
Button3.setText ("White on Black");
Panel.setBackground (Color.yellow);
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public CheckBox1 () {
/* Instantiation */
Layout = new FlowLayout ();
Bold = new JCheckBox ("Bold");
Italic = new JCheckBox ("Italic", true);
Result = new JTextField ("", 25);
/* Location */
Panel.setLayout (Layout);
Panel.add (Bold);
Panel.add (Italic);
Panel.add (Result);
Panel.setBackground (Color.yellow);
/* Configuration */
Bold.addItemListener (this);
Italic.addItemListener (this);
Result.setEditable (false);
/* Decoration */
Bold.setBackground (Color.yellow);
Italic.setBackground (Color.yellow);
/* Initialization */
setState ();
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public ComboBox1 () {
/* Instantiation */
Layout = new FlowLayout ();
ColorList = new String [9];
SansSerif = new Font ("SansSerif", Font.BOLD, 14);
/* Configuration */
Selector.addItemListener (this);
/* Decoration */
Selector.setForeground (Color.red);
Selector.setFont (SansSerif);
/* Initialization */
Selector.setSelectedIndex (5);
Selector.setBackground (Color.yellow);
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public Label1 () {
/* Instantiation */
Layout = new GridLayout (7, 1);
Label1 = new JLabel ("A Simple Label");
Label2 = new JLabel ("A Label with LEFT alignment", JLabel.LEFT);
Label3 = new JLabel ("A Label with CENTER alignment", JLabel.CENTER);
Label4 = new JLabel ("A Label with RIGHT alignment", JLabel.RIGHT);
Label5 = new JLabel ("A Label with LEADING alignment", JLabel.LEADING);
Label6 = new JLabel ("A Label with TRAILING alignment", JLabel.TRAILING);
Label7 = new JLabel ();
Panel = getContentPane ();
/* Location */
Panel.setLayout (Layout);
Panel.add (Label1);
Panel.add (Label2);
Panel.add (Label3);
Panel.add (Label4);
Panel.add (Label5);
Panel.add (Label6);
Panel.add (Label7);
/* Decoration */
Panel.setBackground (Color.yellow);
Label7.setHorizontalAlignment (JLabel.CENTER);
Label7.setForeground (Color.blue);
Label7.setText ("Text added with setText");
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public PasswordField1 () {
/* Instantiation */
Input = new JPasswordField ("Input", 20);
Echo = new JTextField ("Echo", 20);
Layout = new FlowLayout ();
Panel = getContentPane ();
/* Location */
Panel.setLayout (Layout);
Panel.add (Input);
Panel.add (Echo);
/* Decoration */
Input.setBackground (Color.green);
Echo.setEditable (false);
Panel.setBackground (Color.yellow);
/* Configuration */
Input.addActionListener (this);
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RadioButton1 extends JApplet implements ItemListener {
private Container Panel;
private LayoutManager Layout;
private JRadioButton Red;
private JRadioButton Yellow;
private JRadioButton White;
private ButtonGroup Background;
public RadioButton1 () {
/* Instantiation */
Layout = new FlowLayout ();
Panel = getContentPane ();
Red = new JRadioButton ("Red Background");
Yellow = new JRadioButton ("Yellow Background", true);
White = new JRadioButton ();
Background = new ButtonGroup();
/* Location */
Panel.setLayout (Layout);
Panel.add (Red);
Panel.add (Yellow);
Panel.add (White);
/* Decoration */
Red.setBackground (Color.red);
Yellow.setBackground (Color.yellow);
White.setBackground (Color.white);
White.setForeground (Color.red);
White.setText ("White Background");
Panel.setBackground (Color.yellow);
/* Configuration */
Background.add (Red);
Background.add (Yellow);
Background.add (White);
Red.addItemListener (this);
Yellow.addItemListener (this);
White.addItemListener (this);
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public ScrollBar3 () {
/* Instantiation */
Layout = new BorderLayout ();
HSelector = new JScrollBar ();
VSelector = new JScrollBar ();
Report = new JLabel ();
Pad = new Drawing ();
Panel = getContentPane ();
/* Location */
Panel.setLayout (Layout);
Panel.add (Report, BorderLayout.SOUTH);
Panel.add (HSelector, BorderLayout.NORTH);
Panel.add (VSelector, "West");
Panel.add (Pad, "Center");
/* Configuration */
HSelector.setMaximum (200);
HSelector.addAdjustmentListener (this);
VSelector.setMaximum (200);
VSelector.addAdjustmentListener (this);
HSelector.setOrientation (JScrollBar.HORIZONTAL);
/* Decoration */
Report.setHorizontalAlignment (JTextField.CENTER);
Report.setText ("H = " + HSelector.getValue() +
", V = " + VSelector.getValue());
Pad.setBackground (Color.yellow);
Pad.setSize (220, 220);
Pad.setOval (HSelector.getValue (), VSelector.getValue ());
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public TextArea1 () {
Input = new JTextField ("Input", 20);
Echo = new JTextArea (5, 20);
Echo2 = new JTextArea (5, 20);
Layout = new FlowLayout ();
Panel = getContentPane ();
Input.addActionListener (this);
Echo.setEditable (false);
Echo.setBackground (Color.green);
Echo.setLineWrap (true);
Panel.setLayout (Layout);
Panel.add (Input);
Panel.add (Echo);
Panel.add (Echo2);
Panel.setBackground (Color.yellow);
}
import java.applet.Applet;
import java.awt.*;
import javax.swing.*;
public Box1 () {
int i;
*create a menubar:
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
// File->New, N - Mnemonic
JMenuItem newMenuItem = new JMenuItem("New", KeyEvent.VK_N);
fileMenu.add(newMenuItem);
frame.setJMenuBar(menuBar);
frame.setSize(350, 250);
frame.setVisible(true);
}
}
BorderLayout
Applets use a default layout scheme: the BorderLayout (a number of the previous example
have changed the layout manager to FlowLayout).Without any other instruction, this takes
whatever you add( ) to it and places it in the center, stretching the object all the way out to the
edges.
However, there’s more to the BorderLayout. This layout manager hasthe concept of four
border regions and a center area. When you addsomething to a panel that’s using a
BorderLayout you can use theoverloaded add( ) method that takes a constant value as its
first argument. This value can be any of the following:
BorderLayout. NORTH Top
BorderLayout. SOUTH Bottom
BorderLayout. EAST Right
BorderLayout. WEST Left
BorderLayout.CENTER
}
public static void main(String[] args)
{
Console.run (new BorderLayout1(), 300, 250);
}
} ///
For every placement but CENTER, the element that you add is compressed to fit in the smallest
amount of space along one dimension while it is stretched to the maximum along the other
dimension. CENTER, however, spreads out in both dimensions to occupy the middle.
FlowLayout
This simply “flows” the components onto the form, from left to right until the top space is full,
then moves down a row and continues flowing. Here’s an example that sets the layout manager
to FlowLayout and then places buttons on the form. You’ll notice that with FlowLayout
the
components take on their “natural” size. A JButton, for example, will be the size of its string
// <applet code=FlowLayout1 width=300 height=250></applet>
import javax.swing.*;
import java.awt.*;
import com.bruceeckel.swing.*;
public class FlowLayout1 extends JApplet {
public void init() {
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
for(int i = 0; i < 20; i++)
cp.add(new JButton("Button " + i));
}
public static void main(String[] args) {
Console.run(new FlowLayout1(), 300, 250);
}
} ///:~
All components will be compacted to their smallest size in a FlowLayout, so you might get a
little bit of surprising behavior.
GridLayout
A GridLayout allows you to build a table of components, and as you add them they are placed
left-to-right and top-to-bottom in the grid. In the constructor you specify the number of rows
and columns that you need and these are laid out in equal proportions.
.
// <applet code=GridLayout1 width=300 height=250></applet>
import javax.swing.*;
import java.awt.*;
import com.bruceeckel.swing.*;
public class GridLayout1 extends JApplet {
public void init() {
Container cp = getContentPane();
cp.setLayout(new GridLayout(7,3));
for(int i = 0; i < 20; i++)
cp.add(new JButton("Button " + i));
}
public static void main(String[] args) {
Console.run(new GridLayout1(), 300, 250);
}
} ///:~
In this case there are 21 slots but only 20 buttons. The last slot is left empty because no
“balancing” goes on with a GridLayout.
GridBagLayout
The GridBagLayout provides you with tremendous control in deciding exactly how the
regions of your window will lay themselves out and reformat themselves when the window is
resized. However, it’s also the most complicated layout manager, and quite difficult to
understand. It is
intended primarily for automatic code generation by a GUI builder (GUI builders might use
GridBagLayout instead of absolute placement). If your design is so complicated that you feel
you need to use
Absolute positioning
It is also possible to set the absolute position of the graphical components in this way:
1. Set a null layout manager for your Container: setLayout(null).
2. Call setBounds( ) or reshape( ) (depending on the language version) for each
component, passing a bounding rectangle in pixel
coordinates. You can do this in the constructor, or in paint( ), depending on what you want to
achieve. Some GUI builders use this approach extensively, but this is usually not the best way to
generate code.
BoxLayout
Because people had so much trouble understanding and working with GridBagLayout, Swing
also includes BoxLayout, which gives you many of the benefits of GridBagLayout without
the complexity, so you can often use it when you need to do hand-coded layouts (again, if your
design becomes too complex, use a GUI builder that generates layouts for you). BoxLayout
allows you to control the placement of components either vertically or horizontally, and to
control the space between the components using something called “struts and glue.” First, let’s
see how to use the BoxLayout directly, in the same way that the other layout managers have
been demonstrated:
// <applet code=BoxLayout1 width=450 height=200></applet>
import javax.swing.*;
import java.awt.*;
import com.bruceeckel.swing.*;
public class BoxLayout1 extends JApplet {
public void init() {
JPanel jpv = new JPanel();
jpv.setLayout(new BoxLayout(jpv, BoxLayout.Y_AXIS));
for(int i = 0; i < 5; i++)
jpv.add(new JButton("jpv " + i));
JPanel jph = new JPanel();
jph.setLayout(new BoxLayout(jph, BoxLayout.X_AXIS));
for(int i = 0; i < 5; i++)
jph.add(new JButton("jph " + i));
Container cp = getContentPane();
cp.add(BorderLayout.EAST, jpv);
cp.add(BorderLayout.SOUTH, jph);
}
public static void main(String[] args) {
Console.run(new BoxLayout1(), 450, 200);
}
} ///:~
The constructor for BoxLayout is a bit different than the other layout
managers—you provide the Container that is to be controlled by the
BoxLayout as the first argument, and the direction of the layout as the
second argument.
To simplify matters, there’s a special container called Box that uses
BoxLayout as its native manager. The following example lays out
components horizontally and vertically using Box, which has two static
methods to create boxes with vertical and horizontal alignment:
//: c14:Box1.java
// Vertical and horizontal BoxLayouts.
// <applet code=Box1 width=450 height=200></applet>
import javax.swing.*;
import java.awt.*;
import com.bruceeckel.swing.*;
public class Box1 extends JApplet {
public void init() {
Box bv = Box.createVerticalBox();
for(int i = 0; i < 5; i++)
bv.add(new JButton("bv " + i));
Box bh = Box.createHorizontalBox();
for(int i = 0; i < 5; i++)
bh.add(new JButton("bh " + i));
806 Thinking in Java www.BruceEckel.com
Container cp = getContentPane();
cp.add(BorderLayout.EAST, bv);
cp.add(BorderLayout.SOUTH, bh);
}
public static void main(String[] args) {
Console.run(new Box1(), 450, 200);
}
} ///:~
Once you have a Box, you pass it as a second argument when adding
components to the content pane.
Struts add space between components, measured in pixels. To use a strut,
you simply add it in between the addition of the components that you
want spaced apart:
// Adding struts.
// <applet code=Box2 width=450 height=300></applet>
import javax.swing.*;
import java.awt.*;
import com.bruceeckel.swing.*;
public class Box2 extends JApplet {
public void init() {
Box bv = Box.createVerticalBox();
for(int i = 0; i < 5; i++) {
bv.add(new JButton("bv " + i));
bv.add(Box.createVerticalStrut(i*10));
}
Box bh = Box.createHorizontalBox();
for(int i = 0; i < 5; i++) {
bh.add(new JButton("bh " + i));
bh.add(Box.createHorizontalStrut(i*10));
}
Container cp = getContentPane();
cp.add(BorderLayout.EAST, bv);
cp.add(BorderLayout.SOUTH, bh);
}
public static void main(String[] args) {
Console.run(new Box2(), 450, 300);
}
} ///:~
Struts separate components by a fixed amount, but glue is the opposite: it
separates components by as much as possible. Thus it’s more of a “spring”
than “glue” (and the design on which this was based was called “springs
and struts” so the choice of the term is a bit mysterious).
//: c14:Box3.java
// Using Glue.
// <applet code=Box3 width=450 height=300></applet>
import javax.swing.*;
import java.awt.*;
import com.bruceeckel.swing.*;
public class Box3 extends JApplet {
public void init() {
Box bv = Box.createVerticalBox();
bv.add(new JLabel("Hello"));
bv.add(Box.createVerticalGlue());
bv.add(new JLabel("Applet"));
bv.add(Box.createVerticalGlue());
bv.add(new JLabel("World"));
Box bh = Box.createHorizontalBox();
bh.add(new JLabel("Hello"));
bh.add(Box.createHorizontalGlue());
bh.add(new JLabel("Applet"));
bh.add(Box.createHorizontalGlue());
bh.add(new JLabel("World"));
bv.add(Box.createVerticalGlue());
bv.add(bh);
bv.add(Box.createVerticalGlue());
getContentPane().add(bv);
}
public static void main(String[] args) {
Console.run(new Box3(), 450, 300);
}
} ///:~
A strut works in one direction, but a rigid area fixes the spacing between
components in both directions:
//: c14:Box4.java
// Rigid areas are like pairs of struts.
// <applet code=Box4 width=450 height=300></applet>
import javax.swing.*;
import java.awt.*;
import com.bruceeckel.swing.*;
public class Box4 extends JApplet {
public void init() {
Box bv = Box.createVerticalBox();
bv.add(new JButton("Top"));
bv.add(Box.createRigidArea(new Dimension(120, 90)));
bv.add(new JButton("Bottom"));
Box bh = Box.createHorizontalBox();
bh.add(new JButton("Left"));
bh.add(Box.createRigidArea(new Dimension(160, 80)));
bh.add(new JButton("Right"));
bv.add(bh);
getContentPane().add(bv);
}
public static void main(String[] args) {
Console.run(new Box4(), 450, 300);
}
} ///:~
You should be aware that rigid areas are a bit controversial. Since they use
absolute values, some people feel that they cause more trouble than they
are worth.