JAVA Notes Gist
JAVA Notes Gist
Table of Contents:
1. Introduction to JAVA
History of JAVA
Features of JAVA
Introduction to OOPS
A first program in JAVA
2. Developing a JAVA Programming
Data Types
Variables
Literals
Expressions
Operators
Controls
3. Classes
General Structure of a class
Methods
More about classes
Constructors
Finalizer
4. Arrays and Strings
Declaring Array Variables
Multidimensional Array
String Constructors
String Methods
Casting and converting
5. Inheritance
Basics
Overridding
Using Final and Abstract Classes
6. Package & Exception Handling
Packages and Interfaces
Basics of Exception Handling
Exception Types
Creating your own Exception
7. I/O Packages
Files And Streams
Methods in Streams
Types of I/O Streams
Reader and Writer Classes
Stream Tokenizer
8. Events and User Interface Components
Event Handling
Types of Event Handling
Containers
User Interface Component Classes
History of JAVA:
Java has been around since 1991, developed by a small team of Sun Microsystems
developers in a project originally called the Green project. The intent of the project was
to develop a platform-independent software technology that would be used in the
consumer electronics industry. The language that the team created was originally called
Oak.
In 1994, two Sun developers created the first version of HotJava, and then called
WebRunner, which is a graphical browser for the Web that exists today. The browser was
coded entirely in the Oak language, by this time called Java. Soon after, the Java
compiler was rewritten in the Java language from its original C code, thus proving that
Java could be used effectively as an application language. Sun introduced Java in May
1995 at the SunWorld 95 convention.
Features of JAVA:
Sun describes Java as a "simple, object-oriented, interpreted, robust, secure, architecture-
neutral, portable, high-performance, multithreaded, and dynamic language."
Concept of Encapsulation:
Information Hiding – Ensures that objects cannot change the internal state of other
objects in unexpected ways; only the object’s own internal methods are allowed to
access its state. Each type of object exposes an interface to other objects that
specifies how other objects may interact with it.
Abstraction – The ability for a program to ignore some aspects of the information it is
manipulating.
Inheritance: Inheritance is the process by which one object acquires the properties of
another object. It stands for its concept of hierarchical classification. For example
Maruthi is part of the classification car, which in turn is part of the Transport class.
The first step is to run the text editor of choice and create the classic HelloWorld
program.
// HelloWorld.java
class HelloWorld {
public static void main (String args[]) {
System.out.println("Hello World!");
}
}
Save the file as HelloWorld.java in the classes’ directory. After saving your source code
with the extension .java, you can compile it using the Java compiler, javac. To run the
javac compiler, execute it with the following syntax.: javac [ options ] filename.java
If the code compiles correctly, you will see two files in your classes’ directory:
HelloWorld.java and HelloWorld.class. The .class file has now been converted to
bytecode. To run a java file type
The Sun’s Java Development kit (JDK) provides all features to write programs. Java
applications are general programs written in the Java language that do not require a
browser to run.
The Java source file is created in a plain text editor and can also be created in an editor
that saves files in plain ASCII without any formatting characters. A Java program has
two main parts: a class definition that encloses the entire program and a method called
main that contains the body.
Once the program is typed in, it is saved as a file with an extension of .java. Usually java
files have the same name as their class definition. This file is then compiled using javac.
The javac program should be in the execution path for compilation of the java code. Once
completed, a file by the same name, but with the .class extension is created. This is the
java byte code file. The byte code is then run using the java interpreter. In the JDK, the
java interpreter is called java. To execute this, java followed by the filename without the
class extension is typed at the DOS prompt. The above compilation and execution
procedure works only if Sun’s Java compiler is used.
Example:
Open a new file in the editor and type the following script
class Hello {
public static void main (String args[])
{ System.out.pri
ntln("Welcome to DMISS");
}
}
Welcome to DMISS
In addition to compilation and execution, both Java compiler and the Java interpreter
check the Java source code and bytecode to make sure that the Java programmer has not
overrun buffers, stack frames etc.
At first class is declared. Every Java application program has a main ( ) method. It is the
first function run when the program is executed. Void keyword preceding main( )
indicates that it does not return any values. Public indicates that the method is global,
static denotes that main( ) is a class method and can be called without creating an object.
The third step indicates the printing a string on to the screen. The curly braces are used to
enclose the class and main function.
DATA TYPES:
Every variable declared should have a name, a type and a value. Java provides different
data types that include character, double, float, integer, string, Boolean etc. These are
primitive types as they are built into the Java language and are not actual objects thus
making it easier to use them. The data types in Java are machine-independent. New types
are declared by a class definition and objects of this class can be created.
Wrapper classes are provided for the primitive type, have the same name as the
primitive type, but the first letter capitalized. The advantage of using wrappers is that
when an object is passed to a method, the method is able to work on the object itself.
Another advantage is that the user can derive his/her own classes from Java’s built-in
wrapper classes.
Integer:
Integers has four types. It include byte, short, int and long, which are for whole-
valued signed numbers. Each holds a different range of values. The values can either be
positive or negative.
Float:
Float is used to store numbers with decimal point. There are two floating point data types
in Java namely the float( 32bits, single-precision ) and the double(64 bits, double
precision).
Character:
It is used for storing individual characters. The char type has 16 bits of precision and it
is unsigned. Java uses Unicode to represent characters. Unicode defines a fully
international characters set that can represent all of the characters in all human languages.
The range of char is 0 to 65,536. There are no negative characters.
Boolean:
Boolean data types hold either a true or a false value. These are not stored as numeric
values and cannot be used as such. This is the type returned by all relational operators,
such as a < b.
Class BoolTest
{
Public static void main(String arg[] )
{
boolean b;
b = false;
System.out.println(“b is “ +b);
b = true;
System.out.println(“b is “ +b);
}
}
Local Variables are used inside blocks as counters or in methods as temporary variables.
Once the block or the method is executed, the variable ceases to exist. The local
Variables are used to store information needed by a single method.
Class Variables are global to a class and to all the instances of the class. They are useful
for communicating between different objects of the same class or for keeping track of
global status.
The keyword static is used to declare a class variable.
DECLARING A VARIABLE:
Variable name:
Variable names in java can start with a letter, an underscore(-), or a dollar sign($)
but cannot begin with a number. The second character onwards can include any letter or
number. Java is case sensitive and also uses the Unicode character set.
Variable types:
Variable types can be any data type that java supports- the eight primitive types, the
name of a class or interface and an array.
Assigning values:
Values are assigned to variables using the assignment operator “equal to”(=).
Open the new file in the editor and type the following script.
1: class Hello (
2: public static void main (String args[]){
3: int x = 90;
4: short y = 4;
5: float z = 10.87f;
6: String name = “Arun”;
7: System.out.println(“the integer value is “+ x);
8: System.out.println (“the short value is “= y);
9: System.out.println (“the float value is “ = z”);
10: System.out.println(“the string value is “ = name);
11: }
12: }
Save this file as Hello.java and compile using javac Hello.java at DOS
prompt.
On successful compilation, execute the program using java Hello
The output is diaplayed as shown
The integer value is 90
The short value is 4
The float value is 10.87
The string value is Arun
Line 3 – 6 depict declaration, initialization and naming of various data types. The
values of the declared variables are printed from lines 7 – 10. The + operator is used here
as a concatenation operator.
LITERALS:
A Literal represents a value of a certain type where the type describes the behaviour
of the value.
There are different types of literals. They are:
Number literals
Character literals
Boolean literals
String literals
Number:
There are many types of integer literals such as int, long, octal, hexadecimal, etc. 2 is
an example of a decimal integer literal of type int. If a decimal integer literal is larger
than the int, it is declared to be of type long. These integers can also be expressed as octal
or hexadecimal.
Floating point literals have a decimal part and an integer part. Floating point literals result
in floating point numbers of type double. By appending f to a number, it can be changed
as type float. Exponents can be used in floating point literals by using the letter E or e
followed by exponent.
Boolean:
Boolean literals consist of the keywords true or false.
Character:
Character literals are expressed by a single character enclosed within single quotes.
Characters are stored as Unicode characters.
Escape Meaning
\n Newline
\t Tab
\b Backspace
\r Carriage return
\f Form feed
\\ Backslash
\’ Single quote
\” Double quote
\ddd Octal
\xdd Hexadecimal
\udddd Unicode character
Table lists the special codes that represent non-printable characters from Unicode
character set. The letter ‘d ’ in the octal, hex and the Unicode escapes represent a number
or a hexadecimal digit. Java does not include character codes for the bell and the vertical
tab.
String
A string is a combination of characters. String literals are a set of characters that are
enclosed within double quotes. They are real objects, it is possible to concatenate, modify
and test them. For example, “Welcome to DMISS” represents a string. Strings can
contain character constants and Unicode characters.
When a string literal is declared Java automatically creates an instance of the class String
and initializes it with the value specified.
Expressions
Expressions are the simplest form of statements in Java. These statements return a
value that can be assigned to a variable. These statements return a value that can be
assigned to a variable. The following are examples for expressions:
x + 10
total – 1
Operators
Operators are special symbols used in expressions. They include arithmetic operators,
assignment operators, increment and decrement operators, logical operators, bitwise
operators and comparison operators.
Arithmetic Operators
Java has five basic arithmetic operators. Each of these operators takes two operands,
one on either side of the operator.
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Example:
Open a new file and type the following script.
// subtracting numbers
System.out.println(“ A-B =” +(A-B));
System.out.println(“ X-Y =” +(X-Y));
//multiplying numbers
System.out.println(“ A*B =” +(A*B));
System.out.println(“ X*Y =” +(X*Y));
// dividing numbers
System.out.println(“ A/B =” +(A/B));
System.out.println(“ X/Y =” +(X/Y));
//modulus type
System.out.println(“ A%B =” +(A%B));
System.out.println(“ X%Y =” +(X%Y));
//mixing types
System.out.println(“ B+Y =” +(B+Y));
System.out.println(“ A*X =” +(A*X));
}
}
Save this file as hello.java and compile using javac hello.java at DOS prompt.
A-B = -5
X-Y = 20.255
A*B = 1554
X*Y = 198.37
A/B = 0
X/Y = 3.8054
A%B = 37
X%Y = 5.815
B+Y = 49.22
A+X = 1016.58
Java provides special operators that can be used to combine an arithmetic operation with
an assignment. Assignment operators set the value of a variable or expression to some
new value. The simple = operator sets the left-hand operand to the value of the right-hand
operand. If the operands are object references, then a copy of the reference value will be
assigned and not the object body. The assignment operator is evaluated from right to left,
so a = b = c = 0; would assign 0 to c, then c to b then b to a. A selection of assignment
operators is given.
Expression Meaning
x += y x=x+y
x -= y x=x–y
x *= y x=x*y
x /= y x=x/y
x=y x=y
Example:
Open a new file and type the following
Logical Operators
Logical operators available are AND, OR, XOR and NOT.
AND operator (& or &&) returns true only if both sides in an expression are true. If any
one fails, the operator is false.
OR operator ( | or || ) returns true if any expression is true. Only if all the conditions are
false, the expression is false.
XOR operator ( ^ ), returns true if its operands are different. If both its operands are
similar then it returns false.
Bitwise Operators
A shift operator performs bit manipulation on data by shifting the bits of its first operand
right or left. Each operator shifts the bits of the left-hand operand over by the number of
positions indicated by the operator itself. It is used to perform operations on individual
bits in integers.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Left shift
>> Right shift
>>>> Zero fill right shift
~ Bitwise Complement
<<= Left Shift assignment
>>= Right Shift assignment
>>>= Zero fill right shift assignment
x &= y AND assignment
x |= y OR assignment
x ^= y XOR assignment
Example:
Open a new file and type the following script.
Class Bitop
{
public static void main(String args[])
{
int a=1;
int b=2;
int c=3;
a=a /4;
b>>=1;
c<<=1;
a=a^c;
System.out.println(“a=”+a);
System.out.println (“b=” +b);
System.out.println(“c=”+c);
}
}
• Save this file as BitOp.java and compile using javac BitOp.java at the DOS
prompt.
• Execute the source code using: java BitOp
• The output is
a=3
b=1
c=6
Operator precedence
The order which the expressions are evaluated and their overall value is determined by
Operator precedence.
The following table indicates specific precedence of the various operators.
Operator Notes
[],( ), . [] is used for arrays. ( ) group expressions.
Dot is used to access methods and variables
within objects and classes.
++, --, !, - , instance of Returns true or false based on whether the
object is an instance of the named class or
any of that class’s super class.
New( type) expression The new operator is used to create
instances of classes.
*, /, % Multiplication, division, modulus
+, - Addition, subtraction
<<, >> Bitwise left and right shift
<, >, < =,>= Relational comparison tests
= =,!= Equal to and not equal to
& AND
^ XOR
| OR
&& Logical AND
|| Logical OR
?: Ternary operator
=, +=, - =,* =,/=, %=, ^= Assignment
? Ternary operator
Java includes a special ternary operator that can replace certain types of if-then-else
statements. This operator is the ? and it works in Java much like it does in C, C++ and
C#.
When Java evaluates this assignment expression, it first looks at the expression to the left
of the question mark. If it satisfies the condition then expression2 is executed else
expression3 is executed.
Keywords
There are certain sequences of characters, called ‘Keywords’ that have special meaning
in Java. There are around 48 reserved keywords currently defined in Java language, these
keywords, combined with the syntax of the operators and separators, form the definition
of the Java language. These keywords cannot be used as names for a variable, class, or
method.
abstract boolean break byte case cast
catch char class const continue default
do double else extends final finally
float for future if implements import
int interface long native new null
operator package private protected public return
short static super switch synchronized this
throw throws transient try void while
Controls:
A programming language uses control statements to cause the flow of execution, based
on changes to the state of a program. Java’s program control statements can be put into
the following categories: selection, iteration and jump.
The if construct:
The if statement enables your program to selectively execute other statements.
if ( expression)
{
Statement(s) }
To perform a different set of statements if the expression is false? We can use else
statement .
if – else statement:
if ( condition)
body of loop
else
body of loop
Example:
public class grade
{
public static void main(String [] args)
{
int score = 75;
char grade;
Conditional Operator:
The conditional operator is otherwise known as the ternary operator and is considered to
be an alternative to the if else construct. It returns a value and the syntax is:
While( condition){
< statement>
}
At first while statement evaluates condition, which must return a Boolean value. If the
condition returns true then the while statement executes the statements associated with it.
The while statement test the condition and executes its block until the condition returns
false.
do {
statement(s)
}
while(condition);
Instead of evaluating the expression at the top of the loop, do-while evaluates the
expression at the bottom. Thus the statements associated with a do-while are executed
atleast once.
Example:
public class for{
public static void main (String args[]) {
int i;
for (i = 0;i <10; i = i + 2)
{
if ((i%2) = = 0)
System.out.println(“ + i + is a even number”);
}
}
}
Nested loop
Like all other programming languages, Java allows loops to be nested. i.e, one loop
may be inside another.
Break statement has two forms: (i) unlabeled and (ii) labeled.
The unlabeled form of the break statement used to terminate a for, while, or do-while
loop. It encloses switch statement and flow of control transfers to the statement
immediately. The labeled break terminates the statement when the value is found. It does
not transfer the flow of control to be label. The flow of control transfers to the statement
immediately following the labeled (terminated) statement.
Continue:
The continue statement is used to halt the execution of the loop, it starts the next
iteration. The unlabeled form skips to the end of the innermost loop’s body and evaluates
the Boolean expression that controls the loop. The labeled form of the continue statement
skips the current iteration of an outer loop marked with the given label.
Return :
The final Java’s branching statement is the return statement. We use return to exit from
the current method. The flow of control returns to the statement that follows the original
method call. The return statement has two forms: one that returns a value and one that
does not. To return a value, simply put the value after the return keyword:
return ++ count;
The data type of the value returned by return must match the type of the method’s
declared return value. When a method is declared void, use the form of return that does
not return a value:
return;
Switch statement:
The switch statement dispatches control to the different parts of the code based on the
value of a single variable or expression. The value of expression is compared with each
of the literal values in the case statements. If they match, the following code sequence is
executed. Otherwise an optional default statement is executed.
General syntax is
case<value b>:
<result b>;
break;
default :
<defaultresult>;
}
Example:
class switch {
public static void main (String args[]) {
int month = 8;
switch (month) {
case 1:
System.out.println(“ January”);
break;
case 2:
System.out.println(“ February”);
break;
case 3:
System.out.println(“ March”);
break;
case 4:
System.out.println(“ April”);
break;
case 5:
System.out.println(“ May”);
break;
case 6:
System.out.println(“ June”);
break;
case 7:
System.out.println(“ July”);
break;
case 8:
System.out.println(“ August”);
break;
case 9:
System.out.println(“ September”);
break;
case 10:
System.out.println(“ October”);
break;
case 11:
System.out.println(“ November”);
break;
case 12:
System.out.println(“ December”);
break;
}
}
}
Summary:
Java is a programming language developed by Sun Microsystems.
Every Java application requires a class declaration and the main( ) method declaration.
Java data types include Boolean, character, double, float, integer, etc. These are called
the primitive types and they are not actual objects.
Variables are locations in the memory that can hold values and they must have a data
type, a name and a value.
A string is a combination of characters and they are real objects, and hence, it is
possible to concatenate, modify and test them.
Operators are special symbols that are used in expression. Java uses many controls
statements.
CLASSES
The basic element of object-oriented programming is a class. A class
definition is a set of plans; the same is true of software objects. In order to create a
software object in Java, it is necessary for someone to first create a plan. In Java, we refer
to that plan as a class. A class is defined by use of the class keyword. A class defines the
shape and behaviour of an object and is a template for multiple objects with similar
features. Any concept represented in a program is encapsulated in a class. When an
application is written, classes of objects are defined.
Syntax:
class <classname> {
<body of the class>
}
A class called Car includes all its features serving as template. Each property is treated as
an attribute of that class. For example, car name, colour, engine, model, number etc are
the attributes.
class car {
String name;
String color;
int number;
}
A class also defines its functional interface known as methods. For instance, car can have
a method that displays the name of the car.
Once a car class is defined, instances of that class can be created and each instance can
have different attributes. When the program runs, instances of the class are created and
discarded as and when required.
An instance of a class can be used to access the variables and methods that form the part
of the class. Each instance of the class has its own copy of instance variables defined in
the class and hence can hold different attributes. The methods in the class operate on
individual instances of the class. The term instance and object are used interchangeably.
The Java environment comes with a library of classes that implement a lot of the basic
behaviour. By creating classes that use the classes provided by Java, highly maintainable
program can be constructed.
Example:
Open a new file and enter the following code:
class one {
public static void main (String args[] ) {
int a = 1;
int b = 2;
int c = 3;
System.out.println (“a = “+ a);
System.out.println (“b = “+ b);
System.out.println (“c = “ +c);
}
}
Save the file as one.java
Compile the file using javac one.java
Run the file using java one
Attributes:
Attributes are individual properties that differentiate one object from another and
determines appearance, state and other qualities. Each attribute has a corresponding
instance variable.
Instance Variables:
Data is encapsulated in a class by declaring variables inside the class declaration.
Variables declared in this scope are known as instance variables. Instance variables are
declared in the same way as local variables except that they are declared outside the
scope of any particular method, such as main. For example, a class named point can be
created with instance variables namely a and b. Every object of this class has its own
copy of the instance variable.
class point {
int a, b;
}
Dot Operator
The dot notation is used to obtain the value of the instance variables. It has two
parts namely the object on the left side of the dot and the variable on the right side of the
dot. Dot expressions are evaluated from left to right.
General form:
<objectReference>.<variableName>
where <objectReference> is the name of the object and <variableName> is the instance
variable.
We can store values into instance variables using the dot operator.
p.x = 10;
p.y = 20;
System.out.println (“x=” + p.x + “y=” + p.y)
Declaring Objects:
When you create a class, you are creating a new data type. We can use this type to
declare objects of that type. However, obtaining objects of a class is a two-step process.
At first, we need to declare a variable of the class type. This variable does not define an
object. Second, we must acquire an actual, physical copy of the object and assign it to
that variable. We can do this using new Operator.
The new Operator
The new operator creates a single instance of a named class and returns a reference
to that object. This reference is more or less the address in memory of the object allocated
by new. For example, an instance of a named class and returns a reference to that object.
Object b = new Object( );
Here b is a reference to an instance of object. The reference is then stored in the variable.
There is a critical distinction between how simple types and objects are manipulated in
Java. The variable b is a reference to the object. It does not actually contain it.
When an object is no longer referred to by any variable, Java automatically
reclaims memory used by that object. This is known as garbage collection. When a new
object is created a distinct set of instance variables are obtained. Each object has its own
copy of the instance variables of its class, so changes to the instance variables of one
object have no effect on the instance variables of another. Each object’s instance
variables are separate and distinct from the others.
Class Variables
Class variables are global to a class and to all the instances of the class. They are useful
for communicating between different objects of the same class or for keeping track of
global states. The keyword static is used to declare a class variable. For class variable
there is only one copy of the variable. Every instance of the class has access to that
variable. We have to use the dot notation to access the class variable, and instead of using
the object’s name on the left hand side of the dot operator, the class name can be used.
Thus, class variables can be accessed without creating an object of that class.
Methods
A method’s declaration provides information about the method to the compiler, to the
runtime system and to other classes and objects. Methods are functions that operate on
instances of classes in which they are defined. Objects can communicate with each other
using methods and can call methods in other classes. Instance methods apply and operate
on an instance of the class and instance methods. Instance methods apply and operate on
an instance of the class while class methods operate on the class.
Defining Methods
Method definition has four parts. They are:
Name of the method
Type of object
A list of parameters
Body of the method
Method overloading:
Java permits different methods to have the same name as long as the argument list is
different. This is called as method overloading. A basic method definition resembles as
The returntype is the primitive type or class of the value that this method returns. It
should be void if the method does not return a value at all. It is essential to aloe the same
method name to be used with different argument types. And it also must for constructors.
The method’s parameter list is a set of variable declarations. The list is separated by
commas within the parentheses. The parentheses become local variables in the body of
the mehod whose values are passed when the method is called.
Inside the body of the method, statements, expressions and method calls can be present.
If the method has a return type, then a value must be returned using the keyword return.
Calling Methods
Calling a method is similar to calling or referring to an instance variable. The methods
are accessed using the dot notation. The object whose method is called is on the left of
the dot, while the name of the method and its argument are on the right.
Obj.methodname (param1,param2);
The class Area has two instance variables, s1 and s2, which are initialized when an object
is created. The calc method, which does not return any value, is defined. This method
calculates the area and displays it. In the main method, an instance of the class, Area is
created. The calc method of the class, which calculates and displays the area, is called in
the code.
Class Methods:
Class methods, like class variables, are available to instances of the class and can be
made available to other classes. Class methods can be used anywhere regardless of
whether an instance of the class exists or not. Methods that operate on a particular object
should be defined as instance methods. Methods that provide some general utility but do
not directly affect an instance of the class are declared as class methods.
Syntax of class method:
static <returntype> <methodname> (<type1> <arg1>, <type2> <arg2>,………) {
<set of statements>
}
The static keyword indicates that it is a class method and can be accessed without
creating an object. The class methods, unlike instance methods, are not allowed to use
instance variables, as these methods do not operate on an object.
STATIC MEANING:
The this keyword:
With this keyword, we can understand what it means to make a method Static. It means
that there is no this for that particular method. We cannot call non-static methods from
inside static methods and we can call a static method for the class itself, without any
object. A special reference value called this is included in java. The this keyword is used
inside any instance method to refer to the current object. The value of this refers to the
object on which the current method has been called. The this keyword can be used where
a reference to an object of the current class type is required. Methods declared with the
keyword static( class methods) cannot use this.
Overloading methods:
Overloading is a powerful feature, but we should use it only when needed. To create
an overloaded method, different method definitions each with the same name but
different parameter lists are created. Java allows method overloading as long as the each
parameter list is unique for the same method name. Java differentiates overloaded
methods with the same name, based on the number and type of parameters to that method
and not on the return type. When a method is called, Java chooses the method definition
to execute, depending on the method name and number and type of arguments. If
methods are chosen to have the same names and parameter lists but different return types
then the compiler returns an error. The variable names in the parameter list do not matter.
Only the number and the type of the parameters matter.
class Load {
String fname;
String lname;
int age;
String prof;
Load fload( String fname, String lname, int age, String profession) {
this.fname = fname;
this.lname = lname;
this.age = age;
this.profession = profession;
return this;
}
Load fload ( String fn, String ln) {
fname = fn;
lname = ln;
return this;
}
Load fload (String fnme, String lnme, String pr) {
fname = fnme;
lname = lnme;
profession = pr;
return this;
}
Load fload (String fna, String lna, int ag) {
fname = fna;
lname = lna;
age = ag;
return this;
}
void print ( ) {
System.out.println( fname + “ “ + lname + “ “ + age + “ “ +
profession);
System.out.println ( “ “ );
}
public static void main(String args[]) {
Load loads = new Load ( );
System.out.println ( “ The values are : “);
System.out.println ( );
loads.fload (“Arun”,”Kumar”, 23, “Engineer”);
loads.print ( );
loads.fload (“Shankar”,”Narayanan”);
loads.print ( );
loads.fload (“Gautham”,”Bhaskaran”,”Doctor”);
loads.print ( );
loads.fload (“Nakul”,”Mahadevan”,26);
loads.print ( );
}
}
Save the file as Load.java
Compile the file using javac Load.java
Run the file using java Load
It has a print ( ) method that prints the values of the various arguments supplied to the
various methods.
Public
Any method or variable is visible to the class in which it is defined. If the method or
variable must be visible to all classes, then it must be declared as public. A variable or
method with public access has the widest possible visibility. Any class can use it.
Package
Package is indicated by the lack of any access modifier in a declaration. It has an
increased protection and narrowed visibility and is the default protection when none has
been specified.
Protected
This specifier is a relationship between a class and its present and future subclasses. The
subclasses are closer to the parent class than any other class. This level gives more
protection and narrows visibility.
The package and protected access specifiers have been dealt with while dealing
with packages.
Private
It is narrowly visible and the highest level of protection that can possibly be obtained.
Private methods and variables cannot be seen by any class other than the one in which
they are defined. They are extremely restrictive but are most commonly used. Any
representation unique to the implementation is declared private. An object’s primary job
is to encapsulate its data and limit manipulation. This is achieved by declaring data as
private.
class pri {
private int x = 10;
void var( ) {
System.out.println ( “The private value is “ + x);
}
public static void main( String args[]) {
pri p = new pri( );
p.var( );
}
}
Save the file as pri.java
Compile the file using javac pri.java
Execute the file as java pri
The class pri has a private instance variable x. This variable can be accessed only inside
the class. The method var displays this variable using println method. The main method
creates an instance of the class and invokes var method. It is important to note that the
instance variable x of the object cannot be accessed directly from the main since it is
declared private. The following code, when included in main, will result in a compilation
error.
Alternatively, the instanceof operator can be used. This operator has two operands
namely, the object on the left and the name of the class on the right. The expression
returns a boolean depending upon the object being an instance of the named class or
anyone of its subclasses. For example, if a variable s is declared to be an instance of the
string class, then it can be checked if s is an instance of the String class as follows:
String s = new String( );
if ( s instanceof String) {
<set of statements>
}
Object Reference
Each new class created adds another type that can be used just like simple types. When a
new variable is declared, classname can be used as a type. Such variables refer to
instances or objects of that class. These variables are known as object references. An
instance is an individual copy of the class template with its own set of data called
instance variables. When the type of a variable is declared as a class, it has a default
value of null – a reference of type Object and is thus type-compatible with all other
classes. The null object has no value.
The development environment may also include additional classes that provide other
utilities or functionality. Although these classes may be useful, they will not be available
to others, as they are not part of the standard Java library. This is particularly important
for applets, because applets are expected to run on any platform. The classes inside the
Java package are guaranteed to be available in all Java environments.
Importing Class:
Classes external to a program must be imported before they can be used. To import a
class, the import keyword should be used as:
Syntax:
import <classname>;
The classes in Java are arranged in hierarchial order. The Java library consists of a
number of packages. These packages contain a set of related classes. The whole path of
the class must be specified to import a class from the Java library, For instance, to import
the Date class from the util package use the code:
import java.util.Date;
It is also possible to import all classes that belong to a package using * symbol.
import java.awt.*;
All the classes in java.lang package are automatically imported when a program is
compiled.
The point class is imported in the program. An instance of this class is created inside the
main method. The variables in the object are initialized and displayed using println
method.
class Argument {
public static void main(String args[]) {
System.out.println ( “The first argument value is: “ +args[0]);
}
}
In this example, the main method outputs the first command line argument. The example
assumes that at least one argument is passed to the program. If the program is executed
without an argument, an error occurs. If more than one argument is passed, it is ignored.
Constructor
Constructors are called whenever an instance of a given class is created. A constructor
method is a special kind of method that determines how an object is initialized when
created. They have the same name as the class and do not have any return type.
When the keyword new is used to create an instance of a class, Java allocates memory for
the object, initializes the instance variables and calls the constructor methods. Every class
has a default constructor that does not take any argument and the body of it does not have
any statements. Constructors can be overloaded.
class Con {
int i;
int j;
Con ( int a, int b) {
i = a;
j = b;
}
void print ( ) {
system.out.println ( “ The addition of “ + i + “ and “ + j +” gives “ + (i + j));
}
public static void main(String args[]) {
Con c;
c = new con(10,10);
c.print ( );
System.out.println (“ “);
c = new con(25,25);
c.print ( );
System.out.println (“ “);
}
}
Save the file as Con.java
Compile the file using javac Con.java
Run the file using java Con
In this example, the second constructor calls the first constructor and initializes the
instance variables.
Finalizer:
Finalizer method function in contradiction to the constructor method. Finalizers are called
by garbage collector on an object, when garbage collection determines that there are no
more references to the object and its memory is reclaimed. A subclass overrides the
finalize method to dispose of system resources or to perform other cleanup. The finalizer
method is represented by finalize( ).
The object class defines a default finalizer method, which does nothing. To create a
finalizer method for the classes, the finalize( ) method can be overridden as shown in the
following:
Syntax:
protected void finalize ( ) {
<set of statements>
}
Any cleaning required may be included inside the body of the finalize( ) method. This
method can be called at any point of time. Calling finalize( ) need not trigger an object to
be garbage collected. Removing references to an object will cause it to be marked for
deletion. Finalizer methods are best used for optimizing the removal of an object.
Some points on finalize( ) method.
Every class inherits the finalize( ) method from java.lang.Object
The method is called by the garbage collector when I determines no more
references to the object exist.
The Object finalize method performs no actions but it may be overridden by
any class
Normally it should be overridden to clean-up non-Java resources i.e. closing
a file.
If overriding finalize( ) method, it is good programming practice to use a
try-catch-finally statement and to always call super.finalize ( ).
Overloading Constructors:
In addition to overloading normal methods, we can also overload constructor methods.
In fact, for most real-world classes that we create, overload constructors will be a normal
one, not the exception. Constructors can also take varying numbers and types of
parameters. This enables creation of objects with the properties required. The constructor
takes a different number of arguments each time and gives the same to the print method
for display.
Example:
Open a file and type the following
public class Box
{
String iname;
int iqty;
int price;
Box ( int itemqty, String itemname, int itemprice) {
iname = itemname;
iqty = itemqty;
price = itemprice;
}
Box ( int q, String i1name) {
iname = i1name;
price = q;
iqty = price/10;
}
Box (String iiname, int iprice) {
iname = iiname;
price = (int) (iprice – (0.1));
}
void print( ) {
System.out.println (“ item name : “ +iname);
System.out.println (“ Quantity : “ +iqty);
System.out.println (“ price : “ +price);
}
public stati void main (String args[]) {
Box item;
item = new Box(10, “ Pen” 10);
item.print ( );
item = new Box ( 10, “Bag”);
item.print ( );
item = new Box ( “Toys”, 25);
item.print ( );
}
}
Save the file as Box.java
Compile it as javac Box.java
Execute the file as java Box
Inner class:
The most important type of nested class is inner class. An inner class is a non-static
nested class. It has access to all of the variables and methods of its outer class. An inner
class is a nested class whose instance exists within an instance of its enclosing class and
has direct access to the instance members of its enclosing instance.
Syntax:
class <Enclosingclass> {
class <Innerclass> {
<set of statements>
}
}
The interesting feature about the relationship between these two classes is not that the
innerclass is inside the Enclosingclass. The instance of the innerclass can exist only
within an instance of the Enclosingclass and it has direct access to instance variables and
methods of its enclosing instance. Thus, an inner class is fully within the scope of its
enclosing class.
Example:
Open a file and write the following:
class Outer
{
int outer_x = 100;
void test( )
{
Inner inner = new Inner ( );
inner.display ( );
// this is an inner class
class Inner
{
void display ( )
{
System.out.println (“display : outer_x = “ +outer_x);
}
}
}
class InnerClassDemo
{
public static void main(String arg[])
{
Outer outer = new Outer ( );
Outer.test ( );
}
}
Output:
In the program, an inner class named Inner is defined within the scope of class Outer.
Therefore, any code in class Inner can directly access the variable outer_x. An instance
method named display( ) is defined inside Inner. This method displays outer_x on the
standard output stream. The main( ) method of the example creates an instance of class
Outer and invokes its test( ) method. That method creates an instance of class Inner and
the display( ) method is called.
Garbage Collection:
A key feature of Java is its garbage-collected heap, which takes care of freeing
dynamically allocated memory that is no longer referenced. Since the heap is garbage-
collected, Java programmers do not have to explicitly free allocated memoty.
Garbage collection is the process of automatically freeing objects that are no longer
referenced by the program. This frees the programmer from having to keep track of when
to free allocated memory, thereby preventing many potential bugs.
Java has no malloc or free functions. Since every complex data structure is an object,
they are all allocated via the new operator, which allocates space for an object on the
heap of memory.
The memory available for objects is called a heap because the user doesn’t have to
think about it. It is just a loosely collected heap of object instances. From new keyword,
the user actually gets a handle to an object and not the memory address.
The actual memory allocated for this object may move around, as the program runs,
but the user doesn’t have to worry about that because this memory will be available for as
long as the program cares for it. As soon, as the user no longer have any references of any
kind to the object, the memory it is occupying will become available for reuse by the rest
of the system. The user doesn’t have to call free or delete. This is known as garbage
collection.
Garbage Collection occurs during the execution of the program. It will not occur simply
because one or more objects exist that are no longer used.
Garbage Collection can also be known as litter recycling, because the user doesn’t even
have to drag the objects to the curb to have them collected. It’s just dropping and
forgetting them. The garbage collector runs wherever the system is idle, or when a
requested allocation fails to find enough memory.
Summary:
A class is a template for multiple objects with similar features. The requirements for
the creation of a class include a source file with the class keyword in it followed by a
legal identifier and a pair of curly braces for the body.
Attributes are individual things that differentiate an object from another and determine
the appearance, state or other qualities. Class variables are global to a class and to all the
instances of the class.
The new operator creates a single instance of a named class and returns a reference to
that object. Methods are functions that are defined inside classes operating on instances
of those classes. The four levels of access control are public, package, protected and
private. The Java class library provides the set of classes that are guaranteed to be
available in any commercial Java environment. A constructor method is a special kind of
method that determines how an object is initialized when created. Constructors have the
same name as the class and do not have any return type. The constructors are different
from methods in this context.
Finalizer methods function in contradiction to the constructor methods. Finalizers
are called just before the object is garbage collected and its memory is reclaimed. An
inner class is a nested class whose instance exists within an instance of its enclosing class
and has direct access to the instance members of its enclosing instance. In Java
deallocation happens automatically. The technique that accomplishes this is called
garbage collection. Garbage Collection occurs during the execution of the program. It
will not occur simply because one or more objects exist that are no longer used.
Arrays and Strings
An array is an object that stores a list of items. Each slot in an array holds individual
elements. An array should be of single type, comprising of integers, Strings and so on. To
create an array, a variable to hold the array is declared, and a new object is created and
assigned to it. An array is a data structure which defines an ordered collection of a fixed
number of homogeneous data elements. This means that all elements in the array have the
same data type. The size of an array is fixed and cannot increase to accommodate more
elements. Arrays can be primitive data types or reference types. Each array object has an
instance variable, length, which specifies the number of elements the array can
accommodate.
Simple arrays are one-dimensional arrays, i.e. a simple list of values. Since arrays can
store object references, the object referenced can also be array objects. This allows
implementation of array of arrays.
Syntax:
<elementType>[] <arrayName>;
Or
<elementType> <arrayName>[];
Where <elementType> can be a primitive datatype or a reference type (i.e. a class name
or an interface name). Note that the array size is not specified.
Array declaration is akin to any other variable declaration. Array variable indicates the
type of object that the array holds. It also indicates the name of the array followed by
empty brackets. The brackets may be inserted after the specification of the type instead of
succeeding the variable.
Example:
int arr[];
Syntax:
<arrayName> = new <elementType>[<noofElements>];
Initializing an Array:
Java provides the means of declaring, constructing and explicitly initializing an array in
one language construct:
Syntax:
<elementType>[] <arrayName> = { <arrayInitializerCode> };
This form of initialization applies to member as well as local arrays.
The initialization code in the block results in the construction and initialization of array.
Syntax:
int[] anIntArray = {1,3,49,2,7,15};
After declaring an array, create and assign objects to it. Two methods can be used to
create the array – initialization of the array or usage of the new keyword. The new
keyword creates an instance of the array. The number of elements that the array will hold
must be specified. The two modes of creating an array are given:
int iarr[] = new int [10];
char carr[] = {‘a’, ‘b’, ‘c’, ‘d’};
Example:
Open a file and enter the following:
class Array {
int i;
int da[] = {1,2,3,4,5};
void disp( ) {
System.out.println(“Displaying Array Details”);
For ( i=0;i<5;i++) {
System.out.println (da[i]);
}
}
public static void main(String args[]) {
Array d = new Array( );
d.disp( );
}
}
Save the file as Array.java
Compile the file using javac Array.java
Run the file as java Array
The array is being initialized at the point of declaration and hence, it is not necessary to
specify the number of elements that the array would hold or their size. The method, disp,
prints the array elements. In the main method, an instance of the class is created and the
disp method is invoked.
Accessing Array Elements:
The array subscript expression must be used to change and test the values of the array.
To access an element in the array, subscript expression is employed. Array subscripts
start with zero. All array subscripts are checked to ensure that they are within the
boundaries of the array. If the array subscript is calculated at runtime as part of a looping
control and it ends outside the boundaries of the array, then the interpreter produces an
error. To avoid overrunning the end of an array, its length can be tested using the length
instance variable. This variable is available for all array objects irrespective of the type.
The usage is,
int len = arr.length
The add method assigns values to the array. The show method displays element of the
array. In the main method, a new instance of the class is created. The add method is
invoked to assign values that are displayed by calling the show method.
Multidimensional Arrays:
Since array elements can be an object reference and arrays are objects, array elements can
themselves reference other arrays. In Java, an array of arrays can be defined as follows:
is equivalent to
Java does not support multidimensional arrays. However, an array can be created. The
following example shows the creation of an array of arrays.
Example:
Open a file and enter the code.
class Coord {
int i = 0;
int j = 0;
int coor[] [] = new int[3][3];
void set( ) {
coor[0][0] = 1;
coor[0][1] = 0;
coor[0][2] = 0;
coor[1][0] = 0;
coor[1][1] = 1;
coor[1][2] = 0;
coor[2][0] = 0;
coor[2][1] = 0;
coor[2][2] = 1;
}
void show( ) {
for (i=0;i<3;i++) {
for (j=0;j<3;j++) {
System.out.println (coor[i] [j] + “ “);
}
System.out.println (“ “);
}
}
public static void main (String args[]) {
Coord c = new Coord( );
c.set ( );
c.show( );
}
}
Values are set into the array using the set( ) method. The array is displayed using the
show( ) method.
AN INTRODUCTION TO STRINGS
Here, str is an object of type string. It is assigned the string “this is a test”. This string is
displayed by the println( ) statement.
Strings are instances of the class string. They are real objects, and hence, enable
communication, testing and modification. When a string literal is used in the program,
Java automatically creates instances of the string class.
Example:
Open a file and enter the following:
class Strings {
String names[] = {“Aashish”,”Anand”,”Arun”,”Adithya”};
void show( ) {
System.out.println (“My Favourite Names Are “);
}
}
public static void main (String args[]) {
String s = new Strings( );
s.show ( );
}
}
String Constructors:
The String class supports several constructors. To create an empty String, we have to call
the default constructor. Calling the default constructor with no parameters as shown
below can create an empty string:
There is another constructor that follows the specification of the starting index and
number of characters that have to be used. The following code fragment explains this
constructor,
For example:
Char chars[ ] = {‘a’,’b’,’c’,’d’,’e’,’f’};
String s = new String(chars,2,3);
System.out.println(s);
This would print “cde” because ‘c’ was at the index 2 and we specified count of 3
characters to be used to construct the String.
String API:
There are methods for:
Getting the character at a given position within the string – charAt( )
Seeing if a character or string exists within a string – indexOf( )
Getting the number of characters in a String – length( )
Extracting a substring from a string – substring( )
String Length:
The length of a string is the number of characters that it contains. To obtain this value,
call the length( ) method, shown as:
int length( )
The following fragments prints “3”, since there are three characters in the string s:
Char chars[] = {‘a’,’b’,’c’};
String s = new String(chars);
System.out.println(s.length( ) );
String Literals:
We can also use a string literal to initialize a String object. For example, the following
code fragment creates two equivalent strings:
Char chars[ ] = {‘a’,’b’,’c’};
String s1 = new String(chars);
String s2 = “abc”; // use string literal
Since a String object is created for every string literal, we can use a string literal any
place we can use a String object. For example, we can call methods directly on a quoted
string as if it was an object reference, as the following shows. It calls the length( ) method
on the string “abc”. As expected, it prints “3”.
System.out.println(“abc”.length( ) );
String concatenation:
Java does not allow operators to be applied to String objects. The one exception to this
rule is the operator, which concatenates two strings, producing a String object as the
result. This allows to group together the series of + operation. The ‘+’ sign does not mean
“addition” when it is used with String objects. The ‘+’sign does not mean “addition”
when it is used with String objects. When used with strings and other objects, the +
operator creates a single string that contains the concatenation of all its operands.
For example:
In this case, age is an int rather than another String, but the output produced is the same
as before. This is because the int value in age is automatically converted into its string
representation within a String object. This string then concatenated as before. The
compiler will convert an operand to its string equivalent whenever the other operand of
the + is an instance of String.
intern( ) produces one and only string handle for each unique character sequence.
String Methods:
The String class provides a number of methods to compare and search strings. Some
important methods in this class are listed.
Method Use
length( ) Number of characters in String.
charAt( ) The char at a location in the string.
getChars( ), getBytes( ) Copy chars or bytes into an external array.
toCharArray( ) Produces a char[] containing the characters
in the String.
equals( ), equalsIgnoreCase( ) An equality check on the contents of the
two Strings.
compareTo( ) Result is negative, zero or positive
depending on the lexicographical ordering
of the String and the argument. Uppercase
and lowercase are not equal.
regionMatches( ) Boolean result indicates whether the region
matches.
startsWith( ) Boolean result indicates if the String starts
with the argument.
endsWith( ) Boolean result indicates if the argument is a
suffix.
indexOf( ), lastIndexOf( ) Returns-1 if the argument is not found
within this String, otherwise returns the
index where the argument starts.
lastIndexOf( ) searches backwards from
end.
substring( ) Returns a new String object containing the
specified character set.
concat( ) Returns a new String object containing the
original String’s characters followed by the
characters in the argument.
replace( ) Returns a new String object with the
replacements made. Uses the old String if
no match is found.
toLowerCase( ), toUpperCase( ) Returns a new String object with the case
of all letters changed. Uses the old String if
no changes need to be made.
trim( ) Returns a new String object with the
whitespace removed from each end. Uses
the old String if no changes need to be
made.
valueOf( ) Returns a String containing a character
representation of the argument.
intern( ) Produces one and only one String handle
for each unique character sequence
It is seen that every String method returns a new String object when it is necessary to
change the contents. Also notice that if the contents do not require any change, the
method will just return a handle to the original String. This saves storage and overhead.
Example:
Open a file and enter the code:
class String {
public static void main(String args[]) {
String s = “Now is the time for all good men” + “ to come to the aid of their
country” +” and pay their taxes”;
String s1 =”Hello world”;
String s2 = “Hello”;
String s3 = “HELLO”;
System.out.println(“index of t = “ +s.indexOf(‘t’));
System.out.println(“last index of t = “ +s.lastIndexOf(‘t’));
System.out.println(“index of (t,10) =” +s.indexOf(‘t’,10));
System.out.println(“last index of (t,60) = “ +s.lastIndexOf(‘t’,60));
System.out.println(s1.substring(6));
System.out.println(s1.substring(3,8));
System.out.println(s2.concat(“World”));
System.out.println(s2.replace(‘l’,’w’));
System.out.println(s3.toLowerCase( ));
System.out.println(s1.trim( ));
}
}
Save the file as String.java
Compile the file as javac String.java
Execute the file as java String
StringBuffer:
StringBuffer is a peer class of String that provides much of the common use functionality
of strings. Strings represent fixed-length character sequences.StringBuffer represents
varied length character sequences. StringBuffer may have characters and substrings
inserted in the middle, or appended at the end. The compiler automatically creates a
StringBuffer to evaluate certain expressions, in particular when the overloaded operators
+ and += are used with String objects.
In the creation of String s, the compiler is actually performing the rough equivalent of the
subsequent code that uses sb. A StringBuffer sb is created and append( ) is used to add
new characters directly into the StringBuffer object. While this is more efficient, it is
worth noting that each time we create a quoted character string like “abc” and “def”, the
compiler actually turns those into String objects. Thus, there may be more objects created
than we expect, despite the efficiency afforded through StringBuffer.
StringBuffer methods
Method Use
toString( ) Creates a String from this StringBuffer.
length( ) Returns the number of characters in the
StringBuffer.
capacity( ) Returns current number of spaces allocated.
ensureCapacity( ) Makes the StringBuffer hold atleastthe
desired nmber of spaces.
setLength( ) Truncates or expands the previous
character string. If expanding, pads with
nulls.
charAt( ) Returns the char at that location in the
buffer.
setCharAt( ) Modifies the value at that location.
getChars( ) Copy chars into an external array. There is
no getBytes( ) as in String.
Append( ) The argument is converted to a string and
appended to the end of the current buffer,
increasing the buffer if necessary.
insert( ) The second argument is converted to a
string and inserted into the current buffer
beginning at the offset. The size of the
buffer is increased, if necessary.
reverse( ) The order of the characters in the buffer is
reversed.
The most commonly-used method is append( ), which is used by the compiler when
evaluating String expressions containing the ‘+’ and ‘+=’ operators. The insert( ) method
has a similar form, and both methods perform significant manipulations to the buffer
rather than creating new objects.
Casting And Converting:
Casting is used to convert the value of one type to another. Casting is the mechanism of
converting the value of an object or primitive type into another type. The result of the
cast is a new reference or value. Casting does not affect the original object or value. The
concept that is involved in casting is simple enough but for the fact that Java has both
primitive types and object types. Casting is of three types namely, casting between
primitive types, casting between object types and converting primitive types to objects
and then extracting primitive values out of those objects.
TYPE CONVERSION AND CASTING
In any application, there may be many situations in which one data type may need to
be converted to another data type. Also, since java is an object oriented language, we
may have situations where we need to convert between parent and child classes. These
transformations are achieved by means of –what is called process-in java.
TYPES OF CASTING
There are basically 2 types of casting: Implicit casting and explicit casting.
Implicit casting means simply assigning one entity to another without any transformation
guidance to the compiler. If the two types are compatible, then java will perform the
conversion automatically.
Example:
int t = 100;
long h =t;// Implicit casting
CASTING INCOMPATIBLE TYPES
Although the automatic type conversions are helpful, they will not fulfill all needs.
For example, what if you want to assign a long value to a int variable? This conversion
will not be performed automatically, because a int is smaller than a long. This kind of
conversion is sometimes called a narrowing conversion or explicit casting. Explicit
casting means specifically informing the compiler about the transformation that is
expected.
long h = 100.00;
int t = (int) h; // Explicit casting
A different type of conversion will occur when a floating-point value is assigned to an
integer type: truncation. Integers do not have fractional components. Thus, when a
floating-point value is assigned to an integer type, the fractional component is lost. When
integer value is assigned to a floating-point value then a decimal point with two zeros
will be added.
For example:
Class Conversion
{
public static void main(Stringarg[])
{
byte b;
int i = 256;
double d = 323.142;
System.out.println(“\n conversion of int to byte”);
b = (byte) i;
System.out.println(“i and b” + i + “ “ + b);
System.out.println(“\n conversion of double to int”);
i = (int) d;
System.out.println(“d and i “+ d + “ “ +i);
System.out.println(“\nconversion of double to byte”);
b = (byte) d;
System.out.println(“d and b “+ d + “ “ +b);
}
}
Casting Objects:
Instances of class can be cast to instances of other classes. There is only one restriction,
the class of the object being cast and the class that it is being casted to must be related by
inheritance. Some objects may not explicitly cast. An instance of a subclass can be used
anywhere a superclass is expected because a subclass contains all the information that a
superclass contains. Casting an object to an instance of one of that object’s superclass
loses the information the original subclass provided and requires a specific cast. To cast
an object to another class,use:
(classname) object;
The classname is the name of the class we want to cast the object to. Object is a reference
to the object being cast. Casting creates a reference to the old object of the type
classname and the old object of the type classname and the old object continues to exist.
Summary:
An array is a data structure which defines an ordered collection of a fixed number of
homogeneous data elements. Array declaration is similar to any other variable
declaration. To change and test the values of the array, use the array subscript expression.
To assign a value of slot, include an assignment statement after the array access
expression. Java does not multidimensional arrays. However, an array of arrays can be
created.
A combination of characters is known as String. Strings are instances of the class String.
Casting is a mechanism of converting the value of an object or primitive type into another
type. Casting between primitive types allows conversion of one primitive type to another.
This occurs most commonly between numeric types. Conversion of primitive types to
objects cannot be done explicitly.
INHERITANCE
For example:
Organism Class Hierarchy
Organism
A class called Living Organism is derived from the class called Organism. Every instance
of the Living Organism class, apart from Organism, has its own features. From the class
called car, different classes based on model, color, quality, etc. can be derived. Figure
shows some of the subclass of Organism super class.
A simple example:
class SimpleInheritance
{
public static void main(String args[])
{
A superOb = new A( );
B superOb = new B( );
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println(“Contents of superOb:”);
superOb.showij( );
System.out.println( );
subOb.i = 7;
subOb.j = 8;
subOb.k =9;
System.out.println(“Contents of subOb:”);
subOb.showij( );
subOb.showk( );
System.out.println(“Sum of i, j and k in subOb:”);
subOb.sum( );
}
}
The output of the program is:
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
The subclass B includes all of the members of its superclass A. This is why subOb
can access i and j and call showij( ). Inside sum( ), i and j can be referred to directly, as if
they were part of B.
Even though A is a superclass for B, it is also a completely independent, stand-alone
class. Being a superclass for a subclass does not mean that the superclass cannot be used
by itself. Further, a subclass can be a superclass for another subclass.
The general form of a class declaration that inherits a superclass is shown:
We can only specify one superclass for any subclass that we create. Java does not
support the inheritance of multiple superclasses into a single subclass.
The Java class hierarchy begins with the class object as its super class. This is the most
common class in the hierarchy. Each subclass of the hierarchy apart from inheriting the
features of the object class has distinct features. Each of the subclasses has been defined
for a specific purpose. Thus the object class definition is found to be abstract and further
down the hierarchy, there are clear specifications to define an object. If a class is defined
without any superclass, the object class acts as its super class.
Boolean
Character
Object
Compiler
String
Number
Class
Runtime
Thread
Super classes must be defined in such a way that its information can be used
time and again by its derived classes. Changing a class or inserting a class in the
hierarchy reflects in all its derived classes. As a result, the need to recompile all these
classes is eliminated. When an object calls a method, Java compiler first checks for the
method definition in the same class in which the method is defined. If it is not found, it
checks its superclasses one by one. If it is unable to locate the method definition, then the
compiler issues an error message.
Example:
Open a file and type the following:
class Wood {
String type = “teak”;
String finish = “coarse”;
void showDet ( ) {
System.out.println (“ instance of class” + this.getclass( ).getName( ));
System.out.println (“-----------------------------------“);
System.out.println (“type of wood –“ + type);
System.out.println (“finish is – “ +finish);
}
}
Woodtype – teak
finish - coarse
legs – 4
The word extends indicates that Woodtable has been derived from the class Wood. An
attribute called legs and a method called show( ) are defined in the subclass. It not only
displays the details of its attribute, but also of the base class.
class CallingCons {
public static void main(String args[]) {
C c = new C( );
}
}
Method Overriding:
Methods in the derived class can have a similar name as the base class. This is to ensure
that a method, when called in the program, works the same for both the base and the
derived class.
In the class hierarchy, when a method in a subclass has the same name and type
signature as a method in its superclass, then the method in the subclass is said to override
the method in the superclass. When an overridden method is called from within a
subclass, it will refer to the version of that method defined by the subclass. The version of
the method defined by the superclass will be hidden.
When a method is called on an object, the Java compiler first searches for the method in
the class of that object. If the method is not found there, then the compiler searches for
the method in the hierarchy until it is found.
// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show( ) {
System.out.println(“i and j: “ + i + “ “ + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show( ); // this calls show( ) in B
}
}
The output appears as:
K: 3
When show( ) is invoked on an object of type B, the version of show( ) defined within B
is used. That is, the version of show( ) inside B overrides the version declared in A. If we
wish to access the superclass version of an overridden function, we can do so by using
super.
Usage of the keyword super before the methods getDet( ) and showDet( ) in the derived
classes, enables accepting and displaying of details for all three classes. The method
getDet( ) will have an extra line before the try block in both the class and category class
as follows
super.getDet( );
The showDet( ) method also has an extra line before displayingthe details of its own
class, to display the details of its base classes as follows:
super.showDet( );
Abstract class ensures in some way that a subclass does indeed, override all necessary
methods. Java’s solution to this problem is the abstract method. We require that certain
methods to be overridden by subclasses by specifying the abstract type modifier.
To declare an abstract method, use this general form:
class A
{
final void meth( )
{
System.out.println(“This is a final method.”);
}
}
class B extends A
{
void meth( ) { //ERROR! Can’t override.
System.out.println(“Illegal!”);
}
}
Sometimes we need to prevent a class from being inherited. To do this, precede the class
declaration with final. Declaring a class as final, declares all of its methods as final too. It
is illegal to declare a class as both abstract and final since an abstract is incomplete by
itself and relies upon its subclasses to provide complete implementations.
Here is an example of a final class:
final class A {
// ….
}
// The following class is illegal.
Class B extends A { // ERROR! Can’t subclass A
//……
}
As a common implication, it is illegal for B to inherit A since A is declared as final.
Summary:
Java allows to group classes in a collection called a package. Packages are convenient
for organizing the work and for separating the work from code libraries provided by
others. It is possible to run out of unique names for classes in a big programming
environment. There may be situations when two or more persons use the same name for
their classes. So, Java provides us with a feature called package to avoid this problem.
Packages contain a set of classes in order to ensure that class names are unique.
Packages are containers for classes that are used to compartmentalize the class name
space. Packages are stored in a hierarchial manner and are explicitly imported into new
class definitions.
CLASSPATH Variable:
Whenever a class is created without any package statement, it is implied that the class is
included in Java’s default package. In case of writing small programs it is not necessary
for the package name to be mentioned. The necessity for packages can be understood in
real time application environment.
The Java compiler and the interpreter search the .class files in the path specified in
CLASSPATH environment variable. The current working directory is, by default,
included in this variable. Hence, it is possible to compile and execute the programs from
the existing directory. In case of creating a package, ensure that the root directory of the
package is included in the CLASSPATH variable.
Creation of a Package:
The following steps are involved in the creation of a package.
Create a directory, which has the same name as the package
Include package command, along with the package name, as the first statement in
the program.
Write class declarations
Save the file in the directory as NameOfClass.java where NameOfClass is the
name of the class
Compile this file using javac
There are two ways of using this program – change to previous level directory
and use java packageName.className or set the CLASSPATH variable
accordingly.
It explains the creation of a sample package and subpackage and their usage of the same
in a program.
Example:
Open a file and enter the following code:
Create a directory called pack
package pack;
public class Class1 {
public static void main( ) {
System.out.println(“hello”);
}
}
A package called pack has now been created which contains a class Class1.
Create a subdirectory called subpack inside the pack directory\
Open a new file and enter the following code:
package pack.subpack;
public class Class2 {
public static void farewell( ) {
System.out.println(“bye”);
}
}
import pack.*;
import pack.subpack.*;
Class Importer {
public static void main(String arg[]) {
Class1.greet( );
Class2.farewell( );
}
}
hello
bye
Access Protection:
Java has different types of access specifiers namely private, public, protected, private
protected and package. By default, variables and methods declared within a class without
access specifiers are accessible to all classes within the same package.
Importing Packages:
To make use of classes within different packages, the import statement is used. Once
imported, the classes within the package can be used by the program. All standard
packages of Java are included within a package called java. By default, all programs
import the java.lang package. Specific classes belonging to one particular package can be
imported or all of them can be simultaneously imported using *.
java.awt.Graphics. imports the Graphics class of the awt package into the program and
java.awt.* imports all the classes of the awt package into the program. User-defined
packages can also be imported just like the standard packages.
Type the following command at the command prompt, to create the p1 directory.
mkdir p1
Open a new file and enter the following code:
// Uses package p1
import p1.*;
class Testpack {
public static void main(String args[]) {
Lmn a = new Lmn( );
System.out.println(“Creating an object of p1 package Lmn class….”);
System.out.println(“Possible because of importing”);
System.out.println(“Calling method of Lmn class”);
System.out.println(“ ---------------------------“);
a.m3( );
System.out.println(“----------------------------“);
}
}
This program imports Lmn class from package p1. An object of this class is created and
the method m3( ) within it is called.
INTERFACES
An interface is Java’s way of dealing with the common situation of wanting a class to
reflect the behavior of two (or even more) parents. This is often called multiple
inheritance. Though Java possesses most of the features of c++, multiple inheritance is
not supported by Java. In order to balance this drawback, the originators of Java have
introduced the idea of interfaces. An interface consists of a set of method definitions. Any
class implementing it should provide code for all its methods.
Here access is either public or without specification and its accessibility remains as
mentioned. The keyword interface implies that the following method definitions form an
interface rather than a class definition. The interface should not contain implementation
for its methods. Any method belonging to an interface, which is implemented within a
class, should be declared as public.
Variables can also be declared within an interface. When variables are included within an
interface, they become final and static i.e. the variables cannot be changed by the class
implementing them.
Properties of Interfaces:
Although interfaces are instantiated with new, they have certain properties similar to
ordinary classes. For example, once we set up an interface, we can declare that an object
variable will be of that interface type.
Although we cannot put instance fields or static methods in an interface, we can supply
constants in them.
For example:
Public interface Powered extends Moveable
{
public String powerSource(PoweredVehicle);
public static final int SPEED_LIMIT=95;}
Classes can implement multiple interfaces. This gives the maximum amount of flexibility
in defining a class’ behavior. For example, Java has an important interface built into it,
called Cloneable. If class implements Cloneable, the clone method in the object class will
make a bitwise copy of the class’ objects.
The clone method is a protected method of object, which means that our code cannot
simply call it. Only the Day class can clone Day objects.
Implementation:
The methods belonging to an interface are looked up at runtime. Usually, when a method
of a class is called from another method, Java compiler ensures that its definition exists
and is compatible. This leads to static and nonextensible class environment. Thus when a
method has to be used by many classes, it is pushed higher up in the hierarchy, to ensure
that it is available to all of them. Interfaces provide a different approach. They collect
such methods and disconnect them from their hierarchy. Thus classes are able to access
methods of an interface or a series of interfaces.
Interface References:
It is possible to declare variables, which have reference to an interface rather than a
class. An object thus created can access only the implemented method and cannot access
methods of its own class.
Variables in Interfaces:
Variables can be declared within an interface. The advantage of declaring variables
within an interface is that they become globally available to all classes and need not be
declared explicitly in classes implementing them.
Exception Handling:
The Java programming language provides a mechanism known as exception to help
programs report and handle errors. When an error occurs, the program throws an
exception. It means that the normal flow of the program is interrupted and that the
runtime environment attempts to find an exception handler—a block of code that can
handle a particular type of error.
There are five keywords for handling the exceptions. They are as follows- try, catch,
finally, throws and throw.
The try statement identifies a block of statements within which an exception might be
thrown.
The catch statement must be associated with a try statement and identifies a block of
statements that can handle a particular type of exception. The statements are executed if
an exception of a particular type occurs within the try block.
The finally statement must be associated with a try statement and identifies block of
statements that are executed regardless of whether or not an error occurs within the try
block.
The throws statement is used when a method is capable of causing an exception that it
does not handle, it must specify this behavior so that callers of the method can guard
themselves against that exception.
The throw statement enables a program to throw an exception explicitly.
Exception Types:
Unchecked exceptions
Checked exceptions
All exception types are subclass of the built-in class Throwable. It helps to handle
exceptions and errors. The Throwable class has two subclasses – Exception and Error.
Thus, Throwable is at the top of the exception class hierarchy. Error conditions are
normally not trapped by Java programs. Error conditions normally occur in case of
failures, which cannot be handled by programs. Exception of type Error are used by the
Java run-time system to indicate errors having to do with run-time environment. Stack
overflow is an example of error condition.
Exceptions can be caught or re-thrown to a calling method.
Object
Throwable
Error Exception
IOException RuntimeException
Using try and catch:
If there is a possibility of an exception being generated in a program, it is better to handle
it explicitly. This can be handled by using try and catch keywords. Doing so, it provides
two benefits. First, it fixes the error. Second, it prevents the program from terminating
automatically.
To guard against and handle a run-time error, simple enclose the code inside the try
block. Immediately following the try block include the catch clause. The catch clause can
have statements explaining the cause of the exception generated. The scope of each
clause is restricted to a try block. It is possible to have multiple catch statements for one
try block. The exception of a program can continue once the exception has been handled.
General form:
try {
statements(s)
} catch (exceptiontype name) {
statements(s)
} finally {
statements(s)
}
Example:
Division by zero
After catch statement.
Example:
class multicatch
{
try
{
int c[] = {1};
// array of one element is declared.
c[5] = 99;
// here value is assigned to fifth element in array.
System.out.println(“c =” +c[5]);
}
catch(ArithmeticException e )
{
System.out.println(“ divide by 0: “+e);
}
catch(ArrayIndexOutOf BoundsException e)
{
System.out.println(“array index oob: “ +e);
}
System.out.println(“after try/catchblocks:”);
}
}
Finally statement:
When an exception is generated in a program, sometimes it may be necessary to perform
certain activities before termination. The activities may be closing of a file, deleting a
graphics object created, etc. In such cases, the try block, apart from the catch clause, also
has finally block within which activities mentioned above can be performed. This block
is executed after the execution of statements within the try/catch block. In case an
exception is thrown, the finally block will be executed even if no catch matches it. The
finally block can be used to handle any exception generated within a try block. It may be
added immediately after the try block or after the last catch block.
Example:
Open a file and enter the following:
import java.io.*;
class FinallyException {
public static void main(String args[]) {
try {
InputStream f1 = null;
int size = f1.available( );
for (int i = 0;i<size; i++) {
System.out.println((char)f1.read( ));
}
} catch (IOException e) { }
catch (NullPointerException n) {
System.out.println(“exception generated : “ +n);
}
finally {
System.out.println(“---------------------------.”);
System.out.println(“inside finally “);
System.out.println(“Welcome to DMISS”);
System.out.println(“-------------------------.”);
}
}
}
The above program creates an InputStream object and initializes it to null. Utilizing this
object, it checks for the size of the file and tries to read the contents within the for loop.
Since the InputStream object is initialized to null, a NullPointerException is generated
while trying to read it. This is caught by the catch clause. After the execution of the
statements inside the catch clause, finally clause is reached. Once the statement inside,
this block are executed, the program terminates.
inside main
Exception in thread “main” java.lang.ArithmeticException: / by zero
At ThrowsException.main (ThrowsException.java:5)
The main( ) method of this program expects the generation of ArithmeticException but
does not want to handle it using the try/catch block. Note that, after the display of the
description of the exception, the program terminated automatically. The last print
statement in the program is never executed.
throw <Throwableinstance>
where <Throwableinstance> is the instance when the throw has to be executed. The flow
of execution stops immediately after the throw statement and the next statement is not
reached. The closest enclosing try block is inspected to see if it has a catch clause which
matches the type of the Throwable instance. If it finds a match, then control is transferred
to that statement. If no match is found, the next enclosing try statement is inspected and
the cycle continues till the outermost exception handler stops the program.
class throwme
{
public static void main(String args[])
{
try
{
float z (float)x / (float)y;
if (z < 0.01)
{
throw new IOException(“io”);
}
} catch(IOException e)
{
System.out.println(“Input output error” + e); }
}
}
Example:
class MyException extends Exception
{
private int detail;
MyException(int a)
{
detail = a;
}
class ExceptionDemo
{
static void compute(int a) throws MyException
{
System.out.println(“ called compute (“ + a+ “)”);
If(a > 10)
throw new MyException(a);
System.out.println(“normal exit”);
}
Exception Description
ArrayIndexOutOfBoundsException When array index is invalid
CharConversionException For character conversion problems during
ObjectStreamWriter operations
EOFException For signaling the reading of end-of-file
FileNotFoundException For signaling when requested file is not
found
IOException For general problems during I/O operations
InterruptedIOException For signaling that an I/O operation was
interrupted
InvalidClassException When unable to re-create a class during
deserialization
NegativeArraySizeException When array size is negative
NumberFormatException When the string passed is not a number
SQLException When error occurs during a database access
UnknownHostException When the host cannot be located
Summary:
Packages contain a set of classes in order to ensure that its class names are unique.
Packages are containers for classes that are used to compartmentalize the class name
space. An interface is a collection of abstract behavior that individual classes can
implement.
An exception is an abnormal condition, which arises during the execution of a program.
Java handles exceptions using five keywords – try, catch, finally, throws and throw. The
code sequence that is to be guarded should be placed inside the try block. The catch
clause should immediately follow the try block. Whenever a program does not want to
handle exceptions using the try block, it can use the throws clause. Customized
exceptions are necessary to handle abnormal conditions of applications created by the
user.
I/O Packages
The java.io package provides an extensive library of classes for dealing with
input and output. Java provides streams as a general mechanism for dealing with data I/O.
Streams implement sequential access of data. A stream in Java is a path along which data
flows. It has a source and a destination. Both the source and the destination may be
physical devices or programs or other streams in the same program. The concept of
sending data from one stream to another has made streams in Java a powerful tool for file
processing.
There are two kinds of streams: byte streams and character streams. An input stream is
an object that an application can use to read a sequence of data and an output stream is an
object that an application can use to write a sequence of data. An input stream acts as a
source of data and an output stream acts as a destination of data.
The following are the entities that can act as both input and output streams:
An array of bytes or characters
A file
A pipe
A network connection
Again, Java streams are classified into basic types, namely, input stream and output
stream. An input stream extracts (i.e. reads) data from the source (file) and sends it to the
program. Similarly, an output stream takes data from the program and sends (i.e. writes)
it to destination (file).
Streams can be chained with filters to provide new functionality. In addition to dealing
with bytes and characters, streams are provided for input and output of Java primitive
values and objects.
boolean isFile( );
boolean isDirectory( );
boolean canWrite( );
boolean canRead( );
getName( ) Method:
This method is used to obtain the name of the file specified.
getPath( ) / getAbsolutePath( ) Method:
These method facilitate us to obtain the path of the file specified and the absolute path of
the file specified.
getParent( ) Method:
This method returns a String object that contains the Parent directory.
lastModified( ) Method:
This method returns the last modification time of the file.
length( ) Method:
This method is used to know the file size in bytes.
delete( ) Method:
This is used to delete the specified file. In case of directory, it must be empty before it
can be deleted.
The flush( ) method helps in clearing the buffer.
String[] list( )
The list of files is returned in an array of String objects.
e.g.,
File f1 = new File(“/java”);
String s[] = f1.list( );
Filename Filter:
It defines only a single method, accept( ), which is called once for each file in a list. Its
general form is
boolean accept(File directory, String filename);
The accept( ) method returns true for files in the directory specified by directory that
should be included in the list and returns false for those files that should be excluded.
Creating a new Files and Directories:
The file class can be used to create files and directories. A file can be created whose
pathname is specified in a File object using the following method:
mkdir( ) Method:
This method is used to create a directory and returns a Boolean indicating the success of
the creation.
Example:
import java.io.*;
class File{
public static void main(String args[]) throws IOException {
File f = new File(“c:/java/temp”);
if(f.mkdir ( ))
System.out.println(“created a directory”);
else
System.out.println(“unable to create a directory”);
}
}
It creates a directory called temp under c:\java directory. On successful creation the first
message is displayed, if not the second message is displayed.
Methods in Streams:
A stream is a path of communication between the source of information and the
destination.
File Streams:
File stream comprises of the FileInputStream and FileOutputStream.
The classes FileInputStream and FileOutputStream define byte input and output streams
that are connected to files. Data can only be read and written as a sequence of bytes.
File InputStream:
The FileInputStream class helps in reading data from the actual disk files. Any object of
this class can be created using the keyword new.
An input stream for reading bytes can be created using the following constructors.
FileInputStream(String name) throws FileNotFoundException
FileInputStream(File file) throws FileNotFoundException
FileInputStream(FileDescriptor fdobj)
Syntax:
InputStream f = new FileInputStream(“c:/java/temp”);
File f = new File(“c:/java/temp”);
InputStream f1 = new FileInputStream(f);
The file can be specified by its name, through a File or a FileDescriptor object. If the file
does not exist, a FileNotFoundException is thrown. If it exits, it is set to be read from the
beginning.
FileOutputStream:
The FileOutputStream class helps to create a file and write data into it. An Output Stream
for writing bytes can be created using the constructors:
FileOutputStream(String name) throws FileNotFoundException
FileOutputStream(String name, Boolean append) throws FileNotFoundException
FileOutputStream(File file) throws IOException
FileOutputStream(FileDescriptor fdobj)
The System.err method is used to print error messages.
The file can be specified by its name, through a File object or using a File Descriptor
object. If the file does not exist, it is created. If it exists, its contents are reset, unless the
appropriate constructor is used to indicate that output should be appended to the file.
The FileInputStream class provides an implementation for the read( ) methods in its
superclass InputStream. Similarly, the FileOutputStream class provides an
implementation for the write( ) methods in its superclass OutputStream.
The FileInputStream class is used to create objects that can read data files stored on disk.
The class FileOutputStream does not allow appending data to an existing file.
Filter Streams:
A filter is a high-level stream that provides additional functionality to an underlying
stream to which it is chained. The data from the underlying stream is manipulated in
some way by the filter. The FilterInputStream and FilterOutputStream classes, together
with their subclasses, define input and output filter streams. Sub classes
BufferedInputStream and BufferedOutputStream implement filters that respectively
buffer input from, and output to, the underlying stream.
Stream Classes:
The java.io package contains a large number of stream classes that provide capabilities
for processing all types of data. These classes may be categorized into two groups based
on the data type on which they operate.
Byte stream classes – that provide support handling I/O operations on bytes.
Character stream classes – that provide support for managing I/O operations on
characters.
These two groups may further be classified based on their purpose. Byte stream and
character stream classes contain specialized classes to deal with input and output
operations independently on various types of devices.
Byte Stream Classes have been designed to provide functional features for creating and
manipulating streams and files for reading and writing bytes. Since the streams are
unidirectional, they can transmit bytes in only one direction and therefore java provides
two kinds of byte stream classes: input stream classes and output stream classes.
It takes a byte array as its parameter. The next constructor helps to create a
ByteArrayInputStream from the specified array of bytes.
Input Stream
FileInputStream SequenceInputStream
PipeInputStream ObjectInputStream
ByteArrayInputStream StringBufferInputStream
FilterInputStream
BufferedInputStream PushbackInputStream
DataInputStream
DataInput
The super class InputStream is an abstract class and therefore it cannot create instances of
the class. It uses the subclasses that inherit from the class.
OutputStreamClass:
This class implements a buffer, which can be used as an Output Stream.
The size of the buffer increases as data is written into the stream. The data is retrieved
using the methods toByteArray( ) and toString( ).
There are two types of constructors. They are:
Object
Output Stream
FileOutputStream ObjectInputStream
PipeOutputStream ByteArrayObjectStream
FilterOutputStream
BufferedOutputStream PushbackOutputStream
DataOutputStream
DataOutput
The InputStream class defines methods for performing input functions such as
Reading bytes
Closing streams
Marking positions in streams
Skipping ahead in a stream
Finding the number of bytes in a stream
Methods of InputStream/Reader:
BufferedInputStream:
This class accepts input by using a buffered array of bytes that acts as a cache and it
utilizes the mark( ) and reset( ) method.
PushbackInputStream:
This class is used to read a character from the InputStream and return the same.
PrintStream:
This method is widely used in Java applications. The two methods that are very familiar
to us are System.out.println( ) and System.out.print( ). System.in is an InputStream.
Writing bytes
Closing streams
Flushing streams
Methods:
BufferedOutputStream:
The output is stored in a buffered array of bytes, which acts as a cache for writing. A
specific number of bytes can be buffered using the nesting facility offered by the
FilterStream.
FileReader:
The FileReader class enables reading character files. It uses default character encoding.
FileReader class is similar to FileInputStream class and its constructors are identical to
those of FileInputStream class. The constructor shown here, can throw a FileNotFound
Exception:
public FileReader(File f)
CharArrayReader:
The CharArrayReader allows the usage of a character array as an InputStream. The usage
of CharArrayReader class is similar to ByteArrayInputStream. The constructor is:
StringReader:
The StringReader class reads characters from a string. The constructor is:
InputStreamReader:
The InputStreamReader class reads bytes from an input stream and converts them to
characters according to a mapping algorithm. The default mapping identifies bytes as
common ASCII characters and converts them to Java’s Unicode characters. The
constructor is:
public InputStreamReader(InputStream istream)
FilterReader:
The FilterReader class allows the reading of filtered character streams. There is one
instance variable in, which is protected reference to the Reader that is being filtered.
protected FilterReader(Reader r)
BufferedReader:
This class accepts a Reader object as its parameter and adds a buffer of characters to it.
This class is mainly useful because of its readLine( ) method.
public BufferedReader(Readetr r)
Writer class:
There are various methods of writer class. They are:
FileWriter:
The FileWriter allows writing character files. It uses the default character encoding and
buffer size. The usage of FileWriter class is similar to that of FileOutputStream class. The
constructor is given and it can throw an IOException.
public FileWriter(File f)
CharArrayWriter:
It uses a character buffer as an output stream. It is used in situations where
ByteArrayOutputStream is used. The constructor is:
public CharArrayWriter( )
PrintWriter:
The PrintWriter class contains methods that makes the generation of formatted output
simple. It can be used instead of PrintStream. The constructor is:
public PrintWriter(OutputStream ostream)
The stream is not flushed each time the println( ) method is called.
FilterWriter:
The FilterWriter class is used to write filtered character streams. It has one instance
variable out, which is a protected reference to the Writer that is being filtered.
protected FilterWriter(Writer w)
BufferedWriter:
The bufferedWriter class buffers data to the character output stream. BufferedWriter
class functionality is the same as BufferedOutputStream class. The constructor is:
public BufferedWriter(writer w)
The seek( ) method specifies the byte-offset from the beginning of the file, at which input
and output is to commence.
StreamTokenizer:
The class StreamTokenizer, a subclass of Object can be used for breaking up a stream of
text from an input text file into meaningful pieces called tokens. The behaviour of the
StreamTokenizer class is similar to that of the StringTokenizer class that breaks a string
into its component tokens. A stream is tokenized by creating a Stream Tokenizer with a
Reader object as its source and then setting parameters for the screen. A scanner loop
invokes nextToken, which returns the token type of the next token in the screen.
When nextToken recognizes a token, it returns the token type as its value and also sets
the type field to the same value. There are four token types:
TT_WORD: A word is scanned. The String field sval conatins the word that is scanned.
TT_NUMBER: A number is scanned. The double field nval contains the value of the
number. Only decimal floating numbers are recognized.
Summary:
There are different subclasses of the InputStream and the OutputStream. The
FileInputStream and FileOutputStream help in reading/ writing data from actual disk
files. ByteArrayInputStream and ByteArrayOutputStream make use of byte array as the
source and perform the reading and writing operations on that array.
StringBufferInputStream is similar to ByteArrayInputStream. It is used as a stored string
as the source.
PushbackInputStream takes input from the input stream and places it back without
disturbing it. The PrintStream has two methods System.out.print( ) and
System.out.println( ) which are widely used. The StreamTokenizer helps to break the
InputStream into tokens.
Events and User Interface Components
EVENTS:
Events are signals which are fired when the state of a component is changed
(e.g., when a button is pressed, when a menu is pressed etc.). In the event of a signal
firing it is necessary to handle the event based on the requirement. For example, a new
window opens when a button is pressed. If any interactive environment, the program
should be able to respond to actions performed by the user. These actions can be, mouse
click, key press or selection of a menu item. The basis of event-driven programming is
typing events to code that responds to those events.
Java’s Abstract Windowing Toolkit (AWT) communicates these actions to the program
using events. When the user initiates an action, the AWT generates an event and
communicates it to event handlers. These event handlers can respond to the events
appropriately.
Often it may be required to perform some task based on the action performed by the user.
For example, if a user clicks on a button, a text message stating the action performed by
the user may be made to get displayed on the status bar. All these process comprise of
what is called as Event Handling.
When a component is activated, that is, when the internal state of the component is
modified a source is generated. This is nothing but a source to the event.
A single component can take events from different sources. For example, an applet
should be made ready to receive the events from the different sources. This is done by the
Listeners which are nothing but interfaces with abstract methods which could be
implemented on generation of the corresponding event.
Event Listeners are not used whenever a component handles its own events.
The actions that have to be performed on the components listening to the event like a
mouse click on an applet are called Event Handling.
The whole of event handling in Java 1.0 AWT is done using two methods action( )
and handleEvent( ) method. The action( ) method has three parameters namely – the
event that has occurred, the x and y co-ordinates at which this event occurred. The
handleEvent( ) method is called automatically for an object and an Event object is created
and passed on to it.
Event Delegation Model:
In the new event model, an event is propagated from a “source” object to a “Listener”
object by invoking a method on the listener and passing in the instance of the event
subclass which defines the event type generated. When an event is fired, it is received by
one or more listeners that act on that event. Each event listener is an object of a class that
implements a particular type of listener interface. Event types are encapsulated in a class
hierarchy rooted at java.util.EventObject and one level below this is java.awt.AWTEvent
package.
A Listener is an object that implements a specific EventListener interface extended from
the generic java.util.EventListener.
An EventListener interface defines one or more methods that are to be invoked by the
event source in response to each specific event type handled by the interface.
An Event Source is an object that originates events. The source defines the set of events it
emits by providing a set of set<EventType> Listener(for single-cast) and/or
add<EventType>Listener(for multi-cast) methods which are used to register specific
listeners for those events.
An adapter class includes all methods specified by the corresponding interface but not
providing any functionality.
Whenever an AWT component wants to handle its own events, the component’s subclass
created has to do two things:
Enable receipt of events by calling enableEvents( )
Provide a processActionEvent ( ) method which is called whenever the component is
activated.
The delegation method is the best-suited method to handle events. It is not possible for a
component to handle its events at all times. Hence this should be assigned to a different
object called listeners. This process is called delegation. Each component class in AWT
has one addxxxListener( ) method for each event type that the component generates.
ComponentEvent
FocusEvent
InputEvent
KeyEvent
MouseEvent
ContainerEvent
WindowEvent
Semantic Events:
Semantic events are defined at a higher-level to encapsulate the semantics of a user
interface component’s model.
AWT defines semantic class as:
ActionEvent
AdjustmentEvent
ItemEvent
TextEvent
Listener interfaces are
ActionListener
AdjustmentListener
ItemListener
TextListener
The whole point of the adapters is to make the creation of listener classes easy. There is a
downside to adapters, however, in the form of a pitfall. Suppose a code using
WindowAdapter is written like the one below:
Mouse Events:
These are generated whenever a mouse is moved, clicked, pressed, released, etc. The
MouseEvent class represents these events as six constant values. There are two types of
mouse event listeners – MouseListener and MouseMotionListener.
An alternate way of handling mouse events is by letting components process their own
ordinary mouse events using enableEvents(AWTEvent . MOUSE-EVENT_MASK) and
processMouseEvent( ) methods.
Keyboard Events:
These are generated on pressing or releasing a key. The KeyEvent class contains
constants to represent the keys pressed or typed. The event listener corresponding to these
types of events is the KeyListener. The interface has the following definition:
Containers:
The Container class is a subclass of Component. It has additional methods that allow
other Component objects to be nested within it. A Container can store other Container
objects. It is responsible for laying out any components which it contains. User interface
components added to a container are tracked in a list. The order of the list will define the
components front-to-back stacking order within the container. If no index is specified
when adding a component to a container, it will be added to the end of the list.
Components have to be necessarily added to a container if they have to be displayed on
the screen.
The basic functionalities of containers are encapsulated in an abstract class, Container.
This class has methods that allow other components to be nested within it. The Panel is a
simple non-abstract container that can contain other components. The add( ) method of
the Container class can be used to add components to a Panel. The Applet class is derived
from the Panel class and hence, can act as a container. This property of the applet shall be
exploited by adding user interface components and other containers directly to the applet.
The Applet class, though derived from the Panel does not belong to the AWT package.
The AWT package contains a number of component classes that are typical elements of
any interactive user interface. These classes are called as User Interface component
classes, are derived from the abstract Component class. The Component class defines a
number of methods that can be used on any of the classes that are derived from it.
Panel:
The Panel class is a concrete subclass of Container. It does not add any new methods but
uses the methods of Container class. A Panel may be thought of as a recursively nestable,
concrete screen component. Panel is the superclass for Applet. When screen output is
directed to an applet, it is drawn on the surface of a Panel object. In essence, a Panel is a
window that does not contain a title bar, menu bar, or border.
Other Components can be added to Panel object by its add( ) method. Once these
components have been added, they can be positioned and resized manually using the
setLocation( ), setSize( ), or setBounds( ) methods defined by Component.
Window:
The window class creates a top-level window. A top-level window is not contained
within any other project; it is placed directly on the desktop.
Frame:
Frame encapsulates a “window”. It is a subclass of window and has a title bar, menu bar,
borders and resizing corners. When a Frame window is created by a program, rather than
an applet, a normal window is created.
Button:
Buttons are components that can contain a label. The button is similar to a push button in
any other GUI. Pushing a button causes the run time system to generate an event. This
event is sent to the program. The program in turn can detect the event and respond to the
event. Clicking a button generates an ActionEvent. It can be created using the new
keyword in association with the constructors that are defined it. Buttons must be added to
the containers before they can be used. Once the buttons have been created and added the
can be used. When a button is clicked the AWT sends an instance of the ActionEvent to
the button, by calling the processEvent on the button. The processEvent method of the
button receives all the events of the button. This then passes an action event along by
calling its processActionEvent. The processActionEvent then passes the action event to
any action listeners that have registered an interest in action events generated by the
button. Any application that has to perform an action based on the button has to
implement the ActionListener and register the listener to receive the events from the
button, by calling its addActionListener method.
Button Component:
Constructor that can be used with the Button component
Button( ) : It constructs a button with no label.
Button(String label) : It constructs a button with the label specified.
CheckBox:
Checkboxes are user interface components that have dual state: checked and unchecked.
Clicking on it can change the state of the checkbox. The checkbox class is used to
implement labeled checkbox and radio button GUI controls. If a checkbox object is not
associated with a checkboxGroup object, it is implemented as traditional checkbox. If a
checkbox object is associated with a checkboxGroup object, it is implemented as a radio
button. The Checkbox class provides five constructors that allow the checkbox label,
initial state and checkboxGroup object to be specified. The checkbox class provides
methods for getting and setting the label and state of the checkbox and its
checkboxGroup object. The state of the checkbox is Boolean. The checkbox class also
provides methods for identifying event-handling code.
The checkboxGroup class is used with the checkbox class to implement radio buttons.
All checkbox objects that are associated with a checkboxGroup object.
Java supports two types of checkboxes: exclusive and non-exclusive.
Exclusive Checkboxes: Only one among a group of items can be selected at a time. If an
item from the group is selected, the checkbox currently checked is deselected and the
new selection is highlighted. The exclusive checkboxes are also called radio buttons.
Non-Exclusive Checkboxes:
It is not grouped together and each checkbox can be selected independent of the other.
Frame Window:
After the applet, the type of window which user will most often create is derived from
Frame. It creates a standard-style window.
Types of Frame’s constructors:
Frame( )
Frame(String title)
The first form creates a standard window that does not contain a title. The second form
creates a window with the title specified by the string title.
Choice:
The choice class is used to implement pull-down lists that can be placed in the main area
of a window. These lists are known as option menus or a pop-up menu of choices and
allow the user to select a single menu value. The UI component displays the currently
selected item with an arrow to its right. On clicking the arrow, the menu opens and
displays options for a user to select. The Choice class provides a single, parameterless
constructor. It also provides access methods that are used to add items to the list, count
the number of items contained in the list, select a list item, handle events and determine
which list item is selected. To create a choice menu, a choice object is instantiated. Then,
various items are added to the choice by using the addItem( ) method.
Example:
Open a new file and enter the following code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/* <applet code = “choice” height = 300 width =300> </applet>*/
public class choice extends Applet
{
Choice colors;
public void init( )
{
colors = new Choice( );
colors.addItem(“red”);
colors.addItem(“blue”);
colors.addItem(“green”);
add(colors);
}
}
Canvas:
A Canvas component represents a blank rectangular area of the screen onto which the
application can draw or from which the application can trap input events from the user.
An application must subclass the Canvas class in order to get useful functionality such as
creating a custom component. The paint method must be overridden in order to perform
custom graphics on the canvas. The canvas does not have a size that is useful to the end
user and hence the setsize method has to be used to render a meaningful canvas on the
screen.
The constructor is:
Canvas( ): It constructs a new canvas.
Methods:
addNotify( ): It creates a peer o the canvas.
paint(Graphis g): this method is called to repaint the corresponding canvas.
FileDialog:
The FileDialog class displays a dialog window from which the user can select a file.
Being a modal dialog, it blocks the rest of the application until the user has chosen a file.
Label:
The most basic GUI component is the label, which is simply a text that is displayed at a
particular location of a GUI container. The label class of the java.awt package provides
the capability to work with labels. The class ‘label’ provides three label constructors:
A default parameterless constructor for creating blank label objects.
A constructor that takes a String object that specifies the label’s text.
A constructor that takes a String object and an alignment constant.
The Label class provides six methods for working with the label’s text and alignment and
also for performing other operations. The setText( ) and getText( ) methods are used to
access the label’s text. It would display a single line of text in a container. The text can be
changed by an application but the user cannot edit the text. Labels do not generate any
events. A label is similar to a button can be created using its constructor in combination
with a keyword new.
The constructors used are:
Label( ): It constructs an empty label.
Label(String text): It constructs a string with the corresponding text.
Label(String text, int alignment): It constructs a string with the text, with the specified
alignment. The alignment could be CENTER, LEFT, RIGHT.
List:
The List class implements single- and multiple-selection list GUI controls. The lists
provided by the list class are more sophisticated than those provided by the choice class.
The list class lets specifying the size of the scrollable window in which the list items are
displayed and select multiple items from the list. The difference between a list and a
choice menu are:
Unlike Choice, which displays only the single-selected item, the list can be made
to show any number of choices in the visible window.
The list can be constructed to allow multiple selections.
Methods:
add(string item): It adds the specified item at the end of the scrolling list.
add(string item, int index): It adds the specified item at the position specified.
deselect(int index): It deselects the item at the specified index.
getItem(int index): It gets the item at the specified index.
getItemCount( ): It gets the number of items in the list.
getItems( ): It gets the items in the list.
getMinimumSize( ): It determines the minimum size of the scrolling list.
getMinimumSize(int rows): It gets the minimum dimensions for a list with the specified
number of rows.
getPreferredSize( ): It gets the preferred size of the corresponding scrolling list.
getPreferredSize(int rows): It gets the minimum dimension for a list with the specified
number of rows.
getRows( ): It gets the number of visible lines in the corresponding list.
getSelectedIndex( ): It gets the index of the selected item in the list.
getSelectedItem( ): It gets the selected item in the corresponding list.
select(int index): It selects the item at the specified index in the corresponding list.
setMultipleMode(boolean b): It sets the flag that allows multiple selection in the
corresponding list.
ScrollPane:
ScrollPane is a container class which implements automatic horizontal and/or vertical
scrolling for a single child component. The display policy for the scrollbars can be set to
as needed, always and never. The constructors of scrollPane are:
ScrollPane( ): It creates a new scroll pane container with the scroll bar policy of “as
needed”.
ScrollPane(int Scrollbardisplaypolicy): It creates a new scrollpane container.
Methods:
getScrollbarDisplayPolicy( ): It returns the display policy for the corresponding scroll
bars.
setScrollPosition(int x, int y): It scrolls to the specified position within the child
component.
Scrollbar:
Scrollbars are used to select a value between a specified minimum and maximum. It has
the following components:
The arrows at either end allow incrementing or decrementing the value
represented by the scrollbar.
The thumb’s (or handle’s) position represents the value of the scrollbar.
The constructors of scrollbar are:
Scrollbar( ): It constructs a vertical scroll bar.
Scrollbar(int orientation): It constructs a new scroll bar with the specified orientation.
Scrollbar(int orientation, int maxvalue, int visible, int minimum, int maximum): It
constructs a new scroll bar with the specified orientation, initial value, page size,
minimum and maximum values.
Methods:
getBlockIncrement( ): It gets the block increment of the corresponding scroll bar.
getMaximun( ): It gets the maximum value of the corresponding scroll bar.
getMinimum( ): It gets the minimum value of the corresponding scroll bar.
getOrientation( ): It determines the orientation of the corresponding scroll bar.
getValue( ): It gets the current value of the corresponding scroll bar.
setBlockIncrement(int v): It sets the block increment for the corresponding scroll bar.
setMaximum(int newMaximum): It sets the maximum value for the corresponding scroll
bar.
setMinimum(int newminimum): It sets the minimum value for the corresponding scroll
bar.
setValue(int newvalue): It sets the value of the corresponding scroll bar to the specified
value.
Textfield:
Textfields are GUI components that accept text input from the user. They are often
accompanied by a Label control. The Textfield class implements a one-line text entry
field. It provides four constructors that are used to specify the width of the text field in
character columns and the default text to be displayed within the field. It provides several
methods for accessing the field’s size and for specifying whether the characters typed by
the user should be displayed.
The constructors are:
TextField( ): It constructs a new text field.
TextField(int columns): It creates a new text field with the specified number of columns.
TextField(String text): It constructs a new text field initialized with the specified text.
TextField(String text, int columns): It constructs a new text field initialized with the
specified text with the specified number of columns.
Methods are:
getColumns( ): It gets the number of columns in the corresponding text field.
getEchoChar( ): It gets the character that is to be used for echoing.
setColumns(int columns): It sets the number of columns in the text field.
setEchoChar(char c): It sets the echo character for the text field.
setText(String t): It sets the text that is presented by the corresponding text component to
be specified text.
TextArea:
Sometimes, a single line of text input is not enough for a given task. To handle these
situations, the AWT includes a simple multi-line editor called TextArea. TextArea is a
subclass of TextComponent. It behaves like TextFields except that they have more
functionality to handle large amounts of text. The functionalities include:
Text areas can contain multiple rows of text. Text areas have scrollbars that permit
handling of large amounts of data.
The constructors are:
TextArea( ): It constructs a new text area.
TextArea(int rows, int columns): It constructs a text area with the specified number of
rows and columns.
TextArea(String text): It constructs a new text area with the specified text.
TextArea(String text, int rows, int columns): It constructs a new text area with the
specified text, and specified number of rows and columns.
TextArea(String text, int rows, int columns, int scrollbar): It constructs a new text area
with the specified text, and specified number of rows and columns and visibility of the
scrollbar.
Summary:
Java’s AWT generates events when user performs actions like mouse click, key press,
etc. When an event is fired, it is received by one or more listeners that act on that event.
A Listener is an object that implements a specific EventListener interface extended from
the generic java.util.EventListener. An EventListener interface defines one or more
methods that are to be invoked by the event source in response to each specific event type
handled by the interface. The Component class is the abstract superclass of the non
menu-related Abstract Window Toolkit components. All the user interface components
and container classes are derived from the class. The Panel class is a concrete subclass of
Container. Buttons are components that can contain a label. The button is similar to a
push button in any other GUI. The choice class is used to implement pull-down lists that
can be placed in the main area of a window. A Canvas component represents a blank
rectangular area of the screen onto which the application can draw or from which the
application can trap input events from the user. ScrollPane is a container class which
implements automatic horizontal and/or vertical scrolling for a single child component.
Textfields are GUI components that accept text input from the user. They are often
accompanied by a Label control. Text areas can contain multiple rows of text. Text areas
have scrollbars that permit handling of large amounts of data.
Fundamentals of Threads:
Implementing Runnable
The easiest way to create a thread is to create a class that implements the Runnable
interface. Runnable abstracts a unit of executable code. Creation of a thread object
using Runnable interface can be constructed. To implement Runnable, a class needs
to implement a single method called run( ), which is declared as:
Public void run( )
Inside run( ), it will define the code that constitutes the new thread. The run( ) can call
other methods, use other classes and declare variables, just like the main thread can.
Example:
Open a new file and enter the following code:
Passing this as the first argument indicates that a new thread is calling the run( )
method on this object. A new object of NewThread class is created as the first step,
which calls its constructor. Inside the constructor, a new thread is created using one of
Thread class constructor, which takes as parameters- the object itself and a string.
This helps in creating new child threads apart from the main method. The start( )
method starts each of the newly created threads. Automatically, control passes to the
run( ) method. Within it, the sleep( ) method of the Thread class suspends the thread
for 500 milliseconds. Since this method generates an exception, it is enclosed within
try block. Simultaneously, the main thread continues with the execution of the main
program. The main thread enters the try block inside main( ) method and exits at the
end of the for loop. It is ensured that the child thread created is destroyed before main
thread terminates.
The output is
child thread Thread[Dem
calling run method
after calling run method
main thread: L 5
child thread: 5
child thread: 4
main thread: L 4
child thread: 3
child thread: 2
main thread: L 3
child thread: 1
main thread: L 2
child thread: L 1
main thread interrupted.
Extending Thread:
The second way to create a thread is to create a new class that extends Thread and
then to create an instance of that class. The extending class must override the run( )
method, which is the entry point for the new thread. It must also call start( ) to begin
execution of the new thread.
The first constructor of Thread class can be given as
Thread(Runnable, String)
A new thread is created with the specified name. It applies the run( ) method on the
specified target. The next constructor creates a new thread in the specified
ThreadGroup with the specified name and it applies the run( ) method on the
specified target.
Thread(ThreadGroup, Runnable, String)
Example:
class NewThread extends Thread
{
NewThread( )
{
super(“demo thread”);
System.out.println(“child thread: “+this);
start( );
}
public void run( )
{
try
{
for(int i=5; i>0;i--)
{
System.out.println(“child thread: “+i);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println(“child interrupted”);
}
System.out.println(“Existing child thread”);
}
}
class extendthread
{
public static void main(String args[])
{
new NewThread( );
try
{
for(int i=5;i>0;i--)
{
System.out.println(“main thread: “+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(“main thread interrupted”);
}
System.out.println(“main threa exiting”);
}
}
This program generates the same output. The child thread is created by instantiating an
object of NewThread, which is derived from thread. The call to super( ) inside
NewThread, invokes the Thread Constructor:
public Thread(String threadName)
here, threadName is the name of the thread.
The run( ) method executes using the newly created thread while the rest of the program
uses the main thread.
More on Threads:
It intends to introduce concepts like synchronization of threads to enable data
integrity, inter thread communication using wait( ), notify( ) and thread priorities.
Synchronization:
Two or more threads accessing the same data simultaneously may lead to loss of data
integrity. A way to prevent data from being corrupted by multiple threads is to prevent
the interruption of critical regions. Critical regions are placed where only one thread
should be running at once. Java uses the concept of monitor or a semaphore to enable the
loss of data integrity. A monitor is an object, used as a mutually exclusive lock. At a
time, only a thread can access the monitor. A second thread cannot enter the monitor until
the first comes out. Till such time, the other thread is said to be waiting. The keyword
synchronized is used in the code to enable synchronization. The word synchronized can
be used along with a method or within a block.
synchronized (this)
{
num =num+10;
num =num_10;
}
synchronized (this) ensures that only one thread can be in the following code bloc. The
argument this tells the thread to use the lock for this object.
The variable num is also referenced when the string is printed. The new code is as
follows:
synchronized (this)
{
tmp=num;
}
System.out.println(currentThread( ).getName( )+ “sees the number:” +tmp);
A critical region is used to copy num to temporary storage. The string is then printed
using the temporary storage. It would have been possible to synchronize the print line
directly, but it would cut performance because the print line does many other things hat
have nothing to do with referencing num. All the threads waiting to enter the critcal
region will needlessly wait longer while the print line is executed. Generally, the
synchronized blocks should be as small as possible while still protecting the critical
region. Both i and tmp are method variables so each running thread has its own private
copy. So it is not necessary that they have to be synchronized.
Deadlocks:
Deadlock is a special error that needs to be avoided that relates specifically to
multitasking, which occurs when two threads have a circular dependency on a pair of
synchronized objects. Deadlocks are always a danger in multithreaded environments.
Deadlock is a difficult bug to debug for two reasons:
It occurs only rarely, when the two threads time-slice in ju8st the right way.
It may involve more that two threads and two synchronized objects.
A common problem in concurrent programming is coordinating access to a shared
resource by enforcing a synchronization condition between multiple concurrent
processes. There are several algorithms available for preventing deadlocks.
Interthread Communication:
Java has three wait( ) and two notify( ) methods that aid in synchronizing threads. The
wait( ) methods cause the thread to pause in the critical region. While paused, the thread
releases its lock. It must get the lock again before it starts executing again. The notify( )
methods wake up threads that have called wait( ). Calling notify( ) when no wait( ) has
been called has no effect. The methods shown below are in object class and can only be
called in a synchronized block or method.
public final void wait( ): This method causes the thread to wait forever until
a notify( ) or notifyAll( ) is called. The thread releases its lock on the critical
regions so that other threads may enter.
public final void wait(long m): This method causes the thread to wait m
milliseconds for a notify( ) or notifyAll( ) to be called. After the time is
expired, the thread tries to resume execution. However, it must first re-obtain
the lock for the critical region. Another thread may have entered the critical
section while the thread was waiting.
public final void wait(long m, int n): This method is similar to the previous
one except that it waits for m milliseconds plus n nanoseconds.
public final void notify(): This method wakes up a thread that has previously
called wait( ). The thread that was waiting has to get the lock before it can
resume execution. It has to wait until the current thread leaves the critical
region. Only one thread that has called wait( ) is woken up. It is not
guaranteed that the first thread that called wait( ) is the first one woken up.
public final void notifyAll( ): This method wakes up all the threads that have
called wait( ). Each waiting thread has to get the lock for the critical region
before it resumes. There can still be only one thread running in the critical
section at once.
Thread Priorities:
Java assigns to each thread a priority that determines how that thread should be treated
with respect to others. Thread priorities are integers that specify the relative priority of
one thread to another. As an absolute value, a priority is meaningless; a higher-priority
thread does not run any faster than a lower-priority thread it is the only thread running.
Instead, a thread’s priority is used to decide when to switch from one running thread to
the next. This is called a context switch. Each thread created has a priority attached to it.
The scheduler allocates time in accordance to these priorities. A thread with higher
priority can preempt the lower priority thread, thus taking CPU’s time. The yield( )
method enables provision of CPU’s time to threads with equal priority and prevents
monopolization of a single thread.The rules that determine when a context switch takes
place are simple:
A thread can voluntarily relinquish control: This is done by explicitly yielding,
sleeping, or blocking on pending I/O.
A thread can be preempted by a higher-priority thread. In this case, a lower-
priority thread that does not yield the processor is simply preempted- no matter
what it is doing—by a higher-priority thread. Basically, as soon as a higher-
priority thread wants to run, it does. This is called preemptive multitasking.
To set a thread’s priority, use the setPriority( ) method, which is a member of Thread.
here, level specifies the new priority setting for the calling thread. The value of level
must be within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these
values are 1 and 10, respectively. To return a thread to default priority, specify,
NORM_PRIORITY, which is currently 5. These priorities are defined as final variables
within Thread.
Summary:
A thread is a line of execution and is the smallest unit of code that is dispatched by the
scheduler. A process containing multiple threads to execute its different section is called
multithreading. There are four states associated with a thread namely- new, runnable,
blocked and dead. Creation of new threads is done by creating objects of class Thread
and using Runnable interface. The keyword synchronized is used in the code to enable
synchronization. Java offers interprocess communication through the use of wait( ),
notify( ), notifyAll( ) methods of object class and all are synchronized methods. The
thread class has final variables declared like-NORM_PRIORITY,
MINIMUM_PRIORITY and MAXIMUM_PRIORITY to set default priorities.
System class:
System class consists of a number of useful methods that deal with runtime environment.
It contains three public data streams. They are as follows:
Interfaces of java.lang:
It contains three interfaces namely Cloneable, Comparable and Runnable.
Cloneable:
A class implements the cloneable interface to indicate to the Object.clone( ) method. The
exception CloneNotSupportedException will be thrown if the user clones instances,
which do not implement the Cloneable interface. This interface declares no methods.
Comparable:
Classes that implement Comparable interface contain objects that can be compared with
each other. It declares only one method. The syntax is:
int compareTo (Object obj)
This method compares the invoking object with obj. It returns 0 if the values are equal. A
negative value is returned if the invoking object has a lower value. Otherwise, a positive
value is returned. compareTo( ) method is defined by Byte, Character, Float, Long, Short,
String and Integer classes.
Runnable:
Any class that initiates a separate thread of execution must implement the Runnable
interface. It defines only one abstract method, called run( ). It is the method which is the
entry point to the thread. Threads that are created by the user must implement abstract
void run( ) method.
Wrapper class:
The java.lang package includes a number of classes that “wrap” a primitive data type in a
reference object. These classes constitute the wrapper classes. The wrapper classes
provide object versions of primitive data types. These classes include methods for
converting the value from one data type to another.
Number:
The Number class is the super class for the wrapper class like int, long, float and double
types. Any class that expects an instance of a Number may be passed an Integer, Long,
Float or Double class.
Integer:
The Integer class provides a wrapper for the int data type. It contains methods for
converting integers to Strings and vice versa.
The constructor use these form:
public Integer(int val)
public Integer(String s) throws NumberFormatException
Long:
The Long class provides a wrapper for the long data type. It contains methods for
converting long to strings and vice versa. The constructor takes the following form:
public Long(long val)
public Long(String s) throws NumberFormatException
Byte:
The Byte class provides a wrapper for the byte data type. It contains methods for
converting byte to strings and vice versa. The constructor takes the following form:
public Byte(byte val)
public Byte(String s) throws NumberFormatException
Short:
The Short class provides a wrapper for the Short data type. It contains methods for
converting Short to strings and vice versa. The constructor takes the following form:
public Short(Short val)
public Short(String s) throws NumberFormatException
Float:
The Float provides a wrapper for the float data type. In addition to string conversion, it
provides a way to directly manipulate the bits in a float. The following constructors are
supported by the Float class.
public Float(float value)
public Float(double value)
public Float(String s) throws NumberFormatException
Double:
The Double class provides a wrapper for the double data type. This class supports the
following constructors:
public Double(double value)
public Double(String s) throws NumberFormatException
Character:
The Character class provides a wrapper for the char data type. It contains methods for
converting characters to numeric digits and vice versa, to check whether a given character
is an alphabet, number and so on. This class has single constructor.
Boolean:
The Boolean class provides a wrapper for the Boolean data type. It has two types of
constructors.
public Boolean(boolean Value)
public Boolean(String str)
The class has a method called valueOf( ) that accepts a string as its argument. This
method can be used as an alternate way of creating a Boolean object from a String.
Void:
The wrapper class Void is used for rounding out the set of wrappers for primitive types.
This wrapper class has no constructor or method and contains only the TYPE attribute
that is common to all the wrapper classes.
Process:
The abstract Process encapsulates a process-that is an executing program. It is used
primarily as a super class for the type of objects created by exec( ) in the Runtime class.
Process contains the abstract methods.
Void destroy( ): It terminates the process.
int exit Value( ): It returns an exit code obtained from a subprocess.
InputStream getErrorStream( ): It returns an input stream that reads input from the
process’ err output stream.
InputStream getInputStream( ): It returns an input stream that reads input from the
process’ out output stream.
OutputStream getOutputStream( ): It returns an output stream that write output from the
process’ in input stream.
Int waitFor( ) throws: It returns the exit code returned by the interruptedException.
Runtime:
The Runtime class encapsulates the run – time environment. Runtime object can get a
reference by calling the static method Runtime.getRuntime( ).Once the reference to the
current Runtime object is obtained, it calls several methods that control the state and
behaviour of the Java Virtual Machine.
Method:
Process exec(String progName) throws IOException: It executes the program specified
by progName as a separate process. An object of type Process is returned that describes
the new process.
Process exec(String progName, String environment[]) throws IOException) throws
IOException: It executes the program specified by progName as a separate process with
the environment specified by the environment. An object of type process is returned that
describes the new process.
Runtime Permission:
This class is for runtime permission. A runtime Permission contains a target name and
they do not have any specific actions list. The target name is the name of the runtime
permission.
CreateClassLoader: It is the creation of a class loader. Using this permission application
this can instantiate their own class loaders could load their own rogue classes into the
system.
CreateSecurityManager: It is the creation of a new security manager. It is the sensitive
methods, which have information about other classes or the execution stack, can be
disclosed with this permission.
setIO: It is used for setting of System.out, System.in, and System.err. This allows
changing the value of the standard systems streams. A hacker may change System.in to
monitor the user input, or may set System.err to a “null” OutputStream, which would
hide any error messages sent to System.err.
modifyThread: It is used for the modification of threads. This allows a hacker to start or
suspend any thread in the system.
getProtectionDomain: It is used for the retrieval of the ProtectionDomain for a class. This
allows code to obtain policy information for a particular code source.
readFileDescriptor: It is used for reading of file descriptors. This would allow code to
read the particular file associated with the file descriptor read. This is dangerous if the file
contains confidential data.
Class Loader:
The class ClassLoader is an abstract class. It is responsible for loading classes. Array
classes are created automatically by the Java runtime. Class loaders do not create objects
for array classes. Security managers use class loaders to indicate security domains. The
class Loader class uses a delegation model to search for classes and resources. Each
instance of Class Loader has an associated parent class loader.
The ClassLoader searches for the class in its parent class loader before attempting to find
the class itself, whenever called for searching a class.
The virtual machine has a built-in class loader called the bootstrap class loader.
Bootstarp class loader acts as a parent class loader. All the methods and constructors
created by a class loader may reference other classes also.
Security Manager:
The security manager class allows applications to apply a security policy. It can decide an
application whether to allow a sensitive operation to be performed or not. The security
manager is set by the setSecurityManager method in class System and it is obtained by
the getSecurityManager method. checkPermission method has only one argument, which
performs security checks within the current executing thread. To overcome this the
getSecurityContext method includes a context argument.
cos:
The syntax is:
public static double cos(double a)
The cos method has only one double value a as the parameter. It returns the trigonometric
cosine of an angle.
tan:
The syntax is:
public static double tan(double a)
The tan method has only one double value a as the parameter. It returns the trigonometric
tangent of an angle.
asin:
The syntax is:
public static double asin(double a)
The asin method has only one double value a (whose arc sine is to be returned) as the
parameter. It returns the arc sine of an angle, in the range of –pi/2 through pi/2.
acos:
The syntax is:
public static double acos(double a)
The acos method has only one double value as a parameter. It returns the arc cosine of an
angle, in the range of 0.0 through pi.
atan:
The syntax is:
public static double atan(double a)
The atan method has only one double value a (whose arc tangent is to be returned) as the
parameter. It returns arc tangent of an angle, in the range of –pi/2 through pi/2.
toRadians:
The syntax is:
public static double toRadians(double angdeg)
The toRadians method has only one double value angdeg as the parameter. It converts an
angle measured in degrees to the equivalent angle measured in radians.
toDegrees:
The syntax is:
public static double toDegrees(double angrad)
The toDegrees method has only one double value angrad as the parameter. It returns the
measurement of the angle angrad in degrees.
exp:
The syntax is:
public static double exp(double a)
The exp method has only one double value a as the parameter. It returns the exponential
number exponential number e raised to the power of a double value.
log:
The syntax is:
public static double log(double a)
The log method has only one double value a as the parameter. It returns the natural
logarithm (base e) of a double value.
sqrt:
The syntax is:
public static double sqrt(double a)
The sqrt method has only one double value a as the parameter. It returns the square root
of a, if the argument is NaN or less than zero, the result is NaN.
IEEEremainder:
The syntax is:
public static double IEEEremainder(double f1, double f2)
It calculates the remainder operation on two arguments. It has two parameters f1(the
dividend) and f2(the divisor) and is returns the remainder when f1 is divided by f2.
ceil:
The syntax is:
public static double ceil(double a)
The ceil method has only one double value a as the parameter. It returns the smallest
double value that is not less than the argument and is equal to a mathematical integer.
floor:
The syntax is:
public static double floor(double a)
The floor method has only one double value a as the parameter. It returns the largest
double value that is not greater than the argument and is equal to a mathematical integer.
rint:
The syntax is:
public static double rint(double a)
The rint method has only one double value a as the parameter. It returns the closest
double value to a that is equal to a mathematical integer. If two double values that are
equally close to the value of the argument, it returns the integer value that is event.
atan2:
The syntax is:
public static double atan2(double a, double b)
Two double values a and b are the parameters for the method. It converts rectangular
coordinates (b, a) to polar (r, theta). This method computes the phase theta by computing
an arc tangent of a/b in the range of –pi to pi.
pow:
The syntax is:
public static double pow(double a, double b)
Two double values a and b are the parameters for the method. It returns the value of the
first argument raised to the power of the second argument. If (a==0.0) then b must be
greater than 0.0. Otherwise an exception is thrown. An exception will also occur
if(a<=0.0) and b is not equal to a whole number.
round:
The syntax are:
public static int round(float a)
public static long round(double a)
The first syntax has only one float value a as the parameter. It returns the closest integer
to a. If the argument is negative infinity, the result is equal to the value of
Integer.MIN_VALUE. If it is a positive infinity, the result is equal to the value of
Integer.MAX_VALUE.
The second syntax has only one double value a as the parameter. It returns the closest
long to the argument. If the argument is negative infinity, the result is equal to the value
of Long.MIN_VALUE. If it is a positive infinity, the result is equal to the value of
Long.MAX_VALUE.
random:
The syntax is:
public static double random( )
It gives a random number greater than or equal to 0.0 and less than 1.0. The values that
are returned are chosen pseudorandomly.
abs:
The syntax are:
public static int abs(int a)
public static long abs(long a)
public static float abs(float a)
public static double abs(double a)
The first syntax has only one int value a as the parameter. It returns the absolute value of
int value. If the argument is positive, the same argument is returned. If the argument is
negative, the negation of the argument is returned.
The second syntax has only one long value a as the parameter. It returns the absolute
value of long value. If the argument is positive, the same argument is returned. If the
argument is negative, the negation of the argument is returned.
The third syntax has only one float value a as the parameter. It returns the absolute value
of float value. If the argument is positive, the same argument is returned. If the argument
is negative, the negation of the argument is returned.
The fourth syntax has only one double value a as the parameter. It returns the absolute
value of argument. If the argument is positive, the same argument is returned. If the
argument is negative, the negation of the argument is returned.
max:
The syntax are:
public static int max (int a, int b)
public static long max (long a, long b)
public static float max (float a, float b)
public static double max (double a, double b)
The first syntax has two int values a and b. These are the two parameters which returns
the larger of two int values a and b.
The second syntax has two long values a and b. These are the two parameters which
returns the larger of two long values a and b.
The third syntax has two float values a and b. These are the two parameters which returns
the larger of two float values a and b. If either value is NaN, then the result is NaN.
Unlike the numerical operators, this method considers negative zero to be strictly smaller
than positive zero.
The fourth syntax has two double values a and b. These are the two parameters which
returns the larger of two long values a and b. If either value is NaN, then the result is
NaN. Unlike the numerical operators, this method considers negative zero to be strictly
smaller than positive zero.
min:
The syntax are:
public static int min (int a, int b)
public static long min (long a, long b)
public static float min (float a, float b)
public static double min (double a, double b)
The first syntax has two int values a and b. These are the two parameters which returns
the smaller of two int values a and b.
The second syntax has two long values a and b. These are the two parameters which
returns the smaller of two long values a and b.
The third syntax has two float values a and b. These are the two parameters which returns
the smaller of two float values a and b. If either value is NaN, then the result is NaN.
Unlike the numerical operators, this method considers negative zero to be strictly smaller
than positive zero.
The fourth syntax has two double values a and b. These are the two parameters which
returns the smaller of two long values a and b. If either value is NaN, then the result is
NaN. Unlike the numerical operators, this method considers negative zero to be strictly
smaller than positive zero.
Summary:
The object class is the base class of every class in Java. It defines the methods that every
class in Java supports. The Runnable interface identifies a class as being Runnable as a
separate thread. The abstract Process class encapsulates a process –that is, an executing
program. Package class is one that encapsulates version data associated with a package.
Package objects contain version information about the implementation and specification
of a Java package. A RuntimePermission contains a target name and they don’t have any
specific actions list. A class loader is an object that is responsible for loading classes. The
Security Manager class allows applications to apply a security policy.
Util Package
Util package is the Java’s most prominent package and it contains Java’s most
powerful subsystems: Collections. A collection, sometimes called as a container, is
simply an object that groups multiple elements into a single unit. Collections are used to
store, retrieve and manipulate data and to transmit data from one method to another.
Collections represent data items that form a natural group. Java contained collection
implementations like array, Vector, Hashtable and dictionary, they did not contain a
collections framework.
Collection Framework:
A collections framework is a unified architecture for representing and manipulating
collections. All collections frameworks contain three things:
Interfaces:
The core collection interfaces are the interfaces used to manipulate collections and to
pass them from one method to another. The basic purpose of these interfaces is to allow
collections to be manipulated independently of the details of their representation. The
core collection interfaces are the heart and soul of the collections framework. The core
collection interfaces form a hierarchy: a Set is a special kind of Collection and a
SortedSet is a special kind of Set and so forth.
Collection
Set List
SortedSet
Map
SortedMap
Note that the hierarchy consists of two distinct tress: a Map is not a true Collection.
Collection interfaces is at the top of the hierarchy. It enables us to work with group of
objects. The List interface extends the Collection interface and handles sequences. The
Set interface also extends the Collection interface and handles sets. The collection
interfaces allow some methods to be optional. These optional methods enable us to
modify the contents of a collection. Collections that support these methods are called
modifiable and those that do not support are called unmodifiable. If an attempt is made to
invoke an unsupported operation, the UnsupportedOperationException is thrown.
Implementations are responsible for documenting which of the optional operations they
support. All of the JDK’s general purpose implementations all of the optional operations.
Collection Interface:
The collection interface is the root of the collection hierarchy. A Collection represents a
group of objects, known as its elements. Some Collection implementations allow
duplicate elements and others do not. Some are ordered and others unordered. The Java
Development Kit does not provide any direct implementations of this interface: It
provides implementations of more specific sub interfaces like Set and List. This interface
is the least common denominator that all collections implement. Collection is used to
pass collections around and manipulate them when maximum generality is desired.
boolean add(Object a): It adds the given object to the current collection. It returns true
if the object was added.
boolean addAll(Collection c): It adds all the elements of the Collection c to the
current collection. It returns true when the element is added.
void clear( ): It removes all the elements from the current collection.
boolean contains(Object a): It checks whether the object a is an element of the current
collection.
boolean remove(Object a): It removes an instance of the object a from the current
collection.
boolean retainAll(Collection c): It retains only the elements of the Collection c in the
current Collection and removes all the other elements from it.
Object[ ] toArray( ): It returns a copy of all the elements of the current collection to
an Object array.
Object[ ] toArray(Object a[]): It returns a copy of only those elements of the current
collection whose type matches that of the object array a, to an object array.
Set:
A Set is a Collection that cannot duplicate elements. Set abstraction is used to represent
sets like the cards comprising a poker hand, the courses making up a process running on a
machine.
Set Interface:
The Set interface extends Collection and contains no methods other than those inherited
from Collection. It adds restriction that duplicate elements are prohibited. Set also adds a
stronger contract on the behaviour of the equals and HashCode operations, allowing Set
objects with different implementation types to be compared meaningfully. Two Set
objects are equal if they contain the same elements. It also adds restriction on the equals()
and hashCode( )mehods. There are two Set implementations. They are HashSet and
TreeSet. HashSet stores its elements in a hash table, is the best-performing
implementations. TreeSet stores its elements in a red-black tree, guarantees the order of
iteration.
SortedSet Interface:
The SortedSet interface extends the Set interface. The elements of this interface are
sorted in ascending order. If the current set does not contain any element, then many of
the methods listed in the table throw the NoSuchElementException. When an object is
incompatible with the elements in a set then the ClassCastException is thrown. A
NullPointerException is thrown if we attempt to use a null object and null is not allowed
in the set.
Methods:
Comparator comparator( ): It returns the comparartor of the current sorted set. It
returns null if the natural ordering is used for the set.
Object first( ): It returns the first element of the current sorted set.
SortedSet headSet(Object a):It returns a SortedSet that contains elements less than the
object a from the current sorted set.
Object last( ): It returns the last element of the current sorted set.
The methods of the SortedSet interface can be divided into three categories. They are:
Range-view operations
Endpoint operations
Comparator Accessor
Range-view operations:
It performs arbitrary range operations over the sorted set. The range-view of a sorted set
remains valid even if the original sorted set is modified directly. This is because the
range-view of a sorted set is a window of a portion of the set that lies in the designated
part of the element-space. Any change to the range-view is written back to the original
sorted set and vice versa. The methods subSet, headSet and tailSet are the Range-view
operations of the sorted set. The subSet method is used for a sorted set of strings called
stringSet.
int count = stringSet.subset (“a”,”z”).size( )
The search includes a but excludes b while searching. If we want to exclude both the
letters while searching, then the code statement will be as:
int count = stringSet.subset (“a\0”,”z”).size( )
On the other hand, in order to include both the letters in the search, we give the code
statement as:
int count = stringSet.subset (“a”,”z\0”).size( )
The headset method is used to view the sorted set from the beginning upto the specified
object. To view all the letters upto z from the sorted set named stringSet, the code is:
SortedSet s1= stringSet.headSet (“z”);
The tailSet method is used to view the sorted set starting from the specified object upto
the end of the sorted set.
SortedSet s1 = stringSet.tailSet(“z”);
Endpoint Operations:
The Endpoint operations, namely, the first and last methods are used to return the first
and the last elements of the sorted set. These methods can be used in combination with
the range-view operations to get desired result.
String s = stringSet.headSet(“z”).last( )
Comparator Accessor:
The comparator method is the comparator accessor that returns the comparator used to
sort the set. If the set is sorted according to the natural order of its elements, then the
method returns a null.
Iterator Interface:
Iterator allows the user to remove elements from the current collection during the
iteration with well-defined semantics, whereas Enumeration does not allow such removal.
Method names have been improved in Iterators as compared to Enumeration.
There was no safe way to remove elements from a collection while traversing it with an
Enumeration. The semantics of the operation were ill-defined and differed from
implementation to implementation.
The Iterator interface is:
public interface Iterator
{
boolean hasNext( );
Object next( );
void remove( );
}
Object next( ): It returns the next element in the iteration. If the iteration has no more
elements, then it throws the NoSuchElementException.
void remove( ): It removes the last element returned by the iterator, from the current
collection. It can be called only once per call to the next method.
Operations:
It is used in Sets to perform standard set-algebraic operations.
containsAll: It returns true if the target Collection contains all of the elements in
the specified Collection ( c).
addAll: It adds all of the elements in the specified Collection to the target
Collection.
retainAll: It removes from the target Collection all of its elements that are not
also contained in the specified Collection. It retains only those elements in the
target Collection that are also contained in the specified Collection.
removeAll: It removes from the target Collection all of its elements that are
contained in the specified Collection.
clear: It removes all elements from the Collection.
List:
A List is an ordered collection. Lists can duplicate elements. The user of a List generally
has precise control over where in the List each element is inserted. The operations of the
List interface are:
Positional Access: It manipulates element based on their numerical position in the
list.
Search: It searches for a specified object in the list and return its numerical
position.
List Iteration: It extends Iterator semantics to take advantage of the list’s
sequential nature.
Range-view: It performs arbitrary range operations on the list.
Methods:
void add(int index, Object a): It inserts the object a into the current list at the position
specified by index. The preceding elements are shifted up in the list.
boolean addAll(int index, Collection c): It inserts the element of the Collection c into
the current list at the position specified by the index. The preceding elements are
shifted up in the list.
Object get(int index): It returns the object stored at the position specified by index,
within the current collection.
int indexOf(Object a): It searches for the object a in the current list and returns the
index of its first instance.
int lastIndexOf(Object a): It searches for the object a in the current list and returns the
index of the last instance.
ListIterator listiterator(int index): It returns an iterator to the current list that begins at
the position specified by the index.
Object remove(int index): It removes the element at the position specified by index
from the current list.
Object set(int index, Object a): It assigns a to the position specified by index in the
current list.
List subList(int starting, int ending): It returns a list that includes elements from the
position specified by starting to the position specified by ending –I in the current list.
The methods of the interface can be categorized into methods used for Positional Access,
Search, List Iteration and Range-view. The get, set, add, remove and addAll methods are
the methods used for Positional access. The indexOf and lastIndexOf methods are used
for search. The two listIterator methods are used for Iteration. The subList method is the
Range-view method.
Map Interface:
Map is an object that maps keys to values and cannot contain duplicate values. Each key
can map to at most one value only. The interface consists of methods for Basic
operations, Bulk operations, and Collection Views. The basic operations are the put, get,
remove, containsKey, containsValue, size and isEmpty methods. The bulk operations are
putAll and clear methods. The Collection Views are keySet, values and entrySet
methods.
public interface Map
{
//Basic Operations
Object put(Object key, Object value);
Object get(Object key);
Object remove(Object key);
boolean containsKey(Object key);
boolean containsValue(Object value);
int size( );
boolean isEmpty( );
//Operations:
void putAll(Map t);
void clear( );
//Collection Views
public Set keySet( );
public Collection values( );
public Set entrySet( );
//Interface
public interface Entry {
Object getKey( );
Object getValue( );
Object setValue(object val);
}
Method:
Void clear( ): It removes all the mappings from the current map.
boolean containsKey(Object key): It checks whether the current map contains a
mapping for the key key.
boolean containsValue(Object val): It checks whether the current map maps one or
more keys to the value val.
Set entrySet( ): It returns a set view of the mappings in the current map.
boolean equals(Object a): It checks whether the object a is equal to the current map.
Object get(Object key): It returns the value to which the current map maps the key
key.
int hashCode( ): It returns the hash code value of the map.
Boolean IsEmpty( ): It checks whether the current map contains any key value
mappings.
Set keySet( ): It returns a set of view of the keys in the current map.
Object put(Object key, Object val): It associates the val with the key in the current
map.
void putall(Map m): It copies all the mappings from the map m to the current map.
Object remove(Object key): It removes the mapping is present for the key in the
current map.
int size( ): It returns the number of key-value mapping in the current map.
Collection values( ): It returns a collection view of the values contained in the current
map.
SortedSet:
A SortedSet is a set that maintains its elements in ascending order. Several additional
operations are provided to take advantage of the ordering. The SortedSet interface is used
for things like word lists and membership rolls.
SortedMap:
A SortedMap is a Map that maintains its mapping in ascending key order. It is the Map
analogue of SortedSet. The SortedMap interface is used for apps like dictionaries and
telephone directories.
SortedMap Interface:
The SortedMap interface extends the Map interface. The SortedMap interface maintains
its entries in the ascending order, sorted either according to the natural order of the key or
according to a comparator provided while creating the SortedMap.
Object firstKey( );
Object lastKey( );
}
Methods:
Comparator comparator( ): It returns the comparator associated with the current
sorted map.
Object firstKey( ): It returns the currently lowest key in the sorted map.
Object lastKey( ): It returns the currently highest key in the sorted map.
Implementations:
Implementations are the actual data objects used to store the collections. Some of the
classes provide the full implementation and can be used. The others are abstract and are
used as starting points for creating concrete collections. The standard collection classes
are:
AbstractCollection: The AbstractCollection class provides a skeleton
implementation of the Collection interface. To implement an unmodifiable
collection, it is sufficient to extend the class and provide implementations for the
iterator and size methods. We have to additionally override the add method of the
class and the iterator returned by the iterator method must implement its remove
method in order to implement a modifiable collection.
AbstractList: The AbstractList class extends the AbstractCollection class and
provides a skeletal implementation of the List interface. To implement a
modifiable list, it has to additionally override the set and remove methods. To
implement an unmodifiable list, it would extend the class and provide
implementations for the get and size methods.
AbstractSequentialList: This class extends the AbstractList class and it is the
implementation of the List interface. It is used by a collection that uses sequential
access rather than random access to access its elements. To implement a list, it has
to extend the class and provide implementations for the listIterator and size
methods.
LinkedList: It extends the AbstractSequentialList class and implements the List
interface. It implements all the optional list operations.
ArrayList: It extends the AbstractList class and is a resizable-array
implementation of the List interface. It provides methods to manipulate the size of
the array that is used to store the list internally.
AbstractSet: It extends the AbstractCollection class and provides the skeletal
implementation of the Set interface. It doe not override any of the
implementations from the AbstractCollection class. It adds implementations for
equals and hashCode.
HashSet: It extends the AbstractSet class and implements the Set interface. It is
backed by a hash table. It offers constant time performance for the basic
operations.
TreeSet: It extends the Abstractset interface and implements the Set interface. It is
backed by the TreeMap instance. It assures that the sorted set will be in ascending
order, sorted according to the bnatural order.
ArrayList class:
It provides methods to manipulate the size of the array used to store the list internally.
The size of the array is greater than or equal to the size of the list and it can grow or
shrink dynamically as we add or remove elements to or from the list.
The constructors used are:
1. ArrayList( ): It creates an empty array list.
2. ArrayList(Collection c): It creates an array list whose elements are taken from the
Collecton c, in the order returned by c’s iterator.
3. ArrayList(int cap): It creates an empty array list whose initial capacity is specified
by cap.
LinkedList Class:
It provides a linked-list data structure. The constructors are:
LinkedList( ): It creates an empty linked list.
LinkedList(Collection c): It creates a linked list using the elements of the collection c.
void addLast(Object a): It inserts the object a at the end of the current list.
Object getFirst( ): It returns the first element in the current list.
Object removeFirst( ): It removes the first element from the current list.
Object removeLast( ): It removes the last element from the current list.
HashSet Class:
It creates a collection that uses a hash table for storage. It offers constant time
performance for basic operations. The constructors are:
HashSet( ): It creates an empty hash set.
HashSet(Collection c): It creates a hash set whose elements are taken from the
collection c.
HashSet(int cap): It creates a hash set with the initial capacity specified by cap.
HashSet(int cap, float load): It creates a hash set with the initial capacity specified by
cap and the load factor specified by load.
TreeSet Class:
It is used for storing large amounts of sorted information that must be retrieved quickly.
The constructors are:
TreeSet( ): It creates an empty trees set. Its element will be sorted in the ascending
order according to the natural order of the elements.
TreeSet(Collection c): It creates a tree set whose elements are taken from the
collection c.
TreeSet(Comparator com): It creates a tree set whose elements are sorted according to
the comparator com.
TreeSet(SortedSet s): It creates a tree set whose elements are taken from the sorted set
s.
HashMap Class:
It provides all of the optional map operations. It also allows null values and null key.
Initial capacity and the load factor are the two parameters that affect the instance of the
HashMap. The initial capacity determines the capacity of the hash table when it is
created. The load factor determines how full the hash table can become before its
capacity is automatically increased. It implements the method of its predecessors. It does
not contain any method of its own.
The constructors are:
HashMap( ): It creates an empty map with the default capacity and load factor.
HashMap(int cap): It creates an empty map with the capacity specified by cap and
default load factor.
HashMap(int cap, float load): It creates an empty map with the capacity specified by
cap and the load factor specified by load.
HashMap(Map m): It creates a map with the mappings specified by the map m.
TreeMap Class:
It maps in the ascending key order. The constructors are:
TreeMap( ): It creates an empty tree map. The elements of the tree map will be sorted
according to the natural order of its keys.
TreeMap(Comparator com): It creates an empty tree based map. The elements of the
tree map will be sorted based on the comparator com.
TreeMap(Map m): It creates a tree map whose elements are taken from the Map m
and sorted based on the natural order of its keys.
TreeMap(SortedMap s): It creates a tree map whose elements are taken from the
sorted map s and sorted in the same order as that of s. This class implements the
methods of its predecessor and does not define any additional methods of its own.
Algorithms:
It is static method within the Collection class. These methods include methods for
sorting, searching, shuffling, data manipulation, etc. The first argument of this method is
the collection on which the operation is performed. Many of this method operate on the
List interface and a couple of them operate on arbitrary objects of the Collection
interface. When it is comparing incompatible types, this method throw
ClassCastException. To modify an unmodifiable collection, this method throws
UnsupportedOperationException.
The methods are:
int binarySearch(List l,Object a): It searches for the object a in the list l using binary
search algorithm and returns the position of a in the list. If the object is not found, it
returns -1. The collection has to be sorted before this method is executed.
int binarySearch(List l, Object a, Comparator com): It searches for the object a in the
list l according to the comparator c and returns the portion of a in the list. If the object
is not found, it returns -1.
void copy(List l1, List l2): It copies the elements of the list l2 to list l1.
List nCopies(int n, Object a): It returns n copies of the object a in an immutable list.
void reverse(List l): It reverses the sequence of the elements in the list l.
void shuffle(List l, Random rand): It shuffles the list l according to a default source of
randomness.
void sort(List l): It sorts the elements of the list l in the ascending order according to
the natural order according to the natural order of its elements.
void sort(List l, Comparator com): It sorts the elements of the list l according to the
order specified by the comparator com.
Unmodifiable Methods: It returns the views of their corresponding collections. The return
values of the unmodifiable methods cannot be modified. These views are helpful when a
process that uses the collection should not be allowed to modify it.
The Collection class defines two immutable fields. One of them is empty list named
EMPTY_LIST and the other one is an empty set named EMPTY_SET.
Vector:
The Vector container was the only self-expanding sequence in Java. It implements a
growable array of objects. Its component can be accessed using an integer index. Each
Vector maintains a capacity and capacityIncrement. The capacity is always greater than
or equal to the vector size. Vector defines its own methods for adding and retrieving
objects from the container. The difference between a Vector and an ArrayList is that the
methods of the Vector class are synchronized, that is, they can be accessed from multiple
threads.
The constructors are:
Vector( ): It creates an empty vector. Its size is 10 and capacity increment is 0.
Vector(int cap): It creates an empty vector with initial capacity specified by cap and
capacity increment 0.
Vector(int cap, int inc): It creates an empty vector with initial capacity specified by
cap and capacity increment increment specified by inc.
Dictionary:
It is an abstract class which maps keys to values and operates similar to Map. Every key
and value is an object in the class. Each key is mapped to at most one value. It contains
only one constructor, that is: Dictionary( ).
Methods are:
Enumeration elements( ): It returns an enumeration containing the elements in the
current dictionary.
Object get(Object a): It returns the value to which the object a is mapped. If the object
a is not present in the dictionary, then a null object is returned.
boolean isEmpty( ): It checks whether the current dictionary contains any key.
Enumeration keys( ): It returns an enumeration containing the keys in the current
dictionary.
Object put(Object key, Object val): It maps the object key to the object val in the
current directory.
Object remove(Object a): It removes the key specified by the object a and its value
from the current dictionary and returns the value associated with a.
int size( ): It returns the number of entries in the current dictionary.
Hashtable:
It stores key-value pairs in a hash table. It must specify the key and the value to be
mapped to that key. The key is hashed and the hash code is used as the index of the
position at which the value is stored. The object of the Hashtable class must override the
hashcode( ) and equals( ) methods of the Object class. The hashCode( ) method is used to
convert the key to its equivalent hash code, and equals( ) method is used to compare two
objects.
The constructors are:
Hashtable( ): It creates an empty hash table with default capacity and load factor.
Hashtable(int cap): It creates an empty hash table with the initial capacity specified
by cap and default load factor.
Hashtable(int cap, float load): It creates an empty hash table with the initial capacity
specified by cap and the load factor specified by load.
Hashtable(Map m): It creates a hash table whose mappings are those of the map m.
Enumeration:
It is the only one legacy interface. It defines methods, which help us to enumerate the
elements in a collection of objects. It has been superceded by Iterator.
The methods are:
boolean hasMoreElements( ): It checks whether the enumeration contains more
elements.
Object nextElement( ): It returns the next element of the enumeration. If there are no
more elements to retrieve then it throws NoSuchElementException.
Properties:
It is a subclass of Hashtable. It is used to maintain lists of values in which the key is a
String and the value is also a String. The Properties class is used by many other Java
classes. It represents a persistent set of properties. Each key and its value in the property
list is a string. It can also contain another property list as its “defaults”. The default
property list will be searched if the key is not present in the current property list. This
class is used by many other Java classes.
The constructors are:
Properties( ): It creates an empty property list with no default values.
Properties(Properties def): It creates an empty property list with the default
values specified by def.
The Methods are:
String getProperty(String key): It returns the value associated with the key in the
current property list.
String getProperty(String key, String prop): It returns the value associated with
the key in the current property list.
void list(PrintStream out): It sends the property list to the output stream specified
by out.
void list(PrintWriter str): It sends the property list to the output stream specified
by str.
void load(InputStream in): It inputs a property list from the input stream specified
by in.
Enumeration propertyNames( ): It returns an enumeration of the keys in the
current property list.
Object setProperty(String key, String val): It calls the hashtable method put to
associate the value specified by val with the key specified by val.
void store(OutputStream out, Sring desc): It writes the property list in the
Properties table to the output stream specified by out.
Other Classes of the Util Package:
The util package is fundamental to any platform. It provides classes and interfaces. These
classes and interfaces help the programmers to fulfil the wide range of their programming
needs. It also contains collection framework, legacy collection classes, event model, date
and time facilities, internationalization, and utility classes like BitSet, Calendar, String
tokenizer, Date, Locale and Random.
String nextToken( ): It returns the next token from the string tokenizer.
String nextToken(String delim): It returns the next token as a String and sets the
delimiters string.
Object nextElement( ): It returns the same value as the nextToken method, except
that its declared return value is Object rather than String. It exists so that this class
can implement the Enumeration interface.
BitSet:
This class creates a special type of array that holds bit values. It can increase the size as
needed. It makes is similar to a vector of bits. Usually it is use to efficiently store many
“on/off” information. Its efficiency was only seen in size not for speed. The BitSet
container is slightly slower than using an array of some native type. The minimum size of
the BitSet is 64 bits long. The constructors are:
BitSet( ): It creates a default object.
BitSet(int size): It allows the user to specify its initial size.
The methods are:
void and (BitSet bitSet): It adds the contents of the invoking BitSet object with
those specified by bitSet. The result is placed into invoking object.
void andNot (BitSet bitSet): For each 1 bit in bitSet , the corresponding bit in the
invoking BitSet is cleared.
boolean get (int bitIndex): It returns the current state of the bit at the specified
index.
int hashCode( ): It returns the hash code for the invoking object.
String toString( ): It returns the string equivalent of the invoking BitSet object.
Void xor (BitSet bitSet): XORs the contents of the invoking BitSet object with
that specified by BitSet. The result is placed into invoking object.
Date:
The Date class encapsulates the current date and time. It represents a specific instant of
time, with millisecond precision. The Date class has two additional functions. It allows
the interpretation of dates as year, month, day, hour, minute and second values. It also
allowed the formatting and parsing of date strings. The constructors are:
Date( ): It allocates a Date object and initializes the object with current date and
time, so that it represents the time at which it was allocated, measured to the
nearest millisecond.
Date(long millisec): It accepts only one argument that equals the number of
milliseconds that have elapsed.
Date Comparison:
There are three ways to compare any two Date objects. First way is by using getTime( )
to obtain the number of milliseconds that have elapsed. The second way is by using
before( ), after( ) and equals( ). The third way is by using compareTo( ) method, which is
defined by the Comparable interface and implemented by Date.
Calendar:
The Calendar class provides a set of methods that allows the user to convert a time in
milliseconds to a number of useful components. This method provides no public
constructors. It is an abstract base class for converting between a Date object and a set of
integer fields such as year, month, day, hour and so on. A Date object represents a
specific instant in time with millisecond precision. It defines several protected instance
variables. The method areFieldSet is a boolean that indicates if the time components have
been set. The fields is an array of integers that holds the components. The isSet is a
Boolean array that indicates if a specific time component has been set.
The methods are:
Abstract void add (int which, int val): It adds val to the time or date component
Specified by which. To substract, add a negative value, which must be one of the
fields defined by calendar, such as calendar.HOUR.
final void clear ( int which): Zeros the time component specified in the invoking
object.
final int get( int calendarField): It returns the value of one component of the
invoking object. The component is indicated by calendarField.
static locale[ ]getAvailableLocales( ): It returns an array of Locale objects that
contains the locales for which calendars are available.
static Calendar getInstance (TimeZone tz): It returns a Calendar object for the
TimeZone specified by tz. The default locale is used.
static Calendar getInstance (TimeZone tz, Locale locale): It returns a Calendar
object for the TimeZone specified by locale. The default timezone is used.
final void set(int year, int month, int dayOfmonth, int hours, int minutes, int
seconds): It sets various date and time components of the invoking object.
TimeZone:
It is another time-related object. The TimeZone allows the user to work with TimeZone
offsets from Greenwich Mean Time(GMT). TimeZone also computes daylight saving
time. It supplies only the default constructor.
The methods are:
Object clone( ): It returns a TimeZone-specific version of clone( ).
Static String [ ] getAvailableIDs (int timeDelta): It returns a TimeZone object
that represents the names of all TimeZones that are timedelta offset from GMT.
Static TimeZone getDefault( ): It returns a TimeZone object that represents the
default timezone used on the host computer.
abstract int getOffset (int era, int year, int month, int day of month, int day of
week, int millisec): It returns the offset that should be added to GMT to compute
local time.
Abstract int getRawOffset( ): It returns the raw offset that should be added to
GMT to compute local time.
void set Time(long time): It sets the time and date as specified by time.
static void setDefault(TimeZone tz): It sets the default TimeZone to be used on
this host.tz is a reference to the TimeZone object to be used.
abstract void setRawOffset(int millis): It sets the offset in milliseconds from
GMT.
abstract boolean useDaylightTime( ): It returns true if the invoking object uses
daylight saving time.
Simple TimeZone:
It is a subclass of the TimeZone class. It implements TimeZone’s abstract methods an
allows us to work with TimeZones for a Gregorian calendar. The constructors are:
SimpleTimeZone (int timeDelta, String tzName)
SimpleTimeZone (int timeDelta, String tzId, int dstMonth0, int datDayInMonth0,
int dstDay0, int time0, int dstMonth1, int dstDayInMonth1, int dstDay1, int
time1)
SimpleTimeZone(int timeDelta, String tzld, int dstMonth0, int dstDayInMonth0,
int dstDay0, int time0, int dstMonth1, int dstDayInMonth1, int dstDay1, int time1,
int dstDelta)
Locale:
The Locale class is used to produce objects that describe a geographical or cultural
region. The format used to display dates, times and numbers are different in various
regions. The Locale class defines the following constants that are useful for setting the
current locales. The constructor is:
Locale( ): It would represent a specific places.
Random:
The Random class is a generator of pseudorandom numbers. These are called
pseudorandom numbers because they are simply uniformly distributed sequences. The
constructors are:
Random( ): It creates a number generator that uses the current time as the starting value.
Random(long seed): It allows the user to specify a seed value manually. If the user
initializes a Random object with a seed, then it would define the starting point for random
sequence. If the user uses the same seed to initialize another Random object, the user has
to extract the same random sequence. To generate different sequences, different seed
values have to be specified. The easiest way to do is to use the current time to seed a
Random object, thus reducing the possibility of getting repeated sequences.
The Methods are:
Boolean nextBoolean( ): It returns the next boolean random number.
void nextBytes(byte vals[ ]): It fills vals with randomly generated values.
Int nextInt(int n): It returns the next int random number within the range zero to n.
long nextLong( ): It returns the next long random number.
void setTime(long time): It sets the time and date as specified by time, which
represents the time elapsed in milli-seconds from midnight.
void setSeed (long newSeed): This method sets the seed value.
Observable:
The observable class is used to create subclasses that other parts of the program can
observe. When an object of such a sub class undergoes a change, observing classes are
notified. This class would implement the Observer interface, which defines update( )
method. The update( ) method is called when an observer is notified of a change in an
observed object. An object that is being observed must follow the rules. First, if is has
changed, it must call setChanged( ). Second, when it is ready to notify observers of the
change, it must call notifyObservers( ). This causes the update( ) method in the observing
object(s) to be called.
notifyObserver( ) has two forms: One that takes an argument and one that does
not take an argument. If the user calls notifyObservers( ) with an argument, this
object is passed to the observer’s update( ) method as its second parameter.
Otherwise, null is passed to update( ). The user can use the second parameter for
passing any type of object that is appropriate for the application.
The methods are:
void addObserver (Observer obj): It adds to the list of objects observing the
invoking object.
Protected void clearChanged ( ): It returns the status of the invoking object to
“unchanged”.
int countObservers( ): It returns the number of objects observing the invoking
object.
void deleteObserver (Observer obj): It removes obj from the list of objects
observing the invoking object.
void notifyObservers (Object obj): It notifies all the observers that it has changed
by calling update( ).obj is passed as an argument to update( ).
Observer Interface:
The user must implement an observable interface to observe an observable object. It
defines only one method:
void update(Observable observob, Object arg)
observOb is the object being observed, and arg is the value passed by notifyObservers( ).
The update( ) method is called when a change in the observed object takes place.
Summary:
A collection is an object that groups multiple elements into a single unit. A collections
framework is a unified architecture for representing and manipulating collections.
Collection frameworks are composed of three things. They are interfaces,
Implementations and Algorithms. The collection interface is at the top of the hierarchy. It
enables us to work with groups of objects. The List interface extends the Collection
interface and handles sequences. The Set interface also extends the Collection interface
and handles sets. The extension of the Set interface is the SortedSet interface.
Implementations are the actual data objects used to store the collections. Algorithms are
static methods within the Collections class.
These methods include methods for sorting, searching, shuffling, data manipulation, etc.
The legacy classes are Dictionary, HashTable, Properties, Stack and Vector. The legacy
interface is the Enumeration interface. StringTokenizer implements the Enumeration
interface. A BitSet class creates a special type of array that holds bit values. This array
can increase in size as needed. This makes it similar to a vector of bits. The Date class
encapsulates the current date and time. The abstract Calendar class provides a set of
methods that allows the user to convert a time in milliseconds to a number of useful
components. GregorianCalendar is a concrete implementation of a Calendar that
implements the normal Gregorian calendar. The Observable class is used to create
subclasses that other parts of the program can observe.
Windows in AWT:
The AWT defines windows according to a class hierarchy that adds functionality and
specificity with each level. The two most common windows are those derived from
Panel, which are used by applets and those derived from Frame, which creates a Standard
window.
The component class is the superclass, of AWT classes which implements graphical user
interface controls. These components include windows, dialog boxes, buttons, labels, text
fields and other common GUI components. The Component class provides a common set
of methods that are used by all these subclasses, including methods for working with
event handlers, images, fonts, and colors.
Component contains many GUI-related subclasses, its container subclass is used to define
components that can contain other components. It provides methods for adding,
retrieving, displaying, counting and removing the components that it contains. The
container class also provides methods for working with layouts. The layout classes
control the layout of components within a container. The container class has three major
subclasses: Window, panel and scrollpane. Window provides a common superclass for
application mein windows (Frame objects) and Dialog windows.
Java programs are classified into two groups namely applications and applets. Java
applications do not require a browser to run whereas applet requires a browser to run.
They can be created like any normal programming language programs.
Applet:
An applet is a Java class that can be downloaded and executed by the web browser. It is a
specific type of Java technology. An applet runs in the environment of the web browser.
An applet is a dynamic and interactive program that can run inside a web page displayed
by a Java-capable browser such as HotJava or Netscape. HotJava Browser is a World
Wide Web Browser used to view Web pages, follow links and submit forms. It can be
downloaded and play applets on our system.
Running an Applet:
Example:
http://somelocation(new.html)
Here the browser loads the URL.
Then browser loads HTML document(HTML file)
<HTML>
<APPLET CODE….>
</APPLET>
Creation of an Applet:
Open a new file and type the following code:
import java.awt.*;
public class MyApplet extends java.applet.Applet
{
public void paint(Graphics g)
{
g.drawString(“My applet”, 100, 40);
}
}
Save the file as MyApplet and compile it using javac. This will result in the creation of
a .class file for the same.
Now create an HTML file
<html>
<head>
<body>
<APPLET CODE = “MyApplet.class” WIDTH = 400 HEIGHT = 400>
</APPLET>
</body>
</head>
</html>
Save this file as MyApplet.html in the same directory as that of the .java file.
Run the file.
Applet Tag:
The Applet tag is used to start an applet from both an HTML document and from an
applet viewer. The syntax for the standard Applet tag is:
<APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
[WIDTH = pixels HEIGHT = pixels]
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[<PARAM NAME = AttributeName VALUE = AttributeValue>]
[<PARAM NAME = AttributeName 2 VALUE = AttributeValue>]
….
</APPLET>
The <applet> tag is used to start the applet from inside the HTML document as well as
from the appletviewer. Each <applet> tag is executed in separate windows by the
appletviewer while the Java capable browser is capable of executing numerous applets
inside a single web page. This code instructs the browser or the applet viewer to load the
compiled Java applet, namely the .class file. The size of display of the applet is initialized
using the WIDTH and HEIGHT tags. To indicate the end of the applet, </applet> tag is
used. It is essential to end the applet using the tag, otherwise it will not be executed.
CODEBASE:
CODEBASE is an optional attribute that specifies the base URL of the applet code,
which is the directory that will be searched for the applet’s executable class file.
CODE:
It is a required attribute that gives the name of the file containing user applet’s
complied .class file. This file is relative to the code base URL of the applet, which is the
directory that the HTML file was in.
ALT:
The ALT tag is an optional attribute used to specify a short text message that should be
displayed. This attribute is utilized if the browser understands the <Applet> tag but is
unable to display the applet.
NAME:
NAME is an optional attribute used to specify a name for the applet instance. To obtain
an applet by name, use getApplet( ), which is defined by the AppletContext interface.
WIDTH AND HEIGHT:
WIDTH AND HEIGHT are required attributes that give the size (in pixels) of the applet
display area.
ALIGN:
ALIGN is an optional attribute that specifies the alignment of the applet with these
possible values: left, right, top, bottom, middle, baseline, texttop, absmiddle and
absbottom.
VSPACE AND HSPACE:
These attributes are optional. VSPACE specifies the space, in pixels, above and below
the applet. HSPACE specifies the space, in pixels, on each side of the applet.
PARAM NAME AND VALUE:
The PARAM tag allows the user to specify applet specific arguments in an HTML page.
Applets access their attributes with the getParameter( ) method.
USING APPLETVIEWER:
The applet code can be run using an appletviewer. In this case, the appletviewer is typed
at the command prompt followed by the name of the Java file. The general format is:
C> appletviewer filename.java
The applet tag has to be included in the Java file itself and has to be commented.
APPLET HIERARCHY:
All applets are the subclasses of the class Applet. Applet class belongs to the package
java.applet. Therefore, all user-defined applet must import java.applet package. Applet
extends from a class called Panel present in the package java.awt. This class provides
support for Java’s windows-based graphical user interface. Thus, Applet provides all of
the necessary support for window-based activities. The class Component in the java.awt
package has various visual component attributes. The subclass of Component class
namely the Container class contains methods for including various other container
objects. The immediate super class of the Applet class namely Panel class is basically a
window title bar and menu bar.
Passing Parameters to an Applet:
To pass parameters to an applet, two things are required- a special parameter tag in the
HTML file and the code in the applet to parse those parameters. The special parameter
tag in the HTML file is <PARAM>. This has two attributes namely NAME and VALUE.
The init( ) method of the applet, contains a method called getParameter ( ). This method
takes one argument – the string representing the name of the parameter being looked for
and returns a string containing the corresponding value of that parameter. If this method
is required to return types other than strings, it has to be converted explicitly.
The start( ) method: It is executed after the init( ) method. It serves as the
execution entry point for an applet, when it is initially executed and restarts the
applet.
The stop( ) method: It is used to halt the running of an applet. It provides the
capability to stoop( ) an applet’s execution when the Web page containing the
applet is no longer active.
The destroy( ) method: It is used to free the memory occupied by the variables
and objects initialized in the applet. Any clean up activity that needs to be
performed can be done in this method. The destroy( ) method applies only to
applets whereas the finalize( ) method is generally used to clean up a single
object. It is used at the end of an applet’s life cycle to perform any termination
processing. The stop( ) method is always called before destroy( ).
Graphics and Images: In Java, all graphics operations can be performed using the
java.awt package. This package contains various classes and methods for painting
graphics and images.
The Graphics Class:
This method is used for drawing strings, lines, rectangles and other shapes defined in the
Graphics class, which is a part of the java.awt package. To draw figures in Java, one
should understand java’s coordinate system which is a scheme for identifying every
possible point on the screen. Any shape or diagram can be displayed on the screen by
specifying the coordinates.
Methods:
void drawBytes (byte[] data, int offset, int length, int x, int y): It draws the text
given by the specified byte array, using the graphics graphics context’s current
font and color, data- the data to be drawn, offset- the start offset in the data,
length- the number of bytes that can be drawn, x- the x coordinates of the baseline
of the text, y- the y coordinates of the baseline of the text.
void drawChars (char[] data, int offset, int length, int x, int y): It draws the text
given by the specified character array, using this graphics context’s current font
and color.
abstract void drawstring (String str, int x, int y): It draws the text given by the
specified string, using this graphics context’s current font and color.
While drawing a polygon, the number of x coordinates and y coordinates must be equal.
It may be difficult to find the 3D effect of the 3D rectangles due to very small line width.
Methods are:
• getImage ( URL, String) : It loads an image from an URL. URL specifies the
location from which the image is to be loaded. String is usually the name of the
image file.
• drawImage (Image, x, y, imageObserver): It draws an image at the given
coordinates. Image object refers to the picture to be drawn x, y are the coordinates
where the image is to be drawn. ImageObserver is usually the applet itself.
The parameter URL (Uniform Resource Locator) in the getImage( ) method refers to
location where the image is stored. The Applet class provides a helper function
getCodeBase( ) which returns the path (URL) of the .class file. So the method calls the
gif from the directory where the file is stored.
The getImage( ) function loads an image from file and stores it in the instance variable
image. The paint( ) method of the applet, displays the image at coordinates using the
drawImage( ) method. The parameter this passed in the drawImage( ) function call acts as
the ImageObserver which monitors the drawing of the image. For most methods related
toimage, an image observer needs to be passed. The Image class provides two methods
getWidth( ) and getHeight( ) to find the width and height of an image. The showStatus
method is used to display the width and height of the image.
Creating Images:
Java allows the creation of off screen images. The createImage( ) method of the Applet
class creates a blank image of the specified dimensions. To draw on the image surface,
the graphics object of the image is specified.
The getGraphics( ) method of the Image class returns the graphics context of the image.
This Graphics object can be used for drawing on the image surface. Drawings made using
the Graphics object are rendered on the image surface and not on the screen. When the
drawing is complete, the image can be flipped on the screen using the drawImage( )
method.
The Methods are:
• create Image(width, height): It creates a new image of specified width and height.
• get Graphics( ): It gets the graphics context of the image. The graphics object can
be obtained can be used for drawing on the image surface.
Loading an Image:
The getImage( ) method defined by the applet class has the following forms to load an
image:
• image getImage (URL url): It returns an Image object that encapsulates the image
at the location specified by url.
• image getImage (URL url, String imageName): It returns an Image object that
encapsulates the image found at the location specified by url and having the name
specified by imageName.
Displaying an Image:
Image can be displayed by using drawImage( ), which is a member of the Graphics class.
Boolean drawImage(Image imgObj, int left, int top, ImageObserver imgOb).
ImageObserver:
ImageObserver is an interface used to receive notification as an image is being generated.
ImageObserver defines only one method: ImageUpdate( ).
Double Buffering:
Images are useful for storing pictures and for offscreen drawing surfaces. This allows
rendering any image. Drawing a complicated image could take several milliseconds seen
by the user as flashing or flickering. Use of an offscreen image to reduce flicker is called
double buffering, because the screen is considered a buffer for pixels and the offscreen
image is the second buffer, where pixels can be prepared for display.
Media Tracker:
A Media Tracker is an object that will check the status of an arbitrary number of images
in parallel. To use Media Tracker, a new instance is created and addImage( ) method is
used to track the loading status of an image.
Media Tracker is used when loading a group of images. If all of the images are not
downloaded, something else can be displayed to entertain the user until the images get
downloaded.
Clipping:
It is a technique by which drawing area can be restricted to a small portion of the screen.
A clipping region is an area where drawing is allowed. Any drawing outside the clipping
region is clipped off and not displayed. The graphics class method clipRect( ) creates
rectangular clipping regions. Once the clipping rectangle is set, any drawing done outside
the rectangular region is clipped off. If a call to a graphics method results in a drawing
that extends outside the clipping rectangle, only that part of the drawing that lies inside
the clipping region is displayed.
Animation:
Animation is a technique by which an object is moved on the screen. The object to be
moved can be simple drawing or a complex image loaded from an image file. This object,
in animation jargon, is called a frame of animation.
Animation involves the following steps:
• The object is drawn at a location on the screen.
• The object’s location is changed – the object at the old location is erased.
• The object is repainted at the new location.
Animation, involves a loop in which the object gets painted, erased and again repainted.
The loop starts when the animation begins and lasts till the object reaches the destination.
Summary:
An applet is a dynamic and interactive program that runs inside a Web page displayed by
a Java capable browser. This can also be executed using the appletviewer application.
Parameters can be passed to an applet by using the param tag, which has two attributes
NAME and VALUE. The major activities involved in an applet are the initialization and
creation of objects and variables, starting, painting, stopping and destroying the created
objects and variables. There are methods available to do all these activities. The
Graphics, Color and Font classes help in drawing figures, setting colors and fonts. The
getImage( ) method of the Applet class is used to load an image from an image file. The
drawImage( ) method is used to display images either at normal size or scaled to different
sizes. The createImage( ) method of the Applet class creates a blank images of specified
dimension. Clipping is a technique by which drawing area is restricted to a small region.
Animation is a technique by which an illusion of an object moving on the screen is
created.
JFC
The Java Foundation Class was developed to address the AWT. Its visual
components extend the AWT container class. The methods contained in the Component
and Container classes that AWT are valid for JFC visual classes. The AWT user interface
classes are now superseded by classes provided by the JFC. The support classes play an
important part in JFC applications. AWT support classes, those that do not create a native
window are not replaced by JFC classes. JFC includes user interface called the Swing
components.
Swing:
Swing component is a graphical user interface (GUI) development. These components
are a collection of lightweight visual components. Swing components contain a
replacement for the heavy weight AWT components as well as complex user-interface
components. It contain pluggable look and feel (PL&F). This allows all applications to
run with the native look and feel on different platforms. PL&F allows applications to
have the same behavior on various platforms. JFC contains operating system neutral look
and feel. Swing components do not contain peers. Swing components allow mixing AWT
heavyweight and Swing lightweight components in an application.
Lightweight components can have transparent pixels whereas heavyweight components
are always opaque. Lightweight components can be non-rectangular while heavyweight
components are always rectangular.
It is a JavaBean Compliant. This allows components to be used easily in a Bean aware
application building program. The root of the majority of the Swing hierarchy is the
JComponent class. This class is an extension of the AWT container class.
Swing components comprise of a large percentage of the JFC release. The Swing
component toolkit consists of over 250 pure Java classes and 75 interfaces contained in
about 10 packages. They are used to build lightweight user interfaces. Swing consists of
user interface (UI) classes and non-user interface classes. The non-UI classes provide
services and other operations for the UI classes.
Packages are:
javax.swing.plaf.basic: It contains classes that define the default look and feel of swing
components.
javax.swing.border: It contains the border interface and their related interfaces.
javax.swing.plaf.multi: It consists of multiplexing UI classes.
javax.swing.plaf: It consists of classes that provide swing components with pluggable
look and feel capabilities.
javax.swing.table: It contains classes and interfaces specific to the swing table
component.
javax.swing.text: It contains classes and interfaces for text manipulation components
contained in the swing toolkit.
javax.swing.tree: It contains classes that are used with the swing tree component.
javax.swing.undo: It contains interfaces and classes required to implement the undo
functionality.
Wide Variety of Components: Class names that start with ‘J’ are the components that are
added to an application. The remaining files in the swing package contain the utility
classes and interfaces that the components use to function.
Pluggable Look and Feel:
The user can select a look and feel and this can be plugged in. An interface made of
Swing components can look like a Win32 app, a Motif app or a Mac app. It can use the
new look and feel. Any user can select the pluggable look and feel already present or
develop their own pluggable look and feel. The plaf package includes the standard
‘Pluggable Look And Feel’ classes.
MVC Architecture:
It is used throughout the Swing component set. The View and Controller parts of the
architecture are combined in the component. Each component has an associated Model
class and an interface it uses. The user can provide their own data-model for a component
by subclassing the Model class or by implementing the appropriate interface.
Action Objects:
Action-interface objects provide a single point of control for program actions. When the
Action object is disabled, the GUI items that reference it are automatically disabled. The
Action interface extends ActionListener, specifying an enabled property as well as
properties for text-descriptions and graphic icons.
Keystroke Handling:
The JComponent architecture makes it easy to handle keyboard events in nested
components. A user can register interest in a particular combination of keystrokes by
creating a KeyStroke object and registering it with the component. When the keystroke
combination is registered along with its associated action, certain conditions have to be
specified.
The conditions include are
• The component has the focus.
• A child or grandchild of the component has the focus.
• The window in which the component is present has the focus.
Nested Containers:
Swing was designed to manage nested containers gracefully. The main ‘heavyweight’
containers as well as the major ‘lightweight’ containers all delegate their operations to a
JRootPane. This commonality produces a high degree of regularity in container nesting.
The JRootPane class uses a JLayeredPane to manage a content pane and an optional
menu bar in a way that is virtually transparent to the user. It also provides for a glass pane
—a single pane that can overlap multiple containers and can be used for drawing or to
intercept mouse actions.
Virtual Desktops:
The JDesktopPane and JInternalFrame classes can be used to create a virtual desktop, or
‘multiple document interface’. A JInternalFrame can be specified as iconizable,
expandable, or closable, while the JDesktopPane provides real estate for them to operate
in.
Compound Borders:
Insets can be specified with a blank border. Here, many border styles are available, which
can be combined to create compound borders.
Customized Dialogs:
The JOptionPane class provides a variety of static methods that the user can invoke to
create and display both message dialogs and user-choice dialogs in a variety of formats.
The message displayed in the dialog can be a string, a string-generating object, or an
arbitrary component. Choice buttons can be replaced with components that are specified
for user selections.
Java2D:
A set of tools has been introduced for dealing with two dimensional drawings and
images. These extensions include provision for colorspaces, text, line art and printing.
JComponent:
The JComponent class is the root of the visual component class hierarchy in the JFC. The
visual components are known as the “J” classes. The functionality contained in the JFC.
The JComponent class is a repository of functionality for all visual components. The
JComponent class is at the top of the hierarchy of all contained in the JFC.
Client Properties:
A piece of information that can be attached to any JFC component is known as the client
property. The property basically consists of a name – value pair. The name is a key that
uniquely identifies the value for a particular instance. These properties are used internally
by the JFC in many situations. Components that extend JFC visual components can store
data in client properties as well as arbitrary code that create and use instances of JFC
visual components. An arbitrary object can be associated with a JFC visual component
instance by using the putClientProperty method that is present in the JComponent class.
When the property is placed on the component, a key is associated with the object. The
client property can be obtained later using the getClientProperty method and the key used
when adding the property. Any number of client properties can be added to a component.
Each property has a unique key.
When a client property is set, the PropertyChange event is fired by the component that
contains the property. The name of the property change event is the value returned from
the toString method key used to store the client property. This provides a versatile
mechanism for attaching the data to a visual component and allowing other objects to
look for changes in the property.
ToolTip Support:
ToolTips are the pop up windows common in user interfaces that present the user with
short informative messages. These are also known as flyover help. The JComponent class
contains a client property for ToolTips. The ToolTips is stored as a client property rather
than a member variable to save space. All JComponent instances do not contain
ToolTips.
Border Property:
The JComponent class contains a Border property. This refers to a class that implements
the Border interface. Painting of the border is handled by the component when a border is
specified for the component. When a border has been set for a JComponent instance, the
size of the border is used as the insets property for that component.
Size Preferences:
AWT components contain the methods getPreferredSize, getMinimumSize and
getMaximumSize to aid layout managers arrange containers. JComponent adds the
setPreferredSize, setMinimumSize and setMaximumSize methods for setting the sizes. If
one of the sizes has been set via one of these methods, the associated get method returns
the size rather than computing the size based on state. This adds flexibility.
Keystroke Handling:
The JComponent class provides keystroke-handling functionality. These methods provide
much higher level interface than processing individual keystroke events in a subclass of
JComponent. The registerKeyboardAction method is used to bind a keystroke to an
ActionListener. Registering enables the keyboard action. Internally,the JComponent class
stores a Hashable of registered keyboard actions, as a client property. There are three
situations i.e., WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW,
WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, in which the keystroke event
could occur.
The KeyStroke instance contains its key character, key code, modifiers and a flag for key
pressed or released state. The key character is the character representation of the
KeyStroke instance. The key code is the integer code defined in the keyEvent class. The
modifier field represents any modifier for the KeyStroke. The final field represents the
KeyStroke instance as a key pressed or key released keystroke. KeyStroke instances are
immutable. This allows the instances to be cached and shared.
Scrolling Support:
JFC provides traditional scrolling of any component by using the JscrollPane and
Jviewport classes. Once the component is placed in a viewport contained in a scroll pane,
scrollbards can be used to translate the view of the component. The JComponent class
also supports autoscrolling. When the JComponent instance has autoscrolling enabled,
the component will scroll when the mouse is dragged in the component.
Double Buffering:
All JFC components are lightweight components and hence display flashing is a major
concern, making double buffering a necessity. JComponent class does it in a memory
efficient way.
JComponent provides the ability to specify transparency of components, paint parts of
components, and with a pluggable look and feel.
Containers:
JFC has components called containers. Container is used to hold other
components. Some of the containers are general and some are used for specific purposes.
The advantage of containers is that other containers can be added to them. JPanel is the
simplest of JFC containers. It extends JComponent. The Box class is a container
component that contains a BoxLayout. The box class extends Container class.
JLayeredPane is used for controlling components that overlap. It is the parent class for
JDesktopPane. JToolBar is another container that can be dragged around inside its
parent container.
JPanel
JPanel class is provided to give a concrete container class. JPanel inherits the
features contained in the JComponent class.
The various constructors that can be used to create a Jpanel are given below:
• Jpanel()
• Jpanel(boolean isDoubleBuffered)
• Jpanel(LayoutManager layout)
• Jpanel(LayoutManager layout, boolean isDoubleBuffered)
• getAccessibleContext()
• getUIClassID()
• paramString()
• updateUI()
Example:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
class panel extends JFrame {
public panel() {
setTitle("Box 1");
JPanel contentpane = (JPanel)getContentPane();
contentpane.setLayout(new GridLayout());
JButton ok = new JButton("OK");
contentpane.add(ok);
JButton cancel = new JButton("CANCEL");
contentpane.add(cancel);
}
Output:
Box Class
This is a light weight container that uses a BoxLayout object as its Layout
manager. The Box class can create several kinds of invisible components that affect
layout: glue, struts, and rigid areas. The component positions could be controlled by the
glue components. If a fixed amount of space is required between components, then the
strut could be used.
When it is configured to align components along the y-axis adding components to
the Box is like stacking objects in a box. The Box class also contains several static
methods that create invisible components to help control the layout of the container. It
does not extend the JComponent and hence the properties of this class are not inherited.
Since the components are placed next to each other, the container appears
cramped. This could be avoided by adding invisible components to the container. The
Box class contains static methods that return invisible components, which could be used
to arrange components on the container.
There are three types of invisible components. They are:
• Rigid
• Glue
• Struts
Example:
The following examples illustrates the usage of the BoxLayout layout manager:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
try{
setTitle("Box 1");
JPanel contentpane = (JPanel)getContentPane();
contentpane.setLayout(new BorderLayout());
Box mainbox = new Box(BoxLayout.Y_AXIS);
JButton ok = new JButton("OK");
contentpane.add("North",ok);
JButton cancel = new JButton("CANCEL");
contentpane.add("South",cancel);
myadapter myapp = new myadapter();
addWindowListener(myapp);
}
catch(Exception e)
{
System.out.println(e);
}
}
JRootPane:
The fundamental component in the container hierarchy is the JRootPane. In the
same way, JComponent is fundamental to the JFC/Swing components. JRootPane is
fundamental to the JFC/Swing window, frame and pane containers. However while other
classes use inheritance to take advantage of JComponent’s capabilities, the container
classes delegate operations to a JRootPane instance.
This is a unique component with a well-defined role. It acts as only a child for
JWindows. Jdialogs, JFrames and JInternalFrames and controls access to the parent’s
display area. Components are added only through the root pane.
The JRootPane has four parts:
• The Menu Bar
• The Content Pane
• The Layered Pane
• The Glass Pane
i) Menu Bar
The menu bar represents the window, dialog, frame, or the internal
frame’s main menu bar which appears below the title bar. The root pane
does not have a default menu bar and hence the user has to explicitly
assign a menu bar to the root pane. This is done by creating a JMenuBar
and passing this to the root pane with the corresponding method.
ii) Content Pane
The Content pane represents the main display area of the window, dialog,
frame or internal frame. The default content pane, which is an instance of
the Jpanel could be used.
iii) Layered Pane
The layered Panel is an instance of the JLayeredPane and acts as a parent
to the Menu Bar. Content Pane and the Glass Pane. It places the Menu Bar
and Content Pane in the same layer.
iv) Glass Pane
The Glass Pane is transparent and can be completely overlay the window,
dialog, frame or internal frame main area. When set to visible, it is still
invisible but can be used to intercept any input to the components in the
root pane’s Content Pane or Layered Pane.
The Glass Pane is transparent and can completely overlay the window. , dialog,
frame or internal frame main area. When set to visible, it is still invisible but can be used
to intercept any input to the components in the root pane’s Content Pane or Layered Pane.
The constructors that can be used to create a root pane are discussed below:
The various methods that can be used in conjunction with the class are as follows:
• createContentPane()
• createGLassPane()
• createLayeredPane()
• createRootLayout()
• getContentPane()
• getDefaultButton()
• getGlassPane()
• getJMenuBar()
• getLayeredPane()
• setDefaultButton(JButton defaultButton)
• setContentPane(Component glass)
• setGlassPane(Component glass)
• setMenuBar(JMenuBar menu)
• setLayeredPane(JLayeredPane layered)
JToolBar
The various methods that can be used in conjunction with this class are:
• add(Action a)
• addSeparator()
• addSeparator(Dimension size)
• getComponentAtIndes(int i)
• getComponentIndex(Component c)
• getMargin()
• getOrientation()
JTabbedPane
Tabs components are added to a TabbedPane object by using the addTab and
insert Tab methods. A tab is represented by an index corresponding to the position it was
added in, where the first tab has an index equal to 0 and the last tab has an index equal to
the tab count minus 1.
The TabbedPane uses a SingleSelectionModel to represent the set of tab indices
and the currently selected index. If the tab count is greater than 0, then there will always
be a selected index, which by default will be initialized to the first tab. If the tab count is
0, then the selected index will be -1.
This class i.e., JTabbedPane allows multiple components to be added but displays
only a single component at a time. Tabs are located on one of the sides of the displayed
component that allow the user to choose which component is currently visible in the
centre of the tabbed pane. The various constructors that can be used to create a
JTabbedPane are listed below:
• JTabbedPane()
• JTabbedPane(int tabPlacement)
Tab placement is a bound property that can be changed after creation. Changes to the
properties of the class can be done using methods, some of which are listed below:
• add(Component component)
• add(Component component, int index)
• add(Component component, object constraints, int index)
• addTab(String title, Component component)
• getBackgroundAt(int index)
• getBoundsAt(int index)
• getComponentAt(int index)
• getForegroundAt(int index)
• getSelectedComponent()
• getSelectedIndex()
• getTabCount()
• setForegroundAt(int index, color foreground)
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class tab extends JFrame {
JTabbedPane fpane = new JTabbedPane();
JPanel First = new JPanel();
JPanel Second = new JPanel();
JPanel Third = new JPanel();
JPanel contentpane = (JPanel)getContentPane();
public tab()
{
getContentPane().setLayout(new BorderLayout());
fpane.addTab("First",First);
fpane.addTab("Second", Second);
fpane.addTab("Third",Third);
fpane.setSelectedIndex(0);
contentpane.add(fpane);
getContentPane().add(fpane,BorderLayout.CENTER);
}
Scrolling Components
JFC provides the JScrollPane class, which allows any component to be easily
scrolled. The JScrollPane class manages horizontal and vertical scrollbars, column and
row header components, corner components, and a viewport. All components need to be
visible in every scroll pane. The view port in the scroll pane manages the actual
component that is to be scrolled. The horizontal header scrolls right and left as the
contents scrolls, but not vertically.
JViewport:
A viewport can be configured to create an off-screen image the buffers the visual
representation of the visual port of the child component. This allows the viewport to
scroll faster. If the viewport has not been scrolled, when the viewport’s paint method is
called, the component is drawn to the image that is then copied to the display. If the
viewport has been scrolled, the image is moved the appropriate amount and then the
exposed portion of the child component is drawn to the image. The complete image is
then copied to the display. Scrolling is thereby performed faster, because repainting need
not be done for the entire component when only a small scroll is performed. The off-
screen image is known as a backing store.
The JViewport class has methods that can be used for a variety of purposes.
Some of these are listed below:
• getViewPosition()
• getViewSize()
• remove(Component child)
• SetBackingStoreEnabled(boolean x)
• setBorder(Border border)
• setView(Component view)
When a component is first added to a viewport, its upper left corner is aligned with the
upper left corner of the viewport. This is not true when the component is scrolled.
JScrollPane:
• JScrollPane()
• JScrollPane(Component view)
• JScrollPane(Component view, int vsbPolicy, int hsbPolicy)
• JScrollPane(int vsbPolicy, int hsbPolicy)
ScrollPanelLayout Layout Manager:
The ScrollPaneLayout class sizes the horizontal scrollbar and the column header to
their preferred heights and to the width of the scroll pane, less the width of the row
header and vertical scrollbar, if either of them are visible. Similarly, the vertical scrollbar
and the row header are sized to their preferred widths and to the height of the scroll pane,
less the height of the column header and horizontal scrollbar, if either of them is visible.
The viewport is given the remainder of the scroll pane’s size. The corner components are
sized to the height and width of their adjacent components.
Scrollbar display can be controlled by using the corresponding fields and
methods. Similarly, row and column headings can also be controlled. Corner components
can also be controlled.
Split Pane
Many user interfaces allow multiple views to appear in the same frame. The user
can drag the divider between the views to allocate the space given to each view. JFC
provides JSplitPane class to manage two components that can be interactively resized by
the user. Split panes can be nested.
JSplitPane
When the user is resizing the components, the minimum size of the components is
used to determine the max/min position the components can be set to. If the minimum
size of the two components is greater than the size of the split pane, the divider will not
allow resizing.
The constructors that can be used to create split panes are listed below:
• JSplitPane()
• JSplitPane(int newOrientation)
• JSplitPane(int newOrientation, Component newLeftComponent,
Component newRightComponent)
• JSplitPane(int newOrientation, boolean newContinuousLayout,
Component newLeftComponent, Component
newRightComponent)
• JSplitPae(int newOrientation, Boolean newContinuousLayout)
The various methods that can be used to manipulate split panes are listed below:
• getBottomComponent()
• getDividerLocation()
• getDividerSize()
• getLastDividerLocation()
• getLeftComponent()
• getMaximumDividerLocation()
• isContinuousLayout()
• remove(Component component)
• setOrientation(int orientation)
Internal Frames
JInternalFrame
The various constructors that can be used to create an instance of this class are:
• JInternalFrame()
• JInternalFrame(String title, boolean resizable, boolean closable,
Boolean maximizable, Boolean iconifiable)
• JInternalFrame(String title, boolean resizable, boolean closable,
Boolean maximizable)
• JInternalFrame(String title, boolean resizable, boolean closable)
• JInternalFrame(String title, boolean resizable)
• JInternalFrame(String title)
Some of the methods that may be used in conjunction with internal frames are
listed below:
• dispose()
• createRootPane()
• getBackground()
• GetDefaultCloseOperation()
• getDesktopPane()
• getForeground()
• getLayeredPane()
• setBackground(Color c)
• setClosable(boolean b)
• setClosed(boolean b)
• setContentPane(Container c)
JDesktopPane
• JDesktopPane()
Some of the methods that may be used in conjunction with the desktop pane are
listed below:
• getAllFrames()
• getAllFramesInLayer(int layer)
• getDesktopManager()
• setDesktopManager()
• setDesktopManager(DesktopManager d)
DesktopManager Interface
• maximizeFrame(JInternalFrame f)
• MinimizeFrame(JInternalFrame f)
• ActivateFrame(JInternalFrame f)
• endResizingFrame(JComponent f)
• endDraggingFrame(JComponent f)
• dragFrame(JComponent f, int newX, int newY)
• deiconify((JInternalFrame f)
• deactivateFrame(JInternalFrame f)
• beginDraggingFrame(JComponent f)
• closeFrame(JInternalFrame f)
• beginResizingFrame(JComponent f, int direction)
JLayeredPane
This is a general container for controlling components that overlap. Its main role
is to act as the parent class of the JDesktopPane. When components are added to a
JLayeredPane, the setBounds() method should be used to place it because
JLayeredPane uses a null layout manager. Components that are added to a
JLayeredPane can be given relative layer values which determine which components are
on top of other components.
An Integer object specifies each component’s depth in the container, where
higher-numbered components sit “on top” of other components. JLayeredPane divides
the depth-range into several different layers. Putting a component into one of those layers
makes it easy to ensure that components overlap properly, without having to worry about
specifying numbers for specific depths. JLayeredPane manages its list of children like
Container, but allows for the definition of several layers within itself. Children in the
same layer are managed exactly like the normal Container object, with the added feature
that when children components overlap, children in higher layers are displayed above the
children in lower layers. Each layer is a distinct integer number. The layer attribute can
be set on a Component by passing an Integer object during the add call.
The various methods that can be used in conjunction with the layered pane are
listed below:
• getComponentCountInLayer(int layer)
• getComponentsInLayer(int layer)
• getComponentsToLayer()
• getIndexOf(Component c)
• getLayer(Component c)
• highestLayer()
• lowestLayer()
• moveToBack(Component c)
• remove(int index)
• setLayer(Component c, int layer)
• setPosition(Component c, int position)
OVERVIEW :
• The AWT (Abstract Window Toolkit) has been present in all versions of Java
• The AWT objects are built above native code objects, giving a native look-and-
feel
• The AWT objects are a least common denominator of all platforms
• The Swing objects are a separate library for JDK 1.1
• The Swing objects are in pure Java, and have the same look-and-feel on all
platforms
• The L&F of Swing objects can be customised to particular styles
• In JDK 1.2, the Swing objects are part of the Java Foundation Classes
• The JFC objects will provide a superset of each platform's objects
• The AWT objects will decrease in importance over time
• JButton
• JCheckbox
• JCheckboxMenuItem
• JColorChooser
• JComboBox
• JDesktopIcon
• JDesktopPane
• JDialog
• JDirectoryPane
• JEditorPane
• JFileChooser
• JFrame
• JInternalFrame
• JLabel
• JLayeredPane
• JList
• JMenu
• JMenuBar
• JMenuItem
• JOptionPane
• JPanel
• JPasswordField
• JPopupMenu
• JProgressBar
• JRadioButton
• JRadioButtonMenuItem
• JRootPane
• JScrollBar
• JScrollPane
• JSeparator
• JSlider
• JSplitPane
• JTabbedPane
• JTable
• JTextArea
• JTextField
• JTextPane
• JToggleButton
• JToolBar
• JToolTip
• JTree
• JViewport
• JWindow
Capability
• Each object has greater capabilities than its corresponding AWT object
• Some capabilities are object-specific
• Some are available across all objects
o internationalisation
o customisable UI
JFrame
JHello() {
JLabel hello = new JLabel("Hello World");
getContentPane().add(hello, "Center");
setSize(200, 200);
setVisible(true);
}
}
JButton
• JButton's can have an image and/or text label with controllable placement
• Similarly for JLabel, JCheckBox, JRadioButton
• These extend appearance of corresponding AWT objects
import javax.swing.*;
import java.awt.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
getContentPane().add(button, "Center");
pack();
}
}
EVENTS:
AWT events:
• Event model in Java 1.0 is poor s/w engineering, based on class Event
• In Java 1.1 it changes to a new model called AWTEvent
• This event handling model is unchanged for Java 1.2
• Event handling is the same for Swing and AWT components
• Events are handled by listeners, not by subclasses of GUI objects
AWT Event classes:
• ComponentEvent
• FocusEvent
• KeyEvent
• MouseEvent
• WindowEvent
• ActionEvent
• AdjustmentEvent
• ItemEvent
Triggering event:
Events are posted by user actions (or may be done programmatically)
• ActionEvent
o click on JButton
o click on JMenuItem
o press <enter> key in JTextField
Listeners
Listeners are objects that handle events
Listeners as interfaces
Listeners are defined as interfaces and must be implemented by the application
Registering listeners
import javax.swing.*;
import java.awt.event.ActionListener;
public JDelegateDemo() {
// create the GUI objects
JButton left = new JButton("Left");
JButton right = new JButton("Right");
JLabel label = new JLabel(" ",
SwingConstants.CENTER);
// continue constructor
// create a listener and add it to each Button
SimpleListener simple =
new SimpleListener(label);
left.addActionListener(simple);
right.addActionListener(simple);
}
}
/**
* A listener object that is invoked
* when a Button is activated it finds
* the Button's label and sets it in a Label
*/
class SimpleListener implements ActionListener {
public SimpleListener(JLabel l) {
// the listener needs to know the Label
// it will act on
label = l;
}
• The path taken by events is different for AWT components and Swing components
• Native events are generated by user actions, such as mouse clicks.
• Native events are translated into Java events, and sent to a Java object which has
a native window
• The difference is that all AWT objects have a native window, but only some Swing
objects such as JFrame have one
• For the AWT, events have to be finally delivered to native objects to have visual
effect
• For Swing, a container has to pass events to its Swing components to have visual
as well as semantic effect
Event Model (2)
For a mouse press and mouse release on a Button inside a Frame, the following
sequences for Java using X Windows occur
The Motif Pushbutton recognises that it has been clicked and sends an ActionEvent
Event Model (3)
For a mouse press and mouse release on a JButton inside a JFrame, the following
sequences for Java using X Windows occur
Consuming events
Consuming events
This key listener discards non-alphabetic events:
public class Alpha implements KeyListener {
public void keyPressed(KeyEvent e) {
if (! Character.isLetter(e.getKeyChar())) {
Toolkit.getDefaultToolkit().beep();
e.consume();
}
}
public void keyReleased(KeyEvent e) {
// empty
}
public void keyTyped(KeyEvent e) {
// empty
}
}
Generating Events
• Events may be created and placed on the event queue for applications
• The event queue is found from
Toolkit.getDefaultToolkit().getSystemEventQueue()
• The event queue is not accessible yet from applets (need applet queue)
• Posting events works for Swing objects, but not for AWT objects
GEOMETRY:
Insets
• An inset gives a top, bottom, left and right border within which a Container lays
out its contents.
• Insets should probably be treated as readonly
Borders
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public TestBorder() {
Border border = BorderFactory.
createBevelBorder(
BevelBorder.RAISED);
JLabel label = new JLabel("Hello");
label.setBorder(border);
getContentPane().add(label, "Center");
pack();
}
}
Layout Objects
BorderLayout
BorderLayout (2)
import java.awt.*;
public SizeLayout() {
size = new Dimension(0, 0);
}
public SizeLayout(Dimension s) {
size = new Dimension(s);
}
public void
addLayoutComponent(String n, Component c) {
}
public void
removeLayoutComponent(Component c) {
}
public Dimension
preferredLayoutSize(Container parent) {
if (parent.countComponents() == 0)
return new Dimension(width, height);
public Dimension
minimumLayoutSize(Container parent) {
if (parent.countComponents() == 0)
return new Dimension(width, height);
public void
layoutContainer(Container parent) {
if (parent.countComponents() == 0)
return;
public void
addLayoutComponent(String name, Component comp) {
// empty -this should never be called
}
public void
removeLayoutComponent(Component comp) {
// empty - no state maintained here
}
public Dimension
minimumLayoutSize(Container parent) {
if ( ! parent.isValid()) {
layoutButtons(parent);
}
return gridbag.minimumLayoutSize(parent);
}
public void
layoutContainer(Container parent) {
if ( ! parent.isValid()) {
layoutButtons(parent);
}
gridbag.layoutContainer(parent);
}
/**
* Find the height of the first component,
* and add half of it
* above and below using ipady.
* Find the largest width, and set ipadx
* for all components to give it that width
*/
protected void layoutButtons(Container parent) {
if (nbuttons == 0)
return;
constraints.weightx = 1.0;
// stretch each component vertically
constraints.ipady =
parent.getComponent(0).
getPreferredSize().height/2;
compSize = component.getPreferredSize();
constraints.ipadx = maxWidth - compSize.width;
gridbag.setConstraints(component, constraints);
}
}
}
Composite Objects
Rather than doing geometry afresh each time, one can create new composite objects
which are just reused in toto
ButtonModel
Button instance
• Problem: create a button that counts how often it has been pressed
• A state count of the number of times needs to be kept
• Define a new model CountButtonModel to extend DefaultButtonModel by this
count
• Define a new class CountButton to install this model
• Hide the model by access method getCount() on CountButton
CountButtonModel
CountButton
public CountButton() {
this(null, null);
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import CountButton;
public TestCountButton() {
CountButton btn = new CountButton("Press me");
getContentPane().add(btn, BorderLayout.CENTER);
pack();
btn.addActionListener(this);
}
Changing the UI
• The supplied UI's are standard(Windows), motif, jlf (Java Look and Feel)
• Microsoft have not yet granted permission for the standard L&F to be available
on non-Windows platforms
• Changing the UI involves two calls
• UIManager.setLookAndFeel(String)
• SwingUtilities.updateComponentTreeUI(Component)
JList
import javax.swing.event.*;
import javax.swing.*;
public TestList() {
String [] elmts = {"one", "two", "three"};
JList list = new JList(elmts);
getContentPane().add(list, "Center");
pack();
list.addListSelectionListener(this);
}
import javax.swing.event.*;
import javax.swing.*;
public TestIconList() {
ImageIcon images[] = new ImageIcon[2];
images[0] = new ImageIcon("bart.gif");
images[1] = new ImageIcon("swing.small.gif");
import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;
public class TestLabelList extends JFrame {
public TestLabelList() {
public LabelCellRenderer() {
setOpaque(true);
}
public Component
getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
setText(value.toString());
setIcon(images[index]);
setBackground(isSelected ?
Color.red : Color.white);
setForeground(isSelected ?
Color.white : Color.black);
return this;
}
}
Rendering JList
Draw your own shapes in a JList
import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;
public TestDrawList() {
public Component
getListCellRendererComponent(
JList list,
Object value,
int index,
boolean selected,
boolean cellHasFocus) {
this.index = index;
this.selected = selected;
return this;
}
if (selected) {
fg = Color.green;
bg = Color.black;
} else {
fg = Color.red;
bg = Color.white;
}
// fill background
g.setColor(bg);
g.fillRect(0, 0, getWidth(), getHeight());
// draw shape
g.setColor(fg);
if (index == 0) {
g.fillOval(5, 5, 25, 25);
} else {
g.fillRect(5, 5, 25, 25);
}
}
}
Scrolling list
Text replacements
Model
The model is known as a Document, and can be shared between Text objects.
import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;
public Text2() {
JTextArea text1 = new JTextArea("starting text", 5, 30);
JTextArea text2 = new JTextArea(5, 30);
text2.setDocument(text1.getDocument());
Styles
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
public TestStyle() {
JTextPane text = createEditor();
getContentPane().add(text, "Center");
setJMenuBar(createMenu());
setSize(200, 200);
}
mi = new JMenuItem("Green");
color.add(mi);
mi.addActionListener(this);
return mbar;
}
return sc;
}
}
FileChooser
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import javax.swing.*;
public BasicChooser() {
setSize(100, 100);
}
}
Menus
JMenuBar
JMenu
• The constructor
•
• JMenu(String label, boolean tearOff)
TestAction()
{
createMenu();
createToolBar();
setSize(300, 300);
}
fileB.add(openAction);
fileB.add(saveAction);
setJMenuBar(mb);
}
public OpenAction() {
super("Open", new ImageIcon("open.gif"));
}
public SaveAction() {
super("Save", new ImageIcon("save.gif"));
}
Dialogs
Dialog types
The dialog types can be
• ERROR_MESSAGE
• INFORMATION_MESSAGE
• WARNING_MESSAGE
• QUESTION_MESSAGE
• PLAIN_MESSAGE
Dialog buttons
The dialog buttons can be
• DEFAULT_OPTION
• YES_NO_OPTION
• YES_NO_CANCEL
• OK_CANCEL
Use JOptionPane.showMessageDialog():
import javax.swing.*;
import java.awt.event.*;
public TestWarning() {
JButton btn = new JButton("Show dialog");
getContentPane().add(btn, "Center");
pack();
btn.addActionListener(this);
}
Confirmation dialog
import javax.swing.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.*;
public TestInput() {
JButton btn = new JButton("Show dialog");
getContentPane().add(btn, "Center");
pack();
btn.addActionListener(this);
}
Other dialogs
Keyboard traversal
The following program moves an X around a 3x3 set of buttons by use of the arrow keys
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public TestKeyboardAction() {
Container pane = getContentPane();
pane.setLayout(new GridLayout(3, 3));
buttons[n] = button;
}
setSize(200, 200);
}
Summary:
Java Foundation Class was developed to address the AWT. Its visual components
extend the AWT container class. The methods contained in the Component and Container
classes that AWT are valid for JFC visual classes. Swing offers a number of advantages
such as pluggable look and feel, MVC architecture, keystroke handling, action objects,
needed containers, virtual desktops, compound borders etc. Application services covers a
wide range of service, which includes keyboard navigation, multithreaded event queue,
undo, bounded range model etc.