Download Java Notes

Document related concepts
no text concepts found
Transcript
1
• Need for Java
• Java applications are:

Character User Interface (CUI) Applications:Has access to the system
resources, such as file systems and can read and write to files on local
computers.

Graphical User Interface (GUI) Applications: Used in the Windows
environment.

Applets: Are small executable programs that run on a Web page and require a
Java-enabled browser, such as Internet Explorer or Netscape Navigator.

Servlets:Are the programs that are used to extend the functionality of Web
servers.

Packages:Are collection of classes that can be reused by applications and
applets.
Characteristics of Java
•
 Simple
 Object-oriented
 Compiled and interpreted
 Portable
 Distributed
 Secure
•
Java Architecture
Various components of Java Architecture are:
•




Java programming language
Java class file
Java Virtual Machine (JVM)
Java Application Programming Interface (API)
Java Programming Language and class File
•
The Java programming environment
•
•
Java Virtual Machine (JVM)

Components of the JVM:
2

Class loader

Execution engine

Just In Time(JIT) compiler
Java Application Programming Interface (API)
•
•
Components of Java platform
Java architecture security features:
•
 Compiler level security
 Byte code verifier
 Class loader
 Sandbox model
Security levels in Java architecture:
Bytecode is verified in two phases:

In the first phase, the verifier checks
for the structure of the .class file.

The second level phase occurs when
the Bytecode is run.The Bytecode
verifier checks the validity of classes,
variables, and methods used in a
program.
Declaring Variables and Literals
The various data types in Java are:
•

Primitive or the simple data types

Abstract or the derived data types
3
•
Floating point data types:
 Float:Has a range of 32 bits
 Double:Has a range of 64 bits
•
Character data type:
 Has a width of 16-bits
 Has the set of standard ASCII character ranging from 0 to 127
•
Abstract data types:
 Data types derived from the primitive data types
 String stores letters, digits, and characters such as as /, (), :, :, $, and #.
 Declaring Variables and Literals
 (Contd.)
 Keywords available in Java:
abstract
boolean
break
byte
case
catch
char
class
const
continue
default
do
4
double
else
extends
final
finally
float
for
goto
if
implements
Import
instanceof
int
interface
long
native
new
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
try
void
volatile
while
Defining Variables and Literals:
•
 A variable is the name that refers to a memory location where some data
value is stored.
 Each variable that is used in a program must be declared.
Naming Conventions for Variables:
•
•

The name of a variable needs to be meaningful, short, and without any
embedded space or symbol.

A variable name must be unique.

A variable name must begin with a letter, an underscore (_), or the dollar
symbol ($), which can be followed by a sequence of letters or digits (0 to 9),
‘$’, or ‘_’ .

A variable name should not start with a digit.

A variable name should not contain embedded white spaces .

A variable name should not consist of a keyword.

A variable name in Java is case sensitive.
Types of Variables:

Class variables
5

Instance variables

Local variables

Static variables

Automatic variables
Literals in Java:
•

Integer literals

Floating point literals

Character literals

String literals

Boolean literals
Manipulating Variables:
•
•
Assignment Operator

You use the assignment operator (=) to assign a value to a variable.
Using Arrays
o
Arrays:
 One-dimensional arrays
 Multi-dimensional arrays
6
•
Memory allocation to arrays:
Structure of Java Application
•
Creating Classes and Objects
•
The components of a class consists of
•
Data members (Attributes)
•
Methods
Creating Classes in Java
• The statements written in a Java class
must end with a semicolon, ;.
class ClassName
{
//Declaration of data members
//Declaration of methods
}
Double slash, //, are comment entries.
Comments are ignored by compiler.
Creating Objects of Classes
•
An object is an instance of a class having a unique identity.
•
To create an object, you need to perform the following steps:
 Declaration
 Instantiation or creation
Accessing Data Members of a Class
•
Assign values to data members of
the object before using them.
•
You can access the data members of
a class outside the class by
specifying the object name followed
by the dot operator and the data
member name.
e1.employeeName="John";
e2.emmployeeName="Andy";
e1.employeeID=1;
e2.employeeID=2;
e1.employeeDesignation = “Manager”;
7
Adding Methods to a Class
•
Accessing data members directly overrules the concept of encapsulation.
•
Advantages of using methods in a Java program:

Reusability

Reducing Complexity

Data Hiding
The syntax to define a method:
void methodName()
{
// Method body.
}
Declaring the main() Method:
The syntax to declare the main()method:
•
public static void main(String args[])
{
// Code for main() method
}

public: method can be accessed from any object in a Java program.

static : associates the method with its class.

void: signifies that the main() method returns no value.

The main() method can be declared in any class but the name of the file
and the class name in which the main() method is declared should be
the same.

The main() method accepts a single argument in the form of an array of
elements of type String.
Following code snippet creates objects for four employees of an organization:
Employee e1 =new Employee();
Employee e2 =new Employee();
Employee e3 =new Employee();
Employee e4 =new Employee();
Defining Constructors
•
A constructor is a method with the same name as the class name.
8
A constructor of a class is automatically invoked every time an instance of
a class is created.
•
Characteristics of Constructors
•
There is no return type for a constructor.
•
A constructor returns the instance of the class instead of a value.
•
A constructor is used to assign values to the data members of each object
created from a class.
Access Specifiers and Modifiers
•
Access Specifiers
 public
 private
 protected
 friendly
•
The public access specifier
•
Class members with public specifier can be accessed anywhere in
the same class, package in which the class is created, or a package
other than the one in which the class is declared.
•
The public keyword is used to declare a member as public.
public <data type> <variable name>;
•
The private access specifier
•
A data member of a class declared private is accessible at the class
level only in which it is defined.
•
The private keyword is used to declare a member as private.
private float <variableName>; // Private data member of float
private methodName();
•
// Private method
The protected access specifier
•
The variables and methods are accessible only to the subclasses of
the class in which they are declared.
•
The protected keyword is used to declare a member as protected.
protected <data type> <name of the variable>;
•
The friendly or package access specifier
•
If you do not specify any access specifier, the scope of data members
and methods is friendly.
9
Types of Permitted Modifiers
•
Modifiers determine or define how the data members and methods are used in
other classes and objects.

static

final

abstract

native

synchronized
•
static
•
•
•
•

Used to define class variables and methods that belong to a class
and not to any particular instance of the class.

Associates the data members with a class and not the objects of
the class.
final

Indicates that the data member cannot be modified.

Does not allow the class to be inherited.

A final method cannot be modified in the subclass.

All the methods and data members in a final class are implicitly
final.
abstract

Used to declare classes that define common properties and
behavior of other classes.

An abstract class is used as a base class to derive specific classes of
the same type.
native

Used only with methods.

Inform the compiler that the method has been coded in a
programming language other than Java, such as C or C++ .

The native keyword with a method indicates that the method lies
outside the Java Runtime Environment (JRE).
synchronized

controls the access to a block of code in a multithreaded
programming environment.

Java supports multithreaded programming and each thread
defines a separate path of execution.
10
Garbage Collection in JVM
•
Garbage collection is the process that is used to free the memory of the
objects that are no longer in use.
•
When a program stops referencing an object, it is not required any more
and can be deleted.
•
The space that is used by the object is released for use by another objects.
•
The garbage collection feature implies that the new objects are created
and all the unreferenced objects are deallocated from the memory.
•
The different approaches used for detecting garbage objects are:
 Reference-Counting Collectors: Store the references of the objects
used within a program
 Tracing Collectors: A set of roots is defined from the location
where the objects are traced.
 Compacting Collectors: Reduce the fragmentation of memory by
moving all the free space to one side during garbage collection.
Setting the CLASSPATH
•
The CLASSPATH environment variable instructs the JVM class loader to find the
classes that are directly or indirectly invoked, including the system classes.
•
The -classpath option is used when the SDK tools are called, such as java, javac
and javadoc.
•
The following syntax shows how to set the classpath with an SDK tool:
C:> sdktool -classpath <classpath1>;<classpath2>...
The following syntax shows how to set the classpath using the classpath
environment variable:
•
C:> set CLASSPATH=<classpath1>;<classpath2>...
Significance of the Java Class File
•
The Java class file contains the Java Bytecode.
•
The class files are platform independent therefore you can run a Java program
by loading the class file on any system with the Java Runtime Environment
(JRE).
•
The following command shows how to view the contents of a class file:
javap -c <class_filename>
•
The javap command prints the instructions that comprise the Java Bytecode, for
each of the methods in a class.
11
Using Conditional Statements
•
Conditional statements allow selective execution of a set of statements
depending on the value of expressions associated with them.
•
Conditional statements are also known as decision-making statements.
•
You can control the flow of a program using conditional statements.
•
Two types of conditional statements in Java are:

The if-else statement

The switch-case construct
Using the if-else Statement
•
The if-else statement:

Enables you to execute selectively.

Is followed by a boolean expression.

Executes the set of statements depending upon the result of the boolean
expression.
•
Syntax of the if-else statement is:
if(boolean expression)
{
statement(s)
}
else
{
statement(s)
}
In the preceding syntax, if the boolean expression of the if construct evaluates to true,
the Java compiler executes the statements following the if construct else executes the
statements following the else construct.
Relational Operators:

Used to compare the values of two variables or operands and find the
relationship between the two.

The relational operators are therefore called comparison operators also.
12
The following table lists the various relational operators (Contd.):
•
Conditional Operators :
Used to combine multiple conditions in one boolean expression.
Are of two types :
 Unary
 Binary
Various conditional operators are:
 AND(&&)
 OR(||)
 NOT(!)
•
•
•
•
The following table lists the various conditional operators and their
operations:
13
Using the multiple if-else Statement:
•
You can replace a single if construct with multiple if-else statements to write a
compound if statement.
•
The multiple if-else construct allows you to check multiple boolean
expressions in a single compound if statement.
•
The syntax of the multiple if-else statements is:
if (Boolean_expression_1)
{
statements
}
else if (Boolean_expression_2)
{
statements
}
else (Boolean_expression_3)
{
statements}
}
The switch-case Construct:
•
Successively tests the value of an expression or a variable against a list of case
labels with integer or character constants.
•
When a match is found in one of the case labels, the statements associated
with that case label get executed.
•
The switch keyword in the switch-case construct contains the variable or the
expression whose value is evaluated to select a case label.
•
The case keyword is followed by a constant and a colon.
•
The data type of case constant should match the switch variable.
•
The syntax of the switch-case construct is:
switch(expression or variable name)
{
case Expr1:
statements;
break;
•
14
case Expr2:
statements;
break;
default:
statements;
}
•
Statements associated with the default keyword are executed if the value of
the switch variable does not match any of the case constants.
•
The break statement used in the case label causes the program flow to exit
from the body of the switch-case construct.
The break Statement:
•
Causes the program flow to exit from the body of the switch construct.
•
Control goes to the first statement following the end of the switch-case
construct.
•
If not used inside a case construct, the control passes to the next case statement
and the remaining statements in the switch-case construct are executed.
Using Looping Statements
•
A looping statement causes a section of program to be executed a certain
number of times.
•
The repetition continues while the condition set in the looping statement
remains true.
•
When the condition becomes false, the loop ends and the control is passed to the
statement following the loop.
The for Loop:
•
Is a looping statement iterating for a fixed number of times.
•
Consists of the for keyword followed by parentheses containing three
expressions, each separated by a semicolon.
•
The three expressions in the for loop are:
•

Initialization expression

Test expression

IterationExpr expression
Is used when the number of iterations is known in advance.
For example, it can be used to determine the square of each of the first ten
natural numbers.
•
The syntax of the for loop is:
15
for(InitializationExpr; TestExpr; IterationExpr)
{
statement_1
statement_2
…
}
•
In the preceding syntax, the initialization expression is executed only once,
when the control is passed to the for loop for the first time. The initialization
expression gives the loop variable an initial value.
•
The test expression is executed each time the control passes to the beginning
of the loop. If true, the body of the loop is executed, otherwise not.
•
The IterationExpr expression is always executed when the control returns to
the beginning of the loop in each loop iteration.
•
The following figure shows the
use of for loop:
The while Loop:
•
Executes a statement or a block
of statements as long as the
evaluating condition remains
true.
•
The evaluating condition has to
be a boolean expression and must
return a boolean value that can
be true or false.
•
The syntax of the while loop is:
while(Bool_Expr)
{
statements; //executed as long as Bool_Expr is true
}
In the preceding syntax, the statements in the while loop are executed as long as the
Bool_Expr condition is true. When the condition returns false, the statement
immediately following the while block is executed.
The do-while Loop:
•
Used when the body of the loop needs to be executed at least once.
•
The do-while construct places the test condition at the end of the loop.
16
•
The do keyword marks the beginning of the loop and braces form the body of
the loop.
•
The while statement provides the test condition.
•
The test condition checks whether the loop will execute again or not.
•
The syntax of the do-while loop is:
do
{
statements;
}while(Bool_Expr);
The continue statement:
•
•
In the while and do-while loops:

The continue statement returns the control to the conditional expression
that controls the loop.

The control skips any statement following the continue statement in the
loop body.
In the for loop:

control goes to the re-initialization expression first and then to the
conditional expression.
Enhancing Methods of a Class
•
•
Methods are used to access the variables that are defined in a class.
•
A method is an interface to a class.
•
Parameterized methods need some extra information for its execution.
•
The extra information is passed to the method by using arguments.
•
Arguments are also known as parameters of the methods.
•
Parameterized methods use parameters to process data and
generate an output.
•
The output of a parameterized method is not static and depends on
the value of the parameters passed.
•
Parameters in a parameterized method allow the method to be
generalized.
Defining a Method that Returns a Value:
•
You can define a method that can return a value instead of just computing
results and displaying them.
•
The return type of a method is specified to the Java compiler in the method
declaration statement.
17
•
The return type of a method can be of any primitive data type or abstract
data type.
•
The value is returned from a method using the return keyword followed
by the value to be returned.
•
The methods that do not return any value have return type void.
•
Defining a Method that Returns a Value
•
The syntax of any method that returns a value is:
<return_type> method_name(parameter_list)
{
statements;
return value;
}
In the preceding syntax, the return type specifies the type of data returned by the
method and the return statement specifies the value returned.
Overloading Methods
•
Method overloading is defined as the function that enables you to define two
or more methods with the same name but with different signatures within
the class.
•
The methods that share the same name, but have different signatures are
called overloaded methods.
•
The signature of a method consists of:
•

The name of the method.

The number of arguments it takes.

The data type of the arguments.

The order of the arguments.
When an overloaded method is invoked, the Java compiler uses
the type of arguments or the number of arguments to determine which copy of
overloaded method to invoke.
•
Overloading methods must differ in the type or the number of parameters.
•
The return types of overloaded methods can be different.
•
Overloaded methods are used when you need several methods that perform
closely related tasks.
•
Method overloading is a way to implement polymorphism in Java.
•
The following code snippet shows an overloaded multiply() method:
18
public void multiply(int a, int b) //Multiply two integers
public void multiply(float a, float b) //Multiply two floats
public void multiply(double a, double b) //Multiply two doubles
Passing Arguments to a Method
•
Arguments can be passed to a method using two ways:
 Call-by-value: Copies the value of the actual parameters to the
formal parameters. Therefore, the changes made to the formal
parameters have no effect on the actual parameters.
 Call-by-reference: Passes the reference and not the value of the
actual parameters to the formal parameters in a method. Therefore,
the changes made to the formal parameters affect the actual
parameters.
•
You can also pass arguments to the main() method at the run-time of a
program.
Passing Arguments by Value:
•
In Java, when arguments of
primitive data type, such as int
and float are passed to a method
then they are passed by value. The
following figure shows the concept
of passing arguments by value:
•
When arguments are passed by
value, a copy of the actual argument is passed to the formal
arguments of the called method, which is maintained at a separate
memory location. Therefore, when the called method changes the
value of the argument, the change is not reflected in the actual
argument.
Passing Arguments by Reference:
•
Passes a reference to an
argument to the parameter
of a method.
•
In Java, the objects of
abstract data type are
passed by reference.
•
When
arguments
are
passed to the method by
reference then any change
made to the formal
19
argument by the called method is also reflected in the actual
argument. The following figure shows the concept of passing
arguments by reference:
•
•
The argument passed by reference to the formal parameter has the
same memory location as that of the actual parameter.
Passing Arguments at the Command Line:
•
Command-line arguments are used to provide information that a
program needs at startup.
•
The main() method in Java is the first method to be executed,
therefore the command-line arguments are passed to the main()
method.
•
The main() method stores the command-line arguments in the
String array object.
•
In Java, the syntax for command-line argument is:
public static void main(String args[])
{
//statements
} //End of main() method
In the preceding syntax, each of the elements in the array named args[] is a reference to
the command-line arguments each of which is a String object.
Creating Nested Classes
•
Nested Classes:
•
A nested class is a class defined as a member of another class.
•
The scope of nested class is bounded by the scope of its enclosing class.
•
The nested class has access to the members of its enclosing class including
private members.
•
The enclosing class does not have any access to the members of the nested
class.
•
The nested classes are of two types:
•
•
Static: A nested class declared as static is called the static nested
class.
•
Inner: A non-static nested class is called the inner class.
Static Nested Class
•
A static nested class cannot access the members of its enclosing
class directly because it is declared as static.
•
Therefore, it has to access the members of its enclosing class
through an object of enclosing class.
20
•
The following code snippet shows the declaration of a static nested
class:
class EnclosingClass{
//statements
static AstaticNestedClass
{
//statements
}
}
•
Inner Class:
•
An inner class is a non-static nested class, whose instance exists
inside the instance of its enclosing class.
•
An inner class can directly access the variables and methods of its
enclosing class.
•
The following figure shows a nested
class:
•
Use operators
Objectives
•
•
Arithmetic
operators
assignment
•
bit-wise operators
•
shift operators
•
instance-of operator
Identify the operators precedence
Using Unary Operators
•
Using the Increment and Decrement Operators
•
The increment and decrement operators are unary operators.
•
The increment operator (++) increases the value of an operand by 1.
•
The decrement operator (--) decreases the value of an operand by 1.
•
Prefix Form
•
•
The operator precedes the operand.
•
Operator operates on the operand before the value of
operand is used in the expression.
Postfix Form
21
•
In the postfix form, operator follows the operand.
•
Operator operates on the operand after the value of operand
is used in the expression.
Using the Arithmetic Assignment Operators
•
Arithmetic Assignment Operators
•
Addition(+), subtraction(-), multiplication(*), division(/), and
modulo(%) are the arithmetic operators supported by Java.
•
Various arithmetic operators, such as +, -, /, *, and % are combined
with the assignment operator (=) and are called arithmetic
assignment operators.
Using Bit-wise Operators
•
Bit-wise operators
•
Operate on the individual bits of their operand.
22
•
•
Operands can be various data types like int, short, long, char, and
byte.
•
Operands are converted into their binary equivalents before
operation.
•
The result in the binary form after the operation is converted back
into its decimal equivalent.
The following table lists the various bit-wise operators in Java:
Operator
•
•
•
Operation
&(AND)
x&y
Performs bit-wise AND
operation. It evaluates to 1 if
both bits, x and y are 1. If
either or both bits are 0, the
result is 0.
|(OR)
x|y
Performs bit-wise OR
operation. It evaluates to 0 if
both bits, x and y are 0. If
either or both bits are 1, the
result is 1.
Operator
•
Use
Use
Operation
~(inversion)
~x
Performs unary NOT
operation. Converts all the
1s into 0s and all the 0s into
1s.
^(XOR)
x^y
Performs bit-wise XOR
operation. It evaluates to 1 if
bits have different values
and 0 if both the bits have
the same value.
Using the Bit-wise AND Operator
•
The Bit-wise AND operator (&) performs AND operation on two operands.
•
Displays 1 if both bits are 1 else 0 in all other cases.
Using the Bit-wise OR Operator
•
The Bit-wise OR operator (|) performs OR operation on two operands.
•
Displays 0 if both bits are 0 else 1 in all other cases.
Using the Bit-wise NOT Operator
•
Bit-wise NOT operator (~) is a unary operator and performs NOT
operation on each bit of binary number.
•
The NOT operator inverts or complements each of the bits of a binary
number.
Using the Bit-wise XOR Operator
23
•
•
The Bit-wise XOR (^) operator performs XOR operation on two operands.
•
The XOR operator applied on two bits results in 1 if exactly one bit is 1 else
0 in all other cases .
Using Shift Operators
•
Works on the bits of data.
•
Shifts the bits of it’s operand either to left or right.
•
Using Shift Operators (Contd.)
•
Using the Right Shift and Left Shift Operators
•
The right shift and the left shift operators are binary operators.
•
The right shift operator shifts all the bits of a binary number in the
right direction.
operand >> num
•
The left shift operator, <<, shifts all the bits of a binary number in
the left direction.
operand << num
•
Using the Unsigned Shift Operator
•
Unsigned shift operator (>>>) is used to shift the bits of a binary number
to the right.
•
The operator fills the leftmost bits of a binary value with 0 irrespective of
whether the number has 0 or 1 at the leftmost bit.
Using instance of Operator
•
Used to test whether an object is an instance of a specific class.
•
Used at the run time.
•
The syntax of the instanceof operator is:
op1 instanceof op2
•
•
op1 is the name of an object and op2 is the name of a class.
•
Returns a true value if the op1 object is an instance of the op2 class
Operators Precedence
•
Each operator in an expression is evaluated in a predetermined order
called operator precedence.
•
Operators on the same line have equal precedence.
Operators
24
Category
[], (), . , expr++, expr--
Array index, method call, member
access, and postfix operators
++expr, --expr, +, -, !, ~
Unary postfix operators
*, /, %
Multiplicative Arithmetic operators
+, -
Additive Arithmetic operators
Operators
Category
<<, >>, >>>
Shift operators
>, <, <=, >=, instanceof
Relational operators
==, !=
Equality operator
&
Bit-wise AND operator
^
Bit-wise XOR operator
|
Bit-wise OR operator
&&
Conditional AND operator
||
Conditional OR operator
=, +=, -=, *=, /=, %=
Assignment operators
Casting and Conversion in Java
•
Java supports implicit conversion of one data type to another type. are inbuilt in
Java.
•
Implicit conversions are the conversions from one data type to another, which
occur automatically in a program.
•
For example, you can assign a value of int type to a variable of long data type.
•
When you assign a value of a particular data type to another variable of a
different data type, the two types must be compatible with each other.
•
The two data types are compatible to each other if the size of the destination data
type variable is larger than or equal to the size of the source data type variable.
•
Widening conversion takes place when the destination type is greater than the
source type.
•
Assigning a wider type to a narrow type is known as narrowing conversion.
•
The widening conversion is implicit while the narrowing conversions are explicit.
•
Explicit conversion occurs when one data type cannot be assigned to another
data
type using implicit conversion.
•
In an explicit conversion, you must convert the data type to the compatible type.
•
Explicit conversion between incompatible data types is known as casting.
25
•
The following syntax shows how to use a cast to perform conversion between
two
incompatible types:
(type) value
•
Explicit conversion between incompatible data types is known as casting.
•
You can use the following code to perform type casting of an int number,
259 and a double number, 350.55 to byte type:
class TypeCast
{
public static void main(String arr[])
{
byte b;
int i = 259;
double d = 350.55;
b = (byte) i;
System.out.println("Value of int to byte conversion " + b);
b = (byte) d;
System.out.println("Value of double to byte conversion " + b);
i = (int) d;
System.out.println("Value of double to int conversion " + i);
}
}
Overloading Constructors
•
A constructor is a method that is automatically invoked every time an
instance of a class is created.
•
Constructors share the same name as the class name and do not have a
return type.
•
You can use the following code to overload the Cuboid() constructor to
calculate the volume of a rectangle and a square:
class Cuboid
{
double length;
26
double width;
double height;
Cuboid(double l, double w, double h)
{
length = l;
width = w;
height = h;
}
// Overloaded constructor declared which accepts one argument
Cuboid(double side)
{
length = width = height = side;
}
double volume()
{
return length*width*height;
}
}
class ConstrOverloading
{
public static void main(String args[])
{
Cuboid cub1 = new Cuboid(5, 10, 15);
Cuboid cub2 = new Cuboid(5);
double vol;
vol = cub1.volume();
System.out.println("Volume of the Cuboid is: "+ vol);
vol = cub2.volume();
System.out.println("Volume of the Cube is :" + vol);
}
}
Inheritance in Java
27
•
Introduction to Inheritance
•
•
Inheritance enables a class to:
•
Inherit data members and methods from another class.
•
Reuse the functionalities and capabilities of the existing class
by extending a new class from the existing class and adding
new features to it.
•
The class that inherits the data members and methods from another
class is known as the subclass.
•
The class from which the subclass inherits is known as the
superclass.
•
The superclass is also referred to as the base class, and the subclass
is referred to as the derived class.
•
You can create additional data members and methods to add more
features in a subclass.
•
A superclass can also be a subclass of another class.
Implementing Different Types of Inheritance
•
Single level inheritance
•
Derives a subclass from a single superclass. For example,
subclasses B and C inherit
the properties of a single
superclass, A. The following
figure shows the structure of
single level inheritance:
•
The following syntax shows
how to implement single
level inheritance:
class A
{
}
class B extends A
{
}
class C extends A
{
}
28
In the preceding syntax, the extends keyword is used to derive a subclass from a
superclass.
Multilevel inheritance
•
Inherits the properties of another subclass. For example, Class A is a
superclass for the Class B; and Class B is a superclass for the subclass,
Class C. You can include any number of levels in multilevel inheritance.
The following figure shows the structure of multilevel
inheritance:
•
The following syntax shows how to implement
multilevel inheritance:
class A
{
}
class B extends A
{
}
class C extends B
{
}
In the preceding syntax, class A is the superclass and class C is the subclass. The class B
acts as a subclass for the class A and superclass for the class C.
Implementing Method Overriding
•
Method overriding
•
Method overriding is defined as creating a method in the subclass
that has the same return type and signature as a method defined in
the superclass.
•
Signature of a method includes the name, number, sequence, and
type of arguments of a method.
•
The created method of the subclass hides the method defined in the
superclass.
•
Method overriding enables you to create objects that respond to the
same method as defined in the superclass.
•
A subclass must override the abstract methods of a superclass.
•
You cannot override the static and final methods of a superclass.
Implementing Interfaces
•
Overview of Interface
29
•
Interfaces contain a set of abstract methods and static data
members.
•
Interface is known as a prototype for a class.
•
Methods defined in an interface are only abstract methods.
•
An abstract method contains only the declaration for a method
without any implementation details.
•
The implementation of an abstract method is defined in the class
implementing the interface.
•
You can implement multiple interfaces in a single class.
•
The following syntax shows how to define an interface:
interface <interfacename>
{
//interface body
static final data members
return type public methods(parameters);
}
You can implement an interface in one or more than one class before defining it. The
public access specifier must be specified with the methods declared in the interface.
•
The following syntax shows how to implement an interface in a
class:
class <class_name> extends [superclass] implements [interfacename]
{
//Defining the method declared in the interface.
return type public methods(parameters)
{
}
}
In the preceding syntax, a class that extends from a superclass implements an interface
using the implements keyword.
•
Interfaces also enable you to declare constants that can be imported
into multiple classes.
•
The constant values declared in an interface can be implemented in
any class.
•
The constants defined in an interface are declared using the final
keyword.
30
•
Implementing Multiple Interfaces in a class
interface Bank
{
public void bankDeposit();
}
interface FinancialInstitute
{
public void securityDeposit();
}
class Deposit implements Bank, FinancialInstitute
{
int sd = 125;
int bd = 256;
public void bankDeposit()
{
System.out.println(" ");
System.out.println("\t The money deposited in the bank is $" + bd);
System.out.println(" ");
}
public void securityDeposit()
{
System.out.println(" ");
System.out.println("\t The money deposited in the financial institute is $"
+ sd);
System.out.println(" ");
}
public static void main(String args[]) {
Deposit d = new Deposit();
d.bankDeposit();
d.securityDeposit();
}
}
31
Exceptions in Java
•
An exception can be defined as an abnormal event that occurs during
program execution and disrupts the normal flow of instructions.
•
Errors in a Java program are categorized into two groups:
•
Compile-time errors
•
Run Time errors
32
•
•
Concept of Exceptions:
•
•
Running out of memory
•
Resource allocation errors
•
Inability to find files
•
Problems in network connectivity
The following figure shows the Exception class heirarchy:
Built-in Exceptions
•
•
•
Exception Classes
•
•
The unexpected situations that occur during program execution are:
Java consists of the following categories of built-in exceptions:
•
Checked Exceptions
•
Unchecked Exceptions
The following table lists the various checked exceptions in Java:
33
Implementing Exception Handling
•
•
•
You can implement exception-handling in a program by using the
following keywords:
•
try
•
catch
•
throw
•
throws
•
finally
Using try and catch statements
•
The try block encloses the statements that might raise an exception
within it and defines the scope of the exception handlers associated
with it.
•
The catch block is used as an exception-handler. You enclose the
code that you want to monitor inside a try block to handle a run
time error.
The following syntax shows how to declare the try-catch block:
try
{
34
// Statements that cause an exception.
}
catch(ExceptionName obj)
{
// Error handling code.
}
•
Using multiple catch statements
•
•
A single try block can have many catch blocks. This is necessary
when the try block has statements that raise different types of
exceptions.
•
The multiple catch blocks generate unreachable code error.
•
If the first catch block contains the Exception class object then the
subsequent catch blocks are never executed.
•
The Exception class being the superclass of all the exception classes
catches various types of exceptions. The Java compiler gives an error
stating that the subsequent catch blocks have not been reached.
•
This is known as the unreachable code problem.
•
To avoid unreachable code error, the last catch block in multiple catch
blocks must contain the Exception class object.
Using the finally clause
•
The finally block is used to process certain statements, no matter whether
an exception is raised or not.
•
The following syntax shows how to declare the try-finally block:
try
{
// Block of code
}
finally
{
// Block of code that is always executed irrespective of an exception being
raised or not.
}
Throwing an Exception
•
Using the throw statement
35
•
The throw statement causes termination of the normal flow of control of
the Java code and stops the execution of the subsequent statements if an
exception is thrown when the throw statement is executed.
•
The throw clause transfers the control to the nearest catch block handling
the type of exception object throws.
•
The following syntax shows how to declare the throw statement:
throw ThrowableObj
•
Using the throws statement
•
The throws statement is used by a method to specify the types of
exceptions the method throws.
•
If a method is capable of raising an exception that it does not handle, the
method must specify that the exception has to be handled by the calling
method.
•
This is done using the throws statement.
•
Implementing User-Defined Exception
•
The user-defined Exception class also inherits the methods defined in the
Throwable class.
•
The following table lists the various methods defined by the Throwable class:
The Nested try-catch Block
•
The try-catch block is used to handle exceptions in Java applications.
•
You can enclose a try-catch block in an existing try-catch block.
•
The enclosed try-catch block is called the inner try-catch block, and the
enclosing block is called the outer try-catch block.
•
If the inner try block does not contain the catch statement to handle an
exception then the catch statement in the outer block is checked for the
exception handler.
•
The following syntax shows how to create a nested try-catch block:
class SuperClass
36
{
public static void main(String a[])
{
<code>;
try
{
<code>;
try
{
<code>;
}
catch(<exception_name> <var>)
{
<code>;
}
}
catch(<exception_name> <var>)
{
<code>;
} } }
The super and this Keywords
•
The super keyword
•
•
Java provides the super keyword that enables a subclass to refer to
its superclass. The super keyword is used to access:
•
superclass constructors
•
superclass methods and variables
The syntax to invoke the constructor of a superclass using the
super() method is:
super (<parameter1>, <parameter 2>,..,<parameterN>);
In the above syntax, <parameter1>, <parameter 2>,..,<parameterN> refer to the list of
parameters that you need to pass to the constructor of the superclass.
•
If no parameters are passed to the super() method, it invokes the
default constructor of the superclass.
37
•
If the superclass contains the overloaded constructor, you can pass
parameters to the super() method to invoke a particular
constructor.
•
When you use the super() method in the constructor of the subclass,
it should be the first executable statement in the constructor.
•
The syntax to access the member variable of a superclass is:
super.<variable>;
•
The subclass can also access the member methods of the superclass
using the super keyword.
The this Keyword
•
The this keyword is used to refer to the current object.
•
You can use the this keyword when a method defined in a Java class
needs to refer to the object used to invoke that method.
•
The following code snippet shows how to use the this keyword:
Book(int bcode, double bprice)
{
this.bookCode=bcode;
this.bookPrice=bprice;
}
In the above code snippet, the this keyword refers to the object that invokes the Book()
constructor.
•
Another situation where you can use the this keyword is when the
local and instance variables have the same name.
•
The following code snippet shows how to use the this keyword
when instance and formal parameters have the same name:
Book(int bcode, double bprice)
{
this.bcode=bcode;
this.bprice=bprice;
}
In the above code snippet, this keyword refers to the instance variables, bcode and
bprice. The values of the formal parameters, bcode and bprice of the Book() constructor
are assigned to the instance variables.
•
In addition, you can use the this keyword in a constructor of a class
to invoke another constructor of the class.
38
•
Unlike the super keyword, the this keyword can invoke the
constructor of the same class.
•
The following code snippet shows how to invoke a constructor using
the this keyword:
class Book {
public Book(String bname)
{
this(bname, 1001); }
public Book(String bname, int bcode) {
bookName=bname;
bookCode=bcode; }
}
FAQs
•
Can classes inherit from more than one class in Java?
No, a class cannot be inherited from more than one class in Java. A class is
inherited from a single class only. However, multi-level inheritance is possible in Java.
For example, if class B extends class A and class C extends class B, class C automatically
inherits the properties of class A.
•
What is the difference between an interface and a class?
Both, class and interface, contain constants and methods. A class not only defines
methods but also provides their implementation. However, an interface only defines the
methods, which are implemented by the class that implements the interface.
FAQs (Contd.)
•
Do you have to catch all types of exceptions that might be thrown by
Java?
Yes, you can catch all types of exceptions that are thrown in a Java application
using the Exception class.
•
How many exceptions can you associate with a single try block?
There is no limit regarding the number of exceptions that can be associated with
a single try block. All the exceptions associated with a try block should be handled using
multiple catch blocks.
•
What are the disadvantages of inner classes?
The inner classes have various disadvantages. The use of inner class
increases the total number of classes in your code. The Java developers also find it
difficult to understand to implement the concept of inner class within the programs.
•
What is the level of nesting for classes in Java?
There is no limit of nesting classes in Java.
39
Objectives
In this lesson, you will learn to:
•
Create applets in Java
•
Identify various stages of an applet life cycle
•
Identify various graphic methods in Java
•
Use layout managers
•
Create Abstract Windowing Toolkit control components
•
Create Swing components
•
Create a Java applet
Creating Applets in Java
•
•
•
AWT Package
•
JDK consists of a package called Abstract Window Toolkit (AWT).
•
AWT is an Application Programming Interface (API) that is
responsible for building the Graphical User Interface (GUI) in Java.
•
The API of the AWT package consists of a collection of classes and
methods that enables you to design and manage the Graphical User
Interface (GUI) applications.
•
The AWT package supports applets, which help in creating
containers, such as frames or panels that run in the GUI
environment.
Introduction to Applets
•
An applet is a Java program that can be embedded in an HTML Web
page.
•
An applet is compiled on one computer and can run on another
computer through a Java enabled Web browser or an appletviewer.
•
Applets are developed to support the GUI in Java.
The Applet Class
•
The Applet class is a member of the Java API package, java.applet.
•
You use the Applet class to create a Java program that displays an
applet. The following figure shows the hierarchical representation
of the Java classes:
40
•
•
•
The Applet class contains various methods that are used to display
text and image, play an audio file, and respond when you interact
with an applet.
•
The following table lists the various methods of the Applet class:
To create an applet, you need to follow these steps:
1. Create a Java program for the Applet.
2. Compile the Java program.
3. Create a Web page that contains an applet.
4. Run the applet.
41
•
You run an applet in an appletviewer by giving the following command on
the command prompt:
appletviewer filename.html
•
You can also run an applet in a Web browser.
Using HTML Tags in Applets
•
You need to include a java class file in an HTML file to load that file in a
Web browser.
•
The APPLET tag is used to embed an applet in an HTML document.
•
The APPLET tag is written within the BODY tag of the HTML document.
•
The following syntax shows how to specify different parameters in an
APPLET tag:
<HTML> <HEAD> </HEAD>
<BODY>
<APPLET
CODE
CODEBASE
HEIGHT
WIDTH
VSPACE
HSPACE
ALIGN
ALT
<PARAM NAME= parameter_name VALUE=value of the parameter>
</APPLET>
</BODY>
</HTML>
•
The various attributes of an Applet tag are:
•
CODE and CODEBASE
•
The CODE attribute is used to indicate the name of the class
file that holds the current Java applet.
•
The CODE attribute is used when both the .java file and the
.html file are located in the same directory.
•
The CODEBASE attribute indicates the pathname where the
.class file is stored.
42
•
•
•
•
•
The CODEBASE attribute is used, if you store a java file in a
directory different from an HTML file.
•
The CODE attribute specifies the name of the class file
whereas the CODEBASE attribute contains an alternate
pathname where the classes are stored.
HSPACE and VSPACE
•
The HSPACE and VSPACE attributes specify the horizontal
and vertical spaces between an applet and the text.
•
The HSPACE attribute controls the space to the left and right
side of an applet.
•
The VSPACE attribute controls the space above and below an
applet.
ALIGN
•
The ALIGN attribute specifies the alignment of an applet.
•
You can specify various values to the ALIGN attribute, such as
LEFT, RIGHT, BOTTOM, TOP, BASELINE, MIDDLE, TEXTTOP,
ABSBOTTOM, and ABSMIDDLE.
The ALT attribute specifies the alternate text to be displayed if the
browser does not support the applet.
Passing Parameters to Applets
•
You need to pass parameters to an applet whenever you want to
send the details to a Java file through an HTML file.
•
You pass parameters to an applet by using the <PARAM> tag. The
PARAM tag contains the NAME and VALUE attributes.
•
The NAME attribute specifies the name of the parameter passed to
an applet, and the VALUE attribute specifies the value of the variable
to be passed.
•
The following syntax sets the value of the color as red:
<APPLET CODE=”MyFirstApplet.class” HEIGHT = 20 WIDTH =
20>
<PARAM NAME= “color” VALUE= “Red”>
</APPLET>
Identifying the Various Stages of an
Applet Life Cycle
•
The life cycle of an applet describes the sequence of stages, which begin
when an applet is loaded in an appletviewer or a Web browser and ends
when the applet is destroyed.
43
•
An applet inherits the properties and methods of the Applet class.
•
Java provides init(), start(), stop(), paint(), and destroy() as the basic
applet methods to control the execution of an applet.
•
The different stages of an applet life cycle are:
•
Initializing an applet
•
Starting the applet
•
Stopping the applet
•
Destroying the applet
•
Initializing an Applet
•
The init() method initializes an applet when the applet is
loaded for the first time.
•
It defines the objects and variables that are required to
execute an applet.
•
You apply the settings for fonts, colors, and initial parameters,
such as variables and constants in the init() method.
•
The init() method is also used to add components, such as
buttons and check boxes to an applet.
•
The following syntax shows how to define the init() method:
public void init()
{}
•
Starting the Applet
•
The start() method is called to start the execution of an applet
after it’s initialized with the init() method.
•
The start() method can be called more than once in an applet.
•
The following syntax shows how to define the start() method:
public void start()
{
/* start() method definitions. */
}
•
Stopping the Applet
•
The stop() method suspends the execution of an applet.
•
The stop() method is called when either an end user stops an
applet or an applet loses the focus.
44
•
You can use the stop() method to reset the variables and stop
a running applet.
•
The following syntax shows how to define the stop() method:
public void stop()
{
/* stop() method definitions. */
}
•
Destroying the Applet
•
The destroy() method is called when an applet is destroyed.
•
When you want to exit from the Web browser or
appletviewer of Java, an applet calls this method to release
the resources, such as parameters and images.
•
This method occurs only once in the life cycle of an applet.
•
The following syntax shows how to define the destroy()
method:
public void destroy()
{
/* destroy() method definitions. */
}
•
The following figure shows the life cycle of an applet:
45
Various Graphic Methods in Java
•
AWT supports various graphics methods that enable you to draw shapes,
such as line, arc, ellipse, circle, and rectangle in an applet.
•
Drawing Lines, Rectangles, and Polygons
•
You need to draw lines, rectangles, and polygons in an applet
for creating drawings in an applet.
•
The drawLine() method is used to draw lines in an applet.
•
The following syntax shows how to define the drawLine()
method:
void drawLine(int x1, int y1, int x2, int y2)
In the preceding syntax, the x1 and y1 arguments are the starting coordinates of a line.
The x2 and y2 arguments are the ending coordinates of the line.
•
The drawRect() is used to draw a rectangle.
•
The following syntax shows how to define the drawRect() method:
void drawRect(int x, int y, int width, int length)
In the preceding syntax, the x and y arguments specify the top left coordinates of a
rectangle. The width and length arguments specify the dimensions of the rectangle.
•
You can also draw arbitrary shapes, such as polygons using the
drawPolygon() and fillPolygon() methods.
•
The following syntax shows how to use the drawPolygon() method:
(int x[], int y[], int num)
In the preceding syntax, the x and y arguments specify an array of integers representing
the x and y coordinates of a polygon. The num argument specifies the total number of
points of the polygon.
•
Drawing Arcs, Circles, and Ellipses
•
You can draw an arc using the drawArc() method.
•
The following syntax shows how to define the drawArc() method:
void drawArc(int x, int y, int width, int height, int startAngle, int sweepAngle)
In the preceding syntax, the x and y arguments represent the top left end coordinates of
a bounding rectangle. The width and height arguments represent the dimensions of the
rectangle. The startAngle argument represents the angle at which an arc starts and the
sweepAngle argument represents the angular distance covered by the arc.
•
The drawOval() method is used for drawing circles and ellipses.
•
The following syntax shows how to define the drawOval() method:
46
void drawOval(int x, int y, int width, int height)
In the preceding syntax, the x and y arguments are the top left endpoints of a rectangle
enclosing a circle or an ellipse.
•
Painting Various Graphic Objects
•
The fillPolygon() method is used to draw a filled polygon in an
applet.
•
The following syntax shows how to define the fillPolygon() method:
void fillPolygon(int x[], int y[], int num)
In the preceding syntax, the x and y arguments specify an array of integers representing
the x and y coordinates of a polygon. The num argument specifies the total number of
points of the polygon.
•
The fillOval()method is used to draw filled circles and ellipses.
•
The following syntax shows how to define the fillOval() method:
void fillOval(int x, int y, int width, int height)
In the preceding syntax, the x and y arguments are the top left endpoints of an oval.
•
You can draw filled arcs using the fillArc() method.
•
The following syntax shows how to define the fillArc() method:
void fillArc(int x, int y, int width, int height, int startAngle, int sweepAngle)
In the preceding syntax, the x and y arguments represent the top left end coordinates of
a rectangle. The width and height arguments represent the dimensions of the rectangle.
The startAngle argument represents the angle at which an arc starts and the
sweepAngle argument represents the angular distance covered by the arc.
•
You can also draw a filled rectangle in an applet using the fillRect()
method. The following syntax shows how to define the fillRect()
method:
void fillrect(int x, int y, int width, int length)
In the preceding syntax, the x and y arguments specify the top left corner coordinates of
a rectangle. The width and length arguments specify the dimensions of the rectangle.
The AWT Control Components
•
Java provides the AWT control components, which contains classes that
enable you to create standard components, such as buttons, labels, and
text fields in Java.
•
A Java component enables you to accept input from an end user.
•
You can position AWT components in containers using the different layout
managers.
47
•
Using Various AWT Components
•
An AWT control is a component that enables end users to interact
with applications created in Java.
•
All AWT controls in Java are subclasses of the Component class.
•
The Component class provides the add() method to add AWT
components to containers, such as an applet or a window.
•
TextField: User interface components that accept text input
from an end user. A text field enables you to type text in a
single line. An instance of the TextField class is used to create
a text field.
•
TextArea: Used to accept text input from an end user, but it
enables you to type text in multiple lines. An instance of the
TextArea class is used to create a text area.
•
Button: Used for handling events. Java provides the Button
class to create AWT button components.
•
List: Is a scrollable list of text items that enables you to select
either one item or multiple items. You create a list using the
List class in Java.
•
CheckBox: Exist in dual state, checked and unchecked. You
can change the state of a check box by clicking the check box.
You create a check box using the CheckBox class.
•
Choice: Used to create combination boxes that are also
known as drop-down menus using the Choice class in Java.
You create a drop-down menu using the Choice class that
enables you to select a single item from the menu.
•
Labels: Used for displaying a single line of text in a container.
You create a label using the Label class.
The Swing Components
•
Swing components are a collection of lightweight visual components that
provide a replacement for the heavyweight AWT components.
•
Swing components contain the Pluggable Look and Feel (PL&F) feature
that allows applications to have the same behavior on various platforms.
•
Identifying the Swing Component Class Hierarchy
•
The JComponent class is the root of the Swing hierarchy, which is an
extension of the AWT container class.
•
The class hierarchy of the Swing components is categorized into:
48
•
Top-level Swing Containers: Acts as a container for placing
the intermediate-level and atomic swing components, such as
panels, frames, buttons, and check boxes.
•
Intermediate-level Swing Containers: Placed on the toplevel containers and contains atomic components.
•
Atomic Components: Placed on the intermediate-level swing
containers. Atomic components are used to accept input from
a user.
Using the Top-level Swing Containers
•
•
•
•
•
JApplet
•
The JApplet class is an extension of the AWT applet class.
•
The Swing components that contain an applet need to extend
the JApplet class.
•
The JApplet() constructor enables you to create a swing
applet instance when you create an instance of the JApplet
class.
JFrame
•
The JFrame class is an extension of the AWT Frame class.
•
You cannot add components directly to JFrame.
JDialog
•
The JDialog class is an extension of the AWT java.awt.Dialog
class.
•
The JDialog class is used to create modal and non-modal
dialog boxes.
Using the Intermediate Level Swing Containers
•
JPanel
•
JPanel class is an extension of the JComponent class that
provides a replacement for the AWT Panel class.
•
You create a panel and add various components to it.
•
The panel is further added to the content pane, which
represents the display area of a window, a dialog, or a frame.
•
JPanel supports all layout managers of AWT.
•
By default, JPanel applies the flow layout manager.
JTabbedPane
49
•
•
The JTabbedPane class is used to create a tabbed pane
component that enables you to switch between groups
of components by clicking a tab with a given label.
•
Tabs are added to the JTabbedPane object by using the
addTab() method.
•
The JTabbedPane class enables you to add multiple
components but it displays only a single component at
a time.
Using the Atomic Components
•
JButton
•
JTextField
•
JCheckBox
•
JComboBox
•
JLabel
•
JRadioButton
Using Layout Managers
•
The layout managers are used to position the components, such as an
applet, a panel, or a frame in a container.
•
The layout managers implement the java.awt.LayoutManager interface.
•
A layout manager is an instance of the LayoutManager interface in Java.
•
You can use the following method to apply the desired layout to the
components:
void setLayout(layoutManager obj)
In the preceding syntax, obj is the reference to the desired layout manager.
•
Java has various predefined classes of layout managers.
•
All layout managers make use of the setLayout() method to set the layout
of a container.
•
If the setLayout() method is not used, then the default layout of the
container is set.
•
The different types of layout managers are:
•
FlowLayout Manager
•
The flow layout is the default layout manager used for the
Applet class.
•
In the flow layout manager, the components are placed in a
container window in a sequence one after the other in rows.
50
•
•
Java provides the FlowLayout class to apply flow layout to the
various components that you are inserting in an applet.
•
You can use the following constructors to create an instance
of the FlowLayout class:
•
FlowLayout()
•
FlowLayout(int align)
•
FlowLayout(int align, int hgap,int vgap)
The different types of layout managers are:
•
BorderLayout Manager
•
BorderLayout is the default layout of the Frame class.
•
The BorderLayout layout manager divides the
container into north, south, east, west, and centre
regions.
•
You can place five components or controls in each part.
•
Java provides the BorderLayout class to apply the
border layout to the components.
•
The setLayout() method is used for applying border
layout to a container.
•
You specify the directions for the BorderLayout using
the
BorderLayout.NORTH,
BorderLayout.SOUTH,
BorderLayout.EAST,
BorderLayout.WEST,
and
BorderLayout.CENTER constants.
•
You can use the following constructors to create an
instance of the BorderLayout class:
BorderLayout()
BorderLayout(int h, int v)
•
GridLayout Manager
•
The grid layout is the layout that divides the container into
rows and columns.
•
The intersection of a row and a column of the grid layout is
called cell.
•
The GridLayout class of Java enables you to create a grid
layout.
•
All the components in a grid are of the same size.
•
You can use the following constructors to create an instance
of the GridLayout class:
51
•
•
•
GridLayout()
•
GridLayout(int r, int c)
•
GridLayout(int r, int c, int h, int v)
CardLayout Manager
•
The CardLayout class is used to implement an area that
contains different components at different times.
•
The CardLayout is often controlled by a combo box, and the
state of the combo box determines which panel (group of
components) CardLayout displays.
•
You can use the following constructors to create an instance
of the CardLayout class:
•
CardLayout()
•
CardLayout(int hgap, int vgap)
GridBagLayout Manager
•
GridBagLayout places components in a grid of rows and
columns, allowing specified components to span multiple
rows or columns. Not all rows necessarily have the same
height. Similarly, not all columns necessarily have the same
width.
•
GridBagLayout places components in rectangles (cells) in a
grid and uses the components' preferred sizes to determine
the size of the cells.
•
You can use the following constructor to create an instance of
the GridBagLayout class:
•
GridBagLayout()
•
The GridBag layout manager divides a container into a grid of equally sized
cells. In the GridBag layout, a component can extend over multiple rows
and columns.
•
You specify the position of each component by specifying its x and y
coordinates.
•
You can resize the component by assigning weights to the components in
the GridBag layout. Weights specify the horizontal and vertical space
required to fill the display area of a container.
•
The constructor to create an instance of the GridBagLayout class is
GridBagLayout() g = new GridBagLayout();
•
The syntax to define the setLayout() method is panel.setLayout(g);
52
•
You need to specify the constraints for each component, when you want to
size and position the components.
•
You apply the constraints in the GridBag layout manager by using the
setConstraints() method.
•
Constructors of the GridBagConstraints class
•
GridBagConstraints(): Creates a GridBagConstraints object with the
default values for the gridbag layout attributes.
•
GridBagConstraints(int gridx, int gridy, int gridwidth, int gridheight,
double weightx, double weighty, int anchor, int fill. Insets insets, int
ipadx, int ipady): Creates a GridBagConstraints object with the
specified values for the gridbag layout attributes.
Objectives
•
In this lesson, you will learn about:
•
Event-handling in Java
•
Event Classes
•
EventListener Interfaces
•
Adapter Classes
Event-Handling in Java
•
An object that describes a change of state in a source component is called
an event.
•
The source components can be the elements of the Graphical User
Interface (GUI).
•
Events are supported by the classes and interfaces defined in the
java.awt.event package.
•
Identifying the Source Of Events:
53
•
•
An event source is an object that generates an event.
•
An event source registers some listeners, which receive notifications
about a specific type of event generated by that particular event
source.
•
All the registered listeners are notified about the generation of an
event and receive a copy of the event object.
•
This is known as multicasting the event.
•
Some sources allow only single listener to register.
•
This is known as unicasting of event.
Various event sources and the types of events they generate:
Event Listeners and Event Handlers
•
An event listener listens for a specific event and is notified when
that specific event occurs.
•
An event listener registers with one or more event sources to
receive notifications about specific types of events and processes
the events.
54
•
An event-handler is called by the event listener whenever a specific
event occurs.
•
Event listeners are interfaces and the event-handler is a method
declared in the event listener interface that is implemented by the
application.
•
The syntax of a method that registers an event listener with an
event source is:
public void addTYPEListener(TYPEListener obj)
•
The Delegation Event Model
•
The delegation event model is based on the concept that source
generates the event and notifies one or more event listeners.
•
The delegation event model allows you to specify the objects that
are to be notified when a specific event occurs.
•
In delegation event model, the event listener has to be registered
with a source in order to get notified about the occurrence of a
particular event.
Event Classes
•
•
The Java event class hierarchy:
The Action Event class
•
ActionEvent is generated by an AWT component, such as a button,
when a component-specific action is performed.
55
•
The action event is generated when a button is pressed, a list item
double-clicked, or a menu item is selected.
•
The following syntax shows the declaration of the constructor of the
ActionEvent class is:
public ActionEvent(Object source, int id, String
•
•
is
command)
The main methods included in the Action Event class are:
•
String getActionCommand()
•
int getModifiers()
The MouseEvent class
•
The MouseEvent class extends the java.awt.event.InputEvent class.
•
The mouse event indicates that a mouse action has occurred on a
component.
•
The mouse events include:
•
•
Pressing a mouse button
•
Releasing a mouse button
•
Clicking a mouse button
•
Entering of mouse in a component area
•
Exiting of mouse from a component area
The mouse event class defines some integer constants that can be used to
identify several types of mouse events.
56
•
An event listener registers with an event source to receive
about the events of a particular type.
notifications
•
Various event listener interfaces defined in the java.awt.event package:
Using the MouseListener Interface
•
The MouseListener interface is implemented for receiving various mouse
events, such as when you press, click, release, enter, and exit a component.
•
Various public methods declared in the MouseListener interface:
Adapter Classes
57
•
The Java programming language provides adapter classes, which
implement the event listener interfaces containing more than one eventhandling method.
•
An adapter class provides an empty implementation of the event-handling
methods in an event listener interface.
•
The adapter classes are useful because they allows you to receive and
process only some of the events that are handled by a particular event
listener interface.
•
You can define a class that acts as an event listener by extending one of the
adapter classes and overriding its methods to handle a particular type of
event.
•
Using the MouseAdapter Class
•
•
The MouseAdapter class provides empty implementation of mouse
event-handling methods, such as mouseClicked(), mouseEntered(),
mouseExited(), mousePressed(), and mouseReleased().
•
A class that acts as a listener for mouse events extends the
MouseAdapter class and overrides the required methods.
Using the MouseMotionAdapter Class
•
The MouseMotionAdpater class provides empty implementation of
methods, such as mouseDragged() and mouseMoved().
58
•
A class that acts as a listener for mouse motion events extends the
MouseAdapter class and overrides the required method.
Packages in Java
•
A package is a set of classes that are stored in a directory, which has the
same name as the package name.
•
Packages enable you to organize the class files provided by Java.
•
Java packages are classified into two categories:
•
Java API packages
•
Java user-defined packages
The following table lists a few built-in Java packages:
59
The hierarchy of the Java API packages:
User–Defined Packages
•
When you write a Java program, you create many classes. You can organize
these classes by creating your own packages.
•
The packages that you create are called user-defined packages.
•
A user-defined package contains one or more classes that can be imported
in a Java program.
•
Creating a user-defined package
•
The following syntax shows how to create a user-defined package:
package <package_name>
// Class definition
public class <classname1>
{
// Body of the class.
}
public class <classname2>
{
// Body of the class.}
•
To create a user-defined package, perform the following steps:
•
Create a source file containing the package definition
•
Create a folder having the same name as package name and
save the source file within the folder.
•
Compile the source file.
60
•
Importing a user-defined package
•
You can include a user-defined package using the import
statement.
•
The following syntax shows how to implement the userdefined package, empDetails from the app directory in a
program:
import app.empDetails.Employee;
public class Director extends Employee
{
// Body of the class.
}
•
the classes that are available to import are present.
•
CLASSPATH enables you to put the class files in various
directories and notifies the JDK tools of the region of these
classes.
Exploring java.lang Package
•
The java.lang package provides various classes and interfaces that are
fundamental to Java programming.
•
The java.lang package contains various classes that represent primitive
data types, such as int, char, long, and double.
•
Classes provided by the java.lang package:
Objectives
•
In this lesson, you will learn about:
•
Using threads in Java
•
The life cycle of a thread
•
Creating threads
•
Identifying the thread priorities
•
Thread synchronization and inter-threaded communication
•
Garbage collection
Using Threads in Java
•
A thread is defined as the of execution of a program.
•
For example, a Central Processing Unit (CPU) performs various tasks
simultaneously, such as writing and printing a document, installing a
software, and displaying the date and time on the status bar. All these
processes are handled by separate threads.
61
•
•
A process that is made of one thread is known as single-threaded process.
•
A process that creates two or more threads is called a multithreaded
process.
Basic Concepts of multithreading
•
Multitasking is the ability to execute more than one task at the same
time.
•
Multitasking can be divided into two categories:
•
•
•
•
Process-based multitasking
•
Thread-based multitasking
Benefits of multithreading
•
Improved performance
•
Minimized system resource usage
•
Simultaneous access to multiple applications
•
Program structure simplification
Pitfalls of multithreading
•
Race condition
•
Deadlock condition
•
Lock starvation
The Thread class
•
The java.lang.Thread class is used to construct and access individual
threads in a multithreaded application.
•
The Thread class contains various methods that can obtain
information about the activities of a thread, such as setting and
checking the properties of a thread, causing a thread to wait, and
being interrupted or destroyed.
62
•
•
A few methods defined in the Thread class are:
•
getPriority(): Returns the priority of a thread.
•
isAlive(): Determines whether a thread is running.
•
sleep(): Makes the thread to pause for a period of time.
•
getName(): Returns the name of the thread.
•
start(): Starts a thread by calling the run() method.
The first thread to be executed in a multithreaded process is called
the main thread. The main thread is created automatically on the
start up of Java program execution.
The Life-cycle of a Thread
•
•
The various states in the life cycle of a thread are:
•
New
•
Runnable
•
Not Runnable
•
Terminated or Dead
The following figure shows the life-cycle of a thread:
Creating Threads
•
•
You can create a thread in the following ways:
•
Implementing Runnable interface
•
Extending the Thread class
Creating Threads by implementing the Runnable interface
•
The Runnable interface only consists of the run() method, which is
executed when the thread is activated.
63
•
When a program needs to inherit from a class other than from the
Thread class, you need to implement the Runnable interface.
•
The following syntax shows how to declare the run() method:
public void run()
•
You can use the following code to create a thread by implementing
the Runnable interface:
class NewThread implements Runnable
{
Thread t;
NewThread()
{
t = new Thread(this, "ChildThread");
System.out.println("Child Thread:" + t);
t.start();
}
public void run()
{ // Implementing the run() method of the Runnable interface
System.out.println("Child Thread Started");
System.out.println("Exiting the child thread");
}
}
class ThreadClass
{
public static void main(String args[])
{
new NewThread();
System.out.println("Main thread Started");
try
{
Thread.sleep(5000);
}
catch(InterruptedException e)
64
{
System.out.println("The main thread interrupted");}
System.out.println("Exiting the main thread");
}
}
•
Creating Threads by extending the Thread class
•
The class extending the Thread class calls the start() method to
begin the child thread execution.
•
You can use the following code to create a thread by extending the
Thread class:
class ThreadDemo extends Thread
{
ThreadDemo()
{
super("ChildThread"); // calls the superclass constructor
System.out.println("ChildThread:" + this);
start();
}
public void run()
{
System.out.println("The child thread started");
System.out.println("Exiting the child thread");
}
}
class ThreadDemoClass
{
public static void main(String args[])
{
new ThreadDemo();
System.out.println("The main thread started");
System.out.println("The main thread sleeping");
try
65
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("The main thread interrupted");
}
System.out.println("Exiting main thread");
})
•
Creating Multiple threads
•
You can create multiple threads in a program by implementing the
Runnable interface or extending the Thread class.
•
Using the isAlive() Method
•
The isAlive() method is used to check the existence of a
thread.
•
The following syntax shows how to declare the isAlive()
method:
public final boolean isAlive()
•
Using the join() Method
•
It is called the join() method because the thread calling the
join() method waits until the specified thread joins the calling
method.
•
The following syntax shows how to declare the join() method:
public final void join() throws InterruptedException
Identifying the Thread Priorities
•
The Java Run-time Environment executes threads based on their priority.
•
A CPU can execute only one thread at a time. Therefore, the threads, which are
ready for execution, queue up for their turn to get executed by the processor.
•
A thread with higher priority runs before threads with low priority.
•
Defining Thread Priority
•
Thread priorities are the integers in the range of 1 to 10 that specify the
priority of one thread with respect to the priority of another thread.
66
•
•
The threads are scheduled using fixed priority scheduling.
•
The Java Run-time system selects the runnable thread with the highest
priority of execution when a number of threads get ready to execute.
Setting the Thread Priority
•
You can set the thread priority after it is created using the setPriority()
method declared in the Thread class.
•
The following syntax shows how to declare the setPriority() method:
public final void setPriority(int newPriority)
Thread Synchronization and Interthread Communication
•
When two threads need to share data, you must ensure that one thread
does not change the data used by the other thread.
•
Synchronizing Threads
•
Synchronization of threads ensures that if two or more threads need
to access a shared resource then that resource is used by only one
thread at a time.
•
Synchronization is based on the concept of monitor.
•
The monitor controls the way in which synchronized methods
access an object or class.
•
To enter an object’s monitor, you need to call a synchronized
method.
•
When a thread calls the wait() method, it temporarily releases the
locks that it holds. In addition, the thread stops running and is
added to the list of waiting threads for that object.
67
Communication Across Threads
•
A thread may notify another thread that the task has been
completed. This communication between threads is known as
interthread communication.
•
The various methods used in interthread communication are:
•
wait()
•
notify()
•
notifyAll()
Garbage Collection
•
Garbage collection is the feature of Java that helps to automatically destroy
the objects created and release their memory for future reallocation.
•
The various activities involved in garbage collection are:
•
Monitoring the objects used by a program and determining when
they are not in use.
•
Destroying objects that are no more in use and reclaiming their
resources, such as memory space.
•
The Java Virtual machine (JVM) acts as the garbage collector that
keeps a track of the memory allocated to various objects and the
objects being referenced.
•
The various methods of the Runtime class used in memory
management are:
68
•
static Runtime getRuntime(): Returns the current runtime
object.
•
void gc(): Invokes garbage collection.
•
long totalMemory(): Returns the total number of bytes of
memory available in JVM.
Objectives
In this lesson, you will learn about:
•
Layers in JDBC architecture
•
Types of JDBC drivers
•
Classes and interfaces of JDBC API
•
Steps to create JDBC applications
Database Connectivity
•
Sun Microsystems has included JDBC API as a part of J2SDK to develop Java
applications that can communicate with databases.
•
The following figure shows the Airline Reservation System developed in
Java interacting with the Airlines database using the JDBC API:
•
JDBC Architecture:
•
Provides the mechanism to translate Java statements into SQL
statements.
•
Can be classified into two layers:
•
JDBC application layer
•
JDBC driver layer
69
•
•
JDBC Drivers:
•
Convert SQL statements into a form that a particular database can
interpret.
•
Retrieve the result of SQL statements and convert the result into
equivalent JDBC API class objects.
•
Are of four types:
•
JDBC-ODBC Bridge driver
•
Native-API Partly-Java driver
•
JDBC-Net Pure-Java driver
•
Native Protocol Pure-Java driver
JDBC-ODBC Bridge driver
Native-API Partly-Java driver
70
•
JDBC-Net Pure-Java driver
Native-Protocol Pure-Java driver
Using JDBC API
•
The JDBC API classes and interfaces are available in the java.sql and the
javax.sql packages.
•
The commonly used classes and interfaces in the JDBC API are:
•
•
DriverManager class: Loads the driver for a database.
•
Driver interface: Represents a database driver. All JDBC driver
classes must implement the Driver interface.
•
Connection interface: Enables you to establish a connection
between a Java application and a database.
•
Statement interface: Enables you to execute SQL statements.
•
ResultSet interface: Represents the information retrieved from a
database.
•
SQLException class: Provides information about the exceptions that
occur while interacting with databases.
The steps to create JDBC application are:
•
Load a driver
•
Connect to a database
•
Create and execute JDBC statements
•
Handle SQL exceptions
71
•
Loading a Driver
•
•
Programmatically:
•
Using the forName() method
•
Using the registerDriver()method
Manually:
•
•
By setting system property
Using the forName() method
•
The forName() method is available in the java.lang.Class class.
•
The forName() method loads the JDBC driver and registers the
driver with the driver manager.
•
The method call to use the the forName() method is:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
•
Using the registerDriver()method
•
You can create an instance of the Driver class to load a JDBC driver.
•
This instance enables you to provide the name of the driver class at
run time.
•
The statement to create an instance of the Driver class is:
Driver d = new sun.jdbc.odbc.JdbcOdbcDriver();
•
You need to call the registerDriver() method to register the Driver
object with the DriverManager.
•
The method call to register the JDBC-ODBC Bridge driver is:
DriverManager.registerDriver(d);
Setting System Property
•
Add the driver name to the jdbc.drivers system property to load a
JDBC driver.
•
Use the –D command line option to set the system property on the
command line.
•
The command to set the system property is:
java –Djdbc.drivers=sun.jdbc.odbc.JdbcOdbcDriver
•
SampleApplication
Connecting to a Database
•
The DriverManager class provides the getConnection() method to
create a Connection object.
•
The getConnection()method method has the following three forms:
•
Connection getConnection (String <url>)
72
•
•
•
Connection getConnection (String <url>, String <username>,
String <password>)
•
Connection
getConnection
<properties>)
(String
<url>,Properties
Creating and Executing JDBC Statements
•
The Connection object provides the createStatement() method to
create a Statement object.
•
You can use static SQL statements to send requests to a database to
retrieve results.
•
The Statement interface contains the following methods to send
static SQL statements to a database:
•
ResultSet executeQuery(String str)
•
int executeUpdate(String str)
•
boolean execute(String str)
Handling SQL Exceptions
•
The java.sql package provides the SQLException class, which is
derived from the java.lang.Exception class.
•
You can catch the SQLException in a Java application using the try
and catch exception handling block.
•
The SQLException class contains various methods that provide
error information, these methods are:
•
int getErrorCode(): Returns the error code associated with
the error occurred.
•
String getSQLState(): Returns X/Open error code.
•
SQLException getNextException():
exception in the chain of exceptions.
Returns
the
next
Accessing Result Sets
•
A ResultSet object maintains a cursor that enables you to move through
the rows stored in a ResultSet object.
•
Types of Result Sets
•
The various types of ResultSet objects to store the output returned
by a database are:
•
Read only: Allows you to only read the rows in a ResultSet
object.
•
Forward only: Moves the result set cursor from first row to
last row in forward direction only.
73
•
•
Scrollable: Moves the result set cursor forward or backward
through the result set.
•
Updatable: Allows you to update the result set rows
retrieved from a database table.
The createStatement() method has the following three overloaded
forms:
•
Statement createStatement()
•
Statement createStatement(int, int)
•
Statement createStatement(int, int, int)
Querying and Modifying Data Using the PreparedStatement Object
•
The PreparedStatement interface is derived from the Statement interface
and is available in the java.sql package.
•
The PreparedStatement object:
•
•
Allows you to pass runtime parameters to the SQL statements to
query and modify the data in a table.
•
Is compiled and prepared only once by JDBC. The future invocation
of the PreparedStatement object does not recompile the SQL
statements.
•
Helps in reducing the load on the database server and thus
improving the performance of the application.
Methods of the PreparedStatement Interface
•
The PreparedStatement interface inherits the following methods to
execute SQL statements from the Statement interface:
•
ResultSet executeQuery(): Executes a SELECT statements
and returns the result in a ResultSet object.
74
•
int executeUpdate(): Executes an SQL statement, INSERT,
UPDATE, or DELETE and returns the count of the rows
affected.
•
boolean execute(): Executes an SQL statement and returns a
boolean value.
•
The prepareStatement() method of the Connection object is used
to submit parameterized query to a database.
•
The SQL statement can contain ‘?’ symbol as placeholders that can
be replaced by input parameters at runtime. For example,
stat=con.prepareStatement("SELECT * FROM authors WHERE au_id = ?");
•
The value of each ‘?’ parameter is set by calling an appropriate
setXXX() method, where XXX is the data type of the parameter. For
example,
stat.setString(1,"1001");
ResultSet result=stat.executeQuery();
•
Retrieving Rows
•
The code snippet to retrieve books written by an author from the
titles table using the PreparedStatement object is:
String str = "SELECT * FROM titles WHERE au_id = ?";
PreparedStatement ps= con.prepareStatement(str);
ps.setString(1, "1001");
ResultSet rs=ps.executeQuery();
Objectives
In this lesson, you will learn about:
•
Need for JSP
•
Life cycle of JSP application
•
Components of JSP
•
Classes in JSP API
•
Steps to create and deploy a JSP application
JSP Technology
•
Introduction to JSP Technology
•
JSP technology facilitates the segregation of the work profiles of a
Web designer and a Web developer.
•
A Web designer can design and formulate the layout for a Web page
by using HTML.
75
•
•
A Web developer, working independently, can use Java code and
other JSP specific tags to code the business logic.
Differences between servlets and JSP are:
•
Servlets tie up files to independently handle the static presentation
logic and the dynamic business logic. On the other hand, JSP allows
Java to be embedded directly into an HTML page by using special
tags.
•
Servlet programming involves extensive coding. Any changes made
to the code requires identification of the static code content and
dynamic code content to facilitate incorporation of the changes. On
the other hand, a JSP page, by virtue of the separate placement of
the static and dynamic content, facilitates both Web developers and
the Web designer to work independently.
•
JSP Life Cycle is represented as shown:
•
JSP life cycle methods are:
•
•
jspInit(): Is invoked at the time when the servlet is initialized.
•
jspService(): Is invoked when request for the JSP page is received.
•
jspDestroy(): Is invoked before the servlet is removed from the
service.
The following code shows the sample structure of a JSP Page:
<%--This is the HTML content--%>
<%@ page language=”java” %>
<HTML>
<HEAD><TITLE>Simple JSP example></TITLE></HEAD>
76
<BODY>
<H1>This is a code within the JSP tags to display the server time</H1>
<%--This is the JSP content that displays the server time by using the Date class of the
java.util package--%>
<% java.util.Date now=new java.util.Date(); %>
<H2><%= now.getHours() %>:<% =now.getMinutes() %>:<% =now.getSeconds()
%></H2>
</BODY>
</HTML>
Components of a JSP Page
•
•
•
The three components of a JSP page are:
•
JSP directives
•
JSP scripting
•
JSP actions
A directive element in a JSP page provides global information about a
particular JSP page and is of three types:
•
page Directive
•
taglib Directive
•
include Directive
The syntax for defining a directive is:
<%@ directive attribute=”value” %>
•
The page Directive
•
Defines attributes that notify the Web container about the general
settings of a JSP page.
•
The syntax of the page directive is:
<%@ page attribute_list %>
77
The include Directive
•
Specifies the names of the files to be inserted during the compilation
of the JSP page.
•
Creates the contents of the included files as part of the JSP page.
•
Inserts a part of the code that is common to multiple pages.
•
The syntax of the include directive is:
<%@ include file = ”URLname” %>
The taglib Directive
•
Imports a custom tag into the current JSP page.
•
Associates itself with a URI to uniquely identify a custom tag.
•
Associates a tag prefix string that distinguishes a custom tag with
the other tag library used in a JSP page.
•
The syntax to import a taglib directive in the JSP page is:
<%@ taglib uri=“tag_lib_URI” prefix=”prefix” %>
JSP Scripting Elements
•
Embed Java code directly into an HTML page.
•
Include various scripting elements, which are:
•
Declarations: Provide a mechanism to define variables and
methods. Declarative statements are placed within <%! and
%> symbols and always end with a semicolon.
•
Expressions: Insert values directly into the output. The
syntax to include a JSP expressions in the JSP file is:
<%= expression%>
•
Scriptlets: Consists of valid Java code snippets that are
enclosed within <% and %> symbols. The syntax to declare
JSP scriptlets to include valid Java code is:
78
<% Java code %>
JSP Actions
•
Perform tasks, such as insertion of files, reusing beans, forwarding a
user to another page, and instantiating objects.
•
The syntax to use a JSP action in a JSP page is:
<jsp:attribute>