Need for Java

hundredcarriageΛογισμικό & κατασκευή λογ/κού

3 Νοε 2013 (πριν από 3 χρόνια και 9 μήνες)

109 εμφανίσεις

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:Ar
e 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 variab
le 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 Employ
ee();

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 cons
tructor.




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 decl
are 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 sc
ope 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 no
t 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 refe
rencing 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 de
allocated 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 th
e 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>;<clas
spath2>...

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 condition
al 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 se
t 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 t
he 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 keywor
d 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 sta
tement
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 loo
ping 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 t
he 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 s
hows 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.



Th
e 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 a
t 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 l
oop 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 meth
od 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 parame
ters 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 prim
itive 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 a
ny 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 va
lue 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 compi
ler 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.



Overloade
d 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
-
va
lue:

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 th
e 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
pr
imitive 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 a
lso 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 th
e 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() metho
d 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 nes
ted 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 de
claration 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:


Objectives



Us
e operators



Arithmetic assignment
operators



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 o
perators.



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
assi
gnment 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:


















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

Operator

Use

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

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.


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 synt
ax 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 i
s 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.




24

















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 t
ype.



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.

Operators

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


25





The following syntax shows how to use a ca
st 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 Cub
oid



{



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 = heigh
t = 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 fro
m 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 structu
re 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 ov
erride 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 on
ly 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 interfac
e
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.print
ln(" ");



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


E
xceptions 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:



The unexpected situations that occur during program execution are:



Running out of memory



Resource allocation errors



Inability to find files



Problems in network connectivity



Exception Classes



The following figure shows the Exception

class heirarchy:



Built
-
in Exceptions



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 h
andlers 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 r
eached.



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 statement
s, 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 b
y 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 sta
tement.



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
-
cat
ch 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 Supe
rClass

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() metho
d 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 constru
ctor 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 sh
ows 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, doubl
e 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 clas
s.



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; }





}

FA
Qs



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 exten
ds 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 numbe
r 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 r
epresentation
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 CODEBA
SE



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 CODEBA
SE 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, BASE
LINE, 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
sen
d 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:



Initial
izing 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
execut
e 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 sho
ws 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 en
d 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 Met
hods 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 f
or 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 c
ircle 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 preced
ing 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 w
idth 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 i
n 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 rec
tangle. 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
tex
t 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 inte
ract
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 component
s 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:
Exi
st 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 c
lass 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



Swin
g 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 Conta
iners:
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 top
-
level containers and contains atomic components.



Atomic Co
mponents:
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 Fr
ame 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




JP
anel



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 wi
ndow, 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 sing
le 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 ob
j)


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
o
f 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 construct
ors 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, i
nt 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 s
ame
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 r
esize 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 GridB
ag 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.