Java 1
Java 1
Java 1
PROGRAMMING (JAVA)
C-126
Edition: 2017
No part of this publication which is material protected by this copyright notice may be
reproduced or transmitted or utilized or stored in any form or by any means now known
or hereinafter invented, electronic, digital or mechanical, including photocopying,
scanning, recording or . by any information storage or retrieval system, without prior
permission from the publisher.
Information contained in this book has been published by Laxmi Publications Pvt Ltd
and has been obtained by its authors from sources believed to be reliable and are correct
to the best of their knowledge. However, the publisher and its author shall in no event
be liable for any errors, omissions or damages arising out of use of this information and
specially disclaim and implied warranties or merchantability or fitness for any particular
use.
Published by: Laxmi Publications Pvt Ltd., 113, Golden House, Daryaganj, New Delhi-llO 002.
Tel: 43532500. E-mail: [email protected]
DEM-2231-86.50-INTERNET PROG (JAVA) C-126 -o
Typeset at: Goswami Associates, Delhi Printed at:
\
CONTENTS
Units Page No.
ADVANCED CONCEPTS
Unit 8: Applets
8.1 The Applet Class |
8.2 Applet Architecture !
8.3 An Applet Skeleton: Initialization and Termination j
. 8.4 Handling Events
8.5 HTML Applet Tag
\
Unit 9: Graphics and User Interface
. 9.1 Graphics Contexts and Graphics Objects
9.1.1 Color Control ^
9.1.2 Fonts •■'j
K
UNIT Fundamentals of JAVA
Programming
l NOTES
FUNDAMENTALS OF JAVA
PROGRAMMING
STRUCTURE ; J
Now a day, Java is widely used for applications and applets. The code for the
application in object format resides on the user’s machine and is executed by a run
time interpreter. Applications *are stand alone and are executed using a Java
interpreter. Whereas, A Java applet produces object code which restricts local user
resource access and can be normally be interpreted within the user’s browser. Applets
can be very useful, user friendly programs or can be a lot of fun. Applets are written in
HTML documents and are executed from within a Java empowered browser such as
Inter Explorer or Netscape Navigator. For instance, whenever we pull up any web
page, the Java code is embedded within HTML code. On the contrary any program
which is not embedded within HTML code is pertained to as an application. An Applet
Self-Instructional Material 1
Introduction to Internet is a program that runs within a web browser. The main idea of applets is to allow the
Programming (JAVA) program to be launched by any Java Enabled web browser. On the other hand Java
applications runs stand alone (can run like any program Le. on our computer). It
is important to note at this stage that by default, Java applets have some restrictions
NOTES when it Comes to dealing with the operating system. If we developed a program that
would be independent from the system, then applets would be a good solution. There
are certain methods which can help us to modifying those security restrictions. In
order to run an application or an applet on any machine we are required to have a
JVM (Java virtual machine) installed on our machine. Following are some important i
discussions and differences between applets and applications:
• Applets are the small programs while applications are larger programs.
• Applets don’t have the main method while in an application execution starts,
with the main method. Applets can run in our browser’s window or in an
appletviewer.
•. To run the applet in ah appletviewer will be an advantage for debugging^ ^
• Applets are the powerful tools because it covers half of the java language picture.
• Java applets are the best way of creating the programs in java.
• Both (Applets and the java applications) have the same importance at their own
places. Applications are also the platform independent as well as byte oriented
just like the applets. . _
• Applets are designed just for handling the client site problems, while the java
applications are designed to work with the client as well as server.
• Applications are designed to exist in a secure area, while the applets are typically
used.
• Applications and applets have much of the similarity such as both have most of
the same features and share the same resources.
• Applets are created by extending the java.applet. Applet class while the java
applications start execution from the main method.
• Applications are not too small to embed into a HTML page so that the user can
view the application in our browser. On the other hand applets have the
accessibility criteria of the resources.
The key feature is that while they have so many differences but both can perform
the same purpose.
To create an applet just creates a class that extends the java.applet. Applet class
and inherit all the features available in the parent class. The following programs make
all the things clear:
import java.awt.*;-
import java.applet;
class Myclass extends Applet{
public void init{){
/* All the variables, methods and images initialize here will
be called only once because this method is called only once when
the applet is first initializes*/
2 Self-Instructional Material
Fundamentals of JAVA
)
Programming
public void start{){
/* The components needed to be initialize more than once in
applet, are written here. This method can be called more than NOTES
cftice.*/
}
public void stop(){
/*-This method is the counterpart to start(). The code, used to
stop the execution is written here*/
}
public void destroy(){ j
/* Thi's^method contains the code that result-in to release the
resources.-to the applet before it is-.finished. This method is
called only once.*/ f-
• }
public void paint(Graphics g){-
/* Write the code in this method to draw, write, or Color things
on the applet pane are */
}}
In the above applet we have seen that there are five methods. In which two (init()
and destroy) are called only once while remaining three (start(), stopO, and paintO)
can be called any number of times as per the requirements. The major difference
between the two (applet and application) is thatiava applications are designed to
work under the homogenous and more secure areas. Java applets are designed to run
the heterogeneous and probably unsecured environment. Internet has imposed several
restrictions on it. The conclusion is that the java applets provides a wide variety of
formats for program execution and a very tight security model on the open environment
as on the Internet. "
Java applications have the majority of differences with the java applets.
Applications are stand-alone programs that do not require the use of a browser.
Java applications run by starting the Java interpreter from the command line and by
specifying the file that contains the compiled application. Applications usually reside
on the system on which they are deployed. Applications access resources on the system,
and are restricted by the Java security model. The following program illustrates the
structure of the java application: 1
Self-jnstrujpiftyjal Material 3
Introduction to Internet
Programming (JAVA) public static void main(Strihg args[]){
/* The application starts it's actual execution from this place.
★★/
NOTES }}
The main method here is nothing but the system method used to invoke the
application. The code that results an action should locate in the main method. Therefore
this method is more than the other method in any java application.
Self-Instructional Material 5
Introduction to Internet simple. Efficient code is produced: the compiler does automatic register allocation and
' Programming (JAVA) some optimization when it produces the bytecodes.
• Dynamic: In a number of ways, Java is a more dynamic language than C or
C++. It was designed to adapt to an evolving environment. For example, one major
NOTES problem with C++ in a production environment is a side-effect of the way that code is
implemented. If company A produces a class library (a library of plug and play
components) and company B buys it and uses it in their product, then if A changes its
library and distributes a new release, B will almost certainly have to recompile and
redistribute their own software. In an environment where the end user gets A and B’s
software independently (say A is an OS vendor and B is an application vendor) problems
can result. For example, if A distributes an upgrade to its libraries, then all of the
.software from B will break. It is possible to avoid this problem in C++, but it is
extraordinarily difficult and it effectively means not using any of the language’s 00
features directly. j
Package Description
java.beans.beancontext Additional classes that define bean context objects that hold
and provide services to the JavaBeans objects they contain.
(Contd.)
6 Self-Instructional Material
Fundamentals of JAVA
java.io Classes and interfaces for input and output. Although some Programming
of the classes in this package are for working directly with
files, most are for working with streams of bytes or characters.
javaJang The core classes of the language, such as String, Math, NOTES
System, Thread, and Exception.
java.security.cert Classes and interfaces for working with public key certificates.
Above Table 1.1 does not list all the packages in the Java platform. Java also
defines numerous packages for graphics and graphical user interface programming
and for distributed, or enterprise, computing. The graphics and GUI packages are
java.awt and javax.swing and their many subpackages. The enterprise
packages of Java include java.rmi, java.sql, javax.jndi, org.omg.CORBA,
org.omg.CosNaming, and all of their subpackages.
Self-Instructional Material 7
Introduction to Internet
Programming (JAVA) 1.4. JAVA LIBRARIES
A library is a reusable software component that saves developers time by providing
NOTES access to the code that performs a programming task. Libraries exist to assist with'
many different types of tasks. Library design is difficult. Most modem languages try
to help the programmer create good libraries, and the Java language is no exception.
Our objective is to learn how the Java language can help to build an effective library.
To achieve this goal, we’ll discuss the design of a simple library that facilitates
implementing network servers. When creating a network server, there are a number
of issues to consider:
• Listening on a socket.
• Accepting connections.
• Getting access to the streams represented by a connection.
• Processing the incoming data in some way, and sending back a response.
The Java Library is a set of dynamically loadable libraries that Java applications
can call at runtime. Because the Java Platform is not dependent on any specific
operating system, applications cannot rely on any of the existing libraries. The Java
class libraries serve three purposes within the Java Platform:
• Like other standard code libraries, they provide the programmer a well-known
set of useful facilities, such as container classes and regular expressions.'
• In addition, the class libraries provide an abstract interface to tasks that would
normally depend heavily on the hardware and operating system.
•T* Finally, some underlying platforms may not support all of the features a Java
application expects. In these cases, the class libraries can either emulate those .
features using whatever is available.
The Java Class Library is almost entirely written in Java itself, except for the
parts that need direct access to the hardware and operating system (such as for I/O, or
bitmap graphics). The classes that give access to these functions commonly use native
interface wrappers to access the API of the operating system. Almost all of the Java
Class Library is stored in a .single Java archive file called “rt.jar”, which is provided
with JRE and JDK distributions. The Java Class Library (rtjar) is located in the
default bootstrap classpath, and does not have to be found in the classpath declared
for the application.
Features of the Class Library are accessed through classes grouped by packages.
• Java'.lang contains fundamental classes and interfaces closely tied to the
language and runtime system.
• I/O and networking: access to the platform file system and more generally
to networks, is provided through the java.io, and java.net packages.
• Mathematics package: java.math provides regular mathematical
expressions, as well as arbitrary-precision decimals and integer’s numbers.
• Collections and Utilities: provide built-in Collection data structures, and .
various utility classes, for Regular expressions, Concurrency, logging and Data
compression.
8 Self-Instructional Material
• GUI and 2D Graphics: the java.awt package supports basic GUI operations Fundamentals of JAVA
and binds to the underlying native system. It also contains the 2D Graphics Programming
API. '
• ' Sound: provides interfaces and classes for reading, writing, sequencing, and
NOTES
synthesizing of sound data.
• Text: the java.text package deals with text, dates, numbers, and messages.
i
Self-Instructional Material 9
■Introduction to Internet
Programming (JAVA) /* filename: Hello.java
A Simple application program which displays "Hello, world!" to
the terminal,. */
NOTES
public class Hello
{public static void main(String[ ] args)
{System.out.println("Hello, world!");// message string in
in one line
)}
• Every Java program is a class.
• This program MUST be written in a file called Hello.java —
because the class name is Hello.
• Java is case sensitive (Hello is different, from hello).
• The "main" in Java is ALWAYS indicated by "public static
void main(String[] args)"—where "args" is a variable chosen
by the user. ' ' '
• Every statement in Java ends with a semicolon;
•A multi-line comment is bounded by /'* */, and a ingle-line
comment starts with//.
* • System.out is the console terminal.
• println is a "method" which prints a string in one line
(followed by a newline/carriage return).
To compile Java code, we need to use the ‘javac’ tool. From a command line, the
command to compile this program is: javac Hello.java
For this to work, the javac must be in shell’s path or must explicitly specify the
path to the program. If the compilation is successful, javac will quietly end and return
to a .command prompt. To run the program simply you can run with the command:
java Hello and then see the result or output like: Hello, world !
• •. Classes: In Java, everything is an object, because Java is an object oriented
language. In object oriented programming we use what are called classes.
Class is short for classification, and can be thought of as meaning “thing” of
“item” or similar terms. A class has attributes and functions just like real
objects. On my desk there is a water bottle. It has attributes like dimensions,
color, volume, and water level. All water bottles have these attributes. In
Java (and other programming languages), these are modeled as variables.
• Instances:. The distinction between an object and a class is tricky but
Important. A class can be thought of as a type, category, or definition. For
example, the class “water bottle” consists of all the characteristics and functions
that are common to all water bottles. An object, however, is an instance of a
class. The particular water bottle on the desk is an object because it is an
instance of a more general class. For functionality, my water bottle has abilities
like drinking water and throwing it at someone. In Object Oriented progra
mming these are called methods. Methods are things that can do to or with an
Object. The public keyword indicates visibility. It indicates that everyone can
10 Self-Instructional Material
see this class. In Java these are a few visibility levels, but for completeness Fundamentals of JAVA
they are: Programming
• Parameters: The main function takes one parameter called args. Args is an
array of type String which is indicated by the line String[]. Args is used to
receive command line arguments if this program is called from the command
line. Each argument would end up in a different cell for the array.
• Braces: In Java, braces {} are used to begin and end blocks. We see one opening
brace {after the class declaration, which signifies the beginning of the class’s
contents. We next see an opening brace {on the line declaring main to indicate
the beginning of its contents. We then see a} after the System.out.println
statement, which closes the main function and ends its contents. Braces are
always paired.for each opening brace {there must be a closing brace}. Finally,
; the class is closed with the last closing brace}.
• Printing: The statement in.the function that says System.out.println is a
print statement. It sends output to the Java console window. It is actually a
call to a built in Java function that takes a parameter of a String to be printed.
Here we supply the String “Hello World” as a literal String. Strings in Java
are always enclosed in quotations marks
• Semicolon: Finally, this line ends in a semicolon(;). In Java, semicolons end
all lines of the program other than control constructs like for, if and while or
function and class declarations. Everything before the semicolon is one line of
code, even {if.it spans manylines of text.
11 ■ • i
j
Self-Instructional Material 11
Introduction to Internet • Comments: In Java comments being with either // if they are one line or /* if
Programming (JAVA). they span multiple lines, Single line comments end at a carriage return and
multi-line comments end at a */. Comments.are ignored by the compiler and
used by humans to understand their own and other people’s code.
NOTES • Saving a file: Now, open favorite text editor and paste in this source code.
Now save the file as Hello.java it is important that this name be exact. In
Java, the source file name must have the name of the class with a .java
extension, otherwise it will not compile.
\
SUMMARY
• Now a day, Java is widely used for applications and applets. The code for the
application in object format resides on the user’s machine and is executed by
a run-time interpreter.
• Java enables the .construction of virus-free, tamper-free systems. The
authentication techniques are based on public-key encryption. There is a strong
interplay between "robust” and "secure.”
• The sizes of the primitive data types are specified, as is the behavior of
• arithmetic on them.
• The multi platformed environment of the Web places extraordinary demands
on a program, because the program must-execute reliably in a variety of
systems.
• While tKe performance of interpreted bytecodes is usually more than adequate; ;:v:
there are situations where higher performance is required.
REVIEW QUESTIONS
12 Self-Instructional Material
UNIT Data Types, Operators
and Arrays
2 NOTES
Self-Instructional Material 13
Introduction to Internet of java are performed. This behaviour specifies that, Java is a strongly-typed
Programming (JAVA) programming language. The data types in the Java programming language are divided
into two categories i.e., Primitive Data Types and Reference Data Types. Data
types in java can be explained using the following hierarchy structure: '
NOTES
Java Data Types
T
Integer Floating Array Class Interface
Data Types Data Types
1. Primitive Data Types: The primitive data types are predefined data types,
which always hold the value of the same data type, and the values of a primitive data '
type don’t share the state with other primitive values. These data types are named by
a reserved keyword in Java programming language. There are eight primitive
data types supported by Java programming language:
• Byte: The byte data type is an 8-bit signed two’s complement integer. It ranges
from -128 tol27 (inclusive). This type of data type is useful to save memory in
large arrays. We can also use byte instead of int to increase the limit of the
code. The syntax of declaring a byte type variable is shown as: byte b = 5 ;
• Short: The short data type is a 16-bit signed two’s complement integer. It
ranges from -32,768 to 32,767. Short is used to save memory in large arrays.
The syntax of declaring a short type variable is shown as: short s = 2;
• Int: The int data type is used to store the integer values not the fraction .
values. It is a 32-bit signed two’s complement integer data type. It ranges
from -2*147,483,648 to 2,147,483,647 that is more enough to store large number
in your program. However for wider range of values use long. The syntax of
declaring a int type variable is shown as: int num = 50;
. • Long: The long data type is a 64-bit signed two’s complement integer. It ranges
from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data
type with larger range of values. The syntax of declaring a long type variable
is shown as: long In = 746; . \
• Float: The float data type is a single-precision 32-bit IEEE 754 floating point.
It ranges from 1.40129846432481707e-45 to 3.40282346638528860e+38
(positive or negative). Use a float (instead of double) to save memory in large
arrays. We do not use this data type for the exact values such as currency. For -
that we have to use java.math.BigDecimal class. The syntax of declaring a
float type variable is: float f = 105.65 ; float f = -5000.12
• Double: This data type is a double-precision 64-bit IEEE 754 floating point.
It ranges from 4.94065645841246544e-324d to 1.79769313486231570e+308d
(positive or negative). This data type is generally the default choice for decimal
values. The syntax of declaring a double type variable is shown as:
double d 6677.60
14 Self-Instructional Material
• Char: The char data type is a single 16-bit, unsigned Unicode character. It Data Types, Operators
ranges from 0 to 65,535. They are hot integral data type like int, short etc. i:e., and Arrays
the char data type can’t hold the numeric values. The syntax of declaring a
char type variable is shown as: char caps.as‘c*;
• . Boolean: The Boolean data type represents only two values: true and false NOTES
and occupy is 1-bit in the memory. These values are keywords in Java and
represent the two boolean states: on or off, yes or do. We use boolean data
type for specifying conditional statements as if, while, do, for. In Java, true
and false are not the same as True and False. They are defined constants of
the language. The syntax of declaring a-boolean type variable is shown as:
boolean result = true; |
The ranges of these data types can be described with default values using the
following table:
When we declare a field it is not always essential that we initialize it too. The
compiler sets a default value to the fields which are riot initialized which might be zero
or null. However this is not recommended. '
Integer Data Types: So far you would have been known about these data types.
Now let’s take an Integer data type in brief to better understand:
Self-Instructional Material 15
Introduction to Internet As we have described that an integer number can hold a whole number. Java
Programming {JAVA) provides four different primitive integer data types that can be defined as byte, short
int, and long that can store both positive and negative values. The ranges of these
data types can be described using the following table:
NOTES
Data Size (in bits) Minimum Range Maximum Range
Type
Reference Data
Types
In Java a reference data type is a variable that can contain the reference or ar
address of dynamically created object. These types of data type are not predefined likf
primitive data type. The reference data types are arrays, classes and interfaces
that are made and handle according to a programmer in a java program, which cai
hold the three kinds of values as:
> array type //Points to an array instance
> class type //Points to an object or a class instance
> interface type- //Points to ah object and a method, which is
implemented
//to the corresponding interface
• Array Type: An array is a special kind of object that contains values calle<
elements. The java array enables the user to store the values of the sam
type in contiguous memory allocations. The elements in an array ar
identified by an integer index which initially starts from 0 and ends wit’
one less than number of elements available in the array. All elements of a
16 Self-Instructional Material
array must contain the same type of value i.e., if an array is a type of integer Data Types,t Operators
then all the elements must be of integer type. It is a reference data type and Arrays
because the class named as Array implicitly extends java.lang.Object. The
syntax of declaring the array is shown as:
NOTES
DataType [] variable!, variables,. .. variableN;
DataType [] variable « new DataType [ArraySize];
DataType [] variable = {item 1, item 2,..'.item n);
For example:
In the first statement, an array variable “a” is declared of integer data type that
holds the memory spaces according to the size of int. The index of the array starts
from a[0] and ends with a[9]. Thus, the integer value can be aissigned for each or a
particular index position of the array.
In the second statement, the array “b” is declared of string data type that has
the enough memory spaces to directly hold the three string values. Thus each value is
assigned for each index position of the array.
• class type: We know that Java is an object-oriented programming language
where an object is a variable, associated with methods that are described by a
class. The name of a class is treated as a type in a java program, so that you
can declare a variable of an object-type, and a method which can be called
using that object-type variable. .
Whenever a variable is created, a reference to an object is also created using the
name of a class for its type i.e., that variable can contain either null or a reference to
an object of that class. It is not allowed to contain any other kinds of values. Such type
.is called reference types in java. The object becomes ah instance when the memory
is allocated to that object using new keyword. In addition, array types are reference
types because these are treated as objects in Java. For example:
class Fruit
{fColor( H....}
fSize( ){....)
);
Fruit mango;
Fruit banana;
In the given example the Fruit is a class that has the reference variables as
mango and banana through which we can call the behaviours associated with that
class as mango.fColorO; within the main method of the super class.
• Interface Type: Java provides an another kind of reference data type or a
mechanism to support multiple inheritance feature called an interface.
The name of an interface can be used to specify the type of a reference. A
value is not allowed to be assign to a variable declared using an interface type
until the object implements the specified interface.
Self-Instructional Material 17
Introduction to Internet When a class declaration implements an interface, that class inherits all of the.
Programming (JAVA) variables and methods declared in that interface. So the implementations for all of the
methods declared in the interface must be provided by that class. For example, Java
provides an interface called ActionListener whose method named
NOTES actionPerformedO is used to handle the different kind of event. Java also provides a
class called Thread that implements Runnable interface. Thus the following
assignment can be allowed:
Runnable r;
R = new Thread{);
2.2. OPERATORS
Java provides a rich set of operators to manipulate variables. We can divide all
the Java operators into the following groups:
• Arithmetic Operators
• Relational Operators
• Bitwise Operators
• Logical Operators
• Assignment Operators
• Misc. Operators
• The Arithmetic Operators: Arithmetic operators are used in mathematical
expressions in the same way that they are used in algebra. The following
table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20 then:
Show Examples
18 Self-Instructional Material
• The Relational Operators: There are following relational operators Data Types, Operators
supported by Java language and Arrays
Assume variable A holds 10 and variable. B holds 20 theti:
Show Examples
NOTES
Operator Description Example
> Checks if the value of left operand is greater (A > B) is not true.
than the value of right operand, if yes then
condition becomes true. j
< Checks if the value of left operand is less than ; (A < B) is true.
the value of right operand, if yes then condition
becomes true.
>= Checks if the value of left operand is greater (A >= B) is not true.
than or equal to the value of right operand, if yes
then condition becomes true.
<= Checks if the value of left operand .is less than (A <= B) is true.
or equal to the value of right operand, if yes then
condition becomes true.
• The Bitwise Operators: Java defines several bitwise operators which can
be applied to the integer types, long, int, short, char, and byte.
Bitwise operator works on bits and performs bit by bit operation. Assume if
a = 60; and b = 13; Now in binary format they will be as follows:
a = 0011 1100 '
6 = 0000 1101
Self-Instructional Material 19
Introduction to Internet Show Examples
Programming (JAVA)
Operator Description Example
& Binary AND Operator copies a bit to the (A & B) will give 12 which is
NOTES result if it exists in both operands. 0000 1100
« Binary Left Shift Operator. The left A « 2 will give 240 which is
operands value is moved left by the lill 0000
number of bits specified by the right
operand.
>» Shift right zero fill operators. The left A >»2 will give 15 which is
operands value is moved right by the 0000 1111
number of bits specified by the right
operand and shifted values are filled
up with zeros.
• The Logical Operators: The following table lists the logical operators:
Assume boolean variables A holds true and variable B holds false then:
Show Examples
20 Self-Instructional Material
• The Assignment Operators: There are following assignment operators Data Types, Operators '
supported by Java language: and Arrays,
Show Examples
• Misc Operators: There are few other operators supported by Java Language.
• Conditional Operator (?:): Conditional operator is also known as the ternary
operator. This operator consists of three operands and is used to .evaluate boolean
expressions. The goal of the operator is to decide which value should be assigned to the
variable. The operator is written as :
' . * » 4. .
Self-Instructional Material 21
Introduction to Internet
a = 10;.
Programming (JAVA)
b (a == 1) ? 20: 30;
System.out.println{ "Value of b is + b);
NOTES b = (a 10) ? 20: 30;
System.out.println{ "Value of b is : " + b );.
})
Value of b is : 30
Value of b is : 20
• instance of Operator: This operator is used only for object reference variables.
The operator checks whether the object is of a particular type(class type or interface
type), instance of operator is written as:
If the object referred by the variable on the left side of the operator passes the
IS-A check for the class/interface type on the right side then the result will be true.
Following is the example:
This operator will still return true if the object being compared is the assignment
compatible with the type on the right. Following is one more example:
class Vehicle {}
22 Self-Instructional Material
lowest appear at the bottom. Within an expression, higher precedence operators will Data Types, Operators
be evaluated first. and Arrays
Bitwise XOR A
Left to right
Keywords are reserved words that are predefined in the language; see the table
below. All the keywords are in lowercase.
Self-InstructionalMaterial 23
Introduction to Internet • abstract: The abstract keyword is used to declare a class or method to be abstract.
Programming (JAVA) An abstract method has no implementation; all classes containing abstract
methods must themselves be abstract, although not all abstract classes have
abstract methods. Objects of a class which is abstract cannot be instantiated, but
NOTES can be extended by other classes. All subclasses of an abstract class must either
provide implementations for all abstract methods, or must also be abstract.
• boolean: The boolean keyword is used to declare a field that can store a boolean
, value; that is, either true or false. This keyword is also used to declare that a
. method returns a value of type boolean!
• break: Used to resume program execution at the statement immediately following
the current enclosing block or statement. If followed by a label, the program
resumes execution at the statement immediately following the enclosing labeled
statement or block.
• byte: The byte keyword is used to declare a field that can store 'an 8-bit signed
two’s complement integer. This keyword is also used to declare that a method
returns a value of type byte. ,
• case: The case keyword is used to create individual cases in a switch statement;
see switch. .
•- catch: Defines an exception handler—a group of statements that are executed if
an exception is thrown in the block defined by a preceding try keyword. The code
is executed only if the class of the thrown exception is assignment compatible
with the exception class declared by the catch clause.
• char: The char keyword is used to declare a field that can store a 16-bit Unicode
character. This keyword is also used to declare that a method returns a value of
type char.
• class: A type that defines the implementation of a particular kind of object. A
class definition defines instance and class fields, methods, and inner classes as
well as specifying the interfaces the class implements and the immediate
superclass of the class. If the superclass is not explicitly specified, the superclass
is implicitly Object.
• const: Although reserved as a keyword in Java, const is not used and has no
function.
• continue: Used to resume program execution at the end of the current loop body.
If followed by a label, continue resumes execution at the end of the enclosing
\ labeled loop body.
• default: The default can optionally be used in a switch statement to label a block
of statements to be executed if no case matches the specified value.
•. do: The do keyword is used in conjunction with while to create a do-while loop,
which executes a block of statements associated with the loop and then tests a
boolean expression associated with the while. If the expression evaluates to true,
the block is executed again; this continues until the expression evaluates to false.
• double: The double keyword is used to declare a field that can hold a 64-bit
double precision IEEE 754 floating-point number. This keyword is also used to
declare that a method returns a value of type double.
• else: The else keyword is used in conjunction|with if to create an if-else statement,.
which tests ’a boolean expression; if the expression evaluates to true, the block of
• statements associated with the if are evaluated; if it evaluates to false, the block'
of statements associated with the else are evaluated.
24- Self-Instructional Material
• enum: A Java keyword used to declare an enumerated type. Enumerations extend Data Types, Operators
the base class Enum. and Arrays
. Self-Instructional Material 25
Introduction to Internet native: Used in method declarations to specify that the method is not implemented
Programming (JAVA) in the same Java source file, but rather in another language.
new: Used to create an instance of a class or array/an object.
NOTES package: A group of types. Packages are declared with the package keyword.
Private: The private keyword is used in the declaration of a method, field, or
inner class; private members can only be accessed by other members of their own
class.
protected: The protected keyword is used in the declaration of a method, field,
or inner class; protected members can only be accessed by members of their own
class, that class’s subclasses or classes from the same package.
public: The public keyword is used in the declaration of a class, method, or field;
public classes, methods, and fields can be accessed by the members of any class.
return: Used to finish the execution of a method. It can be followed by a value
required by the method definition that is returned to the caller.
short: The short keyword is used to declare a field that can hold a 16-bit. signed
two’s complement integer. This keyword is also used to declare that a method
returns a value of type short.
static: Used to declare a field, method or inner class as a class field. Classes
maintain one copy of class fields regardless of how many instances exist of that
class, static also is used to'define a method as a class method,
strictfp: A Java keyword used to restrict the precision and rounding of floating
point calculations to ensure portability.
super: Used to access members of a class inherited by the class in which it appears.
Allows a subclass to access overridden methods and hidden members of its
superclass. The super keyword is also used to forward a call from a constructor to
a constructor in the superclass.
switch: The switch keyword is used in conjunction with case and default to create .
a switch statement, which evaluates a variable, matches its value to a specific
case, and executes the block of statements associated with that case.
synchronized: Used in the declaration of a method or code block to acquire the
mutex lock for an object while the current thread executes the code. For static
methods, the object locked is the class’ Class. The mutex lock is automatically
released when execution exits the synchronized code.
this: Used to represent an instance of the class in which it appears. This can be
used to access class members and as a reference to the current instance. This
keyword is also used to forward a call from one constructor in a class to another
constructor in the same class. ’ ' ’ ’
throw: Causes the declared exception instance to be thrown. This causes execution
to continue with the first enclosing exception handler declared by the catch
keyword to handle an assignment compatible exception type.
throws: Used in method declarations to specify which exceptions are not handled
within the method but rather passed to the next higher level of the program.
transient : Declares that an instance field is not part of the default serialized
form of an object. When an object is serialized, only the values of its non-transient
instance fields are included in the default serial representation.
26 Self-Instructional Material
• try: Defines a block of statements that have exception handling. If an exception Data Types, Operators
is thrown inside the try block, an.optional catch block can handle declared and Arrays
exception types. A try block must have at least one catch clause or a finally block.
• void: The void keyword is used to declare that a method does not return any
value. NOTES
, 1 •
• volatile: Used in field declarations to specify that the variable is modified
asynchronously by concurrently running threads. Methods, classes and interfaces
thus cannot be declared volatile. !
• .while: The while keyword is used to create a while loop, which tests a boolean
expression and executes the block of statements associated with the loop if the
expression.evaluates to true; this continues until the expression evaluates to
false.
Reserved words for literal values
> false: A boolean literal value.
> hull: A reference literal value.
> true: A boolean literal value.
intt = 3.2 + 2.5; intt = error intt can’t receive a decimal value
dub = 3.2 + 2.5; dub = 5.7 * this is a loss of precision error
intt = 3/2; intt = 1 . intt and dub both get the truncated
dub = 3/2; dub = 1.0 value of 1.5, dropping the decimal to get 1
Self-Instructional Material 27
Introduction to Internet Division with Integers: The last example requires further analysis. The rule
Programming (JAVA) to remember is that integers mixing with integers results in an integer. Even though
the result is stored in a double, it is a truncated integer before it is stored. So how can
we get the correct decimal answer when dividing integers? Below are two ways to
NOTES accomplish that. Assume the variable declarations given.
the result is that intt will contain 5, the truncated form of 5.7. This technique can be •
used in problem 12, when we want to round down to the nearest integer.
Type casting refers to changing an entity of one datatype into another. This is
important for the type conversion in developing any application. If.we stored an int
value into a byte variable directly, this will be illegal operation. For storing our
calculated int value in a byte variable we have to change the type of resultant data.
This type of operation has illustrated below:
1 In this example we will see that how to convert the data type by using type casting.
Inlthe given line of the code c = (char)(t?l:0); illustrates that if t which is boolean type
variable is true then value of c which is the char type variable will be 1 but 1 is a
numeric value. So, 1 is changed into character according to the Unicode value. But in
this line c = (char)(tVl 't'O); 1 is already given as a character which will be stored as it
is in the char type variable c.
Code of the program:
28 Self-Instructional Material
Data Types, Operators
long 1 = 24000;
and Arrays
float f = 3.14f;
double d = 0.000000000000053;
String g = "string"; NOTES
System.out.println{"Value•of all the variables like");
System.out.printlh("t = " + t ); I
System.out.println("b ="'+b);
System.out.println{"s = " + s );
System.out.println{"c ="+c);
System, out .println{ "i = " + i ); -|
System.out.println("l = "+.!);
System.out.println{"f = " + f );
System.out.println("d = " + d ); 1 • ' .
System.out.println("g = " + g ); j
I
System.out.println(); 1 - .
//Convert from boolean to byte.
b = (byte) <t?l:0); ' . . ,
System.out.println("Value of b after conversion : " + b);
//Convert from boolean to short,
s = (short)(t?l:0);
System.out.println("Value of s after conversion : " + s);
//Convert from boolean to int.
i = {int) {t ?1:0); ,|
System.out.println("Value, of i after conversion : " + i);
//Convert from boolean to char,
c = (char)(t?'l,:'0,);
System.out.println{"Value of c after conversion : " .+ c);
c (char) (t?l: 0);
System.out.println("Value ofc after conversion in Unicode
: " + c);
//Convert from boolean to long.
.1 (long)(t?l;0); '■
System.out.println("Value of 1 after conversion : " + 1);
//Convert from boolean to float.'
f (float)(t?1:0);
System.out.println("Value of f after conversion : " + f);
//Convert from'boolean to double. * '
d (double) (t?1: 0);
System.out.println{"Value of d aft$r conversion : " + d);
//Convert from boolean.to String.
\.
Self-Instructional Material .29
Introduction to Internet
g = String.valueOf{t);
Programming (JAVA)
System.out.println("Value of g after conversion : " + g);
g (String){t?"l":"0");
NOTES System.out.println("Value of g after conversion : " + g);
*int sum = (int) (b+i+l+d+f);
System.out.println{"Value of sum after conversion : " +
/ sum); -
• ))
Every class has at least one it’s own constructor. Constructor creates a instance
/
/ for the class! Constructor initiates something related to the class’s methods. Constructor
/. is the method which name is same to the class. But there are many difference between
the method s and the Constructor. In this example we will see that how to implement
the constructor feature in a class. This program is using two classes. First class is .
TestConstructor and second is the main class which name is TestConstructorClient:
Class TestConstructor •
{ int x,y;
I
TestConstructor (int a, int b){
I x a; y = b;
}
TestConstructor {)
{ x = 2; y 3;
}
int area{)
f
{ int ar = x*y; return(ar); •
}}
public class TestConstructorClient
{ public static void main(String[] args)
{ TestConstructor a = new TestConstructor ();'
System.out .println( "Area of rectangle : " + a.areaO);'
TestConstructor b = new TestConstructor(l,l);
System.out<println("Afea of rectangle : " + b.areaO);
}}
Constructors are used to assign initial values to instance variables of the class. A
default constructor with no arguments will be called automatically by the Java Virtual
Machine (JVM). Constructor is always called by new operator. Constructors are declared
just like as we declare method^, except that the constructor doesn’t have any return
type. Constructor caii be overloaded provided they should have different arguments
30 Self-Instructional Material
because JVM differentiates constructors on the basis of arguments passed in the . Data Types, Operators
constructor. s . and Arrays
Whenever we assign the name of the method same as class name. Remember this
method should not have any return type. This is called as constructor overloading. We
have made one program on a constructor overloading, after going through it the concept NOTES
of constructor overloading will get more clear. In the example below we have made
three overloaded constructors each having different arguments types so that the JVM
can differentiates between the various constructors.
Self-Instructional Material 31
Introduction to Internet
Prog ramming (JAVA) public int second()
{return{1 * b);
}
NOTES public Rectangle(float^x){
p = x; q = x;
}
public float third(){
return(p * q);
}
public Rectangle(float x, float y){
p. =:x; q y;
}
public float fourth (■){
return(p * q);
}}' .
2.7. ARRAYS
When you need to store same ‘type’ of data that can be logically grouped together,
then we can go for java array. For example, imagine if we have to store the list of
countries in individual java variables and manipulate them. We required more than
hundred variables to manage. Array is the most important thing in any programming
language. By definition, array is the static memory allocation. It allocates the memory
for the same data type in sequence. It contains multiple values of,same types. It also
store the values in memory at the fixed size. Multiple types of arrays are used in any
programming language such as:
one-dimensional, two-dimensional or can say multi-dimensional.
Declaration of an array:
int num[]; or int num = new int[23;
Some times user declares an array and it's size simultaneously.
We may or may not be define the size in the declaration time.-
such as:
int num[] = {50,20,45,82,25,63);
In this program we will see how to declare and implementation. This program
illustrates that the array working way. This program takes the numbers present in
the num[] array in unofdered list and prints numbers in ascending order. In this
program the sort() function of the java.util.*; package is using to sort all the numbers
present in the num[] array. The Arrays.sortO automatically sorts the list of number
in ascending order by default. This function held’the argument which is the array
name num.
32 Self-Instructional Material
Here is the code of the prograin: Data Types, Operators
and Arrays
import java.util.*;
public class array
{public static void main{String[] args) NOTES
{int num[] = {50,20,45,82,25,63);
int 1 = num. length-;
int i,j,t;
System.out.print("Given number : ");
for {i = 0;i < l;i++ \
{System.out.print(" " + num[i]);
>
System.out.println('‘\n"');
System.out.print{"Ascending order number : ")
Arrays.sort(num);
.:
for(i =0; i < 1; i++)
.{System, out .print ( " " + num[i])?
>}}
SUMMARY
• Data type defines a set of permitted values on which the legal operations can
be performed.
• The byte data type is an 8-bit signed two's complement integer. It ranges from
-128 to!27 (inclusive). This type of data type is useful to save memory in
large arrays.
• The short data type is a $6-bit signed two’s complement integer. It ranges
from -32,768 to 32,767. _
• The int data type is used to store the integer values not the fraction values.
Self-Instructional Material 33
Introduction to Internet The float data type is a single-precision 32-bit IEEE 754 floating point.
Programming (JAVA)
The Boolean data type represents only two values: true and false and occupy
is 1-bit in the memory.
A floating-point number represents a real number that may have a fractional
NOTES
values.
An array is a special kind of object that contains values called elements.
Conditional operator is also known as the ternary operator. This operator
consists of three operands and is used to evaluate boolean expressions.
Keywords are reserved words that are predefined in the language
The boolean keyword is used to declare a field that can store a boolean value;
that is, either true or false.
\ ' The byte keyword is used to declare a field that can store an 8-bit signed two’s
complement integer.
Although reserved as a keyword in Java, goto is not used and has no function.
Used at the beginning of a source file to specify classes or entire Java packages
to be referred to later without including their package names in the reference.
Type Casting refers to changing an entity of one datatype into another. This
is important for the type conversion in developing any application.
REVIEW QUESTIONS
34 Self-Instructional Material
UNIT Classes and Objects
in Java
3 NOTES
STRUCTURE
— Self-Instructional Material 35
Introduction to Internet
Programming (JAVA) 3.1. CLASSES AND OBJECTS
. To understand objects, we must understand classes. To understand classes, we
NOTES need to understand objects. Here we shall discuss about the concepts of Classes and
Objects.
• Object: Objects have states and behaviors. Example: A dog has states-color,
name, and breed as well as behaviors-wagging, barking and eating. An object is
an instance of a class.
• Class: A class can be defined as a template/blue print that describe the behaviors/
states that object of its t^e support.
Objects in Java: Let us now look deep into what are objects. If we consider the
real-world we can find many objects around us, Cars, Dogs, and Humans etc. All these
objects have a state and behavior. If we consider a dog then its state is: name, breed,
color and the behavior is; barking, wagging, running. If we compare the software object
with a real world object, they have very similar characteristics. Software objects also
have a state and behavior. A software object’s state is stored in fields and behavior is
shown via methods; So in software development methods operate on the internal state
of an object and the object-to-object communication is done via methods.
A typical Java program creates many objects. Object interactions, a program can
carry out various tasks, such as implementing a GUI, running ah animation, or sending
and receiving information over a network. Once an object has completed the work for
which it was created, its resources are recycled for use by other objects. Here’s a small
program, called CreateObjectDemo, that creates three objects: one Point object and
two Rectangle objects. You will need all three source files to compile this program.
36 Self-Instructional Material ■
System, out .prinCln('\Y Position of rectTwo: Classes and Objects
in Java
"+ rectTwo.origin.y);
i
Self-Instructional Material 37
Introduction '.o Internet • Class variables: Class variables are variables declared with in a class, outside
Programming (JAVA) any method, with the static keyword.
A class can have any number of methods to access the value of various kinds of
methods. In the above example, barking (), hungry () and sleeping () are variables.
NOTES
Below mentioned are some of the important topics that need to be discussed when
looking into classes of the Java Language. The introduction to object-oriented concepts
in the lesson titled Object-oriented Programming Concepts used a bicycle class as an
example, with racing bikes, mountain bikes and tandem bikes as subclasses. Here is
sample code for a possible implementation of a Bicycle class, to give an overview of a
class declaration. .Subsequent sections of this lesson will back up'and explain class
declarations step by step.
38 Self-Instructional Material
7/ the MountainBike subclass has one constructor Classes and Objects
in Java
public MountainBike(int startHeight, int startCadence,
int startSpeed, int startGear) ^
{ super(startCadence, startSpeed, startGear); NOTES
•seatHeight = startHeight;
}
'// the MountainBike subclass has one jnethod
public void seatHeight(int newValue) ^
{ seatHeight = newValue;
}}
MountainBike inherits all the fields and methods of Bicycle and adds the field,
seat Height and a method to set it. .
3.2. CONSTRUCTOR
A constructor is a special method that is used to initialize a newly created
object and is called just after the memory is allocated for the object. It can be used to
initialize the objects, to required, or default values at the time of object creation. It
is not mandatory for the coder to write a* constructor for the class. When discussing
about classes one of the most important sub topic would be constructors. Every class
has a constructor. Ifwe do not explicitly write a constructor for a class the java compiler
builds a default constructor for that class. Each time a new object is created at least
one constructor will be invoked. The main rule of constructors is that they should have
the same name as the class. A class can have more than one constructor. Example of a
constructor is given below:
class Puppy
{ public puppy() .
{ }
public puppy (String name){ j
// This constructor has one parameter, name.
}}
Java also supports Singleton Classes where you would be able to create only one
instance of a class. Constructors are similar to methods, but with some important
differences. Some of the important discussions about cipnstructor are given below:
• Constructor name is class name: A constructors must have the same name
as\ the class its in.
• Default constructor: If you don’t define a constructor for a class, a default
parameterless constructor is automatically created by the compiler. The default
constructor calls the default parent constructor (super ()) and initializes all
instance variables to default value (zero for numeric types, null for object
references, and false for booleans). j
Self-Instructional Material 39
Introduction to Internet • Default constructor is created only if there are no constructors: If you
Programming (JAVA) define any constructor for your class, no default constructor is automatically
created.
• Differences between.xnethods and constructors:
NOTES
There is no return type given in a constructor signature (header). The value is
this object itself so there is no need to indicate a return value.
There is no return statement in the body of the constructor.
The first line of a constructor must either be a call on another constructor in
the same class (using this), or a call on the superclass constructor (using
super). If the first line is neither of these, the compiler automatically inserts
a call to the parameterless super class constructor.
If no user defined constructor is provided for a class, compiler initializes member
variables to its default values.
• numeric data types are set to 0
• char data types are set to null character(‘\0’)
• reference variables are set to null .
In order to create a Constructor observe the following rules
1. It has the. same name as the class
2. It should not return a value not even void
Example:
class Demo
{ int valuel, value2;
Demo{)
{. valuel = 10;
value2 20;
System.out.printin'("inside Constructor");
}
public void display(){
System.out.println ("Valuel === " + valuel);
System.out.println < "Value2 === " + value2);
}
public static void main(String args[]){
Demo dl = new Demo () ;
dl.display ();
}
40 Self-Instructional Material
Account (int a); Classes and Objects
in Java
Account (int a, Int b);
Account (String a, int b);
Example: NOTES
class Demo ! .
{ int valuel, yalue2;
/* Demo ()
{ valuel = 10; value2 =20;
System.out.println {"Inside 1st Constructor ");
)*/ .
Demo (int a){
. valuel = a;
System.out.println ("Inside 2nd Constructor ");
3.3. SUBCLASSING
Declaring one class to be a subclass of another (class ... extends ...)—this allows
a subclass to inherit functionality from its superclass. To create an extendable class:
• all constructors, readObject, and clone must not invoke an overridable method
(one that is not static, private, or final)
Self-Instructional Material 41
Introduction to Internet • if a method depends on an implementation of a overridable method, this
Programming (JAVA) dependence must be explicitly stated in its javadoc.
• do not implement Serializable unless you absolutely need to.
NOTES • do not implement Cloneable unless you absolutely need to.
Consider using an “interface + default implementation” pair. This will allow users to
choose the desired style of inheritance:
• subclass the default implementation directly, •
• use the default implementation as a field, and forward calls to it,
• ignore the default implementation, and implement the interface entirely from
scratch. .
A Java subclass is a class which inherits a method or methods from a Java
superclass. A Java class may be either a subclass, a superclass, both, or neither!
The Cat class in the following example is the subclass and the Animal class is the
superclass.
public.class Animal {
public static void hide() {
System.out.println("The hide ,method in Animal.");
}
public void override()
{ System.out.println ("The override method in-Animal;
}}
public class Cat extends Animal
{ public static void hide() {
.System.out.println("The hide method in Cat.");
}
public void override()
{ System.out.println("The override method in Cat.");
}
public static void main(String[] args)
42 Self-Instructional Material
as identifiers i'.e., you cannot declare a variable or class with this name in your Java Classes and Objects
program. In Java, every class is a subclass ofjava.lang.Object. For example, Class X in Java
extends class Y to add functionality, either by adding fields br methods to class Y, or
by overriding methods of class Y. Take a look at the following example, which
demonstrates the use of the ‘extends’ keyword. 1 NOTES
public class A
{ public int number;
}
class B extends A
{ public void increment{)
{ number++;
}}
In this example, we inherit from class A, which means ^that B will also contain a
field called number. Two or more classes can also be inherited from the same parent
class, extends keyword is also used in an interface declaration to specify one or more
superinterfaces.
For instance:
interface Mylnterface {
•5 •?
}
interface Mylnterface extends Superinterface {
\
} '
The instanceof operator can be useful to call a method based explicitly on the
class of same object instead of implicitly using ah overridden method and polymorphism.
The instanceof operator determines if a given obj ect is of the type of a specific class. To
be more specific, the instanceof operator tests whether its first operand is an instance
of its second operand. The test is made at runtime. The first operand is supposed to be
the name of an object or an array element, and the second operand is supposed to be
the name of a class, interface, or array type. The syntax is : <opl> instanceof <op2>
The result of this operation is a boolean: true or false. If an object specified by
<opl> is an instance of a class specified by <op2>, the outcome of the operation is true,
and otherwise is false. The outcome of the operation will also be true if <op2> specifies
an interface that is implemented either by the class of the object specified by <opl> or
by one of its superclasses. For example, consider the following code fragment:
interface X{}
class A implements X {}
class B extends A {}
A a = new A();
B b new ri() ;
)•
Self-Instructional Material 43
Introduction to Internet Note that class B does not implement the interface X directly, but class A does,
Programming (JAVA) and class B extends class A. Given this code, all of the following statements are true:
if(b instanceof X)
NOTES if(b instanceof B)
if(b instance of A)
if (a instance, of A),
if{a instanceof X)
Knowing the type of an object at runtime is useful for the following reasons:
• Some invalid casts (explicit type conversions) involving class hierarchies cannot
be caught at compile time. Therefore, they must be checked at runtime (using
the instanceof operator), to avoid a runtime error.
• You might have a situation where one process is generating various kinds of
objects, and the other process is processing them. The other process may need
to know the object type before it can properly process it. In this situation the
instanceof operator would be helpful, too.
The instanceof operator allows us to determine the type of an object. It takes an
object on the left side of the operator and a type on the right side of the operator and
returns a boolean value indicating whether the object belongs to that type or not. This
is most clearly demonstrated with, an example:
Package test;
import java . util.Date;
import java .util .HashMap; •
import java.util.Map;
public class InstanceofTest {
public static void main{String[] args) {
Map m = new HashMapO;
System.out.println(wm instanceof Map: ” + (m instanceof Map));
System.out.println(wm instanceof HashMap: " +. <m instanceof
HashMap));
System.out.println("m instanceof Object: " + (m instanceof
Obj ect));
System.out .println {"m instanceof Date: " + (m instanceof Date)) ;
m=null;
/
System.out.println("m = null, m instanceof HashMap:
" + (m instanceof HashMap));
}}
44 Self-Instructional Material
We started by creating a Map object that is implemented using a HashMap. Map Classes and Objects
is an interface. Notice from the results that m is both ail instanceof Map and an in Java
instanceof HashMap. Thus, we can use interfaces in addition to classes on the right
side of the instanceof operator. From the results, also notice that m is an instanceof
Object. This makes sense, since every object in Java inherits from Object. The instanceof NOTES
operator returns' true if we ask if an object is an instanceofj one of its parent classes.
Notice that m is not an instanceof Date, since m is a Map object and is not an
implementation of the Date class. ; .
These class methods also can be called even when no instance of the class exists.
The code in a class method can only refer to static variables arid the argument variables.
There are situations in which the method’s behavior does not depend on the state of an
object. So, there Will be no use of having an object when the method itself will not be
instance specific.
Variables and methods marked static belong to the class rather than to any
particular instance of the class. These can be used without having any instances of
- that class at all. Only the class is sufficient to invoke a static method or access a static
variable. A static variable is shared by all the instances of that class i.e., only one copy
of the static variable is maintained.
class Animal
{
static int animalCount=0;
public Animal()
{animalCount + =1;
} public static void main(String[] args)
{ new Animal();
new Animal{);
new Animal();
System.out.println("The Number of Animals is: "+ animalCount);
}) 1 .
class Animal
{ static int animalCount = 0;
public Animal{)
{ animalCount + =1;
}
public static int getCount()
{return animalCount;
}}
class TestAnimal
{ public static void main(String[] args)
• { new Animal();
new Animal(); .
new Animal();
System.out.println("The Number of Animals is:
"+ Animal.getCount());
}}
final keyword can also apply to a method or a class. When applied to a method—it
means the method cannot be over-ridden. Specially useful when a method assigns a
state that should not be changed in the classes that inherit it, and should use it as it is
(not change the method behavior).When applied to a class it means that the class
cannot be instantiated. A common use is for a class that only allows static methods as
entry points or static final constants-to be accessed without a class-instance.
Advantages: !
• It is used only when we know that the value is not going to be changed further.
• It won’t allow anyone to change that value further iii anyway.
• It helps the compiler to generate code faster.
}}
Self-Instructional Material 47
/•
Introduction to Internet
Programming (JAVA) 3.8. ACCESS CONTROL
Encapsulation links data with the code that manipulates it. However
NOTES encapsulation provides another important attribute: access control. Through
encapsulation, we can control what parts of a program can access the members of a
class. We can define access control as the methods by which interactions with resources
are limited to collections of users or programs for the purpose of enforcing integrity,
confidentiality, or availability constraints. How a member can be accessed is determined
by the access specifier that modifies its declaration.
Java supplies a rich set of access specifiers. Some aspects of access control are
related mostly to inheritance or packages. Java’s access specifiers are public, private
and protected. Java also defines a default access level. When a member of a class is
modified by the public specifier then that member can be accessed by any other code in
your program. When a member of a class is specified as private then that member can
only be accessed by other members of its class.
When no access specifier is used then by default the member of a class is public
within it’s own package but cannot be accessed outside of its package.
When a member of a class is specified as protected it is available to all classes in
the same package and also available to all subclasses of the class that owns the protected
feature. This access is provided even to subclasses that reside in a different package
from the class that owns the protected feature. There are two levels of access control:
• At the top level—public, or package-private (no explicit modifier).
• At the member level—public, private, protected, or package-private (no explicit
modifier).
A class may be declared with the modifier public, in which case that class is
visible to all classes everywhere. If a class has no modifier, it is visible only within its
own package. Every class has declared an access control, whether you explicitly type
one or not. When a class has access to another class it means he can do one of 3 things
• Create an instance of that class.
• Extend the class (become a subclass).
• Access certain methods and variables within that class.
48 Self-Instructional Material
Example (1): Classes and Objects
in Java
class A {
int i;
A (int a, int b)
NOTES
{ i = a + b;
} void add() !
{System.out.println ("Sum of a and b is: " +. i);
• }}
class B extends-A
{ int j;
B(int a, int b, int c).
{ super (a, b);
a + b + c;
}
void add O'.
.{ super.addO;
System, out.println ("Sum of a, b and c is:'-" + j);
}}
class MethodOverriding {
.public static void main(String args[]) {
B b = new B(10, 20, 30);
b.add();
))
In a class hierarchy, when a method in a subclass has the same name and type
signature as a method in its superclass, then the method in the subclass is said to
override the method in the superclass. When an overridden method is called from
within a subclass, it will always refer to the version of that method defined by the
subclass. The version of the method defined by the superclass will be hidden. Consider
the following:
Example: (2) Method overriding.
class A {
int i, j;
A (int a, int b) {
i a;
j = b;
Self-Instructional Material 49
Introduction to Internet
}
Programming (JAVA)
// display i and j
void show()
NOTES {'
System.out.println{"i and j: " + i + " " + j) ;
}} '
class B extends A
{ int k;
B(int a, int b, int c)
{ super(a, b);
k c;
}
// display k - this overrides show () in A
void show
{' System.out\println("k: " + k);
}}
Class Override {
public static void main{String args [ ] ). {
B subOb new B(l,2,3);-
subOb.shpw(); // this calls show() in B
}}
The output produced by this program is shown here:
k: 3
When show() is invoked on an object of type B, the version of show() defined
within B is used. That is, the version of show() inside B overrides the version declared
in A. If we wish to access the superclass version of an overridden function, then.we can
do so by using super. For example, in this version of B, the superclass version of
show() is invoked within the subclass’ version.
50 Self-Instructional Material
Abstract classes cannot be instantiated; they must be subclassed and actual Classes and Objects
implementations must be provided for the abstract methods. Any implementation in Java
specified can, of course, be overridden by additional subclasses. An object must have,
an implementation for all of its methods. You need to create a subclass that provides
an implementation for'the abstract method. A class abstract Vehicle might be specified NOTES
as abstract to represent.the general abstraction of a vehicle, as creating instances of
the class would not be meaningful.
abstract class Vehicle {
int numofGears;
String•color;
abstract boolean hasDiskBrake() ;
• abstract int getNoofGears();
}
We can also implement the generic shapes class as an abstract class so that we
can draw lines, circles, triangles etc. All shapes have som€ common fields and methods,
but each can, of course, add more fields and methods. The abstract class guarantees
that each shape will have the same set of basic properties. |Ve declare this class abstract
because there is no such thing as a generic shape. There can only be concrete shapes
such as squares, circles, triangles etc.
Y = 0;
}
public double area()
{ return 0;
}
Self-Instructional Material 51
;
Introduction to Internet
public double perimeter()
Programming (JAVA)
{ return 0;
)
NOTES public static void print() {
System.out.println'("Point: " + x + + y) ;
}
public static void main(String'args[])
{ Point p = new Point{);
p.print(); .
}}
Output:
Point: 0, 0
Notice that, in order to create a Point object, its class cannot be abstract. This
means that all of the abstract methods of the Shape class must be implemented by the
Point class. The subclass must define an implementatiojtfor every abstract method of
the abstract superclass, or the subclass itself will also be abstract. Similarly other
shape objects can be created using the generic Shape Abstract class. A big Disadvantage
of using abstract classes is not able to use multiple inheritances. In the sense, when a
class extends an abstract class, it can’t extend any other class.
There are situations in which you will want to define a superclass that declares
the structure of a given abstraction without providing a complete implementation of
every method. That is, sometimes you will want to create a superclass that only defines
a generalized form that will be shared by all of its subclasses, leaving it to each subclass
to fill in the details. Such a class determines the nature of the methods that the
subclasses must implement. One way this situation can occur is when a superclass is
unable to create a meaningful implementation for a method. Here is a simple example
of a class with an abstract method, followed by a class which implements that method:
52 Self-Instructional Material
/
Notice that no objects of class A are declared in the program. As mentioned, it is Classes and Objects
not possible to instantiate an abstract class. One other_point: class A implements a in Java
concrete method called cailmetoo( ). This is perfectly acceptable. Abstract classes
can include as much implementation as they see fit.
NOTES
The classes and interfaces we have seen so far in this chapter have all been top-
level classes (i.e., they are direct members of packages, not nested within any other
classes). Starting in Java 1.1, however, there are four other types of classes, loosely
known as inner classes that can be defined in a Java program. Used correctly, inner
classes are an elegant and powerful feature of the Java language. These four types of
classes are summarized here:
• Static member classes: A static member class is a class (or interface) defined
as a static member of another class. A static method is called a class method,
so, by analogy, we could call this type of inner class a “class class,” but this
terminology would obviously be confusing. A static member class behaves much
like an ordinary top-level class, except that it can access the static members of
the class that contains it. Interfaces can be defined as static members of classes.
• Member classes :A member class is also defined as a member of an enclosing
class, but is not declared with the static modifier. This type of inner class is
analogous to an instance method or field. An instance of a member class is
always associated with an instance of the enclosing class, and the code of a
member class has access to all the fields and methods (both static and non
static) of its enclosing class. There are several features of Java syntax that
exist specifically to work with the enclosing instance of a member class.
Interfaces can only be defined as static members of a class, not as non-static
members.
• Local classes: A local class is a class defined within a block of Java code. Like
a local variable, a local class is visible only within that block. Although local
classes are not member classes, they are still defined within an enclosing class,
so they share many of the features of member classes. Additionally, however, a
local class can access any final local variables or parameters that are accessible
in the scope of the block that defines .the class. Interfaces cannot be defined
locally. ’
• Anonymous classes: An anonymous class is a kind of local class that has no
name; it combines the syntax for class definition with the syntax for object
instantiation. While a local class definition is a Java statement, an anonymous
class definition (and instantiation) is a Java expression, so it can appear as
part of a larger expression, such as method invocation. Interfaces cannot be
defined anonymously.
.Use of Inner classes: Inner classes allow us to do several things.
1. Naming, if we have a class whose only purpose is for its outer class, then we
can put it there to help describe its meaning.
Self-Instructional Material 53
'W
Introduction to Internet 2. non-static inner classes keep a reference to the outer class allowing it to access
Programming (JAVA)
member variables of the outer class.
3. access, we can declare an inner class non-public to only allows private or
protected access. Inner classes can also access the private variables of its outer
NOTES
class.
SUMMARY
54 Self-Instructional Material
Classes and Objects
REVIEW QUESTIONS in Java
Self-Instructional Material 55
Introduction to Internet UNIT
- Programming (JAVA)
NOTES
EXCEPTION HANDLING
V
STRUCTURE
56 • Self-Instructional Material
• A network connection has been lost in the middle of communications, or the Exception Handling
JVM has run out of memory.
Some of these exceptions are caused by user error, others by programmer error,
and others by physical resources that have failed in some manner.
NOTES
To understand how exception handling works in Java, you need to understand
the three categories of exceptions:
• Checked exceptions: A checked exception is an exception that is typically a
user error or a problem that cannot be foreseen by the programmer. For example,
if a file is to be opened, but the file cannot be found, an exception occurs. These
exceptions cannot simply be ignored at the time of compilation.
• Runtime exceptions: A runtime exception is ail.exception that occurs that
probably could have been avoided by the progran mer. As opposed to checked
exceptions, runtime exceptions are ignored at the time of compilation.
• Errors: These are not exceptions at all, but problems that arise beyond the
control of the user or the programmer. Errors are typically ignored in your code
because you can rarely do anything about an er*or. For example, if a stack
overflow occurs, an error will arise. They are also ignored at the time of
compilation.
The hierarchy of exception classes commence from Throwable class which is
the base class for an entire family of exception classes, declared in java Jang package
as java.lang.Throwable. A throwable contains a snapshot of the execution stack at
• the time it was created and also a message string that gives more information about
the error. This class can be instantiated and thrown by the program. The throwable
class is further divided into two subclasses:
1. Exceptions: Exceptions are thrown if any kind of unusual condition occurs
that can be caught. Sometimes it also happens that the exception could not be
caught and the program may get terminated. Remember that they are a
member of Exception family and can be type of Checked or Unchecked
exception.
2. Errors: When any kind of serious problem occurs which could not be handled
easily like OutOfMemoryError then an error is* thrown. Well, errors are not
something which is thrown by you rather they are thrown by the Java API or
by the Java virtual machine itself i.e., only the exceptions are thrown by
your code and not the errors. Also remember that' they are a member of Error,
family.
The exception classes can be explained as well seeing the exception hierarchy
structure:
Object
java.lang.Throwable * java.lang.Error
I
java.lang.Exception java.lang.Runtime
Exception
Self-Instructional Material 57
/
Introduction to Internet The java.lang package defines several classes and exceptions. Some of these
Programming (JAVA) classes are not checked while some other classes are checked.
58 Self-Instructional Material
Lets tweak the diagram below. Exception Handling
Throwable
1 NOTES
Exception
1
SpeedException
VcryFastExcepfion
1 VerySlowException
It is clear from the above program that there is something abnormal with the
speed of the car i.e., either it is very fast or it is very slow. Hence two exceptions are
thrown by the program-VeryFastException and VerySlowException. To be more
precise the SpeedException family specifies three new exceptions thrown by the
program which indicate some abnormal conditions. That is the SpeedException specifies
that there is something unusual with the speed; VeryFastException and
VerySlowException specifies the abnormal conditions of the speed.
import java.io.*;
public class exceptionHandle{
■ .-.ft
public static void main(String[] args) throws Exception^
try{
int a,b;
BufferedReader in;
* = new Buf feredReader (new InputStreamR.eader (System.in)) ; •
a' = Integer.parselnt(in.readLineO ) ; 1
b = Integer.parseInt(in.readLine()); j
Self-Instructional Material 59
Introduction to Internet
}
Programming (JAVA)
catch(NumberFormatException ex){
System.out.printIn{ex.getMessage( )
NOTES +." is not a numeric value.");
System:exit(0);
) )>
try
.{ • •
//Protected code
}catch(ExceptionName el)
{ //Catch block
)
A catch statement involves declaring the type of exception you are trying to catch.
If an exception occurs in protected code, the catch block (or blocks) that follow the try
.is checked. If the type of exception that occurred is listed in a catch block, the exception
is passed to the catch block much as an argument is passed into a method parameter.
Example: The following is an array is declared with 2 elements. Then the code
tries to access the-3rd element of the array which throws an exception.
60 Self-Instructional Material
Exception Handling
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code. NOTES
d = 0;
a = 42 7 d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println{"After catch statement.");
}}
Self-Instructional Material 61
Introduction to Internet
Programming (JAVA) 4.3. HANDLING MULTIPLE EXCEPTIONS
A single try block can have many catch blocks. This is necessary when the try
NOTES block has statements that raise different types of exceptions. For e.g., the following
code traps three types of exceptions:
// Demonstrate finally.
class FinallyDemo. .{
/,/ Through an exception out of the method.
static void procA() {
try { System.out.printIn("inside procA");
throw new RuntimeException("demo");
}finally (
System.out.printIn("procA's finally");
}}
II Return from within a try block.
static void procB() {
try {
System.out.printIn("inside procB");
return;
} finally {
System.out.printIn("procB's finally");
}
}
// Execute a try block normally.
static void procC() {
try {
Self-Instructional Material 63
Introduction to Internet
Programming (JAVA) System.out.println("inside procC");
} finally {
System, out .println ( "procC'.s finally" ) ;
NOTES > > . '
public static void main(String args[]) {
try { ' . ' .
procA();
} catch {Exception e) {
System.out.println("Exception caught");
)procB();
procC{);
}}
Output:
inside procA
procA's finally
Exception caught
inside procB
procB's finally
inside procC
procC's finally
In this example, procA( ) prematurely breaks out of the try by throwing ah
exception. The finally clause is executed on the way out. procB( )’s try’ statement is
exited via a return statement. The finally clause is executed before procB() returns.
In procC(), the try statement executes normally, without error. However, the finally
block is still executed.
Note; If a finally block is associated with a try, the finally block will be executed
upon conclusion of the try.
The built-in exceptions in j ava are categorized on the basis of whether the exception
is handled by the java compiler or not. Java consists of the following categories of
built-in exceptions:
f • - •
• Checked Exceptions.
• Unchecked Exceptions.
\
Checked Exceptions'. Checked exceptions are the objects of the Exception class
dr any of its subclasses excluding the Runtime Exception class. Checked Exceptions
are the invalid conditions that occur in a java program due to invalid user input,
network connectivity problem or database problems. Java uses the try-catch block to
handle the checked exceptions. The statements Vithin a program that throw an
exception are placed in the try block. You associate an exception-handler with the try
block by providing one or more catch handlers immediately after the try block. Various
checked exceptions defined in the java.lang.package are:
1. ClassNotFoundException.
2. IllegalAccessException.
64 Self-Instructional Material
3. InstantiationException. Exception Handling
4. NoSuchMethodExceptibn.
;
Unchecked Exceptions: Unchecked exceptions are the ruh-time errors that
occur because of programming errors, such as invalid arguments passed to a public NOTES
method. The java complier does not check the unchecked exceptions during program
compilation. Various UncheckedExceptions are:
1. ArithmeticException. ‘
2. ArraylndexOutOfBoundsException. j
3. ArrayStoreException. j '
4. ClassCastException.
I
5. IllegalArgumentException.
6. NegativeArraySizeException.
7. NullPointerException. /
8. NumberFormatException.
Java defines several exception classes inside the standard package java.lang.
The most general of these exceptions are subclasses of the standard type
RuntimeException. Since java.lang is implicitly imported into all Java programs, most
exceptions derived from RuntimeException are automatically available. Java defines
several other types of exceptions that relate to its various class libraries. Following is
the list of Java Unchecked RuntimeException.
Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArraylndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException 4 Assignment to an array element of an incompatible
type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument.used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an
unlocked thread.
IllegalStateException Environment or application is in incorrect state.
Ille'galThreadStateException Requested operation not compatible with current
thread state.
IndexQutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException. Attempt to violate security.
StringlndexOutOfBounds Attempt to index outside the bounds of a string.
UnsupportedOperationException An unsupported operation was encountered.
Self-Instructional Material 65
Introduction to Internet Following is the list of Java Checked Exceptions Defined in java.lang.
Programming (JAVA)
Exception Description
ClassNotFoundException Class not found.
NOTES \
CloneNotSupportedException Attempt to clone ah object that does not implement
the Cloneable interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or
interface.
InterruptedException One thread has been interrupted by another
thread.
. NoSuchFieldException A requested field does not exist. .
NoSuchMethodException A requested method does riot exist. . .
class ThrowStatement
{ Static void throwdemo ( )
{ try { throw new IllegalStateException { );
} catch (NullPointerException objA)
{ System.out.println {"Not Caught by the catch block inside
throwDemo ().");
}.} public 'static void main (String args[ 3)
{ try { throwDemo ( ); • .
•} Catch (IllegalStateException objB)
{ System.out.println ("Exception Caught in:"+objB);.
H }
66 Self-Instructional Material
Output: Exception Handling
javac ThrowStatement.java
java’ThrowStatement r
Exception Caught in: java.lang.IllegalStateException ' NOTES
The programmer can throw an Exception from a method using the statement
throw. A call to the above mentioned sample method should be always placed in a try
block as it is throwing a Checked Exception-IOExceptionj.
i
Example:
//Statements
//if (somethixigWrpng)
lOException e = newlOExpeption{);
throw e;
//More Statements
}
. In Java, to invoke a method,, the programmer needs to know the name of the
method, list of parameters, the return type and the Checked Exceptions being thrown’
by the method. Java syntax mandates the programmer to list all the Checked Exceptions
that are being thrown from a method using the throws clause. If method is trying to
. throw an exception, then the programmer must handle the exception either with try/
catch block or with throws clause. In case a method throws more than one exception,
all of.them should be listed in throws.
Example:
class Number{ i
private int num; ■
public void accept(int n) throws Excepticn{
if{ n == 0 ){ *
throw new Exception ("can' t assign zero...'');.
}
else if(n < 0){
throw new Exception ( "can' t assign -ve value...");
}
else{ . • ,
System.out.printIn("\n\n\tValid value.");
num = n;
})}
public class ThrowsDemo{
public static void main(String args[]){
Number ob = new Number();
try {
Self-Instructional Material 61
Introduction to Internet
ob.accept(-8) ;
Programming (JAVA)
//ob.accept(10);
}
NOTES catch(Exception e){
System.out.println{"\n Error: " + e) ;
}
System.out.printIn("\n\n");
})'
Result:
Error: java.lang.Exception: can't assign -ve value.
To catch an exception in Java, you write a try block with one or more catch clauses.
Each catch clause specifies,one exception type that it is prepared to handle. The try
block places a fence around a bit of code that is under the watchful eye of the associated
catchers. If the bit of code delimited by the try block throws an exception, the associated
catch clauses will be examined by the Java virtual machine. If the virtual machine .
finds a catch clause that is prepared to handle the thrown exception, the program
continues execution starting with the first statement of that catch clause.
As an example, consider a program that requires one argument on the command
line, a string that can be parsed into an integer. When you have a String and want an
int, you can invoke the parselntO method of the Integer class. If the string you pass
represents an-integer, parselntO will return the value. If the string doesn’t represent
an integer, parselntO throws NumberFormatException. Here is how you might parse
an int from a command-line argument:
68 Self-Instructional Material
Exception Handling
It Create a new coffee cup and set the temperature of its
coffee.
CoffeeCup cup = new CoffeeCup();.
cup.setTemperature{temperature); NOTES
// Create and serve a virtual customer.
VirtualPerson oust = new VirtualPerson();
VirtualCafe.serveCustomer(cust,' cup);
}}
Here, the invocation of parselntO sits inside a try block. Attached to the try block
is a catch clause that catches NumberFormatException:
catch{NumberFormatException e) .
{ System.out.,println( "Must enter integer as first'argument;
return;
}
Self-Instructional Material 6
Introduction to Internet If any code inside a try block throws an exception, its catch clauses are examined
Programming (JAVA) in their order of appearance in the source file. For example, if the try block in the
above example .throws an exception, the catch clause for TooColdException will be
examined first, then the catch clause for TooHotException. During this examination
NOTES process, the first catch clause encountered that handles the thrown object’s class gets
to “catch” the exception. The ordering of catch-clause examination matters because it
is possible that multiple catch clauses of a try block could handle the same exception.
CustomExceptionTestJava
70 Self-instructional Material
In the CustomExceptionTest class, the age is expected to be a positive number. It Exception Handling
would throw the user defined exception NegativeAgeException if the age is assigned a
negative number. At runtime, we get the following exception since the age is a negative
number.
Exception in thread “main” Age cannot be negative -10 NOTES
at tips.basics.exception.CustomExceptionTest.main
(CustomExceptionTestJava:10)
SUMMARY
REVIEW QUESTIONS
NOTES 5
PACKAGES AND INTERFACES
STRUCTURE
5.0 Learning Objectives
5.1 Creating Packages
5.2 Adding Classes to Existing Packages
5.3 Interface
5.4 Creating Interfaces
5.5 Exceptions
• Summary
• Review Questions
72 Self-Instructional Material
If a package statement is not used then the class, interfaces, enumefai Packages and Interfaces
aniintation types will be put into an unnamed packa™ Lr..* us look at
ere n package called animals. It is comino:i ;■/ use •
pac ;-.r '.'.s t.n avoid any conflicts with the names of inlerface^
:s- NOTES
package animals';
inCerface.Animal
{ public void eat();
public.void travel();
>
package animals;
public class Mammallnt implements Animal
•{ public void eat(){
System.out.println("Mammal eats");
} .
public void travel{){
System, out .println ( "Mammal travels" ) •;
} .
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
Mammallnt m = new Mammallnt();
m. eat{);
m. travel();
}}
Now you compile these two files and put them in sub-directory called animals
and try to run as follows:
package mymath;
class^mathops
{public static void add(int i,int j)
{ int k=i+j;
System.out.println("The sum of " + i + " and"+j + " is "+k) ;
}
public void sub(int i,int j) . • '
{ int k=i-j; .
System.out.println("The substaction of "+i+" and"+j+" is "+k);
Self-Instructional Material 73
Introduction to Internet
Programming (JAVA) }
public static void mul(int i,int j)
{' int k=i*j;
NOTES System.out.println(”The multiplication of "+i+" and"+j + " is "+k) ;
}
public void div{int i,int j)
{ int k=i/j; -
System.out.println("The division of "4i+" and"+j + " is "+k) ;
}}
How to create a package: Suppose we have a file called HelloWorld.java,
and we want to put this file in a package world. First thing we have to do is to specify ‘
the keyword package with the name of the package we want to use (world in our case)
on top of bur source file, before the code that defines the real classes in the package, as
shown in our HelloWorld class below:
// only comment can be here
package world;
public class HelloWorld
{ public static void main(String[] args)
{ System.out.println("Hello World");
}}
One thing is important that after creating a package for the class is to create
nested subdirectories to represent package hierarchy of the class. In our case, we have
the world package, which requires only one directory. So, we create a directory world
and put our HelloWorld.java into it.
CAworid 13
[FotfeT....... x Name I Seel Type
$-C5> (0) ^KekWoridjava 1KB JAVA Fie
1-Pi ,mec
B-E) Diamond
£ o fond000
Pi hetpife
fflEl Kpow
§-£) Mutimed»Ffes
-0 My Download Fiet
-0 My Muse
(20 ProgtamFle*
Recycled
(1-0 T emp
-0 weUogic_piJ)hh
B-0 Wrrt
L0 world F El
lobjectftl fceeVpece: 2Fl^B| zrj.
Fig. 5.1. HelloWorld in world package (C:\world\HelloWorld.java)
That’s it!!! Right now we have HelloWorld class inside world package. Next, we
have to introduce the world package into our CLASSPATH.
Setting up the CLASSPATH: From Fig. 5.1 we put the package world under ,
C:. So we just set our CLASSPATH as:
74 Seif-Instructional Material
set CLASSPATH^.;C:\; Packages and Interfaces
We set the CLASSPATH to point to 2 places, . (dot) and C:\
directory.
When compiling HelloWorld class, we just go to the world direc NOTES
tory and type the command:
C:\world\javac HelloWorld.java .
If you try to run this HelloWorld using java HelloWorld, you
will get the following error:
C:\world>java HelloWorld t
Exception in thread "main" java.lang.Nod’assDefFoundError:
HelloWorld (wrong name:
world/HelloWorld). i
To make this example more understandable, let’s put the HelloWorld class along
with its package (world) be under C:\myclasses directory iiistead. The new location
of our HelloWorld should be as shown in Fig. 5.2.
Fig. 5.2. HelloWorld class (in world package) under myclasses directory
We just changed the location of the package from C:\world\HelloWorld.java to
C:\myclasses\world\HelloWorld.java. Our CLASSPATH then needs to be changed to
point to the new location of the package world accordingly, i
set CLASSPATH=. ;C:\ntyclasses;
Thus, Java will look for java classes from the current directory and C:\myclasses
directory instead. We can run the HelloWorld from anywhere as long as we still include
the package world in~the CLASSPATH. For example,
C:\>set CLASSPATH=.;C:\;
C:\>set CLASSPATH // see what we have in CLASSPATH
CLASSPATH=.;C:\;
C: \>cd world'^ -
C: \world>java 'world.HelloWorld
Hello World
C:\world>cd ..
C:^>java world.HelloWorld
Hello World
V
Self-fnsinictional Material 75
Introduction to Internet
Subpackage (package inside another package)
Programming (JAVA)
Assume we have another file called HelloMoon.java. We want to store it in a
subpackage “moon”, which stays inside package world. The HelloMoon class should
look something like this:
NOTES
package world.moon;
public' class HelloMoon {
private String holeName = "rabbit hole";
public getHoleName() {
return hole;
}
public setHole{String holeName) {
this.holeName = holeName;
> }
• In order to add a class to an existing package just adds the package statement
as the first statement before the class definition.
• Save the file in the folder that contains other classes of that package.
• Compile the file to generate the class file.
• Now the new class is added into the package and can be imported into the
other programs.
To add a Class to an existing Java Package do the following:
To add the class MyClass to the Java Package v2k.awt, add the following
statement to the MyClass.java source file. (It must be the first non-comment
statement of the file):
MyClass.java:
i package v2k.awt;
Move the Java source file MyClass.java to ^he source directory for Package
v2k.awt:
UNIX example: • ,
% mv MyClass.java/GUI/jav^/src/v2k/awtA
You are ready to compile the new class and ma^ce it part of the v2k.awt Java
Package. If the CLASSPATH environment variable is set (the path to search
for classes being imported by MyClass.java), do the following:
% javac -d /GUI/java/classes /GUI/java/src/v2k/awt/MyClass.java
The -d option tells the compiler to place the MyClass.class file in the directory:
/
■ /GUI/java/classes/v2k/awt.
If the CLASSPATH environment is not set, do the following:
% javac -d /GUI/java/classes -classpath .:/GUI/java/classes:/usr/java/classes
. /GUI/java/src/v2k/awt/MyClass.java
76 Self-Instructional Material
The -d option tells the compiler to place the MyClass.class file in the directory: Packages and Interfaces
/GUI/java/classes/v2k/awt.
The -classpath option tells the compiler to search for classes being imported.by
MyClass.java in the path: .:/GUI/java/classes/. ; NOTES
The class “MyClass” is now part of the Java Package v2k.awt. We can now import
this class using the statement import v2k.awt.MyClass.
5.3. INTERFACE
interface Bounceable
{ void setBounce(); // Note the semicolon:-
// Interface methods are public.and abstract.
// Think of them as prototypes only; no
implementations are allowed.
}
Self-Instructional Material 77
Introduction to Internet Defining an interface: Interfaces are defined with the following syntax (compare
Programming (JAVA) to Java’s class definition):
The body of the interface contains abstract methods, but since all methods in an
interface are, by definition, abstract, the abstract keyword is not required. Since the
interface specifies a set of exposed behaviors, all methods are implicitly public.
Thus, a simple interface may be
The member type declarations in an interface are implicitly static, final and public,
but otherwise they can be any type of class or interface. The syntax for implementing
an interface uses this formula: '
If a class implements an interface and does not implement all its methods, it
must be marked as abstract. If a class is abstract, one of its subclasses is expected to
implement its unimplemented methods.
Classes can implement multiple interfaces
public class Frog implements Predator, Prey { . ... }
Interfaces are commonly used in the Java language for callbacks. Java does not
allow the passing of methods (procedures) as arguments. Therefore, the practice is to
define an interface and use it as the argument and use the method signature knowing
that the signature will be later implemented.
78 Self-Instructional Material
Subinterfaces: Interfaces can extend several other interfaces, using the same Packages and Interfaces
formula as described below. For example
is legal and defines a subinterface. Note how it allows multiple inheritances, unlike
classes. Note also that predator and venomous may possibly define or inherit methods
with the same signature. When a class implements VenomousPredator it will implement
both methods simultaneously.
Examples: Some common Java interfaces are:
• Comparable has the method compareTo, which is used to describe two objects
as equal, or to indicate one is greater than the other. Generics allow
implementing classes to specify which class instances can be compared to
them. -
• Serializable is a marker interface with no methods or fields - it has an empty
body. It is used to indicate that a class can be serialized. Its.Javadoc describes
how it should function, although nothing is programmatically enforced.
interface check {
public void message();
}
public class Interface {
public static void main (String [•] args) {
try {
check t = new check!) { .
public void message!) ( .
Systern.out.println("Method• defined in the interface");
*>};
t.message() ; ' .
.}
catch (Exception ex)
{ Systern.out.println{"" +• ex.getMessage());
> ) )
The Interface Declaration: The declaration for the Sleeper interface uses the
two required elements of an interface declaration—the interface keyword and the name
of the interface—plus the public access modifier:
80 Self-Instructional Material
An interface declaration can have one other component: the public access specifier Packages and Interfaces
and a list of super interfaces. The full interface declaration looks like this figure:
(
InterfaceBody
}
The public access specifier indicates that the interface can be used by any class
in any package. If you do not specify that your interface is public, then your interface
will be accessible only to classes that are defined in the same package as the interface.
To create an interface definition: f
<
• define it like a Java class, in its own file that matches the interface name
• use the keyword interface instead of class.
• declare methods using the same approach as abstract methods:
• note the semicolon after each method declaration-and that no executable
code is supplied(and no curly braces).
• the elements will automatically be public and abstract, and cannot have
any other state; it is OK to specify those terms, but not necessary (usually
public is specified and abstract is not-that makes it easy to copy the list of
methods, paste them into a class, and modify them ).
• The access level for the entire interface is usually public:
• it may be omitted, in which case the interface is only available to other
classes in the same package (i.e., in the same directory).
• note, for the sake of completeness, there are situations where the interface
definition could be protected or private; these involve what are called inner
classes.
Syntax:
5.5. EXCEPTIONS
Self-Instructional Material 81 .[
Introduction to Internet • JVM Exceptions: These are exceptions/errors that are exclusively or logically
Programming (JAVA) thrown by the JVM. Examples: NullPointerException, ArraylndexOutOf
BoundsException, ClassCastException.
• Programmatic exceptions: These exceptions are thrown explicitly by the
NOTES application or the API programmers Examples: IllegalArgumentException,
IllegalStateException.
Provides classes and interfaces for handling exceptions thrown by the SDK layer.
Exception Summary
BICapabilityNotSupportedException Thrown when a certain feature is not
supported by a connector.
BIConnectionFailedException Thrown to indicate that a connection has not
been successfully established.
BIConnectorException Thrown to indicate miscellaneous error
situations in a connector.
BIException General-purpose exception for the BI Java
SDK.
BIJmiVerifyException Exception thrown by generated JMI objects of
the BI Java SDK;
BIOIapQueryException Checked exception which is thrown within the
context of an OLAP query.
BIOlapQueryRuntimeException Runtime exception which is thrown within the
context of an OLAP query. .
BIResourceExcepti on Thrown to indicate a lower-level problem.
BIRuntimeException Represents BI Java SDK-specific runtime
exceptions.
BISQLException Exception providing information on errors
occurring while interacting with BI Java SDK
relational connectors.
BISQLWarning Exception providing information on errors
occurring while interacting with BI J ava SDK
relational connectors.
Provides classes and interfaces for handling exceptions thrown by the SDK layer.
Exception handling in the BI Java SDK both conforms to SAP'standards and supports
legacy exceptions. All exceptions thrown by the SDK interfaces implement the
IBaseException interface in order to comply with SAP solution production standards.
This also provides integration with SAP’s Java logging and tracing framework used
for instrumenting the code in case of error situations.
The SDK exceptions either directly implement the IBaseException interface,
as in the case of BIResourceException, or they extend exceptions in the package
com.sap.exception, as with BaseException. Legacy exceptions, which are
exceptions that are thrown by components outside the SDK, do not implement
the IBaseException interface but are handled by providing wrapper exceptions.
These wrappers have exactly the same semantics as the underlying legacy
exception and simply add the implementation, of IBaseException. For example,
the legacy exception BIResourceException wraps exceptions of the type
javax.resource.ResourceException.
. 82 Self-Instructional Material
The diagram below illustrates how the BI Java SDK exceptions relate to legacy Packages and Interfaces
exceptions such as javax.resource.RescourceExceptioh and the SAP Exception
Framework base exceptions:
ResourceException
com,sap.exception |
com.sap.ip.pl.sok.exception |
SUMMARY
Java is an object oriented programming language and any Java programmer
will quickly build a large number of different classes for use in each application
that they develop.
When creating a package, we should choose a name for the package and put a
package statement with that name at the top of every source file that contains
the classes, interfaces, enumerations and annotation types that we want to
include in the package.
*# In order to add a class to an existing package just adds the package statement
as the first statement before the class definition.
An interface in the Java programming language is an abstract type that is
used to specify an interface that classes must implement. Interfaces are
declared using the interface keyword and may only contain method signatures
and constant declarations. An interface may never contain method definitions.
One benefit of using interfaces is that they simulate multiple inheritance.
Interfaces are used to encode similarities which the classes of various types
share, but do not necessarily constitute a class relationship.
.. j
Self-Instructional Material 83
Introduction to Internet
Programming (JAVA) REVIEW QUESTIONS
1. How you can creating a packages in Java? Explain with an example.
NOTES 2. How the class can be added to an existing packages?
3. What is interface? Explain with an example.
4. How you can define an interface?
5., What is subinterfaces? What are the common java interfaces?
6. How you can create an interface? Explain with an example.
7. What are exceptions?
■v
MULTITHREADED PROGRAMMING
STRUCTURE
6.0 Learning Objectives
6.1 Multithreading an Introduction
6.2 The main Thread
6.3 Java Thread Model
6.4 * Thread Priorities
6.5 Synchronization in Java
6.6 Interthread Communication
• Summary
• Review Questions
We know about a single thread. Let us know about the concept of multithreading
and learn the implementation of it. But before that, let’s be aware from the multitasking.
Multitasking: Multitasking allow to execute more than one tasks at the same
time, a task being a program.In multitasking only one CPU is involved but it can
switches from one program to another program so quickly that’s why.it gives the
appearance of executing all of the programs at the same time. Multitasking allow
processes (i.e., programs) to run concurrently on the program. For Example running
the spreadsheet program and you are working with word processor also. Multitasking
is running heavyweight processes by a single OS.
Self-Instructional Material 85
■Introduction to Internet Multithreading is a technique that allows a program or a process to execute
Programming (JAVA) many tasks concurrently (at the same time and parallel). It allows a process to run'its
tasks in parallel mode on a single processor system. In the multithreading concept,
several multiple lightweight processes are run in a single process/task or program by
NOTES a single processor. For Example, when you use a word processor you perform a
many different tasks such as printing, spell checking and so on. Multithreaded
software treats each process as a separate program.
In Java, the Java Virtual Machine (JVM) allows an application to have multiple
threads of execution running concurrently. It allows a program to be more responsible
to the user. When a program contains multiple threads then the CPU can switch
between the two threads to execute them at the same time. For example, look at the
diagram shown as:
Single Process
Thread! , Thread 2
Operation 1 Operation 1
Operation 2 Operation 2
Operation N Operation N
In this diagram, two threads are being executed having more than one task. The
task of each thread is switched to the task of another thread.
Advantages of multithreading over multitasking:
• Reduces the computation time.
• Improves performance of an application.
• Threads share the same address space so it saves the memory.
• Context switching between threads is usually less expensive than between
processes.
• Cost of communication between threads is relatively low.
Different states implementing Multiple-Threads are:
Leaving non-mnnable
♦^Ready-to-noir^
Start Non-runnablc states
: .chedulii g Entering
non-nmnab!c r Blocked for > Blocked for
Running Sleeping Join Completion I/O
C impIeted/lTerminated
Waiting for on notification Blocked for N
Dead notification *\lock acquisition
As we have seen different states that may be occur with the single thread. A
running thread can enter to any non-mnnable state, depending on the circumstances.
A thread cannot enters directly to the running state from non-mnnable state, firstly it
goes to runnable state. Now let’s understand the some non-mnnable states which may
be occur handling the multithreads.
. 86 Self-Instructional Material
• Sleeping: On this state, the thread is still alive but it is not runnable, it might Multithreaded
be return to runnable state later, if a particular event occurs. On this state a Programming
thread sleeps for a specified amount of time. You can use the method sleep() to
stop the running state of a thread.
NOTES
static void sleepdong millisecond) throws Interrupted Exception
• Waiting for Notification: A thread waits for notification from another thread.
The thread sends back to runnable state after sending notification from another
thread.
final void waitdong timeout) throws InterruptedException
final void waitdong timeout, int nanos) throws InterruptedException
final void wait() throws InterruptedException
• Blocked on I/O: The thread waits for completion of blocking operation. A thread
can enter on this state because of waiting I/O resource. In that case the thread
sends back to runnable state after availability of resources.
• Blocked for joint completion: The thread can come on this state because of
waiting the completion of another thread.
• Blocked for lock acquisition: The thread can come on this state because of
waiting to acquire the lock of an object.
Short summary of Multithreading: Many applications can run on the same
computer at the same time. Each instance, in the running condition, is known as process.
Each process can have one or more threads. A thread is a sequence of code, this code is
often responsible for one aspect of the programmer one task a program has beengiven.
For instance a program doing a complex long calculation may split into two threads,
one to keep a user interface responsive, and one (or more) to progress through the
lengthy calculation. ,
Java has a built in support, for multithreading programming. A multithreading
is a specialized form of multitasking. Multitasking threads require less overhead than
multitasking processes. A thread has various stages during it’s life cycle. For example,
a thread is bom, started, runs, and then dies. Given below diagram contains various
stages during it's life cycle: .
O New
Program starts
thread
Unlock signal Thread completes
—I signal all r-------1 —i task ' i
Waiting Runnable * Terminated
♦
Await
lock Await Interval
sleep expires
Timed waiting
Self-Instructional Material 87
Introduction to Internet The description of the stages of a thread during it’s life cycle are given below:
Programming (JAVA)
Life Cycle Stage Description
tfew A new thread begins its life cycle in the new state. It remains in
NOTES this state until the program starts the thread. It is also referred
to as a born thread.
Runnable After thread born in ‘New’ Stage, the thread becomes runnable.
A thread in this state is considered to be executing its task.
Waiting A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in these state transitions back to the
runnable state when that time interval expires or when the event
it is waiting, for occurs.
Timed Waiting A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in these state transitions back to the
runnable state when that time interval expires or when the event
it is waiting for occurs.
Terminated A runnable thread enters the terminated state when it completes
its task or otherwise terminates
The ‘mainO’ method in Java is referred to the thread that is running, whenever a
Java program runs. It calls the main thread because it is the first thread that starts
running when a program begins. Other threads can be spawned from this main thread.
The main thread must be the last thread in the program to end. When the main thread
stops, the program stops running. Main thread is created automatically, but it can be
controlled by the program by using a Thread object. The Thread object will hold the
reference of the main thread with the help of currentThreadO method of the Thread
class. Listing shows how main thread can be controlled by a program:
class MainThread
{
public static void main(String args U )
{
Thread t = Thread.currentThread ( );
System.out.println ("Current Thread: " + t);
System.out.println ("Name : " + t.getName ( ) );
System.out.println {" ");
t.setName ("New Thread");
System.out.println ("After changing name");
System.out.println ("Current Thread: " + t);
System.out.println ("Name: " + t.getName ());
System.out.println (" ");
88 Self-Instructional Material'
Multithreaded
System.out.println ("This thread prints first 10 numbers"); Programming
try - i / . ■
{ for (int i=l; i<=10;i++) ' . J
{ System.out.print(i); ' NOTES
System.out.print(" "); !
Thread.sleep(1000) ; j
} }
catch (Interrupted^xception e)
{ System.out.println(e) ;
} ) )
In this program, a reference to the current thread (the main thread, in this case)
is obtained by calling currentThread( ), and this reference is stored in the local
variable t. Next, the program displays information about the thread. The program
then calls setName() to change the internal name of the thread. Information about
the thread is then redisplayed. Next, a loop counts down from five, pausing one second
between each line. The pause is accomplished by the sleep() method. The argument
to sleep() specifies the delay period in milliseconds. Notice the try/catch block around
this loop. The sleep() method in Thread might throw an InterruptedException.
This would happen if some other thread wanted to interrupt this sleeping one. This
example just prints a message if it gets interrupted. In a real program, you would
need to handle this differently. Here is the output generated by this program:
Current thread: Thread [main,5, main]
After name change: Thread [My Thread,5,main]
5
4
3
2
1
90 Self-Instructional Material
Notice the output produced when t is used as an argument to println (). These Multithreaded
displays, in order: the name of the thread, its priority, and the name of its group. By Programming
default, the name of the main thread is main. Its priority is 5, which is the default
value, and main is also the name of the group of threads to which this thread belongs.
A thread group is a data structure that controls the state of a collection of threads as NOTES
a whole. This process is managed by the particular run-time environment and is not
discussed in detail here. After the name of the thread is changed, t is again output.
This time, the new name of the thread is displayed.
Waiting
The multithreading systerrHn Java is built upon the Thread Class, its methods
and its companion'interface, Runnable'. To create a new thread, your program will
Self-Instructional Material 91
Introduction to Internet either extend Thread Class or implement the Runnable interface. The Thread Class
Programming (JAVA) defines several methods that help in managing threads.
For example, if you have to create your own thread then you have to do one of the
following things:
NOTES i
1)
class MyThread extends. Thread
{
MyThread(arguments) // constructor
}//initialization
>
•public void run{)
{
//- perform operations
}
}
Write the following • code to create a thread and start it
. running:
MyThread p = new MyThread(arguments); ‘ .
p.start();
2)
class MyThread implements Runnable
{
MyThread(arguments)
•{
/./initialization
' }
public void run()
{
// perform operation
}
l
}
92 Self-Instructional Material
Thread(ThreadGroup group, Runnable target, String name) Thread(ThreadGroup Multithreaded
group, Runnable target, String name, long stackSize) Thread(ThreadGroup group, Programming
String name).
Thread Class Method
NOTES
Some commonly used methods of Thread class are given below:
static Thread currentThreadO Returns a reference to the currently executing
thread object. j
String getNameO Returns the name of the thread in which it is called
int getPriorityO Returns the Thread’s priority
void interruptO Used for Interrupting the thread,
static boolean interrupted() Used to tests whether the current thread has been
interrupted or not.
boolean isAliveO Used for testing whether a tread is alive or not.
boolean isDaemonO Used for testing whether a thread is a daemon thread or
not.
void setName(String NewName) Changes the name of the thread to NewName
void setPriority(int newPriority) Changes the priority of thread.
static void sleepdong millisec) Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
. void startO Used to begin execution of a thread .The Java Virtual Machine calls
the run method of the thread^in which this method is called.
String toStringO Returns a string representation of thread.String includes the
thread’s name, priority, and thread group.
static void yieldO Used to pause temporarily to currently executing thread object
and allow other threads to execute.
static int activeCountO Returns the number of active threads in the current
thread’s thread group.
void destroyO Destroys the thread without any cleanup.
Creating Threads: Java provides native support for multithreading. This support
is centered on the Java.lang.Thread class, the Java.lang.Runnable interface and
methods of the Java.lang.object class. In Java, support for multithreaded programming
is also provided through synchronized methods and statements.
The thread class provides the capability to create thread objects, each with its
own separate flow of control. The thread class encapsulates the data and methods
associated with separate threads of execution and enables multithreading to be
integrated within Java’s object oriented framework. The minimal multithreading
support required of the Thread Class is specified by the java.lang.Runnable interface.
This interface defines a single but important method run.
public void run ( ) |.
This method provides the entry point for a separate thi;ead of execution. As we
have discussed already Java provides two approaches for creating threads. In the first
approach, you create a subclass of the Thread class and override the run() method to
provide an entry point for the Thread’s execution. When you create an instance of
subclass of Thread class, you invoke start() method to cause the thread to execute as
Self-Instructional Material 93
Introduction to Internet an independent sequence of instructions. The start( ) method is inherited from the
Programming (JAVA) Thread class. It initializes the thread using the operating system’s multithreading
Capabilities, and invokes the run() method.
Now let us SG2 the program given below for creating threads by inheriting the
NOTES Thread class.
//program
class MyThreadDemo extends Thread
{
public String MyMessage [ ]= {"Java"is ","very","good",
"Programming","Language"};
MyThreadDemo(String s)
{
super{s);
}• .
public void run( )
{
String name = getName( );
for ( int i=0; i < MyMessage.length;i++)
{
Wait{ ); .
System.out.println (name +":"+ MyMessage [i]);
}
}
void Wa'it( )
{
try
(
sleep(lOOO);
}
catch (InterruptedException e)
{
System.out.println {" Thread is Interrupted");
/
}
}
} .
class ThreadDemo
r
\
public static void\main. ( String args [ ])
{ i
i
94 Self-Instructional Material
Multithreaded
MyThreadDemo Tdl= new MyThreadDemo("thread 1: ’)•;
Programming
MyThreadDemo Td2= new MyThreadDemo{"thread 2:
Tdl.start { );
Td2.start - ( ); NOTES
boolean isAlivel true;
boolean isAlive2. true ;
do
' {
• if (isAlivel && ! Tdl.isAlive( )')
{
isAlivel=.false;
System, out .println ("Thread 1' is dead");
}
if (isAlive2 && !.Td2. isAlive ( ) )
{
isAlive2= false; .
System.out.println ("Thread 2 is dead");
}
}
• while(isAlivel || isAlive2);
}
\
}
Output:
thread l::Java
thread 2::Java
thread l::is
thread 2:;is
thread T.ivery
thread 2::very
thread l::good
thread 2::good *\
thread 1 "Programming
thread 2::Programming
thread l;:Language
thread 2::Language
Thread 1 is dead
Thread 2 is dead
This output shows how two threads execute in sequence, displaying information
on the console. The program creates two threads of execution, Td 1 and Td2. The
threads display the “Java”,“is”,“very”,“good”,“Programming”,“Language” message word
Self-Instructional Material 95
Introduction to Internet by word, while waiting a short amount of time between each word. Because both threads
Programming (JAVA) share the console window, the program’s output identifies which thread wrote to the
console during the program’s execution.
Now let us see how threads are created in Java by implementing the
NOTES java.lang.Runnable interface. The Runnable interface consists of only one method,
i.e., run ()method that provides an entry point into your threads execution.
In order to run an object of class you have created, as an independent thread, you
have to pass it as an argument to a constructor of class Thread.'
//program
class MyThreadDemo implements Runnable
{
public String MyMessage [ ]
= {"Java","is","very","good","Programming","Language"};
String name;
public MyThreadDemo{String s)
{
name - s;
}
public void run( )
-{
for ( int i=0; i < MyMessage.length;i++)
{
Wait (, ) ;•
System.out.println (name +":"+ MyMessage [i]);
}
}
void Wait( )
{ '
try
{
Thread.currentThread(.) .sleep(lOOO) ;
)
catch (InterruptedException e)
{
• System.out.println (" Thread is Interrupted");
}
)
} i
class ThreadDemol
{
96 Self-Instructional Material
Multithreaded
public static void main { String args [ ])
Programming
{
Thread Tdl= new Thread( new MyThreadDemol"thread 1:"));
Thread Td2= new Thread{new MyThreadDemo{"thread 2:")); NOTES
Tdl.start ( );
Td2.start { );
boolean isAlivel true;
. boolean•isAlive2 true;
do.
{
if (isAlivel && \ Tdl.isAlive( ))
{
isAlivel= false;
System.out.println ("Thread 1 is dead");
}
if(isAlive2 && !Td2.isAlive( ))
{
isAlive2= false;
System.out.println ("Thread 2 is dead");.
}
}
• while ( isAlivel |'| 'isAlive2);y
> /
/
/
} /
Output:
thread l::Java
thread 2::Java
thread l::is
thread 2::is
/
thread l::very
thread 2::vefy
thread l::good
thread 2::good
thread l::Programming
■ \
thread 2::Programming
thread l::Language
Thread 1 is dead ■w
thread 2::Language \
:
Thread 2 is dead
••7:
Java assigns to each thread a priority that determines how that thread should be
treated with respect to others. Priorities are integer values. A higher-priority thread
doesn’t run any faster than a low-priority thread if it is the only thread running. Instead,
a priority is used to determine when to switch from one running thread to the next.
This is called context-switch. A thread can voluntarily relinquish control (yielding,
sleeping or blocking on pending I/O). A higher-priority thread (Preemptive multitasking)
can preempt another thread.
In Java, thread scheduler can use the thread priorities in the form of integer
value to each of its thread to determine the execution schedule of threads. Thread
gets the ready-to-run state according to their priorities. The thread scheduler
provides the CPU time to thread of highest priority during ready-to-run state. Priorities
are integer values from 1 (lowest priority given by the constant
Thread.IVIIN_PRlORITY) to 10 (highest priority given by the constant
Thread.MAX_PRIORITY). The default priority is 5 (Thread.NORM_PRIORITY).
Constant Description
Thread.MIN PRIORITY The maximum priority of any thread (an int value of 10)
Thread.MAX_PRIORITY The minimum priority of any thread (an int value of 1)
Thread.NORM_PRIORITY The normal priority of any thread (an int value of 5)
The methods that are used to set the priority of thread shown as:
Method Description
When a Java thread is created, it inherits its priority from the thread that created
it. At any given time, when multiple threads are ready to be execftted, the runtime
system chooses the runnable thread with the highest priority for execution. In Java
runtime system, preemptive scheduling algorithm is applied. If at the execution
time a thread with a higher priority and all other threads are runnable then the runtime
system chooses the new higher priority thread for execution. On the other hand, if
two threads of the same priority are waiting to be executed by the CPU then the
round-robin algorithm is applied in which the scheduler chooses one of them to run
according to their round of time-slice.
98 Self-Instructional Material
Thread Scheduler: In the implementation of threading scheduler usually applies Multithreaded
one of the two following strategies: i Programming
• Preemptive scheduling: If the new thread has a higher priority then current
running thread leaves the runnable state and higher priority thread enter to
the runnable state. NOTES
• Time-Sliced (Round-Robin) Scheduling: A running thread is allowed to be
executing for the fixed time, after completion the time, current thread indicates
to the thread to enter it in the runnable state. }
We can also set a thread’s priority at any time (after its creation using the
setPriority method. Let’s see, how to set and get the priority of a thread.
Self-Instructional Material 99
Introduction to Internet
Programming (JAVA) public class ThreadPriority{
public static void main(String args []){
MyThreadl ml=new MyThreadl{"My Thread 1");
NOTES MyThread2 'm2=new MyThread2("My Thread 2");
}.
//program
class Call_Test
{
.synchronized void callme (String msg)
{
//This prevents other threads £rom entering call( ) while
another thread is using it.
System.out.print ("["+msg);
try
( -
Thread.sleep (2000);
}
catch (• InterruptedException e)
{
System.out.println ("Thread is Interrupted ) ;
}
System.out.println ("]");
}
}
class Call implements Runnable
{
String msg;
Call_Test obi;
Thread t; .
public Call (Call_Test tar, String s)
{
System.out.println("Inside caller method");
obl= tar; .
msg s;
Output:
Inside caller method
Inside caller method
Inside caller method
Inside caller method
Inside caller method
[Hi]
[This ]
[is]
[Synchronization]
[Testing]
1
]
This result is because when in program sleep( ) is ca led, the callme( ) method
allows execution to switch to another thread. Due to this, o itput is a mix of the three
message strings.
So if at any time you have a method, or group of methods, that manipulates the
internal state of an object in a multithreaded situation, you should make these methods
synchronized. It helps in avoiding conflict.
An effective means of achieving synchronization is to create synchronized methods
within classes. But it will not work in all cases, for example, if you want to synchronize
access to object’s of a class that was not designed for multithreaded programming or
the class does not use synchronized methods. In this situation, the synchronized
statement is a solution. Synchronized statements are similar to synchronized methods.
It is used to acquire a lock on an object before performing an action.
The synchronized statement is different from a synchronized method in the sense
that it can be used with the lock of any object and the synchronized method can only be
used with its object’s (or class’s) lock. It is also different in the sense that it applies to
a statement block, rather than an entire method. The syntax of the synchronized
statement is as follows:
synchronized (object)
{
/./ statement (s)
}
The statement(s) enclosed by the braces are only executed when the current thread
acquires the lock for the object or class enclosed by parentheses.
Now let us see how interthread communication takes place in java.
All these methods must' be called within a try-catch block. Let’s see an example
implementing these methods:
class Shared {
int num=0;
boolean value = false;
synchronized int get() {
if (value= =false)
try {
wait();
}•
catch {InterruptedException e) {
• System.out,println{"InterruptedException caught");
}
System.out.println("consume: " + num);
value=false;
notify(); .
return'num;
}
synchronized void put{int num) {
if {value==true)
try {
wait();
}
catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.num=num;
System:out.println("Produce: " + num);
}
public void run() {
s.get{);
}}
public class InterThread{
public static void main (String [ ] args.)
(
Shared s=new Shared{);
new.Producer(s) ;
new Consumer(s);
}}
synchronized(this) {
notifyAll();
}catch(Exception e){)
}}
class Demol extends Thread{
DemoWait d;
Demol(DemoWait d) - {
this.d=d;
start();
} public void run{){
try{ System.out.println("Demol value is " + d.val); •
d.valchange(40);
}catch(Exception e){}
}}
• Multitasking allow to execute more than one tasks it the same time, a task
being aerogram.In multitasking only one CPU is involved but it can switches NOTES
from one program to another program so quickly that’s why it gives the
appearance of executing all of the programs at the same time. Multitasking
allow processes (i.e., programs) to run concurrently on the program.
• Multithreading is a technique that allows a program or a process to execute
many tasks concurrently (at the same time and parallel). It allows a process
to run its tasks in parallel mode on a single processc r system.
•. The ‘mainO’ method in Java is referred to the thread that is running, whenever
a Java program runs. It calls the main thread because it is the first thread
that starts running when a program begins.
• In Java, thread scheduler can use the thread priorities in the form of integer
value to each of its thread to determine the execution-schedule of threads.
Thread gets the ready-to-run state according to their priorities.
• Synchronized methods are used to coordinate access to objects that are shared
among multiple threads. These methods are declared with the synchronized
keyword. Only one synchronized method at a time cari be invoked for an object
at a given point of time.
• When a synchronized method is invoked for a given object, it tries to acquire
the lock for that object. If it succeeds, no other synchronized method may be
invoked for that object until the lock is released.
REVIEW QUESTIONS
NOTES 7
I/O IN JAVA
STRUCTURE
- \
108 Self-Instructional Material
• It can move the work from the server to the client, making a web solution more Applets
scalable with the number of users/clients.
(
• If a standalone program talks to a web server, that server normally needs to
support all prior versions for users which have not kept their client software
updated. In contrast, a properly configured browser loads (and caches) the latest NOTES
applet version, so there is no need to support legacy versions.
• The applet naturally supports the changing user state, such as figure positions
on the chessboard.
• Developers can develop and debug an applet direct simply by creating a main
routine and calling initQ and start() on the applet.
• An untrusted applet has no access to the local machine and can only access the
server it came from. This , makes such an applet much safer to run than a
standalone executable that it could replace. However, a signed applet can have
full access to the machine it is running on if the user agrees.
• Java applets are fast-and can even have similar performance to native installed
software. |
Disadvantages: A Java applet may have any of the following disadvantages:
• It requires the Java plug-in.
• Some organizations only allow software-installed, by the administrators. As a
result, some users can only view applets that are| important enough to justify
contacting the administrator to request installation of the Java plug-in. •
• As with any.client-side scripting, security restrictions may make it difficult or
even impossible for an untrusted applet to achieve the desired goals.
• Some applets require a specific JRE. This is discouraged.
• If an applet requires a newer JRE than available on the system, or a specific
JRE, the user running it the first time will need to wait for the large JRE
download to complete. I
• Java automatic installation or update may fail if a proxy server is used to access
the web. This makes applets with specific requirements impossible to run unless
Java is manually updated. The Java automatic updater that is part of a Java
installation also may be complex to configure if it must work through a proxy.
• Unlike the older applet tag, the object tag needs workarounds to write a cross
browser HTML document..
Below is the list given for Do’s and Don’ts of Java Applets:
Do's
• Draw pictures on a web page.
• Create a-new window and draw the picture in it.
• Play sounds.
• Receive input from the user through the keyboard or the mouse.
• Make a network connection to the server from where the Applet is downloaded,
and send to and receive arbitrary data from that server.
Don’ts
•• Write data on any of the host’s disks.
• Read any data from the host’s disks without the user’s permission. In some
environments, notably Netscape, an Applet cannot read data from the user’s
disks even with permission.
• Delete files.
Self-Instructional Material 137
Introduction to Internet • Read from or write to arbitrary blocks of memory, even on a non-memory-
Programming (JAVA) protected operating system like the MacOS
• Make a network connection to a host on the Internet other than the one from
which it was downloaded.
NOTES • Call the native API directly (though Java API calls may eventually lead back to
native API calls). ; .
• Introduce a virus or Trojan horse into the host system.
Java Applets are essentially Java programs that run within a web page. Applet
programs are Java classes that extend the Java. Applet. Applet classes are embedded
by reference within a HTML page. You can observe that when Applets are combined
with HTML, they can make an interface more dynamic and powerful than with HTML
alone. While some Applets do nothing more than scroll text or play animations, but by
incorporating these basic features in web pages you can make them dynamic. These
dynamic web pages can be used in an enterprise application to view or manipulate
data coming from some source on the server. For example, an Applet may be used to
browse and modify records in a database or control runtime aspects of some other
application running on the server.
Besides the class file defining the Java Applet itself, Applets can use a collection
of utility classes, either by themselves or archived into a JAR file. The Applets and
their class files are distributed through standard HTTP requests and therefore can be
sent across firewalls with the web page data. Applet code is refreshed automatically
each time the user revisits the hosting website. Therefore, keeps full application up to
date on each client desktop on which it is running. Since Applets are extensions of the
Java platform, you can reuse existing Java components when you build web application
interface with Applets. As we’ll see in example programs in this unit, we can use
complex Java objects developed originally for server-side applications as components
of your Applets . In fact, you can write Java code that can operate as either an Applet •
or an application. In Fig. 8.1, we can see that using Applet program running in a Java-
enabled web browser can communicate to the server.
HTTP
WWW Server
Browser
4------- *
0
JVM
0
Applet)
Here, we will discuss about the Applet life cycle. If you think about the Basic
Applet Life Cycle, the points listed below should be thought of:
1. The browser reads the HTML page and finds any <APfLET> tags.
2. The browser parses the <APPLET> tag to find the CODE j ind possibly CODEBASE
attribute.
3. The browser downloads the. Class file for the Applet from the URL (Uniform
Resource Locator) found in the last step. -
4. The browser converts the raw bytes downloaded into a Java class, that is a
Java.lang.Class object.
5. The browser instantiates the Applet class to form an Ap Diet object. This requires
the Applet to have a no-args constructor.
6. The browser calls the Applet’s init () method.
7. The browser calls the Applet’s start () method.
8. While the Applet is running, the browser passes all the events intended for the
Applet, like mouse clicks, key presses, etc. to the Applet’s handle Event () method.
9. The default method paint() in Applets just draw messages or graphics (such as
lines, ovals etc.) on the screen. Update events are us'ed to tell the Applet that it
needs to repaint itself.
10. The browser calls the Applets stop () method.
import Java.applet.Applet;
import Java.awt,Graphics;
public class HelloWorldApplet extends Applet
{ /
public void paint(Graphics g)
C
g.drawstring{"Hello world!", 50, 25);.
}
If you observej that this Applet version of Hello World is1 a little more complicated
than to write an application program to say Hello World, it will take a little more
effort to run it as well. . i
First you have to type in the source code and save it into file called
. HelloWorldApplet.Java.
Compile this file in the usual way. If all is well a file called HelloWorldApplet.class
will be created.
Now you need Were ate an HTML file that will include: 'our Applet. The following
simple HTML file will do. .
<HTML>
<HEAD>
<TITLE> Hello World </TITLE>
</HEAD> .
<BODY>
This is the Applet :<P>
<Applet code=“HelloWorldApplet” width=“150” heigl:t=“50">
</Applet>
</BODY> t
</HTML> .
Self-Instructional Material 141
Introduction to Internet Save this file as HelloWorldApplet.html in the same directory as the
Programming (JAVA) RelloWorldApplet.class file.
When you’ve done that, load the HTML file into a Java enabled browser like
Internet Explorer or Sun’s Applet viewer. You should see something like below, though
NOTES of course the exact details depend on which browser you use.-
If the Applet is compiled without error and produced a HelloWorldApplet.class
file, and yet you don’t see the string “Hello World” in your browser chances are that
the class file is in the wrong place. Make sure HelloWorldApplet.class is in the same
directory as HelloWorld.html.
Also make sure that you’re using a version of Netscape or Internet Explorer which
supports Java. Not all versions do.
. In any case Netscape’s Java support is less than the perfect, so if you have trouble
with an Applet, the first thing to try is load it into Sun’s Applet Viewer. If the Applet1
Viewer has a problem, then chances are pretty good the problem is with the Applet
and not with the browser.
According to Sun “An Applet is a small program that is intended not to be run on
its own, but rather to be embedded inside another application. The Applet class provides
a standard interface between Applets and their environment.”
The output of the program will be like:
IB
Applet Vlev£ prialffgf
Applet
Hello world!
Applet started.
f
buttonOKPressed();
} NOTES
else if (e..target ==-buttonCancel) -
(
buttonCancelPressed();
)
)
return super.handleEvent(e);
}
The problem with this method is that events cannot be delivired to specific objects.
Instead, they have to be routed through a universal handler, which increases complexity
and therefore, weakens your design.
But Java 1.1 onward has introduced the concepts of the event delegation model.
This model allows special classes, known as “adapter classes” to be built and be
registered with a component in order to handle certain events.' ’hree simple steps are
required to use this model: - . .
1. Implement the desired listener interface in your adapter class! Depending on
what event you’re handling, a number of listener interfaces are available.
These include: j
ActionListener, WindowListener, MouseListener, MouseMotion
Listener, ComponentListener, FocusListenerj and ListSelection
Listener.
2. Register the adapter listener with the desired component(s). This can be in
the form of an add XXX Listener () method supported by the component for
example include add ActionListener (), add MouseListener (), and add
FocusListener ().
3. Implement the listener interface’s methods in your adapter class. It is in this
code that you will actually handle the event. !
The event delegation model allows the developer to separate the component’s
display (user interface) from the event handling (application data) which results in a
cleaner and more object-oriented design.
Components of an Event: Can be put under the follow ng categories.
1. Event Object: When the user interacts with the applica ion by clicking a mouse
button or pressing a key an event is generated. The Operating System traps this event
and the data associated with it.. For example, info about time at which the event
occurred, the event types (like keypress or mouse click etc.). This data is then passed
on to the application to which the event belongs.
You must note that, in Java, objects, which describe the events themselves,
represent events. Java has a number of classes that descritJe and handle different
categories of events. I
2. Event Source: An event source is the object that generated the event, for
example, if you click a button an ActionEvent Object is generated. The object of the
ActionEvent class contains information about the event (button click).
As you have studied about interfaces in Block 2 Unit 3 of th s course, an Interface Applets
contains constant values and method declaration. The Java.awt. jvent package contains
definitions of all event classes and listener interface. The semantic listener interfaces
defined by AWT for the above-mentioned semantic events are:
• ActionListener, NOTES
• AjdustmentListener,
• ItemListener,
• TextListener.
The low-level event listeners are as follows:
• ComponentListener,
• ContainerListener,
• FocusListener,
• KeyListener,
• MouseListener,
• MouseMotionListener,
• WindowsListener.
Action Event using the ActionListener interfaces.* In Fig. 8.2 the Event
Handling Model of AWT is given. This figure illustrates the usage of ActionEvent and
ActionListener interface in a Classic Java Application.
You can see in the program given below that the Button Listener is handling the
event generated by pressing button “Click Me”. Each time t!he button “Click Me” is
pressed; the message “The Button is pressed” is printed in the output area. As shown
in the output of this program, the message. “The Button is pressed” is printed three
times, since “Click Me” is pressed thrice.
Event object
Event handling
v methods
import Java.awt.event;
import Java.awt.*;
public class MyEvent extends.Frame
{
public MyEvent()
{
super("Window Title: Event Handling");
Button bl;
bl = new Button("Click Me");
\
Click
j ,
I
1
. i
7. The addAction Listener () method registers the listener object for the button.
8. SetVisible () method displays the window.
9. The Application waits for the user to interact with it. NOTES
10. Then the user clicks on the button labeled “Click-Me”: The “ActionEvent” event
is generated. Then the ActionEvent object is created and delegated to the
registered listener object for processing. The Listener object contains the
actionPerformed () method which processes the ActionEvent In the
actionPerformed 0 method, the reference to the event source is retrieved using
getSource 0 method. The message “The Button is Pressed” is printed.
} •
You also need an HTML file that references your Applet. The following simple
HTML file will do:
<HTML>
. <HEAD>
<TITLE> Draw String </TITLE>
</HEAD>
<BODY>
This is the Applet:<P>
<APPLET code=”Draw String Applet” width=”300" height=”50">
<PARAM name=”Message” value=”My new Parameter value!”>
</APPLET>
</BODY>
</HTML>
Applet started.
Of course you are free to change “My new Parameter value!” to a “message” of
' your choice. You only need to change the HTML, not the Java source code. PARAMs
let you customize Applets without changing or recompiling the code.
This Applet is very similar to the HelloWorldApplet. However rather than
hardcoding the message to be printed it’s read into the variable str through get
. parameter () method from a PARAM in the HTML.
You pass get ParameterO a string that names the parameter you want. This
string should match the name of a <PARAM> tag in the HTML page. getParameter()
returns the value of the parameter. All values are passed asj strings. If you want to get
another type like an integer, then you'll need to pass it as a string and convert it to the
type you really want.
The <PARAM> HTML tag is also straightforward. It occurs between <APPLET>
and </APPLET>.Tt has two attributes of its own, NAME and VALUE. NAME identifies
which PARAM this is. VALUE is the value of the PARAM as a String. Both should be
enclosed in double quote marks if they contain white space!
An Applet is not limited to one PARAM. You can pass as many named PARAMs
to an Applet as you like. An Applet does not necessarily need to use all the PARAMs
that are in the HTML. You can be safely ignore additional PARAMs.
Processing an Unknown Number Of Parameters: Sometimes the parameters
are not known to you, in that case most of the time you have a fairly good idea of what
parameters will and won’t be passed to your Applet or perhaps you want to write an
Applet that displays several lines of text. While it would be possible to cram all this
information into one long string, that’s not too friendly to | authors who want to use
your Applet on their pages. It’s much more sensible to give each line its own <PARAM>
tag. If this is the case, you should name the tags via some predictable and numeric
scheme. For instance in the text example the following set of <PARAM> tags would be
sensible:
<PARAM name=uparamlf1 value=”Hello Good Morning”>
<PARAM name=“param2" value=”Here I am “>
SUMMARY
• An applet is just a Java class that runs in a Web Browser such as. Internet
Explorer or Netscape.
• To test our Applet in a Web Browser, we need to be sure that our Web Browser
supports Java. Assuming that your Browser has Java turned ‘on’, load up the
HTML file we created into the Browser. Both Internet Explorer and Netscape
REVIEW QUESTIONS
9 NOTES
We all wonder that on seeing 2D or 3D movies or graphics, even on the Internet > *
we see and admire good animation oh various sites. The java technology provides you
the platform to develop these graphics using the Graphics class. In this unit you have
to overview several java capabilities for drawing two-dimensioial shapes, colors and
fonts. You will learn to make your own interface, which will b i user-interactive and
friendly. These interfaces can be made either using java AWT components or java
SWING components. In this unit you will learn to use some basic components like
button, text field, text area, etc.
4
154 Self-Instructional Material
Each draw method call will look like: g.drawString(“HeIIo World”, 0, 50); Graphics and User
Interface
Where g is the particular Graphics object with which you’re drawing. For
convenience sake in this unit the variable g will always refer to a pre-existing object of
the Graphics class. It is not a rule you are free to use some other name for the particular
Graphics context, such as myGraphics or applet-Graphics or anything else. NOTES
Color Control i
Color Methods: To apply color in your graphical picture (objects) or text two
Color methods get Color and set Color are provided. Method get Color returns a Color
object representing the current drawing color and method set Color used to sets the
current drawing color.
Color Constructor:
public Color(int r, int g, int b): Creates a color based on the values of red,
green and blue components expressed as integers from 0 to 255.
Fonts
You must have noticed that until now all the applets have used the default font.
However unlike HTML Java allows you to choose your fonts. Java implementations
are guaranteed to have a serif font like Times that can be accessed with the name
“Serif”, a monospaced font like courier that can be accessed with the name “Mono”,
and a sans serif font like Helvetica that can be accessed with the name “SansSerif”.
How can you know the available fonts on your system for an applet program?
You can list the fonts available on the system by using the getFontListO method from
java.awt.Toolkit. This method returns an array of strings containing the names of the
available fonts. These may or may not be the same as the fonts to installed on your
system. It is implementation is dependent on whether or not all the fonts in a system
are available to the applet.
Choosing a font face is very easy. You just create a new Font object and then call.
setFont(Font f).
To instantiate a Font object the constructor
public Font(String name, int style, int size) can be used, name is the name of the
font family, e.g., “Serif’, “SansSefif”, or “Mono”.
Size is the size of the font in points. In computer graphics a point is considered to
be equal to one pixel. 12 points is a normal size font.
Style is an mnemonic constant from java.awt.Font that tells whether the text
will be bold, italics or plain. The three constants are Font.PLAIN, Font.BOLD, and
Font.ITALIC.
In other words, The Class Font contains methods and constants for font control. Graphics and User
Font constructor takes three arguments Interface
Coordinate System
By Default the upper left corner of a GUI component (such as applet or window)
has thie coordinates (0,0). A coordinate pair is composed of ^-coordinate (the horizontal
coordinate) and a y-coordinate (the vertical coordinate). The r-coordinate is the
horizontal distance moving right from the upper left corner.
The y-coordinate is the vertical distance moving down from t re upper left corner.
The x-axis describes every horizontal coordinate, and they-axis describes every vertical
coordinate. You must note that different display cards have different resolutions
(i.e., the density of pixels varies). Fig. 9.2 represents coordinate system. This may
cause graphics to appear to be different sizes on different monitors.
y 4
NOTES <*.»
+
Y axis
Fig. 9.2. Co-ordinate System
Now we will move towards drawing of different objects. Here, we will demonstrate
drawing in applications.
Drawing Lines '
Drawing straight lines with Java can be done as follows:
call
g.drawLineOcl, yl, x2, y2)
method, where (xl, yl) and (x2, y2) are the endpoints of your lines and g is the
Graphics object you are drawing with. The following program will result in a line on
the applet. /
import java.applet.*; import java.awt.*; public class SimpleLine extends Applet {
public void paint(Graphics g) { g.drawLine(10, 20, 30, 40); } }
Output:
I iBisn
mm
Applet started.
Drawing Rectangle
Drawing rectangles is simple. Start with a Graphics object g and call its drawRectO
method:
public void drawRect(int x, int y, int width, int height)
The first argument int is the left hand side of the rectangle, the second is the top
of the rectangle, the third is the width and the fourth is the height. This is in contrast
to some APIs where the four sides of the rectangle are given.
Remember that the- upper left hand corner of the applet starts at (0, 0), not at
(1, 1). This means that a 100 by 200 pixel applet includes the points with x coordinates
between 0 and 99, not between 0 and 100. Similarly the y coordinates are between 0
and 199 inclusive, not 0 and 200.
Drawing Ovals and Circles
Java has methods to draw outlined and filled ovals. These methods are called
drawOvaK) and fillOvaK) respectively. These two methods are:
public void drawOvaKint left, int top, int width, int height)
public void fillOvaftint left, int top, int width, int height)
/
158 Self-Instructional Material
i
Instead of dimensions of the oval itself, the dimensions of the smallest rectangle, Graphics and User
which can enclose the oval, are specified. The oval is drawn as large as it can be to Interface
touch the rectangle’s edges at their centers. Figure 9.3 may help you to understand
properly. *
NOTES
/
9.3. BUILDING USER INTERFACE WITH AWT
In order to add a control to a container, you need to perform the following two
steps:
1. Create an object of the control by passing the required arguments to the
constructor.
2. Add the component (control) to the container.
Controls Functions
Textbox Accepts single line alphanumeric entry.
'TextArea Accepts multiple line alphanumeric entry.
Push button . Triggers a sequence of actions.
Label Displays Text.
Check box Accepts data that has a yes/no value. More than one checkbox can be
selected.
Radio button Similar to check box except that it allows the user to select a single
option from a group.
Combo box Displays a drop-down list for- single item selection. It allows new value
to be entered.
List box Similar to combo box except that it allows a user to select single or
multiple items. New values cannot be entered.
Controls Class
• Textbox TextField
TextArea TextArea
Push button Button
Check box CheckBox
Radio button CheckboxGroup with CheckBox
Combo box Choice
List box List
Compiling Applets:.
javac HelloWorldAppletJava
Running Applet from console:
c
java HelloWorldApplet
Running Applet from Web browser:
•Running applet in browser is very easy job, create an html file with the following
code:
i
<:html>
i
<head>
<title>A Simple Applet program</title>
</head>
<body>
<APPLET CODE=”HelloWorldApplet.class” WIDTH=700 HE1GHT=500>
</APPLET>
i
</body>
</html> 1
The Applet tag in html is used to embed an applet in the web page.
<APPLET CQDT&=nHelloWorldApplet.class” WIDTH=700 HEIGHT=500>
CODE tag is usedito specify the name of Java applet class name. To test your
applet opens the html file in web browser. You browser should display applet.
Advantages: A Java applet can have any or all of the following advantages:
• It is simple to make it work on Linux, Microsoft Windows and Mac OS X i.e., to
make it cross platform. Applets are supported by most web browsers.
• The same applet can work on “all” installed versions of Java at the same time,
rather than just the latest plug-in version only. However, if an applet requires
a later version of the Java Runtime Environment (JRE) the client will be forced
to wait during the large download.
• Most web browsers cache applets so will be quick to load when returning to a
web page. Applets also improve with use: after a first applet is run, the JVM is
already running and starts quickly.
136 Self-Instructional Material
Applets
Miciasoll Internet Lxplo/ei HE?
Look A }Q Practice B fe)
m
NOTES
J
4*
Back
* . Stop
® (2
flerftejh
a
Home i
&
Search
»
hove Java
As you can see, the results are basically the same as those we found when running
within the Applet Viewer—the difference is that the Web Browser is now acting as the
container for our object, not the Applet Viewer.
Example of class Applet: Applet is a program provided by java which is designed
for execution within the web browser. Applets are mostly used for a small internet and
intranet applications because of small size and it’s compatibility among almost all
web browsers. Applets are also very secure. For example, Applets can be used to serve
animated graphics on the web. Following example creates a simple applet that displays
Hello World message
import java.applet.Applet;
import j ava.awt.*;
import j ava.awt.event.*;
public class HelloWorldApplet extends Applet!
public static void main(String!] args){
Fraune frame = new Frame("Roseindia.net"} ;
frame.setSize(400,200) ;
Use the Applet Viewer to test our Applet: Java includes, in its Java Developers
Kit, a special interpreter called the Applet Viewer which can be used to test the Applets
we write. To execute it, >pen up a Command Window and enter the following
instructions to execute the HTML file we just wrote.
C:'.WiNMT\Sy*tcm32\r.oimnand.ct>m BSD
C:\JJ3! LESVPRflCT ICE>rtppietw-iowcr Exonp Lel4_l. .htnl
il
J JJ £
If we now press the ENTER key, we should seethe Applet Viewer display window,
and within it, the results of the execution of our Java applet...
I love Java
Applet started.
The Applet Viewer can be shut down simply by, clicking on its close button or
Control Menu Icon.
Display our Applet in a Web Browser: To test our Applet in a Web Browser,
we need to be sure that our Web Browser supports Java. Assuming that your Browser
has Java turned ‘on’, load up the HTML file we created into the Browser. Both Internet
Explorer and Netscape permit you to display local HTML pages by selecting File-Open
from the Menu Bar and Lelecting the HTML page.
import java.applet;
public class Examplel4_l extends Applet {
public void paint(Graphics-g) { NOTES
g.drawstring("I love Java",20,20);
}
}
Let’s take a closer look at the code and then well compile it and discuss how to
‘run’ it in a Web page.
The first thing to note is the two import statements. We need to import ‘awt’ in
order to produce the window within our browser. The second import statement is
necessary because all Applets extend; or inherit from, the Java applet class.
import java.awt.*;
import java.applet;
Because of that, the line of code defining the Applet class must use the keyword
‘extends’as this one does here...
public class Examplel4_l extends Applet {
The second thing to note is that Java Applets, unlike the Java Applications we
followed in the book, may not have a mainO method. A Java Applet, when it fires up in
a Web Browser, automatically looks to execute three methods in this order.
• initO
• startO . .
• paint \
We can choose which of these to code:
• The initO method is executed when an Applet object is first instantiated.
• The startO method is executed after the initO method completes execution and
every time the user of the browser returns to the HTML page on which the
applet resides.
• The paintO method is called after the init method has completed and after the
startO method has begun-most importantly, code in the paintO method is
guaranteed to run each time the window needs to be re-drawn (i.e., after the
browser has been minimized, covered, the HTML page has changed, etc.,)
For our purposes, we coded the paint method, which uses a Graphics object (here
defined as‘g*) to do the drawing...
public void paint(Graphics g) {
The code in the paintO method is used to draw the window that will be displayed
in the Web Browser. To do that we use the drawStringO method of the Graphics object,
supplying the text that we wish to appear in the window and it’s dimensions...
g.drawString(‘T love Java”,20,20); _
As we know that Applet classes need to run within a Web Browser. Assuming
you have now compiled the Java source file into a Bytecode file, we now need to create
an HTML document Which will create an instance of our Applet class when displayed
in a Web Browser. Here’s the HTML necessary to create an instance of our object and.
Self-Instructional Material 133
Introduction to Internet UNIT
Programming (JAVA)
NOTES 8
APPLETS
STRUCTURE
8.0 Learning Objectives
8.1 The Applet Class
8.2 The Applet Architecture
8.3 An Applet Skeleton: Initialization and Termination
8.4 Handling Events
8.5 HTML Applet Tag
• Summary '
• Review Questions
REVIEW QUESTIONS
1. What are the I/O basics in Java? Also explain the difference between InputStream
and OutputStream.
2. What are the Stream and Stream Classes? Explain with an example.
3. What is the methods of InputStream class and Methods of OutputStream class?
4. Define Character Stream Classes with an example.
5. Explain Predefined Stream.
6. How you can reading and writing a file?
7. Write short notes on the following:
(i) Transient and Volatile Modifiers.
(ii) Transient-Keyword.
(tii) Volatile Modifier. . ^
(iu) Using Native Methods.
8. Write a program for I/O operation using BufferedlnputStream and
BufferedOutputStream.
9. Write a program using FileReader and PrintWriter classes for file handling.
10. Which class may be used for reading from console?
11. Object of which class may be used for writing on console. -S.
12. Write a program to read the output of a file and display it on console.
class ShowMsgBox
{
public static void main(String [] args)
{ '
ShowMsgBox app = new ShowMsgBox();
app.ShowMessage("Generated with Native Method");
}
private native void ShowMessage(String msg);
{
System. loadLibrary("Msglmpl" )' ;
}
)
Output:
Login is = Logon info:
Username: Java
Date: Thu Feb 03 04:06:22 GMT+05:30 2005
Password: sun
Recovering object at Thu Feb 03 04:06:32 GMT+05:30 2005
login a = Logon info:
Username: Java
Date: Thu Feb 03 04:06:22 GMT+05:30 2005
Password: (n/a)
In the above exercise Date and Username fields are ordinary (not transient),
and thus are automatically serialized. However, the password is transient, and so it
is not stored on the disk. Also the serialization mechanism makes no attempt to recover
it. The transient keyword is for use with Serializable objects only.
Volatile Modifier: The volatile modifier is used v/hen you are working with
multiple threads. The Java language allows threads that access shared variables to
keep private working copies of the variables. This allows a more efficient
implementation of multiple threads. These working copies need to be reconciled with
the master copies in the shared (main) memory only at prescribed synchronization
points, namely when objects are locked or unlocked. As a rule, to ensure that shared
variables are consistently and reliably updated, a thread should ensure that it has
exclusive use of such variables by obtaining a lock and conventionally enforcing mutual
exclusion for those shared variables. Only variables may be volatile. Declaring them
so indicates that such methods may be modified asynchronously.
//Program
- import Java.io.*;
import Java.util, * .
public class SerialDemo implements Serializable
{
private Date date = new Date();
private String username;
private transient String password;
SerialDemo(String name, String pwd)
• {
username = name;
password = pwd;
}
public String toStringO
•{ .
String pwd = (password == null) ? "(n/a)" : password;
return "Logon into: \n " + "Username: + username +
"\n Date: " + dale + "\n Password: " + pwd;.
}
public static void main{String[1 args)
throws lOException, ClassNotFoundException
)
Output:
Enter some text on the keyboard...
(Az to terminate)
hello students ! enjoying Java Session
AZ
Open out.txt you will find
“hello students ! enjoying Java Session” is stored in it.
import Java.io.*;
class FileWriteDemo
{
public static void main{StringU' args) throws ICException
{ // open keyboard for input
BufferedReader stdin = new BufferedReader(new
InputStreamReader(System.in));
String s = "output.txt";
//check if output file exists
File f = new File(s);
if {f.exists{)) ■
{ System, out. print ("Overwrite " + s + " (y/n)?
if ( ! stdin. readLine () . toLowerCase () ..equals ( "y" ) )
return;
}
// open file.foi: output k
See the program written below open a text file called input.txt and to
count the number of lines and characters in that file.
//program
import Java.io.*;
public class FileOperation
{
public static void main(String[] args) throws lOException
{
// the file must be called 'input.txt'
String s = "input.txt"
File f = new File{s);
//check if file exists
if (!f.exists())
{
System, out .println \ + s +'"\' does not exit!");
return;
}
// open disk file for input
Buf feredReader inputFile = new Buf feredReader (new FileReader (s) ) ;
// read lines from the disk file, compute stats
String line;
» int nLines = 0;
int nCharacters = 0;
while ((line = inputFile.readLine()) != null)
{
nLines++;
nCharacters += line-, length () ;
}
// output file statistics
System.out.println{"File statistics for \'" + s + w\'...");
System.out.println("Number of lines = " + nLines);
System.out.println("Nuinber of characters = " + nCharacters);
inputFile.close(); .1
}
V
Output:
C: \ JAVA \ B IN>Java Consolelnput
What is your name? Java Tutorial
Hello, Java Tutorial
Java automatically imports the Java.lang package. This package defines a class
NOTES called System, which encapsulates several aspects of run-time environment. System
also contains three predefijied stream objects, in, out, and errs. These objects are
declared as public and static within System. This means they can be used by other
parts of your program withlout reference to your System object.
Access to standard input, standard output and standard error streams are
provided via public static System.in, System.out and System.err objects. These are
usually automatically associated with a user’s keyboard and screen.
System.out refers to standard output stream. By default this is the console.
System.in refers to standard input, which is keyboard by default.
System.err refers to standard error stream, which also is console by default.
System.in is an object of InputStream. System.out and System.err are objects
of PrintStream. These ar 2 byte streams, even though they typically are used to read
and write characters from and to the console.
The predefined Prim Streams, out, and err within system class are useful for
printing diagnostics when debugging Java programs and applets. The standard input
stream System.in is available, for reading inputs.
Now we will discuss how we can take input from console and see the output on
console.
Reading Console Input: Java takes input from console by reading from
System.in. It can be assc dated with these sources with reader and sink objects by
wrapping them in a reader object. For System.in an InputStreamReader is appropriate.
This can be further wrapped in a BufferedReader as given below, if a line-based input
is required. |
BufferedReader b!r = new BufferedReader
(new InputStreamReader(System.in))
After this statement br is a character-based stream that is linked to the console
through System Jn
The program given below is for receiving console input in any of your
Java applications.
//program
import Java.io.*;
.class Consolelhput
{ •
static String readLine()
{
StringBuffer response = .new StringBuffer{);
C:\COMPUTEO\system32\cfnd.exe . pixl
C:\snr\way2java\iojava FileToFi1e2 1
abc
def
ghi
ll
File copying with Character Streams: The files can be read with character
streams also. In the following program, file to file copying is done with FileReader and
FileWriter. It is equivalent to FileToFilel.java of byte streams copying.
import java.io.*;
public class FileToFile2
W public static void main(String args[]) throws lOException
' { FileReader fr =• new FileReader{"pqr.txt");
FileWriter fw = new FileWriter("xyz.txt");
int readO
int read{char cbufd).
int read(char cbuf[], int offset/ int length)
int write(int c)
int write {chair cbufd )
int write(char cbufd, int offset, int length)
CharArrayReader
StringReader
InputStreamRcader FilcReader
Object Reader
FilterReatler PushbackReadcr
BuffercdRcader LineNumberReader
PipedReadcr
Abstract class
PrintWriter
PipedWriter
BufferedWriter
Object r FilterWriter
Writer
OutputStreamWriter FileWriter
CharArrayWriter
StringWriter
Abstract class
Introduction to Internet
{ buffout.write(a);
Programming (JAVA)
a = a+3;
}
NOTES
buff out. close’() ;
FilelnputStfeam filein = ,new FileInputStream{"out.txt");
BufferedlnputStream buffin = new BufferedlnputStream(filein);
int i=0;
do
{ i=buffin.read <) ;
if (i ! = -1).
System, out .print'ln ( ". "+ i);
} while (i != -1);
buffin.close();
catch (lOExcepti on e) , .
{ System.out.pri ntln("Error Opening a file" + e) ;
} ) }
Output:
1
4
7
10
13
16
19
22
25
//program
import Java.io.*;
' \ ■ 1
Output:
test.txt has 42 available bytes
42 bytes were read - .
Bytes read are: This program is for Testing I/O Operations.
Source File
Reads from file
Input Stream
Places in the RAM
Stores as variable
RAM Memory in the program
Draws from the RAM
Output Stream
' Writes to file
Destination File
NOTES
Network SocketlnputStream -► Socketoutput Network
Stream
Flow of Data
&
OutputStream
Java input and output are based on the use of streams, or sequences of bytes that
travel from a source to a destination over a communication path. If a program is writing
to a stream, you can consider it as a stream’s source. If it is reading from a stream, it
is the stream’s destination. The communication path is dependent on the type of I/O
. being performed. It can consist of memory-tormemory transfers, a file system, a network,
and other forms of I/O.
Streams are powerful because they abstract away the details of the communication
path from input and output operations. This allows all I/O to be performed using a
common set of methods. These methods can be extended to provide higher-level custom
I/O capabilities.
Three streams given below are created automatically:
• System.out-standard output stream.
• System.in-standard input stream.
• System.err-standard error.
An InputStream represents a stream of data from which data can be read. Again,
this stream will be either directly connected to a device or else to another stream.
An OutputStream represents a stream to which data can be written. Typically,
this stream will either be directly connected to a device, such as a file or a network
connection, or to another output stream.
Java.io package: This package provides support for basic I/O operations. When
you are dealing with the Java.io package some questions given below need to be
• addressed.
• What is the file format: text or binary?
• Do you want random access capability? .
• Are you dealing with objects or non-objects?
• What are your sources and sinks for data?
• Do you need to use filtering (You will know about it in later section of this
. . unit)?
—K^^B^eAnaylnputStream^^
—FilelnputStream
DataInputStream~^^>
—K^^O^ectlnputStream^]^
LineNumberInputStream[^>
InputStream —► —»<]^F»lterInputStreani^^>
BufferlnputStream^^)
—PipedlnputStrcam
PushbacklnputStrearrT^>
—K![^Se^enceInputStream^]^
—K^sS^BufferJnpuiStream^)
. InputStream is inherited from the Object class. Each class of the InputStreams
provided by the java.io package is intended for a different purpose.
• OutputStream: The OutputStream class is a sibling to InputStream that is
used for writing byte and array of bytes to an output source. Similar to input
sources, an output source can be anything such as a file, a string, or memory
containing the' data. Like an input stream, an output stream is automatically
opened when you create it. You can explicitly close an output stream with the
close!) method, or let it be closed implicitly when the object is garbage collected.
The classes inherited from the OutputStream class can be seen in a hierarchy
structure shown below:
<^ByteAnayOutputStTeam^>
FileOutput$tream~~^^> Kl[^DataOutputStreani^]>
ObjectOutputStream^^) ><^BufTcredOutputStream^>
PipcdOutputStrcam^^)
OutputStream is also inherited from the' Object class. Each class of the
OutputStreams provided by the java.io package is intended for a different purpose.
How Files and Streams Work: Java uses streams to handle I/O operations
through which the data is flowed from one location to another. For example, an
InputStream can flow the data from a disk file to the internal memory and an
OutputStream can flow the data from the internal memory to a disk file. The
ByteArraylnputStream^^)
java.io.
PileInputStream^J^>
ObjectlnputStreanT^^)
■*\ •
FilterlnputStream^^)
* InputStream
PipedInputStream~^]]^>
*<^SequenceI nputStream^>
x^SfaingBufferlnputStre^]]]^
»<^B^AnayOutputStream^
FieOutputStream^^^>
♦ OutputStream ><^^FUcterOutputSncam^^
»<^^~^jectQutputStrcan7^^>
PipedOutputStrcanT^^
• The Button: Let us first start with one of the simplest of UI components: the • Graphics and User
button. Buttons are used to trigger events in a GUI environment The Button Interface
class is used to create buttons. When you add components to the container, you
don’t specify a set of coordinates that indicate where the components are to be
placed. A layout manager in effect for the container handles the arrangement NOTES
of components. The default layout for a container is flowj layout (for an applet
also default layout will be flow layout). More about different layouts you will
learn in later section of this unit. Now let us write a simple code to test our
button class. !
To create a button use, one of the following constructors:
ButtonO creates a button with no text label.
Button(String) creates a button with the given string as label.
.Example Program:
Output:
H5I fstVi
Applet started.
As you can see this program will place two buttons on the Applet with the caption
Play and Stop.
. • The Label: Labels are created using the Label class. Labels are basically used
to identify the purpose of other components on a given interface; they cannot be
import java.awt.*;
public class checkboxTest extends java.applet.Applet
{ Checkbox cl s new Checkbox ("Java");
Checkbox c2 = new Checkbox ("XML");
Checkbox c3 = new Checkbox ("VB");
public void init()
{ add(cl);
add{c2); . -
add(c3);
> >
Applet started.
t
• The Checkbox group: CheckboxGroup is also called like a radio button or
exclusive check boxes. To organize several Checkboxes into a group so that only
one can be selected at a time, you can create CheckboxGroup object as follows:
CheckboxGroup radio = new CheckboxGroup (); {
The CheckboxGroup keeps track of all the check boxes in its group. We have to
use this object as an extra argument to the Checkbox constructor.
Checkbox (String, CheckboxGroup, Boolean) creates a checkbox labeled
with the given string that belongs to the CheckboxGroupj indicated in the second
argument. The last argument equals true if box is checked and false otherwise.
The set Current (checkbox) method can be used to make the set of currently
selected check boxes in the group. There is also a get Current () method, which
returns the currently selected checkbox. j
• The Choice List: Choice List is created from the Choice class. List has
components that enable a single item to be picked from a pulldown list. We
encounter this control very often on the web when filling out forms.
The first step in creating a Choice: *
You can create a choice object to hold the list, as shown below:
Choice egender = new ChoiceO;
Items are added to the Choice List by using addltem(String) method the object.
The following code adds two items to the gender choice list.
cgender.addltem (“Female”);
cgender.addItem(“Male”);
After you add the Choice List it is added to the container like any other component
using the add() method.
The following example shows an Applet that contains a list of shopping items
in the store.
import java.awt.*;
Public class ChoiceTest extends java.applet.Applet
{ Choice shoplist e new ChoiceO;
Public void initO
{ shoplist.addltemp'Bed And Bath");
shoplist. addXteni( "Furniture");
lyeoAnd^bam 3
[Furniture
luiotmng
[Home Appliance
^oys and Accessories
Applet startetr
The choice list class has several methods, which are given in Table 9.3.
• The Text Field: To accept textual data from user, AWT provided two classes,
TextField and TextArea. The TextField handles a single line of text and does
not have scrollbars, whereas the TextArea class handles multiple lines of text.
Both the classes are derived from the TextComponent class. Hence they share
many common methods. TextFields provide an area where you can enter and
edit a single line of text. To create a text field, use one of the following •
constructors:
TextFieldO: creates an empty TextField with no specified width.
TextField(int): creates an empty text field with enough width to display the
specified number of characters (this has been depreciated in Java2).
TextField(String): creates a text field initialized with the given string.
TextField(String, int): creates a .text field with specified text and specified
width.
For example, the following line creates a text field 25 characters wide with the
string “Brewing Java” as its initial contents:
TextField txtfld = new TextField (“Brewing Java”, 25); add(txtfld);
You must be thinking that when you can make GUI interface with AWT package
then what is the purpose of learning Swing-based GUI? Actually Swing has lightweight
components 'and does not write itself to the screen; but redirects it to the component it
builds on. On the other hand AWT are heavyweight and have their own view port,
which sends the output to the screen. Heavyweight components also have their own
2-ordering (look and feel) dependent on the machine on which the program is running.
This is the reason why you can’t combine AWT and Swing in the same container. If
you do, AWT will always be drawn on top of the Swing components.
Introduction to Internet Another difference is that Swing is pure J ava, and therefore platform independent,
Programming (JAVA) Swing looks identically on all platforms, while AWT looks different on different
platforms.
See, basically Swing provides a rich set of GUI components; features include
NOTES model-UI separation and a plug able look and feel. Actually you can make your GUI
also with AWT but with Swing you can make it more user-friendly and interactive.
Swing components make programs efficient.
- ' Swing GUI components are packaged into Package javax.swing.
In the Java class hierarchy there is a. class:
Class Component which contains method paint for drawing Component onscreen
Class Container which is a collection of related components and contains method add
for adding components and Class JComponent which has Pluggable look and feel for
customizing look and feel Shortcut keys (mnemonics)
Common event-handling capabilities, The Hierarchy is as follows:
Object—> Component—> Container—» Component
In Swings we have classes prefixed with the letter ‘J’ like
JLabel ■> Displays single line of read only text
JTextField ■> Displays or accepts input in a single line
JTextArea -> Displays or accepts input in multiple lines
JCheckBox ->Gives choices for multiple options
JButton -> Accepts command and does the action
JList • > Gives multiple choices and display for selection
JHadioButton - > Gives choices for multiple option, but can select one at a time.
When you add a component to an applet or a container, the container uses its
layout manager to decide where to put the component. Different LayoutManager classes
use different rules to place components.
java.awt.LayoutManager is an interface. Five classes in the java packages
implement it:
• FlowLayout,
• BorderLayout,
• CardLayout,
• GridLayout,
• GridBagLayout,
• plus javax.swing.BoxLayout.
• FlowLayout: A FlowLayout arranges widgets from left to right until there’s
no more space left. Then it begins a row lower and moves from left to right
again. Each component in a FlowLayout gets as much space as it needs and
no more.
This is the default LayoutManager for applets and panels. FlowLayout is the
default layout for java.awt.Panel of which java.applet.AppIet is a subclasses.
166 Self-Instructional Material
;
• \
Therefore you don’t-need to do anything special to create a FlowLayout in an Graphics and User ’
applet. However you do need to use the following constructors if you want to Interface
use a FlowLayout in a Window.LayoutManagers have constructors like any
other class. • •
The constructor for a FlowLayout is . / NOTES
public FlowLayoutO
Thus to create a new FlowLayout object you write'
FlowLayout fl;
fl = new FlowLayoutO; '
As usual this can be shortened to
FlowLayout fl = new FlowLayoutO;
You tell an applet to use a particular LayoutManager instance by passing the
object to the applet’s setLayoutO method like this: this.setLayout(fl);
Most of the time setLayoutO is called in the initO method. You normally just
create the LayoutManager right inside the call to setLayoutO like this
this.setLayout(new FlowLayoutO);
For example the following applet uses a FlowLayout to position a series of
buttons that mimic the buttons on a tape deck.
import java.applet.*;
import java.awt.* ;
public class FlowTest extends Applet {
public void initO {
this.setLayout(new FlowLayout(});
this.add( new ButtonCAdd")} ;
this.add( new Button("Modify"));
this.add( new Button("Delete"));
this.add( new Button("Ok"));
this.add( new Button("CANCEL"));
)
}
-
Output:
fc:
[j|| Applet Viewer: FlowTcst.doss; :rJinixi
Applet
iAddH I Modify"] I Delete I [~o7| |cANC£l |
l
Applet started.
j
Introduction to Internet You can change the alignment of a FIowLayout in the constructor. Components
Programming (JAVA) are normally centered in an applet. You can make them left or right justified. To do
this just passes one of the defined constants FIowLayout.LEFT, FlowLayout.RIGHT
or FIowLayout.CENTER to the constructor, e.g., this.setLayout(new
NOTES FlowLayout(FlowLayout.LEFT));
Another constructor allows you spacing option in FIowLayout:
public FlowLayout(int alignment, int horizontalSpace, int verticalSpace); i
For instance to set up a FIowLayout with a ten pixel horizontal gap and a twenty
pixel vertical gap, aligned with the left edge of the panel, you would use the constructor
FIowLayout fl = new FlowLayout(FlowLayout.LEFT, 20,10);
Buttons arranged according to a center-aligned FIowLayout with a 20 pixel
horizontal spacing and a 10 pixel vertical spacing
• BorderLayout: A BorderLayout organizes an applet into North, South, East,
West and Center sections. North, South, East and West are the rectangular
edges of the applet. They’re continually resized .to fit the sizes of the widgets
included in them. Center is whatever is left over in the middle.
A BorderLayout places objects in the North, South, East, West and center of an
applet. You create a new BorderLayout object much like a FIowLayout object,
in the initO method call to setLayout like this:
this.setLayout(new BorderLayoutO);
There’s no centering, left alignment, or right alignment in a BorderLayout.
However, you can add horizontal and vertical gaps between the areas. Here is
how you would add a two pixel horizontal gap and a three pixel vertical gap to
a BorderLayout:
this.setLayout(new BorderLayout(2, 3));
To add components to a BorderLayout include the name of the section you wish
to add them to do like done in the program given below.
NOTES
Pity
JJitrt
Appltt aftrttd.
^ GridLayout Demo
#■
-TaiS
one two three
import java.awt.*;
public class.GridbagLayouttest extends Frame
• {
Button bl,b2,b3,b4/b5;
GridBagLayout gbl=new GridBagLayout();
GridBagConstraints gbc=new GridBagConstraints(
public GridbagLayouttest()
{
• setLayout (gbl.) ;
Output:
.Trfgf'rxt'
FWl-20,3-1
»*■
You must be thinking that container will be a thing that co: itains something, like
a bowl. Then you are right!! Actually container object is derived from the NOTES
java.awt.Container class is one of (or inherited from) th1*ee primary classes:
java.awt.Window, java.awt.Panel, java.awt.ScrollPane.
The Window class represents a standalone window (either an application window
: in the form of a java.awt.Frame, or a dialog box in the form of a java.awt.Dialog).
' , The java.awt.Panel class is not a standalone window by it self; instead, it acts as
a background container for all other components on a form. For instance, the
java.awt. Applet class is a direct descendant of java.awt.Panel.
' The three steps common for all Java GUI applications ;are:
1. Creation of a container.
2. Layout of GUI components. \
3. Handling of events.
The Container class contains the setLayoutO method so that you can set the
default LayoutManager to be used by your GUI. To actually c.dd components to the
container, you can use the container’s addO method: /
Panel p = new java.awt.PanelO;
Button b = new java.awt.Button(“OK”);
p.add(b);
A JPanel is a Container, which means that it can contain other components. GUI
design in Java relies on a layered approach where each layer uses an appropriate
layout manager.
FlowLayout is the default for JPanel objects. To use a ilifferent manager use
either of the following:
JPanel pane2 = new JPaneK) // make the panel first
pane2.setLayout(new BorderLayoutO); //then reset its manager
JPanel pane3 = new JPanel(new BorderLayoutO); // all i:i one!
1 SUMMARY
Interfaces using GUI allow the user to spend less time trying to remember
which keystroke sequences do what and allow spenk more time using the
program in a.productive manner. It is very important to learn how you can
beautify your components placed on the canvas area using FONT and COLOR
class.
Controls are components, such as buttons, labels and text boxes that can be
added to containers like frames, panels and applets. The Java.awt package
provides an integrated set of classes to manage user interface components.
Buttons are used to trigger events in a GUI environment
Labels are basically used to identify! the purpose of other components on a
given interface; they cannot be edited directly by the user.'
\ !
Self-Instructional Material 173
Introduction to Internet The TextField handles a single line of text and does not have scrollbars,
Programming (JAVA) whereas the TextArea classjiandles multiple lines of text. Both the classes
are derived from the TextComponent class.
TextFieldQ creates an empty TextField with no specified width.
NOTES
A FlowLayout arranges widgets from left to right until there’s no more space
left.
A BorderLayout organizes an applet into North, South, East, West and Center
sections. North, South, East and West are the rectangular edges of the applet.
They’re continually resized to fit the sizes of the widgets included in them.
A CardLayout breaks the applet into a deck of cards, each of which has its
. own Layout Manager.'
A GridLayout divides an applet into a specified number of rows and columns,
which form a grid of cells, each equally sized and spaced.
GridBagLayout is the most precise of the five AWT Layout Managers. It is
similar to the GridLayout, but components do not need to be of the same size.
A GridBagConstraints object specifies the location and area of the component’s
display area within the container (normally the applet panel) and how the
component is laid out inside its display area.
The gridx and gridy fields specify the x and y coordinates of the cell at the upper
left of the Component’s display area.
The gridwidth and gridheight fields specify the number of cells in a row
(gridwidth) or column (gridheight) in the Component’s display area.
The GridBagConstraints fill field determines whether and how a component
is resized if the component’s display area is larger than the component itself.
The Window class represents a standalone window (either an application
window in the form of a java.awt.Frame, or a dialog box in the form of a
java.awt.Dialog).
REVIEW QUESTIONS
8. Write a program that will give you the Fontmetrics parameters of a String.
9. Write a program which draws a line, a rectangle; and an oval on the applet. NOTES
10. Write a program that draws a color-filled line, a color-filled rectangle, and a color
filled oval on the applet.
11. Write a-program to add various checkboxes under the CheckboxGroup
12. Write a program in which the Applet displays a text area that is filled with a
string, when the programs begin running.
13. Describe the features of the. Swing components that subc ass J Component.
14. What are the difference between Swing and AWT?
15. Why do you think Layout Manager is important?
16. How does repaintO method work with Applet?
17. How many Listeners are there for trapping mouse movements:
i
\
\
>
(
4