JAVA
JAVA
JAVA
OBJECTIVES
Procedural Programming:
In procedural programming, the tasks are divided in to a number of subtasks
according to their functions. These subtasks are called procedures or methods. Any
procedure can be called at any point during the program execution. The program has global
and local data. Data moves freely from one procedure to another. Most of the procedure
share common data. Procedural programming uses Top-Down programming Approach.
Here the importance is given toalgorithms.
The main disadvantage of this paradigm is the difficulty in debugging and the
identification of the data and its correspondingprocedure.
ex : FORTRAN,Pascal.
Main program
Main Function
Object-1 Object -2
Method Method
Data Data Data
2
1.1.2. Basic concepts of Object OrientedProgramming
class : Student
Name
RollNumber Data
Birthdate
add()
delete()
M Methods
update()
display()
object object
add() add()
delete() delete()
update() update()
display() display()
3
Data abstraction and Encapsulation
The process of hiding internal details and showing functionality is known as
abstraction. It groups the essential details and ignore the other details. For example: phone
call, we don't know the internal processing. In java, abstract class and interface is used to
achieve abstraction.
The binding or wrapping code (methods) and data together into a single unit is known
as encapsulation. The data is not accessible to the outside world. The methods that are
wrapped with the data only can access it. These methods provide the interface between the
objects data and program. This insulation of the data from direct access by the program is
called data hiding. For example: capsule, it is wrapped with different medicines. A java class
is the example of encapsulation.
Data
Information “in” Information “out”
and
Method
Inheritance
Inheritance is the process of deriving new class from the existing class. The existing
class is called base class and the inherited class is called derived class. The derived class
contains all the attributes and methods of the base class and also its own attributes and
methods. This provides the idea of reusability.
Polymorphism
Polymorphism means the ability to take more than one form. The same principle is
applicable in object oriented programming where the objects at runtime decide what
behavior will be invoked. For example, an operation may exhibit different behaviour in
different instances. The behavior depends on the types of data used in the operation. For an
add operation the input of two numbers will result in sum, while the input of two strings
results in concatenation of the string. Polymorphism is implemented in Java using method
overloading and methodoverriding.
4
Shape
draw()
Dynamic binding
Binding is defined as the linking of the procedure or function call to the corresponding
program code to be executed. The binding which occurs during execution or runtime is
called as dynamic binding.
Message communication
An object oriented program consists of set of objects that communicate with each
other. Objects communicate with one another by sending and receiving information much
the same way as people pass messages to one another. It is defined as a process of
sending a request to execute a function for an object. It involves specifying the name of the
object, the name of the method (message) and the information to be sent. The general form
is
object_name.message( information);
ex : student.add(“prasanna”,101,12-02-2000);
Here student is the object and add is a message sent by the object student and the
information are inside the parenthesis.
5
1.1.3. Differences between Procedure Oriented Programming andObject
Orientedprogramming
6
1.4.Benefits of OOPs
a. Reusability:
In OOP’s programs functions and modules that are written by a user can be
reused by other users without anymodification.
b. Inheritance:
It helps to eliminate redundant code and extend the use of existing classes.
c. DataHiding:
The programmer can hide the data and functions in a class from other
classes. It helps the programmer to build the secureprograms.
Object-oriented programming is the best paradigm to solve the complex oriented problem.
The following areas make the use of OOP:
1. Image Processing and PatternRecognition
2. Computer Aided Design andManufacturing
3. Computer AidedTeaching
4. Intelligent Systems
5. Database ManagementSystems
6. Web basedApplications
7. Distributed Computing andApplications
8. Component basedApplications
9. Data security andmanagement
10. MobileComputing
11. Data Warehouse and DataMining
12. ParallelComputing
7
1.2. JAVA:
Java is a programming language and a platform. Java is a high level, robust,
secured and object-oriented programming language.
1.2.1. History
Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank,
and Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first
working version. This language was initially called “Oak,” but was renamed “Java” in 1995.
Between the initial implementation of Oak in the fall of 1992 and the public announcement of
Java in the spring of 1995, many more people contributed to the design and evolution of the
language. Bill Joy, Arthur van Hoff, Jonathan Payne, Frank Yellin, and Tim Lindholm were
key contributors to the maturing of the originalprototype.
The primary motivation was the need for a platform-independent (that is, architecture-
neutral) language that could be used to create software to be embedded in various
consumer electronic devices, such as microwave ovens and remote controls. So many
different types of CPUs are used as controllers. The problem is that compilers are expensive
and time-consuming to create for different types of CPU. An easier—and more cost-
efficient—solution was needed. In an attempt to find such a solution, Gosling and others
began work on a portable, platform-independent language that could be used to produce
code that would run on a variety of CPUs under differing environments. This effort ultimately
led to the creation of Java.
About the time that the details of Java were being worked out, a second, and
ultimately more important, factor was emerging that would play a crucial role in the future of
Java. This second force was, of course, the World Wide Web. Java might have remained a
useful but obscure language for programming consumer electronics. However, with the
emergence of the World Wide Web, Java was propelled to the forefront of computer
language design, because the Web, too, demanded portable programs.
Simple
Java was designed to be easy for the professional programmer to learn and use
effectively. Assuming that you have some programming experience, moving to Java will
require very little effort. Because Java inherits the C/C++ syntax and many of the object-
oriented features of C++, most programmers find easy to learn Java.
Object-Oriented
Java is a pure object oriented language. It follows “everything is an object” paradigm.
The object model in Java is simple and easy to extend, while primitive types, such as
integers, are kept as high-performance non objects.
Robust
The multi platform environment of the Web places extraordinary demands on a
program, because the program must execute reliably in a variety of systems. Thus, the
ability to create robust programs was given a high priority in the design ofJava.
Java is robust, because of the two main reasons for program failure: memory
management mistakes and mishandled exceptional conditions (that is, run-time errors).
8
Memory management can be a difficult, tedious task in traditional programming
environments. For example, in C/C++, the programmer must manually allocate and free all
dynamic memory. This sometimes leads to problems, because programmers will either
forget to free memory that has been previously allocated or, worse, try to free some memory
that another part of their code is still using. Java virtually eliminates these problems by
managing memory allocation and de-allocation. In fact, de-allocation is completely
automatic, because Java provides garbage collection for unusedobjects.
Exceptional conditions in traditional environments often arise in situations such as
division by zero or “file not found,” and they must be managed with hard-to-read constructs.
Java helps in this area by providing object-oriented exception handling. In a well-written Java
program, all run-time errors can—and should—be managed by the program.
Multithreaded
Java was designed to meet the real-world requirement of creating interactive,
networked programs. To accomplish this, Java supports multithreaded programming, which
allows to write programs that do many things simultaneously. The Java run-time system
comes with an elegant yet sophisticated solution for multi process synchronization that
enables to construct smooth running interactive systems.
Architecture-Neutral
One of the main problems facing programmers is that no guarantee exists that a
program runs today, will run tomorrow—even on the same machine. Operating system
upgrades, processor upgrades, and changes in core system resources can all combine to
make a program malfunction. The Java designers made several hard decisions in the Java
language and the Java Virtual Machine in an attempt to alter this situation. Their goal was
“write once; run anywhere, anytime, forever.” To a great extent, this goal was accomplished.
Distributed
Java is designed for the distributed environment of the Internet because it handles
TCP/IP protocols. In fact, accessing a resource using a URL is not much different from
accessing a file. Java also supports Remote Method Invocation (RMI). This feature enables
a program to invoke methods across anetwork.
Dynamic
Java programs carry with them substantial amounts of run-time type information that
is used to verify and resolve accesses to objects at run time. This makes it possible to
dynamically link code in a safe manner. This is crucial to the robustness of the Java
environment, in which small fragments of bytecode may be dynamically updated on a
runningsystem.
Security
As downloading a “normal” program, the downloaded program might contain a virus,
Trojan horse, or other harmful code. At the core of the problem is the fact that malicious
code can cause its damage because it has gained unauthorized access to system
resources. For example, a virus program might gather private information, such as credit
card numbers, bank account balances, and passwords, by searching the contents ofyour
9
computer’s local file system. In order for Java to enable applets to be downloaded and
executed on the client computer safely, it was necessary to prevent an applet from launching
such an attack. Java achieved this protection by confining an applet to the Java execution
environment and not allowing it access to other parts of the computer. The ability to
download applets with confidence that no harm will be done and that no security will be
breached is considered by many to be the single most innovative aspect of Java.
Portability
Portability is a major aspect of the Internet because there are many different types of
computers and operating systems connected to it. If a Java program were to be run on
virtually any computer connected to the Internet, there needed to be some way to enable
that program to execute on different systems. For example, in the case of an applet, the
same applet must be able to be downloaded and executed by the wide variety of CPUs,
operating systems, and browsers connected to the Internet. It is not practical to have
different versions of the applet for different computers. The same code must work on all
computers. Therefore, some means of generating portable executable code wasneeded.
1.2.3. JavaEnvironment
Installing the Java Development Kit (JDK) and the Java Runtime Environment
Download
There are many versions of the JDK to download, so choose the one that best suits
the types of applications development. Download the latest release of the "Java SE
Development Kit (JDK)". (e.g. jdk-6u18-windows-i586.exe)
Installation
Double click the executable file to begin the installation of the Java Development Kit.
Accept the license agreement to continue. By choosing the default option, It will install the
JDK in the system into a folder like C:\Program Files\Java\jdk1.6.0_18.When the JDK has
been installed, it will attempt to install the latest version of the Java Runtime Environment
(JRE). Before starting on any Java development, it is essential that machine have the most
current Java Runtime Environment installed.
Note that the latest version of Java is 8.
Setting the PATH Environment Variable
If default option is selected during the installation, the JDK installed itself into
\Program Files\Java\ jdk1.6.0_18\bindirectory.
Setting the Path
1. Right click the "My Computer"icon
2. Choose "Properties" from the popupmenu
3. Click the "Advanced"tab
4. Click on the Environment Variablesbutton
5. Under System Variables, find PATH and double clickit
6. In the Edit System Variable dialog box, go to the text box labeled Variablevalue:
7. Scroll to the end of the text (hitting the <End> key will dothat)
8. Insert a semicolon (';') and then the full path name of the JDK binaries directory (e.g.
C:\ProgramFiles\Java\jdk1.6.0_18\bin)
9. Click OK to close the window(s)
10
Popular Java Editors
To write java programs a text editor is needed. There are even more sophisticated IDEs
available in the market. some of them are
Notepad − On Windows machine, any simple text editor like Notepad ,textpad can
be used.
Netbeans − A Java IDE that is open-source and free which can be downloaded
fromhttps://www.netbeans.org/index.html.
Eclipse − A Java IDE developed by the eclipse open-source community and can be
downloaded fromhttps://www.eclipse.org/.
11
1.3. Introduction to Java:
1. Creating a program:
In Java, a source file is officially called a compilation unit. It is a text file that contains
one or more class definitions. Using any text editor such as notepad in windows or edit in
DOS etc , a java source file can be created. The created java file should be saved with
extension as java.
The general form is filename.java
If the source file has more than one class, then the filename should be the class name which
is having the main method in it.
The general form of a java source file is
class classname
{
// Your program begins with a call to main().
public static void main(args[ ])
{
}
}
Here class name is user defined and class is a keyword.
example
class First
{
12
Save the file asFirst.java
2.Compiling theprogram
javac compiler is used to compile the java program. The java source program is
compiled into class files. Java compiler creates a class file and the class files contains the
byte codes of the program.
1.3.3. JavaTokens:
The Smallest individual elements in a program are called tokens. Java language
includes five types of tokens. More than one token can appear in a same line separated by
spaces. They are as follows
1.Keywords
2.Identifiers
3.Literals
4.Operators
5.Separators
example :
class First
{
int x,y,z;
}
keyword – class
identifier – x y z First
separators - , ; { }
Keywords
keywords are the words which belongs to the java language. They have standard
predefined meaning. They should be used only for the intended purpose. They should be
written in small case letters. Here is a list of keywords in the Java programming language.
They cannot be used as identifiers in the programs. The keywords const and goto are
13
reserved, even though they are not currently used. true, false, and null might seem like
keywords, but they are actually literals;
Character set
A character set is a set of textual and graphic symbols, each of which is mapped to a
set of nonnegative integers. Character set defines the characters that are used in a
programming languages. Java uses unicode character set. Unicode is a 16-bit character set
designed to cover all the world's major living languages, in addition to scientific symbols and
dead languages that are the subject of scholarly interest. The first 256 values are the same
as the ASCII character set.
Identifiers
Identifiers are used for class names, method names, and variable names. An
identifier may be any descriptive sequence of uppercase and lowercase letters, numbers, or
the underscore and dollar-sign characters. They must not begin with a number. Java is case-
sensitive, so VALUE is a different identifier thanValue.
Some examples of valid identifiers are
AvgTemp
count
a4
$test
this_is_ok
Invalid identifier names include these:
2count // Cannot start with numeral
high-temp // Cannot have hyphensymbol
Not/ok //operators are not allowed
asidentifierMyClass // spaces are
notallowed
Literals
A constant value in Java is created by using aliteral representation of it. For
example, here are some literals:
Integer literals: 10 15 2
Floating-point literals: 2.3 1.1
Character literals: '(' 'J' 'j'
Boolean literals: true false
String literals: "Java" "100" "x"
14
Separator
In Java, there are a few characters that are used as separators. The most commonly
used separator in Java is the semicolon. It is used to terminate statements. The separators
are shown in the following table:
1. Single linecomment
Single line comment starts with //.
// text
The compiler ignores everything from // to the end of the line.
2. Multilinecomment
Multiline comment starts with /* and ends with */.
/* text */
The compiler ignores everything from /* to */.
3. Documentationcomment
Documentation comment starts with /** and ends with */.
/** documentation */
The compiler ignores everything from /** to */. The JDK javadoc tool uses doc comments
when preparing automatically generated documentation.
example
16
Review Questions
Short answer Questions
17
UNIT II CONTROL STRUCTURES, ARRAYS, AND VECTORS
OBJECTIVES
2.1. Elements:
2.1.1. Constants:
A constant value in Java is created by using a literal representation of it. For
example, here are some literals:
100 98.6 'X' "This is a test"
Left to right, the first literal specifies an integer, the next is a floating-point value, the
third is a character constant, and the last is a string. A literal can be used anywhere a value
of its type is allowed.
2.1.2. Variables:
Variable is name of reserved area allocated in memory. Its value changes during
execution.
2.1.3. Datatypes:
18
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and
boolean. The primitive types are also commonly referred to as simple types. These can be
put in four groups:
• Integers This group includes byte, short, int, and long, which are for whole-valued signed
numbers.
• Floating-point numbers This group includes float and double, which represent numbers
with fractionalprecision.
• Characters This group includes char, which are symbols in a character set,like letters and
numbers.
• Boolean This group includes boolean, which is a special type for representing true/false
values.
Integers
Java defines four integer types: byte, short, int, and long. All of these are signed,
positive and negative values.
byte
The smallest integer type is byte. This is a signed 8-bit type that has a range from –
128 to 127. Byte variables are declared by use of the byte keyword. For example, the
following declares two byte variables called b and c:
byte b, c;
short
short is a signed 16-bit type. It has a range from –32,768 to 32,767. Here are some
examples of short variable declarations:
short s; short t;
int
The most commonly used integer type is int. It is a signed 32-bit type that has a
range from –2,147,483,648 to2,147,483,647.
long
long is a signed 64-bit type and is useful for those occasions where an int type is not
large
enough to hold the desired value. The range of a long is quite large.
Floating-Point Types
19
Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision. For example, calculations such as square root,
or transcendental such as sine and cosine, result in a value whose precision requires a
floating-point type. There are two kinds of floating-point types, float and double, which
represent single- and double-precision numbers, respectively.
float
The type float specifies a single-precision value that uses 32 bits of storage. Here
are some example float variabledeclarations:
float hightemp, lowtemp;
double
Double precision, as denoted by the double keyword, uses 64 bits to store a value.
Characters
In Java, the data type used to store characters is char. For this purpose, it requires
16 bits. Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536.
Booleans
Java has a primitive type, called boolean, for logical values. It can have only one of
two possible values, true or false. This is the type returned by all relational operators, as in
the case of a < b. boolean is also the type required by the conditional expressions that
govern the control statements such as if and for.
20
outside of its block, the line y = 100; is commented out. If the leading comment symbol is
removed, a compile-time error will occur, because y is not visible outside of its block. Within
the if block, x can be used because code within a block (that is, a nested scope) has access
to variables declared by an enclosing scope.
2.1.5. Typecasting
It is fairly common to assign a value of one type to a variable of another type. If the
two types are compatible, then Java will perform the conversion automatically. However, not
all types are compatible, and thus, not all type conversions are implicitly allowed. For
instance, there is no automatic conversion defined from double to byte. Fortunately, it is still
possible to obtain a conversion between incompatible types by using cast, which performs
an explicit conversion between incompatibletypes.
When one type of data is assigned to another type of variable, an automatic type
conversion will take place if the following two conditions are met:
• The two types arecompatible.
• The destination type is larger than the sourcetype.
When these two conditions are met, a widening conversion takes place. For
example, the int type is always large enough to hold all valid byte values, so no explicit cast
statement is required. For widening conversions, the numeric types, including integer and
floating-point types, are compatible with each other. However, there are no automatic
conversions from the numeric types to char or boolean. Also, char and boolean are not
compatible with each other. Java also performs an automatic type conversion when storing a
literal integer constant into variables of type byte, short, long, orchar.
To create a conversion between two incompatible types, use a cast. A cast is
simply an explicit type conversion. It has this generalform:
(target-type) value
Here, target-type specifies the desired type to convert the specified value to. For example,
the following fragment casts an int to a byte. If the integer’s value is larger than the range of
a byte, it will be reduced modulo (the remainder of an integer division by the) byte’s range.
int a;
byte b;
// ...
b = (byte) a;
2.1.6. Operators:
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:
Operator Result
+ Addition
– Subtraction (also unaryminus)
* Multiplication
/ Division
% Modulus
++ Increment
–– Decrement
The operands of the arithmetic operators must be of a numeric type.
Relational Operators
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering. The relational operators are shown here:
21
Operator Result
== Equalto
!= Not equalto
> Greaterthan
< Lessthan
>= Greater than or equalto
<= Less than or equalto
The outcome of these operations is a boolean value. The relational operators are
most frequently used in the expressions that control the if statement and the various loop
statements. Any type in Java, including integers, floating-point numbers, characters, and
Booleans can be compared using the equality test, ==, and the inequality test, !=. As stated,
the result produced by a relational operator is a boolean value. For example,the following
code fragment is perfectly valid:
int a = 4;
int b = 1;
boolean c = a < b;
In this case, the result of a<b (which is false) is stored in c.
22
The Bitwise Operators
Java defines several bitwise operators that can be applied to the integer types, long,
int, short, char, and byte. These operators act upon the individual bits of their operands.
They are summarized in the followingtable:
Operator Result
~ Bitwise unaryNOT
& BitwiseAND
| BitwiseOR
^ Bitwise exclusiveOR
>> Shiftright
>>> Shift right zerofill
<< Shiftleft
Since the bitwise operators manipulate the bits within an integer, it is important to
understand what effects such manipulations may have on a value. Specifically, it is useful to
know how Java stores integer values and how it represents negative numbers. All of the
integer types are represented by binary numbers of varying bit widths. For example, the byte
value for 42 in binary is 00101010, where each position represents a power of two, starting
with 20 at the rightmost bit. The next bit position to the left would be 21, or 2 , continuing
toward the left with 22, or 4, then 8, 16, 32, and so on. So 42 has 1 bits set at positions 1, 3,
and 5 (counting from 0 at the right); thus, 42 is the sum of 21 + 23 + 25, which is 2 + 8 + 32.
All of the integer types (except char) are signed integers. This means that they can
represent negative values as well as positive ones. Java uses an encoding known as two’s
complement, which means that negative numbers are represented by inverting (changing 1’s
to 0’s and vice versa) all of the bits in a value, then adding 1 to the result. For example, –42
is represented by inverting all of the bits in 42, or 00101010, which yields 11010101, then
adding 1, which results in 11010110, or –42. To decode a negative number, first invert all of
the bits, then add 1. For example, –42, or 11010110 inverted, yields 00101001, or 41, so
when 1 s added , the result will be42.
23
The Bitwise OR
The OR operator, |, combines bits such that if either of the bits in the operands is a 1,
then the resultant bit is a 1, as shown here:
00101010 42
|00001111 15
00101111 47
The BitwiseXOR
The XOR operator, ^, combines bits such that if exactly one operand is 1,
then the result is 1.Otherwise, the result is zero. The following example shows the
effect of the ^. This example also demonstrates a useful attribute of the XOR
operation. Notice how the bit pattern of 42 is inverted wherever the second operand
has a 1 bit. Wherever the second operand has a 0 bit, the first operand is
unchanged. You will find this property useful when performing some types of bit
manipulations.
00101010 42
^00001111 15
00100101 37
The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of
if-then-else statements. This operator is the ?. The ? has this general form:
expression1 ? expression2 : expression3
Here, expression1 can be any expression that evaluates to a boolean value. If
expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated. The
result of the ? operation is that of the expression evaluated. Both expression2 and
expression3 are required to return the same type, which can’t be void.
Here is an example of the way that the ? is employed:
ratio = denom == 0 ? 0 : num / denom;
When Java evaluates this assignment expression, it first looks at the expression to
the left of the question mark. If denom equals zero, then the expression betweenthe
question mark and the colon is evaluated and used as the value of the entire ? expression. If
denom does not equal zero, then the expression after the colon is evaluated and used for
the value of the entire ? expression. The result produced by the ? operator is then assigned
to ratio.
2.1.7. SPECIALOPERATOR
1. instanceofOperator
This operator is used to know if an object is an instance of a particular class or not.
This operator returns “true” if an object given at the left hand side is an instance of
the class given at right hand side. Otherwise, it returns “false”.
Example
circle instanceof Shape
The above statement checks if the object “circle” is an instance of the class “Shape”.
If yes, it returns “true”, else returns “false”
2. Dotoperator
This operator is used to access the variables and methods of a class.
Example 1
student.mark
Here we are accessing the variable “mark” of the “student” object
Example 2
student.getMarks()
Here we are accessing the method “getMarks” of the “student” object.
This operator also can be used to access classes, packages etc.
24
2.1.8. Expressions- Evaluation ofExpressions
int a = 0;
int b = 100;
int c;
c= a+ b;
if (value1 == value2)
System.out.println("value1 == value2");
The data type of the value returned by an expression depends on the elements used
in the expression. The expression c = a + b returns an int because the assignment operator
returns a value of the same data type as its left-hand operand; in this case, c is an int. As
from the other expressions, an expression can return other types of values as well, such
as boolean orString.
Highest
() []
++ -- ~ !
* / %
+ -
>> >>> <<
> >= < <=
== !=
&
^
|
&&
||
?:
=op=
Lowest
Parentheses are used to alter the precedence of an operation. The square brackets
provide array indexing. The dot operator is used to dereference objects. Parentheses raise
the precedence of the operations that are inside them.
The Java programming language allows to construct compound expressions from
various smaller expressions as long as the data type required by one part of the expression
matches the data type of the other. Here's an example of a compound expression:
1*2*3
In this particular example, the order in which the expression is evaluated is
unimportant because the result of multiplication is independent of order; the outcome is
always the same, no matter in which order you apply the multiplications. However, this is not
25
true of all expressions. For example, the following expression gives different results,
depending on whether you perform the addition or the division operation first:
x + y/100 //ambiguous
If the order is not mentioned explicitly for the operations to be performed, the order is
determined by the precedence assigned to the operators in use within the expression.
Operators that have a higher precedence get evaluated first. For example, the division
operator has a higher precedence than does the addition operator. Therefore, the following
two statements are equivalent:
x+y/100
When writing compound expressions, be explicit and indicate with parentheses which
operators should be evaluated first.
In this case, if num contains a value that is less than 100, the conditional expression
is true, and println( ) will execute. If num contains a value greater than or equal to 100, then
the println( ) method is bypassed.
26
2.2.2. if elsestatement
The if else statement is Java’s conditional branch statement. It can be used to route
program execution through two different paths. Here is the general form of the if else
statement:
if (condition) statement1;
else statement2;
2.2.3. Nestedif
A nested if is an if statement that is the target of another if or else. Nested ifs are
very common in programming. When ifs are nested, the main thing to remember is that an
else statement always refers to the nearest if statement that is within the same block as the
else and that is not already associated with an else. Here is an example:
if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d; // this if is
else a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)
As the comments indicate, the final else is not associated with if(j<20) because it is
not in the same block (even though it is the nearest if without an else). Rather, the final else
is associated with if(i==10). The inner else refers to if(k>100) because it is the closest if
within the same block.
27
The final else acts as a default condition; that is, if all other conditional tests fail, then
the last else statement is performed. If there is no final else and all other conditions are
false, then no action will take place.
Here is a program that uses an if-else-if ladder to determine which season a
particular month is in.
2.2.5. switch
The switch statement is Java’s multi-way branch statement. It provides an easy way
to dispatch execution to different parts of your code based on the value of an expression. As
such, it often provides a better alternative than a large series of if-else-if statements. Here is
the general form of a switch statement:
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
The expression must be of type byte, short, int, or char; each of the values specified in the
case statements must be of a type compatible with the expression. Each case value must
be a unique literal (that is, it must be a constant, not a variable). Duplicate case values are
not allowed.
The switch statement works like this: The value of the expression is compared with
each of the literal values in the case statements. If a match is found, the code sequence
following that case statement is executed. If none of the constants matches the value of the
28
expression, then the default statement is executed. However, the default statement is
optional. If no case matches and no default is present, then no further action is taken. The
break statement is used inside the switch to terminate a statement sequence. When a
break statement is encountered, execution branches to the first line of code that follows the
entire switch statement. This has the effect of “jumping out” of the switch. Here is a simple
example that uses a switch statement:
// A simple example of the switch.
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
}
The output produced by this program is shown here:
i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.
29
Looping Statements
Java’s iteration statements or looping statements are for, while, and do-while.
These statements create loops. A loop repeatedly executes the same set of instructions
until a termination condition is met. Java has a loop to fit any programmingneed.
2.2.6. While
The while loop is Java’s most fundamental loop statement. It repeats a statement or
block while its controlling expression is true. Here is its general form:
while(condition) {
// body of loop
}
The condition can be any Boolean expression. The body of the loop will be executed
as long as the conditional expression is true. When condition becomes false, control passes
to the next line of code immediately following the loop. The curly braces are unnecessary if
only a single statement is being repeated.
Here is a while loop that counts down from 10, printing exactly ten lines of “tick”:
// Demonstration of while loop.
class While {
public static void main(String args[]) {
int n = 10;
while(n > 0) {
System.out.println("tick " + n);
n--;
}
}
}
When you run this program, it will “tick” ten times:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
Since the while loop evaluates its conditional expression at the top of the loop, the
body of the loop will not execute even once if the condition is false to begin with. For
example, in the following fragment, the call to println( ) is never executed:
int a = 10, b = 20;
while(a > b)
System.out.println("This will not be displayed");
2.2.7. do-while
If the conditional expression controlling a while loop is initially false, then the body of
the loop will not be executed at all. However, sometimes it is desirable to execute the body
of a loop at least once, even if the conditional expression is false to begin with. In other
words, there are times to test the termination expression at the end of the loop rather than
at the beginning. Fortunately, Java supplies a loop that does just that: the do-while. The do-
while loop always executes its body at least once, because its conditional expression is at
the bottom of the loop. Its general formis
do {
// body of loop
30
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then
evaluates the conditional expression. If this expression is true, the loop will repeat.
Otherwise, the loop terminates. As with all of Java’s loops, condition must be a Boolean
expression.
Here is an example that demonstrates the do-while loop.
It generates the same output as before.
// Demonstration of do-while loop.
class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
System.out.println("tick " + n);
n--;
} while(n > 0);
}
}
2.2.8. for
It is a powerful and versatile construct. Here is the general form of the traditional for
statement:
for(initialization; condition; iteration) {
// body
}
If only one statement is being repeated, there is no need for the curly braces. The for
loop operates as follows. When the loop first starts, the initialization portion of the loop is
executed. Generally, this is an expression that sets the value of the loop control variable,
which acts as a counter that controls the loop. It is important to understand that the
initialization expression is only executed once. Next, condition is evaluated. This must be a
Boolean expression. It usually tests the loop control variable against a target value. If this
expression is true, then the body of the loop is executed. If it is false, the loop terminates.
Next, the iteration portion of the loop is executed. This is usually an expression that
increments or decrements the loop control variable. The loop then iterates, first evaluating
the conditional expression, then executing the body of the loop, and then executing the
iteration expression with each pass. This process repeats until the controlling expression is
false.
Here is an example uses a for loop:
// Demonstration of for loop.
class ForTick {
public static void main(String args[]) {
int n;
for(n=10; n>0; n--)
System.out.println("tick " + n);
}
}
2.2.9. break
In Java, the break statement has three uses. First, it terminates a statement
sequence in a switch statement. Second, it can be used to exit a loop. Third, it can be used
as a “civilized” form of goto. By using break, immediate termination of a loop, bypassing the
conditional expression and any remaining code in the body of the loop is forced. When a
31
break statement is encountered inside a loop, the loop is terminated and program control
resumes at the next statement following the loop. Here is a simple example:
// Using break to exit a loop.
class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<100; i++) {
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
2.2.10. Labelledloop
The statement continue may specify a label to describe which enclosing loop to
continue. Here is an example program that uses continue to print a triangular multiplication
table for 0 through 9. The continue statement in this example terminates the loop counting j
and continues with the next iteration of the loop counting i.
32
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81
2.2.11. continue
Sometimes it is useful to force an early iteration of a loop. That is, it might want to
continue running the loop but stop processing the remainder of the code in its body for this
particular iteration. This is, in effect, a goto just past the body of the loop, to the loop’s end.
The continue statement performs such an action. In while and do-while loops, a continue
statement causes control to be transferred directly to the conditional expression that controls
the loop. In a for loop, control goes first to the iteration portion of the for statement and then
to the conditional expression. For all three loops, any intermediate code is bypassed. Here is
an example program that uses continue to cause two numbers to be printed on each line:
// Demonstrate continue.
class Continue {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
System.out.print(i + " ");
if (i%2 == 0)continue;
System.out.println("");
}
}
}
This code uses the % operator to check if i is even. If it is, the loop continues without
printing a newline. Here is the output from this program:
01
23
45
67
89
Good uses of continue are rare. One reason is that Java provides a rich set of loop
statements which fit most applications. However, for those special circumstances in which
early iteration is needed, the continue statement provides a structured way to accomplish it.
33
2.3 ARRAYS
2.3.1 Arrays
An array is a collection of variables of the same type, referred by a common name. The
number of values that can be stored in an array is known as size of the array. The size of the
array must be integer and cannot be changed during run time. The individual value of an
array is called element. A specific element in an array is accessed by writing a number is
known as index or subscript. An index always start with zero.
2.3.1.1 One DimensionalArray
An array with only one subscript is known as one dimensional array.
eg: If we want to store a set of marks for a student, then we use one dimensional array.
Int mark[ ] = { 70,68,72,60,75,74};
The elements of an array are stored in contiguous locations of memory.
70
68
72
60
75
74
2.3.1.2 Creating anArray
Arrays must be declared and created in the computer memory before they are used.
Creation of an array involves three steps. They are
(i). Declaring an array
(ii). Allocate memoryspace
(iii). Store thevalues
(i) Declaring thearray
It may be declared in two ways.
34
2.3.1.3 Arrayprocessing
We know that array is a group of data of same data type, so to use the array elements we
use any one of the looping statements. Normally for loop is used.
Example: To find the average of array elements
public class Example1
{
public static void main(String args[ ])
{
double sum=0,avg;
int x[]= {22,32,42,52,62};
for( int i=0; i<5; i++)
sum= sum+x[i];
avg = sum/5;
System.out.println("Average of array elements are:"+avg);
}
}
Example: To find the largest array element
public class Example2
{
public static void main(String args[ ])
{
int max;
int x[]= {122,12,40,5,68};
max = x[0];
for( int i=1; i<5; i++)
if (x[i]> max) max= x[i];
System.out.println("Largest array element is :"+max);
}
}
2.3.1.4 Multi DimensionalArray
In Java, a multidimensional array is an array of arrays. An array with more than one
subscripts is known as multi dimensional array.
35
2.3.2 Vectors
Vector
Vector is a class which is used to create dynamic array. Dynamic array means size
can be changed at run time. It also stores different types of objects. Vector class is defined
in java.utilpackage.
Creation of Vector
A Vector can be created in three ways.
Description Syntax Example::
To create an empty Vector vectorname = new Vector(); Vector v1= new Vector ( );
vector with the default
initial capacity of 10. It creates vector v1 of
capacity10.
To create a vector Vector vectorname = newVector(capacity); Vector v2= new Vector (5 );
with the given
capacity It creates vector v2 of given
capacity 5.
To create a vector Vector vectorname = newVector(capacity,n); Vector v3= new Vector (5,2);
with the given
capacity & It creates a vector v3 of given
increment. capacity 5 and
Increment is 2.
Methods
All the vector methods are called using the syntax
Vectorobject.methodname();
Sl. Method name Use Example::
No
1. int capacity() This method returns Vector v2= new Vector (5 );
the maximum v2.capacity();
number of objects to
be stored inthe
vector
2. int size() It returns the number Vector v2= new Vector (5 );
of objects present in v2.size();
the vector
3. void addElement(Object ) It inserts the object at Vector v2= new Vector (5 );
the end of the vector. v2.addElement(“Fruits”);
36
elements of the v2.removeAllElements( );
vector
9. copyInto(arrayname) It copies all the Vector v2= new Vector (5 );
objects of vector into v2.copyInto(x);
array
Example:
import java.util.*;
public class Example4
{
public static void main(String args[ ])
{
Vector v1 = new Vector(2);
System.out.println("Initial Size is: "+v1.size());
System.out.println("Initial capacity is: "+v1.capacity());
v1.addElement("C");
v1.addElement("C++");
v1.addElement("Java");
System.out.println("Size after adding elements: "+v1.size());
System.out.println(" capacity after adding elements: "+v1.capacity());
v1.insertElementAt("VB",2);
for(int i=0; i<v1.size();i++)
System.out.println("\t Elements are:" +v1.elementAt(i));
v1.removeElementAt(1);
System.out.println("Size after removing element: "+v1.size());
for(int i=0; i<v1.size();i++)
System.out.println("\t Elements are:" +v1.elementAt(i));
}
}
Difference between Array and Vector
Array Vector
Size of the array cannot be changed Size of the vector can be changed
Values of same data types can be stored Objects of different data types can be stored
2.3.3 ArrayList
ArrayList class is used to create dynamic array. Dynamic array means,the size of the array
can be changed at the run time.
Array lists are created with an initial size. When this size is exceeded, it is automatically
enlarged. When objects are removed, the array may be shrunk. It is defined in java.util
package.
Creation
An ArrayList can be created in two ways.
Description Syntax Example::
To create an empty ArrayList name = new ArrayList (); ArrayList a1= new ArrayList ( );
array list with the
default initial It creates ArrayList a1 of
capacity of10. capacity10.
Methods
All the ArrayList methods are called using the syntax
ArrayListname.methodname();
37
Sl. Method name Use Example::
No
1. int size() This method returns ArrayList a1= new ArrayList ( );
the number of a1.size();
elements in this list.
2. boolean add(Object) It inserts the object at ArrayList a1= new ArrayList ( );
the end of the list. a1.add(“oops”);
3. void add(int n, Object) It inserts the object at ArrayList a1= new ArrayList ( );
the nth position of a1.add(3,“oops”);
the list
4. Object get(int n) It returns the element ArrayList a1= new ArrayList ( );
at the nth positionin a1.get(2);
this list.
5. Object set(int n, Object) It replaces the ArrayList a1= new ArrayList ( );
element present at a1.set(3,“java”);
the nth position with
the given object.
6. Object remove(int n) It removes the ArrayList a1= new ArrayList ( );
element at the nth a1.remove(2);
position of thelist.
7. void clear() It removes all of the ArrayList a1= new ArrayList ( );
elements from this a1.clear();
list.
Example:
import java.util.*;
public class Example5
{
public static void main(String args[ ])
{
ArrayList a1 = new ArrayList();
System.out.println("Initial Size is: "+a1.size());
a1.add("C");
a1.add("C++");
a1.add("Java");
System.out.println("Size after adding elements: "+a1.size());
a1.add(2,"VB");
System.out.println("After adding element: ");
for(int i=0; i<a1.size();i++)
System.out.println("\t Elements are:" +a1.get(i));
a1.remove(0);
a1.set(1,"c#");
System.out.println("After removing & changing element: ");
for(int i=0; i<a1.size();i++)
System.out.println("\t Elements are:" +a1.get(i));
a1.clear();
System.out.println("Size after removing element: "+a1.size());
}
}
38
Advantages of ArrayList over Array
1. Its size can be changed at the runtime.
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
39
3. Converting primitive data type to stringobject
40
REVIEW QUESTIONS
PART - A
1. What is avariable?
2. Defineconstant.
3. What is mean by typecasting?
4. What is the use of breakstatement?
5. What is the use of continuestatement?
6. Definearray.
7 What is one dimensional array?.
8. What is arrayprocessing?.
9. Definevector.
10.What is the use ofaddElement()?.
11.List the differences between array andvector.
12.What isArraylist?
13.List the advantages of arraylist over array.
14.What is the use of clear()?.
15.What is wrapper class?.
16.List any 4 wrapper classes.
PART - B
1. Write notes on scopes of variables.
2. What are labeledloops?
3. Write the difference between while and do whilestatement?
4. Define multidimensional array.Explain
5. Write a note on creating avector.
6. Which methods are used to delete elements fromvector?.Explain.
7. Write a note on creating anarraylist.
8. Name the methods used to add elements to an arraylist andexplain.
PART - C
1. Explain the various control statements injava.
2. Explain the various operators available in java.
3. Explain the switch statement withexample.
4. What are the looping statements available in java ?Explain.
5. Explain the creation of one dimensionalarray.
6. Write a program to find the smallest elements in anarray.
7. Write a program to find the average of N elements in anarray.
8. Explain in detail about methods of Vector class.
9. Explain methods of ArrayListclass.
10. Explain aboutwrapperclass.
41
UNIT III STRINGS, CLASSES AND INTERFACES
OBJECTIVES
3.1 Strings:
In java, string is basically an object that represents sequence of char values. An
array of characters works same as java string. Forexample:
char[] ch={'j','a','v','a'};
String s=new String(ch); is same as:
String s="java";
String is probably the most commonly used class in Java’s class library. The obvious
reason for this is that strings are a very important part of programming. The first thing to
understand about strings is that every string is actually an object of type String. Even string
constants are actually String objects.
For example, in the statement
System.out.println("This is a String, too");
the string “This is a String, too” is a String constant.
The second thing to understand about strings is that objects of type String are
immutable;once aString object is created, its contents cannot be altered. Java defines a
peer class of String, called StringBuffer, which allows strings to be altered, so all of the
normal string manipulations are still available in Java.
3.1.1. StringArray
A Java String Array is an object that holds a fixed number of String values.
String Array Declaration
Square brackets is used to declare a String array. There are two ways of using it. The first
one is to put square brackets after the String reserved word. For example:
String[] thisIsAStringArray;
Another way of declaring a String Array is to put the square brackers after the name of the
variable. For example:
String thisIsAStringArray[];
42
This will declare a String Array with 5 elements. Each element can be accessed sing
index that starts with 0. The fist element is "thisIsAStringArray[0]", the second element is
"thisIsAStringArray[1]", and so on. Here is an example of declaring a String Array with size 5
and assigning values to each element:
String[] thisIsAStringArray;
if (fruits) {
thisIsAStringArray = new String[] {"Apple", "Banana", "Orange"};
} else {
thisIsAStringArray = new String[] {"Asparagus", "Carrot", "Tomato"};
}
Note that the value of the array depends on the value of fruits variable. The array can have
the values {"Apple", "Banana", "Orange"} if fruits is true, or {"Asparagus", "Carrot",
"Tomato"} if fruits is false.
Note that initializing an array will override the old contents of the array. For example
43
String[] thisIsAStringArray = {"Apple", "Banana", "Orange"};
thisIsAStringArray = new String[] {"Asparagus", "Carrot","Tomato"};
System.out.println( thisIsAStringArray[0]);
System.out.println( thisIsAStringArray[1] );
System.out.println( thisIsAStringArray[2]);
The code will have the output below. This is because the old contents {"Apple", "Banana",
"Orange"}, will be discarded and replaced with the new contents.
Asparagus
Carrot
Tomato
Also note that even the size of array will be changed if re-initialized. For example:
44
3.1.2. StringMethods
45
// Demonstrating some String methods.
class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of strOb1: " +
strOb1.length());
System.out.println("Char at index 3 in strOb1: " +
strOb1.charAt(3));
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
}
}
This program generates the following output:
Length of strOb1: 12
Char at index 3 in strOb1: s
strOb1 != strOb2
strOb1 == strOb3
46
Here is an example:
// StringBuffer length vs. capacity.
class StringBufferDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer = " + sb);
System.out.println("length = " + sb.length());
System.out.println("capacity = " + sb.capacity());
}
}
Here is the output of this program, which shows how StringBuffer reserves extra space for
additional manipulations:
buffer = Hello
length = 5
capacity = 21
Since sb is initialized with the string “Hello” when it is created, its length is 5. Its
capacity is 21 because room for 16 additional characters is automatically added.
setLength( )
To set the length of the buffer within a StringBuffer object, use setLength( ). Its
general form is shown here:
void setLength(int len)
Here, len specifies the length of the buffer. This value must be nonnegative.
The value of a single character can be obtained from a StringBuffer via the charAt()
method.The value of a character within a StringBuffer using setCharAt( ). Their general
forms are shown here:
char charAt(int where)
void setCharAt(int where, char ch)
For charAt( ), where specifies the index of the character being obtained. For
setCharAt( ), where specifies the index of the character being set, and ch specifies the new
value of that character. For both methods, where must be nonnegative and must not specify
a location beyond the end of the buffer.
The following example demonstrates charAt( ) and setCharAt( ):
// Demonstrate charAt() and setCharAt().
class setCharAtDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer before = " + sb);
System.out.println("charAt(1) before = " + sb.charAt(1));
sb.setCharAt(1, 'i');
sb.setLength(2);
System.out.println("buffer after = " + sb);
System.out.println("charAt(1) after = " + sb.charAt(1));
}
}
Here is the output generated by this program:
buffer before = Hello
charAt(1) before = e
buffer after = Hi
charAt(1) after = i
47
append( )
The append( ) method concatenates the string representation of any other type of data to
the end of the invoking StringBuffer object. It has several overloaded versions. Here are a
few of its forms:
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
String.valueOf( ) is called for each parameter to obtain its string representation. The
result is appended to the current StringBuffer object. The buffer itself is returned by each
version of append( ). This allows subsequent calls to be chained together, as shown in the
following example:
// Demonstrate append().
class appendDemo {
public static void main(String args[]) {
String s;
int a = 42;
StringBuffer sb = new StringBuffer(40);
s = sb.append("a = ").append(a).append("!").toString();
System.out.println(s);
}
}
The output of this example is shown here:
a = 42!
insert( )
The insert( ) method inserts one string into another. It is overloaded to accept values
of all the simple types, plus Strings, Objects, and CharSequences. Like append( ), it calls
String.valueOf( ) to obtain the string representation of the value it is called with. This string
is then inserted into the invoking StringBuffer object. These are a few of its forms:
StringBuffer insert(int index, Stringstr)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)
Here, index specifies the index at which point the string will be inserted into the invoking
StringBuffer object.
The following sample program inserts “like” between “I” and “Java”:
// Demonstrate insert().
class insertDemo{
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like");
System.out.println(sb);
}
}
The output of this example is shown here:
I like Java!
reverse( )
The characters can be reversed within a StringBuffer object using reverse( ), shown
here:
StringBuffer reverse( )
This method returns the reversed object on which it was called. The following program
demonstrates reverse( ):
48
// Using reverse() to reverse a StringBuffer.
class ReverseDemo{
public static void main(String args[]) {
StringBuffer s = new StringBuffer("abcdef");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
Here is the output produced by the program:
abcdef
fedcba
The deleteCharAt( ) method deletes the character at the index specified by loc. It returns
the resulting StringBuffer object.
replace( )
To replace one set of characters with another set inside a StringBuffer object by
calling replace( ). Its signature is shown here:
StringBuffer replace(int startIndex, int endIndex, String str)
The substring being replaced is specified by the indexes startIndex and endIndex.
Thus, the substring at startIndex through endIndex–1 is replaced. The replacement string is
passed in str The resulting StringBuffer object is returned.
49
StringBuffer sb = new StringBuffer("This is a test.");
sb.replace(5, 7, "was");
System.out.println("After replace: " + sb);
}
}
Here is the output:
After replace: This was a test.
A Java program must be encapsulated in a class that defines the state and behavior of basic
program components known as objects. Classes create objects and objects use methods to
communicate between them.
Classes contain a group of logically related data items (called as fields) and functions
(called as methods) that operate on them. Calling a specific method in an object is
described as sending the object amessage.
A class is a user defined data type with a template that serves to define its
properties. Objects are nothing but instances of classes. They can be created using
declarations. The basic form of a class definitionis
Everything inside square bracket is optional. Classname and superclassname are any
valid Java identifiers. The keyword extends indicates that the properties of the super class
are extended to the sub class. A class can have emptybody.
Data in a class is encapsulated by placing data fields inside the body of the class
definition. These variables are called as instance variables and they are created whenever
an object of the class is instantiated. Instance variables are declared in the same way as
localvariables.
50
Here, length and width are two integer type instance variables. They do not occupy
any memory space. They are also called as member variables.
A class can have any no. of methods called as instance methods. Methods are used
to manipulate the data contained in the class. Method definitions should be present inside
the class immediately after the instance variables declarations. A method is of theform
where
type can be either user defined or class type. It specifies the type of value
returned by the method. The type is void, if the method doesn’t return any
value.
The method name is any valid identifiername.
The parameter list contains list of variable names and their types, which act
as input to the method separated by commas. The parameter list can be
empty but the parentheses aremust.
The body contains a set of statements that perform operations on thedata.
Instance variables and methods in classes are accessible by all the methods in a
class but a method cannot access the variables declared in other methods.
An object in Java is a block of memory having enough space to store all instance
variables. Objects can be created using the new operator which creates an object of the
specified class and returns a reference to that object .The general form for creating an object
is
classname object;
object = new classname( );
51
where classname is any already defined class name and object is the name of the
object.
Statement Action
Rectangle rect1; declare Result
rect1 = new Rectangle( ); instantiate
Rectangle object
Each object has its own set of variables and methods. We cannot access these
variables and methods directly from outside the class. For this purpose, the dot operator is
used. Its general from is
objectname.variablename
objectname.methodname (parameter list)
where
objectname is the name of theobject
variablename is the name of the instancevariable
methodname is the name of themethod
parameter list is a list of actual values separated bycommas.
Eg;-
rl.len =15;
rl.wid =10;
r2.len =20;
r2.wid=12;
52
R1.length r2.length
15 20
R1.width r2.width
10 12
We can also assign values to variables using methods declared inside the class
R1.length 15
10
R1.width
ii) by calling the rectArea( ) method declared inside the Rectangle class
int area1 = rl.recArea();
53
3.2.2 Constructors
where constructor name is same as that of the class name. Constructors return instance of
a class and hence they do not specify a return type. A constructor may or may not have
arguments.
Eg;-
1) constructor without arguments
Rectangle ( )
{
length=15;
width =10;
}
2) Constructor with arguments
Rectangle (int x, inty)
{
length =x;
width = y;
}
}
}
54
3.2.3 Methodoverloading
Method overloading is used when objects are required to perform similar tasks but
using different input parameters. All the methods have same name but they have different
parameter lists and different definitions. When a method is called, java first matches the
method name and then it matches the number and type of parameters to decide which one
of the definitions is to be executed. This process is known aspolymorphism.
3.2.4 Staticmembers
The static members can be declared as common to all the objects and accessed without
using a particular object.
55
The member that are declared as static are called static members. Static variables and static
methods are also called as class variables and class methods.
Eg:-
class mathoperation
{
static float mul (float x, float y);
{
return x*y;
}
static floatdivide (float x, float y);
{
returnx/y;
}
}
classmathapplication
{
public static void main (String args[])
{
float a = mathoperation.mul (4.0, 5.0);
float b = mathoperation.divide (a, 2.0);
System.Out.println (“b=”+b);
}
}
Output:
b = 10.0
Note:
1. Static methods are called using the classname.
2. Static methods can only call other staticmethods.
3. Static methods can only access staticdata..
4. Static methods cannot refer to this or super in anyway.
A method can be called by using only its name by another method of the same class. This is
known as nesting of methods.
Eg:-
class nesting
{
int m, n;
nesting(int x, int y) // constructor method
{
m =x;
n = y;
}
int largest ()
{
if (m>= n)
return(m);
else
return(n);
56
}
void display()
{
int large = largest(); // calling a method
System.Out.println(“ largest value = “+ large);
}
}
Output:
largest value = 50
A method can call any number of methods. It is also possible for a called method to
call another method.
3.2.6 thiskeyword
Sometimes a method will need to refer to the object that invoked it. this keyword is
defined for the purpose. It can be used inside any method to refer to the current object. this
always refers to the object on which the method was invoked. this can be used anywhere,
where a reference to an object of the current class type is permitted.
When a local variable has the same name as an instance variable, it hides the
instance variable. To resolve this problem, this keyword can be used.
If our programs have to act in a particular way depending on the input given at the
time of execution, command line arguments are used. Command line arguments are
parameters that are supplied to the program at the time of invoking it for execution.
Eg;-
class Comlinetest
{
public static void main (String args [])
{
int count, i=0;
String s;
count =args.length;
System.out.println (“No. of arguments =”+count);
57
while (i<count)
{
s=args [i];
i=i+1;
System.out.println (i + ”. ”+”java is”+s);
}
}
}
Compile using
javac comlinetest.java
Run using
java comlinetest simple object_oriented distributed robust secure
The command line arguments are passed to the program through the array args.
The command line has 5 arguments. They are assigned to the array args as follows
args[0]=”simple”
args[1] = “object_oriented”
args[2] = “distributed”
args[3] =“robust”
args[4] = “secure”
Output
No. of arguments =5
1. java is simple
2. java is objectoriented
3. java isdistributed
4. java is robust
5. java issecure
3.3 Inheritance
The process of deriving a new class form an existing one is called as inheritance.
The old class is called as the base class or super class or the parent class and the new
class is known as derived class or subclass or child class. The subclass inherits all the
variables and methods of the super class plus its own variables and methods.
B
b) Multiple inheritances – A subclass is derived from more than one superclass
A B
58
Java doesn’t supportmultipleinheritance. This concept is implemented using a
secondary inheritance path in the form ofinterfaces.
c) Hierarchical inheritance – More than one subclass is derived from a super class. This can
be extended to any no. oflevels.
A
B C D
The keyword extends signifies that the properties of the super class are extended to
the subclass. The subclass will have its own variables and methods as well as that of the
super class.
Eg;-
class Rect
{
int l,b;
Rect (int x, int y)
{
l=x;
b=y;
}
int area ( )
{
return (l*b);
}
}
class Box extends Rect
{
int h;
Box (int a, int b, int ( )
{
59
super (a, b);
h=c;
}
int vol ( )
{
return(l*b*h);
}
}
class Volume
{
public static void main (String args[ ])
{
Box b1 = new Box 10,10,10);
int a = b1.area( );
int v = b1.vol( );
System.out.println(“Area =” +a);
System.out.println(“Volume=” +v);
}
}
The program defines a class Rect and extends it to another class box. The
constructor in the derived class uses the super keyword to pass values that are required by
the base class constructor.
3.3.2.1 Subclassconstructor
It is used to construct the instance variables of both the sub class and the super
class. It uses the keyword super to invoke the constructor of the super class.
super(argument list);
The super keyword can only be used inside a subclass, and it must be the first
statement within the subclass. The argument list should match the order and type of
instance variables declared in the superclass.
C
The class A serves as a base class for the derived class B which in turn serves as
the base class for the derived class C .The chain ABC is known as inheritancepath.
class Line
{
int l;
60
Line (int x);
{
l =x;
}
}
class Square extends Line
{
Square (int y)
{
super (y);
}
int area ( )
{
return l*l;
}
}
class Cube extends Square
{
Cube (int z)
{
super (z);
}
int vol ( )
{
return l*l*l;
}
}
class Main ( )
{
public static void main (String args[ ])
{
Cube c1 = new Cube(5);
System.out.println (“Area=” c1.area ));
System.out.println (“Volume=” c1.vol( ));
}
}
3.3.4 Hierarchicalinheritance
A
B C D
class Polygon
{
int noofside;
Polygon(int s)
{
61
noofside =s;
}
}
class Triangle extends Polygon
{
intb,h;
Triangle(int x, int y)
{
super(3);
b = x;
h =y;
}
int area ( )
{
return b*h*2;
}
}
class Square extends Polygon
{
int s;
Rectangle (int a)
{
super (4);
s = a;
}
int area ( )
{
return s*s;
}
}
class Hierarchy
{
public staic void main (String args[ ])
{
Triangle T = new Triangle(10,5);
System.out.println(“Triangle”);
System.out.println(“No. of sides =” noofside);
System.out.println(“Area =” +T.area ( ));
Square R = new Square(5);
System.out.println(“Rectangle”);
System.out.println (“No.of sides =” noofside);
System.out.println(“Area=” +R.area ( ));
}
}
3.3.4 Overridingmethods
Suppose that an already defined method in a super class is redefined with the same
name, arguments and return type as a method in the subclass. When the method is called,
then the method defined in the subclass is invoked and executed and the super class
method is neglected. This concept is known asoverriding.
62
class Super1
{
int x;
Super1 (int a)
{
x = a;
}
void disp( )
{
System.out.println (“x”= +x);
}
}
class Sub extends super1
{
int y;
Sub (int a, int b)
{
super (a);
y = b;
}
void disp( )
{
System.out.println (“y = “ + y);
}
}
class Test
{
public static void main (String args[ ])
{
Sub s1 =new Sub(10,20);
sl.disp( );
}
}
Output
y =20
super.superclass method ( )
Output
x = 10
y = 20
63
3.3.5 Final variables andmethods
By default, all the methods and variables in super classes can be overridden. If we
want to prevent the subclass from overriding the members of the super class, they can be
declared using the modifier final. If a method or variable is declared as final, it can never be
changed. If we try to change, the compiler generates an error message.
Output
x=5
y = 10
64
3.3.5.1 Finalclasses
A final class is defined with the modifier final. If a class is declared as final, then all
its variables and methods are final and hence it cannot be inherited. We cannot derive
subclasses for a final class. Suppose that we have a final class named xxx
final class xxx
{
……
}
Thenitisimpossibletodefineanewsubclass. Trying to do so will produce an error
message.
The modifier abstract when used in method definition indicates that the method must
always be redefined in a subclass, thus making overriding compulsory. Its general from is
When a class contains one or more abstract methods, then it should also be defined
as abstract. Its general form is
Abstract classes cannot be used to instantiate objects directly. The abstract methods
of an abstract class should be redefined in its sub class. We cannot create abstract
constructors or abstract static methods.
Eg;-
abstract class First
{
int x;
abstract void disp( );
}
class Second extends first
{
int y;
void disp( )
{
System.out.println (“x = “ + x);
System.out.println (“y =” + y);
}
65
}
class Demoabs
{
public static void main (String args[ ])
{
Second obj = new Second( ) ;
obj.x =10;
obj.y =20;
obj.disp( );
}
}
Output
x = 10
y = 20
3.3.7 Visibilitycontrol
Restricting the access of certain variables and methods from outside the class is
some times unavoidable. For this visibility modifiers are applied to the instance variables and
methods. The visibility modifiers are also known as access modifiers. There are five types of
visibility modifiers. They are
1. public
2. private
3.protected
4.friendly
5.private protected
3.3.7.1 Publicaccess
Syntax:
public datatype variablename;
public returntype methodname()
{
----
}
66
Syntax
datatype variablename;
returntype methodname()
{
----
}
Example:
float y;
int add (int x, int y)
{
----
}
3.3.7.3 Protectedaccess
Example
protected int x;
protected void add()
{
----
}
3.3.7.4 Privateaccess
A variable or method declared as private are visible only to its own class.
Example
private int x;
private void add()
{
----
}
A variable or method declared as private protected are visible only in sub class in all
the packages.
Example
private protected int x;
private protected void add()
{
----
}
67
3.3.8 Interfaces
The interface name can be any valid Java variable name. The variables are declared
as follows
Static final datatype variable = value;
Methods declaration will contain only a list of methods without any body.
Syntax
returntype methodname (parameterlist);
68
Eg;- interface Area
{
final static float PI =3.14f;
float compute (float x, float y)
void show ( );
}
3.3.8.2 Extendinginterface
Interfaces can be extended i.e one interface can be derived from the other one. This
is achieved with the help of extends keyword.
The sub interfaces cannot define the methods declared in the super interfaces. All
the methods should be defined only in the class that implements the derivedinterface.
3.3.8.3 Implementinginterfaces
Interfaces are used as super classes whose properties are inherited by classes.
Hence, it is necessary to create a class that inherits the interface.
69
The implementation of interface can take various forms
Interface
A A Interface class A D interface
implementation
B class implementation extension extension
B E
C B C
Eg;-
interface Area
{
final static float pi = 3.14f;
float compArea (float x, float .y);
}
class Rectangle implements Area
{
public float compArea(float x, float y)
{
return (x*y);
}
}
Output
Area of Rectangle = 200
Area of circle = 314
70
If a class that implements an interface, doesn’t implement all the methods of the
interface, the class becomes an abstract class and hence cannot be instantiated.
Interfaces can be used to declare a set of constants that can be used in different
classes. This is similar to creating header files. Such interfaces do not contain methods.
The constant values are available to any class that implements the interface. The values
can be used in any method, as part of variable declaration or anywhere where we can use a
finalvalue.
Eg;-
interface Cricket
{
int noofplayers = 11,
int noof keepers = 1;
}
class Game implements Cricket
{
void print ( )
{
System.out.println (“No.of players =” +noofplayers);
System.out.println (“No.of keepers = “ + noof keepers);
}
}
class Header
{
public static void main (String args [ ])
{
Game g = new Game ( );
g.print ( );
}
}
Output
No. of players = 11
No. of keepers = 1
class Stud
{
int rollno;
void getNo(int n)
{
rollno = n;
}
void putNo( )
{
System.out.println (“Roll No. =” + rollno);
}
}
71
class Test extends Student
{
int m1, m2, m3;
void getMarks(int x, int y, int z)
{
m1 = x;
m2 = y;
m3 = z;
}
void putMarks( )
{
System.out.println(“Mark 1 =” + m1);
System.out.println(“Mark 2 =” +m2);
System.out.println(“Mark 3 =” +m3);
}
}
interface Sports
{
int bonus = 100;
void showBonus ( );
}
Class Result extends Test implements Sports
{
int total;
public void showBonus( )
{
System.out.println (“Bonus marks =” +bonus);
}
void disp( )
{
total = m1 +m2 + m3 + bonus;
putNo( );
putMarks ( );
showBonus ( );
System.out.println (“Total Score =” total);
}
}
class Hybrid
{
public static void main (String args[ ])
{
Result s1 = new Result( );
S1.getNo(98430);
S1.getMarks(99,73,87);
S1.disp( );
}
}
72
Review Questions
Part A (2 marks)
Part B (3 marks)
Part C (5 marks)
73
Unit IV- PACKAGES, APPLETS, AWT AND EVENT HANDLERS
Objectives
4.1 Packages
Packages act as “containers” for classes. They provide a functional way of grouping
classes and /or interfaces together. Packages help us to reuse the code already created.
Benefits
Classification
1) java.lang
This is the default package that is automatically imported and it contains classes that
support the java language including primitive types, strings, Math functions, Threads and
exceptions.
2) java.util
This contains classes for utilities such as vectors, hash tables, random nos., date etc.
3) java.io
This contains classes for supporting input and output operations.
4) java.awt
This contains classes for implementing GUI elements such as windows, buttons, lists,
menus.
5) java.net
This contains classes for networking with local computers as well as with the internet
servers.
6) java.applet
This contains classes for creating and implementing the applets.
74
java
lang util io awt net applet
java
awt
Color
Font
Graphics
Image
This is achieved by using the package name containing the class and then appending the
class name to it using the dot operator.
Eg;- java.awt.font
refers to the class font in the awt package which is inturn contained in the java package
2. Using importstatement
This is used when either one or more classes belonging to a package are used at one or
more places in a program.
Syntax
import packagename.packagename. .................... classname;
(Or)
import package name.*;
The import statement appears before the class definition
75
Eg;- 1) importjava.awt.color:
imports the class color
2) import java.awt.*;
imports all the classes in the awtpackage.
4.1.1.2 Namingconventions
Any standard identifier can be used as a package name. By convention, all package
names start with lowercase letters.
Eg;-
double y=java.lang.Math.sqrt (x) ;
Package names must be unique. Duplicate names cause runtime errors. Since, java
programmers work on Internet, duplicate package names are unavoidable. Hence, the java
designers suggest the users to use the domain names as prefix to the package names.
Eg;- Vnr.VSVP.mypackage
4.1.2 Creatingpackages
1. Create a subdirectory with the same name as that of the package name inside the
directory where classes that will import the package to be created arestored.
2. Declare the package using the package statement. This must be the first statement
in a Java sourcefile.
package packagename;
3. Define new classes for the package. A package file can have more than one class
definition. Declare any one class aspublic.
Java also supports the concept of package hierarchy. This is done by specifying multiple
package names separated by dots in a package statement
package package name1.packagename2;
This helps us to group related classes into a package and then group related packages
into a package and then group related packages into a larger one. The new package should
be stored in the subdirectory with package name2, which is in turn the subdirectory of
directory with package name1,which is in turn the subdirectory of the directory where the
source files that will import the package arestored.
76
4.1.3 Accessing a userpackage
Eg;- college.student.Print
This will access the class Print in the sub package student which in turn belongs to
the package college.
This statement can be used to search a list of packages for a particular class.
There can be more than one import statement and it should appear before the class
definitions.After an import statement is defined, all the members can be directly accessed
without using the package name or class name
Eg;- 1. importstudent.Result;
2. importstudent.*;
3. importcollege.student.Result;
Allows us to use the class Result in the sub package student in the package college.
The short cut approach has the advantage that we need not use long package
names repeatedly in our programs. But it has the disadvantage that it is difficult to
determine from which package a particular member came, when a large no. of packages
are imported.
77
4.1.4 Using apackage
package college;
public classStudent
{
int rollno;
Stringname;
public Student (int r, string n)
{
rollno = r;
name =n;
}
public void print ()
{
System.out.printn (“Roll No :” + roll no);
System.out.println (“Name:” + name);
}
}
Store the file in the subdirectory college with the name Student.java. Compile the file
and store the class files in the same directory.
package course;
public class Diploma
{
String discipline;
String year;
public Diploma(String d,String y)
{
discipline = d;
year = y;
}
public void print ( )
{
System.out.println (“course:” + discipline):
System.out.println (“year:” + year):
}
}
Store the file in the subdirectory course with the name Diploma.java. Compile the file
and store the class file in the same directory.
import college.*;
import course.*;
class Stuinfo
{
public static void main (String args[])
{
Student s1 = new Student (“98630”, “kumar”);
Diploma d1 = new Diploma (“Computer”, “III”);
s1.print();
d1.print();
}
}
78
Output
Roll No : 98630
Name : Kumar
Course : Computer
Year III
To create a package with multiple public classes, create them as separate source
files with the package statement at the top of each file and compile them individually to
produce the class files.
4.1.6 Hidingclasses
Whenever a package is imported using * option, only public classes are imported.
Other classes which are not declared as public are hidden from access from outside the
package.
79
4.2 Applets
4.2.1 Introduction
Applets are small Java programs that are primarily used in Internet computing. They
can be transported over the Internet from one computer to another System. It can be run
using the Applet viewer or any web browser that supports Java. An applet can perform
arithmetic operations, display graphics, play sounds, accept user input, create animation and
play interactive games. A web page can now contain not only a simple text or a static image
but also a Java applet which when run, can produce graphics, sounds and moving images
1. Localapplet
They are developed locally and stored in a local System. Internet connection is not
required. When a web page is trying to find a local applet, it simply searches the directories
in the local System and locates and loads the specifiedapplet.
2. Remoteapplets
A remote applet is the one developed by the remote user and stored on a remote
computer connected to the Internet. A remote applet can be downloaded on to our System
through the Internet and executed.
To locate and load a remote applet, the applets address should be known. This
address is known as Uniform Resource Locator (URL) and must be specified in the applets
HTML document as the value of the CODEBASE attribute.
Eg;-
If the applet is local, CODEBASE may be absent or may specify a local directory.
Applets are not full featured application programs. They are usually written to
accomplish a small task or a component of a task. They are usually designed for use on the
Internet.
80
1. Applets do not have main() method for initiating execution of the code. Applets when
loaded automatically call certain methods of applet class to start and execute the
appletcode.
2. Applets cannot run independently. They are run from inside a web page using a
special feature known as HTMLtag.
3. Applets cannot read from or write to the files in the localcomputer.
4. Applets cannot communicate with other servers on thenetwork.
5. Applets cannot run any program from the localcomputer.
6. Applets are restricted from using libraries from other languages such as C orC++.
7. Applets are event driven whereas the applications are controldriven.
1. Initializationstate
Whenever an applet is loaded, it enters into initialization state. This is achieved by
called the init() method of the Applet class. The initialization occurs only once in the applets
life cycle and it results in the birth of the applet. At this stage, wecan
a. create objects needed by theapplet
b. setup initialvalues
c. load images orfonts
d. setup colors
The init() method should be overridden in our program to achieve the same.
public void init ( )
{
……
}
81
2. Runningstate
When the start() method of the Applet Class is called, an applet enters into the
running state. This occurs automatically after the applet is initialized. An applet can also be
restarted from idle or stopped state. The start() method can be overridden to create a thread
to control the applet
public void start ()
{
…..
}
3. DisplayState
An applet can enter display state at any time form the running state. At this state, it
perform some output operation on the screen by calling the paint ( ) method. Hence, the
paint ( ) method should be overridden to displayinformation.
public void paint (Graphics g)
{
…..
}
4. Idle or stoppedstate
An applet is stopped from running when stop() method is called and it becomes idle.
Stopping occurs automatically when we leave the page containing the currently running
applet.
public void stop()
{
……
}
5. Dead state
When an applet is removed from memory, it enters into the dead state. When we
quit the browser, an applet automatically becomes dead by invoking the destroy() method.
Dead state occurs only once in the applets life cycle. If the applet has created any
resources like threads, they should be cleaned up by overriding thecode.
public void destroy()
{
…..
}
4.2.3.1 Creating anapplet
The applet code uses the services of two classes namely Applet and Graphics from
the Java class library. The Applet Class is contained in the java.applet package and
provides life and behavior to the applet through its methods. The Applet class therefore
maintains the life cycle of anapplet.
Methods
1. init( )
It is used to initialize the variables. This is the firstmethodcalled andis
called only once during the runtime.
void init ( )
2. start ()
This method is called by the browser after the init() method is called. It is also
used to restart an applet after it has been stopped.
void start ( )
3. stop()
This method is used to suspend the execution of the applet. The execution can be
restarted at any time using start() method.
82
void stop( )
4. destroy ()
This method removes the applet completely from the memory. Before using this
method, the applet should be stopped with the stop ( ) method.
void destroy( )
5. paint ()
This method is used to display the result of the applet code on the screen. The
output may contain text, graphics or sound. This method can be called any no. of times and
it requires an instance of a Graphics class as itsargument.
public void paint (Graphics g)
Hence, the graphics class contained in the java.awt package should be imported.
The graphics class contains a method drawString( ) to display the graphical applet o/p.
g.drawString(string, x, y)
where string denotes any given string and x and y denote the starting location of the screen
(in pixels) where the output is drawn.
Eg;-
g.drawString (“Welcome”, 10,100);
Output
100
10
welcome
83
The Applet class contained in the java.applet package itself is a subclass of the
panel class in java.awt package which is again a subclass of the container class, a subclass
of the component class, a subclass of the object class in the java.lang package. Hence, the
main Applet class inherits all the above classes i.e we can use the variables and methods
from all the aboveclasses.
java.lang.object
java.awt.component
java.awt.container
java.awt.panel
java.applet.Applet
Executable applet is nothing but the class file of the applet which is obtained by
compiling the source code using the command
javac filename.java
The output will have the name filename.class and is stored in the same directory
where the .java file is stored. During compilation, it any errors occur, then they should be
corrected and the source file is to be recompiled.
Note: Make sure that the applet source code file with extension .java, executable applet file
with extension .class and HTML file with extension .HTML are stored in the current directory.
84
Output
appletviewer:Hello.java
Applet
Hello java
To run using web browser, start the browser, give the file name as
C:\directory\HTML file
Output
Hello Java
4.2.4 APPLETtag
The APPLET tag is contained in the body section and starts with <APPLET> and
ends with </APPLET>. It contains the name of the applet to be loaded. It tells the browser
about the space requirements of the applet.
<APPLET
CODE = Name of the applet
WIDTH = Applet width
HEIGHT = Applet height>
</APPLET>
EG;- <APPLET
CODE = HelloJava.class
WIDTH = 400
85
HEIGHT = 200>
<APPLET>
The above section of code tells the browser to load the applet HelloJava.class and
display it in an area with 400 pixels width and 200 pixels height.
The <APPLET> tag is inserted in the HTML page at the place where the output must
appear.
Eg:-
<HTML>
<! Display a welcome title and message>
<HEAD>
<TITLE>
welcome to JAVA Applets
</TITLE>
</HEAD>
<BODY>
<CENTRE>
<H1>
welcome to the world of applets
<H1>
</CENTRE>
<BR>
<CENTER>
<APPLET
CODE = HelloJava.class
WIDTH = 400
HEIGHT = 200>
</APPLET>
</CENTER>
</BODY>
</HTML>
The file is stored with the name HelloJava.HTML in the directory where the
executable applet is stored.
2. CODEBASE
It specifies the directory in which the applet resides. If the applet resides in the same
directory as the HTML file, the CODEBASE need not be present. If the applet is local and
resides in different directory, then the CODEBASE should contain the path of the directory
where the executable applet resides. If the applet is remote and resides in a distant
computer, the CODEBASE contains the URL of the directory where the executable applet
resides.
3. WIDTH
It specifies the width of the applet in no. of pixels.
4. HEIGHT
It specifies the height of the applet in no. of pixels.
5. NAME
It specifies a name for the applet so that the other applet on the page can refer to this
applet for inter applet communication.
6. ALIGN
Specifies the location on the HTML page where the applet will appear. We can align
them at TOP, BOTTOM, LEFT, RIGHT, MIDDLE, ABSMIDDLE, ABSBOTTOM, TEXTTOP
and BASELINE.
6. HSPACE
Specifies the amount of horizontal blank space in no. of pixels, the browser should
leave surrounding the apple t(Used only when ALIGN is set to LEFT OR RIGHT).
7. VSPACE
Specifies the amount of vertical blank space in no of pixels, the browser should leave
surrounding the applet (Used only when ALIGN is set to TOP or BOTTOM).
8. ALT
Specifies the text to be displayed in non Java. The attributes CODE, WIDTH and
HEIGHT must compulsorily be present in an applet. Others are optional.
4.2.5 Passing parameters toapplets
<PARAM ……> tags can be used to pass user defined parameters to an applet.
Each <PARAM …..> tag has a name attribute and a value attribute. Inside the applet code,
the applet can refer to that parameter by name to find itsvalue.
Eg;-
<PARAM NAME = text VALUE = “ I LOVE INDIA”>
Changes the text to bedisplayed
<PARAM NAME = color VALUE =“red”>
Changes the color of the text to be displayed as red.
To setup and handle parameters
1. Include appropriate <PARAM ….> tags in the HTMLdocument.
2. Provide code in the applet to parse theseparameters
When an applet is loaded, parameters are passed to it. The init( ) method can be
defined to get hold of the parameters in the <PARAM> tags using getParameter( ) method.
The method takes one string argument representing the name and returns a string
containing the value of that parameter.
Eg;-
import java.awt.*;
import java. applet.*;
public class HelloJavaParam extends Applet
87
{
String str;
public void init ( )
{
str = getParameter (“String”);
if (str = = NULL)
str = “JAVA”;
str = “Hello” + Str;
}
public void paint (Graphics g)
{
g.drawString (str,50,50);
}
}
<HTML>
<HEAD>
<TITLE>
welcome to Java applets
</TITLE>
</HEAD>
<BODY>
<APPLET
CODE = HelloJavaParam.class
WIDTH = 400
HEIGH T = 200
>
<PARAM NAME = “ String” VALUE = “APPLET !” >
</APPLET>
</BODY>
</HTML>
Output
Hello APPLET !
Output
Hello Java
4.2.6 Graphicsclass
The class has methods for drawing many different types of shapes, from simple lines
to polygons to text in a variety of fonts. These methods have arguments representing end
points, corners or starting locations of a shape as values in the applets coordinate System.
Eg;- g.drawLline(10,10,50,50);
Draws a line from (10,10) to (50,50)
(10,10)
(50,50)
88
G is the Graphics object passed to paint() method.
The drawRect ( ) method is used to draw a rectangle. It takes 4 arguments. The first
two represent the x&y coordinates of the top left corner of the rectangle and the remaining
two the width and height of the rectangle.
Eg;- g.drawRect(10,60,40,30);
40
(10,60)
30
Draws a rectangle starting at (10, 60) having a width of 40 pixels and a height of 30
pixels.
The fillRect( ) method is used to draw a filled rectangle. It also takes 4 arguments as
drawRect( ).
g.fillRect(60,10,30,80);
(60,10) 30
80
g.drawRoundRect(10,100,80,50,10,10):
80
50
The fillRoundRect( ) method draws a filled rounded rectangle. The arguments are
same as that for drawRoundedRect( ).
g.fillRoundRect(20,110,60,30,5,5);
60
89
30
import java.awt.*;
importjava.applet.*;
public class LineRect extendsApplet
{
public void paint (Graphicsg)
{
g.drawRect(10,100,80,50);
g.fillRoundRect (20,110,60,30,5,5);
g.drawLine(10,100,90,150);
g.drawLine(10,150,90,100);
}
}
HTML file
<APPLET
CODE = LineRect. Class
WIDTH = 250
HEIGHT = 200>
</APPLET>
The drawOval() method can be used to draw a circle or an ellipse. It takes four
arguments. The first two represent the top left corner of the imaginary rectangle and the
other two represent the width and height of theoval.
If the width and height are equal, the oval becomes a circle.
Eg;- g.drawOval(10,10,120,60);
Eg;- g.fillOval(10,10,50,50);
90
Eg;-
public void paint (Graphics g)
{
g.drawOval(20,20,200,120);
g.setColor(color.green );
g.fillOval(70,30,100,100);
}
The drawArc() method is used to draw arcs. It takes six arguments. The first four
are same as that of the drawOval( ) method and the last two represent the starting angle of
the arc and the no. of degrees around the arc(sweepangle).
Eg:- g.drawArc(10,10,100,50,90,180)
180
50
100
If the sweep argument is negative, then the arc is drawn in backward direction.
91
50
100
The fillArc( ) method is used to draw a filled arc. Filled arcs are drawn as if they were
sections of a pie. Instead of joining the two end points, they are joined to the centre of the
oval.
import java.awt.*;
import java.applet.*;
public class Face extends Applet
{
public void paint (Graphics g)
{
g.drawOval (40,40,120,150); // Head
g.drawOval (57,75,30,20); // Left eye
g.drawOval (110,75,30,20);//Right eye
g.fillOval (68,81,10,10); // Left pupil
g.fillOval (121,81,10,10); // right pupil
g.drawOval (85,100,30,30); // nose
g.fillArc (60,12,80,40,180,180); //Mouth
g.drawOval (25,92,15,30);//left ear
g.drawOval (160,92,15,30) // right ear
}
}
92
10,20
We can also draw using the drawPolygon( ) method. It contains 3 arguments. The first one
is an array of integers having x coordinates. The second one is an array of integers having y
coordinates and the third one is an integer for the total no.of points. Repeat the first point at
the end for closing the polygon. The arrays x and y should be of samesize.
import java.awt.*;
import java.applet.*;
public class Poly extends Applet
{
int x1[ ] = {20,120,220,20);
int y1[ ] = {20,120,20,20};
int n1 = 4;
int x2[ ] = {120,220,220,120};
int y2 [] = {120,20,220,120};
int n2 = 4;
public void paint (Graphics g)
{
g. draw Polygon (x1, y1,n1);
g. fill Polygon (x2, y2, n2)
}
}
We can also treat the polygon as an object
93
1. Define the x coordinate values as anarray
2. Define the y coordinate values as anarray
3. Define the no. of pointsn
4. Create a polygon object and initialize it with abovevalues.
5. Call the drawPolygon() or fillPolygon() method with the polygon object as
argument.
public void paint (Graphics g)
{
int x[ ] = {20,120,220,20};
int y[ ] = {20,120,20,20};
int n =x.length;
Polygon poly = new Polygon (x,y,n);
g.drawPolygon(poly);
}
Now we can easily add points to the polygon using addPoint( ) using
Object.addPoint(x,y);
public void paint (Graphicsg)
{
Polygon poly = new Polygon ( ); // creates emptypolygon
poly.addPoint(20,20);
poly.addPoint(120,120);
poly.addPoint (220,20);
poly.addPoint(20,20);
g.drawPolygon(poly);
}
4.2.6.5 DrawingLineGraphs
A line graph is useful for displaying data or information that changes continuously
over time. Another name for a line graph is a line chart. A line chart or line graph is a type
of chart which displays information as a series of data points called 'markers' connected by
straight linesegments.
import java.awt.*;
import java.applet.*;
public class Linechart extends Applet
{
public void paint(Graphics g)
{
int x1[ ] = {20,120,200,225,250};
int y1[ ] = {20,120,20,150,25};
int n =x1.length;
g.drawString("Y", 10, 20);
g.drawString("X",300,200);
g.drawLine(10,10,10,200);
g.drawLine(300,200,10,200);
for(int i=0;i<n;i++)
g.drawLine(x1[i],y1[i],x1[i+1],y1[i+1]);
}
}
HTML file
<HTML>
94
<APPLET
CODE = Linechart.class
WIDTH = 400
HEIGHT = 200>
</APPLET>
</HTML>
Output
4.2.6.6 DrawingBarchart
Applets can be designed to display bar charts, which are commonly used in
comparative analysis of data.
Rs.crores
These data are input using the method getParameter(). The method getParameter()
returns only string values and therefore the wrapper class method parseInt() is used to
convert strings to the integer values.
import java.qwt.*;
import java.applet.*;
public class Barchart extends Applet
{
int n =0;
String label[];
intvalue[];
public void init()
{
n= Integer.parseInt(getParameter(“columns”));
label = new String[n];
95
value = new int[n];
label[0] = getParameter(“label1”);
label[1] = getParameter(“label2”);
label[2] = getParameter(“label3 ”);
label[3] = getParameter(“label4”);
value[0] = Integer.parseInt(getParameter(“c1”));
value[1] = Integer.parseInt(getParameter(“c2”));
value[2] = Integer.parseInt(getParameter(“c3”));
value[3] = Integer.parseInt(getParameter(“c4”));
}
public void paint(Graphics g)
{
for(int I =0;i<n;i++)
{
g.Setcolor(color.red);
g,drawstring(label[i],20,i*50+30);
g.fillrect(50,i*50+10,value[i],40);
}
}
}
HTML file
<HTML>
<APPLET CODE =Barchart.class
WIDTH = 300
HEIGHT = 250 >
<PARAM NAME = “columns”VALUE=”4”>
<PARAM NAME = “c1”VALUE=”110”>
<PARAM NAME = “c2”VALUE=”150”>
<PARAM NAME = “c3”VALUE=”100”>
<PARAM NAME = “c4”VALUE=”170”>
<PARAM NAME = “label1”VALUE=”91”>
<PARAM NAME = “label2”VALUE=”92”>
<PARAM NAME = “label3” VALUE=”93”>
<PARAM NAME = “label4” VALUE=”94”>
</HTML>
The Abstract Window Tool Kit (AWT) supports Graphical User Interface (GUI)
programming. The AWT package contains set of classes for windows, buttons, labels,
menus etc.
4.3.2 Events
96
Java is an event driven language. An event is an action triggered by the user such as
a key press or mouse click. Java is an OOP language, so each event is considered as an
object of class. Java provides a class called EventObject. The java.awt package contains a
class called AWT event which is a subclass of EventObject.
Event classes
4.3.2.1 EventGenerators
Example
97
Event Listeners
o ActionListener.
o AdjustmentListener.
o ComponentListener.
o ContainerListener.
o FocusListener.
o ItemListener.
o KeyListener.
o MouseListener.
o MouseMotionListener.
o WindowListener.
The programmer developing an applet or application will write event handlers. The
programmer will also need to register the handler with the appropriate event generator.
register(handler) remember
who
registered
event
occurs
98
Buttons generate Action Events. An event handler is technically called a
listener in Java. A listener is registered with a button, by some object sending it the
addActionListener method, with a parameter indicating who the listener ( handler ) is going
to be. The button remembers who is registered. This is done automatically by code in the
Javalibraries.
When the event occurs, the button informs the listeners that the event occurred by
sending the action performed message to each of the listeners. This is also done
automatically by Java library code.
register(handler) remember
who
registered
event
occurs
The label component is the simplest of Java’s AWT and consists of a text string for display
only.
Syntax
Label labelname = new label ( “ Text message “ );
Example
Label L1 = new label ( “Comp Engg “ );
The above example creates a label with name L1 and displays the message
Comp Engg.
Methods
99
getAlignment ( ) To get the alignment of the int x = L1.getAlignment ( );
label.
Example
add ( one );
add ( two );
add ( three );
}
}
add ( one ) of method is used to add the label one to the applet..
HTML file
< HTML>
< BODY>
<APPLET
CODE = Labe demo . class
WIDTH = 400
HEIGHT = 400 >
< / APPLET >
< / BODY>
< / HTML>
Output
Applet Viewer : Label demo
Applet
4.3.3.2 Text-Component
The TextField and TextArea classes implement one dimensional and two
dimensional components for text input display and editing. Both classes extend from the
TextComponentclass.
100
Component
TextComponent
TextField TextArea
4.3.3.2.1 TextField
It is used for Single line text entry. It is also called as edit control.
Constructors
1. TextField ( ) Constructs an empty textfield.
2. TextField ( int cols ) Constructs an empty text field with specified number
ofcolumns.
3. TextField ( String text ) Constructs a textfield whose initial content is
text.
4. TextField ( String text , int cols ) Constructs a textfield whose initial
content is text with the specified number ofcolumns.
Methods
Example
TextField tf1 = new TextField ( “ Java” ); - It creates a text field with the content Java.
4.3.3.2.2 TextArea
Methods
101
getText() Returns the text content of thecomponent.
SetText() Sets the text content of thecomponent.
Example
4.3.3.3 Buttons
A push button is a component that contains a label and generates an event when it is
pressed.
Constructors
Syntax
Example
Methods
Example
4.3.3.4 Checkboxes
Constructors
o Checkbox ()
o Checkbox ( String S)
o Checkbox ( String S, boolean state )
If the state is not specified the default state isfalse.
Methods
4.3.3.5 Choice
The choice class is used to create a pop-up list of items from which the user may
choose. A choice control is a form of menu. Each item can be added using addItem( )
method.
Syntax
Example
103
C1. addItem( “Item” );
Methods
Example
Applet
Red
Green
4.3.3.6 Scrollbars
The scrollbar class provides a user interface to scroll through a range of integer
values.
Constructors
104
Constructs a scroll bar with the specified orientation, value of the scroll
bar,sizeof the visible portion, minimum and maximumvalue.
Example
Scrollbar mark;
mark = new Scrollbar ( Scrollbar.HORIZONTAL, 42, 10, 0, 100 );
Methods
A menu bar displays a list of Top-level menu choices. The menu bar has a
horizontal bar in which the menu title and the pull down menu appears on the Screen.
Classes used
1. MenuComponent.
2. MenuItem.
3. MenuBar.
4. Menu.
5. CheckboxMenuItem.
The Menu Component class is an abstract class from which the MenuBar and
MenuItem classes are derived.
Methods
1. setFont ( Font f ) Sets the display font for the Menu Componentobject.
2. getFont() Gets the font of the Menu Component and returns the font
object.
Syntax
MenuBar mb = new MenuBar( )
105
creates an empty Menu Bar. A menu object can be added using add( ) method.
Suppose mb is a MenuBar object and rep is a MenuObject the command
mb.add( rep )
Syntax
Methods
4.3.3.7.4 MenuClass
Menu is a derived class of MenuItem class. This means that a Menu object can be
considered as a MenuItem.
Syntax
Menu mu = new Menu ( String S, boolean b )
This method constructs a Menu object with label s. When the boolean value b is true
this creates a tear-off menu. A tear-off menu is the one which is still displayed after click and
release the mouse button.
Method
Example
import java.applet.*;
import java.awt.*;
public class samplemenu extends Frame
{
MenuBar mainmenu;
Menu file;
106
MenuItem op,ne,sa,qu;
Menu help;
MenuItem commands,about;
Sample menu()
{
setTitle (“Menu Demo”);
setLayout (new FlowLayout());
mainmenu = new MenuBar();
setMenuBar (mainmenu);
mainmenu.add(file);
help = new Menu(“Help”);
commands = new MenuItem(“commands”);
about = new MenuItem(“About”);
help.add(commands);
help.add(about);
mainmenu.add(help);
}
public static void main(String args[])
{
Frame f = new samplemenu();
f.setBounds(1,1,400,400);
f.setVisible(true);
}
}
Output
Menu Demo
File Help
open
new
save
Quit
4.3.4.1 BorderLayout
The BorderLayout is used to arrange the components in five regions: NORTH, SOUTH,
EAST, WEST AND CENTER. Each region may contain one component only.
1. public static final intNORTH
2. public static final intSOUTH
3. public static final intEAST
4. public static final intWEST
5. public static final intCENTER
Constructors
import java.awt.*;
import javax.swing.*;
public class Border
{
JFrame f;
Border()
{
f=new JFrame();
import java.awt.*;
import javax.swing.*;
f.setLayout(new GridLayout(3,3));
f.setSize(300,300);
f.setVisible(true);
}
}
public static void main(String[] args)
{
new MyGridLayout();
}
4.3.4.3 FlowLayout
The FlowLayout is used to arrange the components in a line, one after another.It is the
default layout of applet or panel.
Fields
Constructors
FlowLayout() - creates a flow layout with centered alignment and a default 5 unit
horizontal and verticalgap.
FlowLayout(int align) - creates a flow layout with the given alignment and a default 5
unit horizontal and verticalgap.
FlowLayout(int align, int hgap, int vgap) - creates a flow layout with the given
alignment and the given horizontal and verticalgap.
Example
110
import java.awt.*;
import javax.swing.*;
4.3.5.1 Keyevents
When an event is generated through the key board, the KeyHandler class
responds. We can generate three types of key events. They are
The KeyListener interface has three methods corresponding to the above events.
They are
keyPressed (keyEvent e)
keyReleased (keyEvent e)
keyTyped (keyEvent e)
All the methods take an object of keyEvent class as the parameter. The keyEvent
class has a method getKeyChar( ) which returns the character of the key from which the
event is generated.
Eg;-
if e is a KeyEvent, then
Char C;
C = e.getKeyChar ( );
Returns the character in C.
Eg;-
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class keyEventDemo extends Applet
{
String msg = “”;
public void init ( )
{
addKeyListener (new KeyManager ( ));
requestFocus ( );
}
public void paint (Graphics g)
{
font f = new Font (“Ariel”, Font Bold, 30);
g.setFont (f);
g.drawString (msg, 50,50);
}
class KeyHandler implementsKeyListener
{
public void keyPressed (KeyEvent e)
{
char c = e.getKeyChar ( );
switch ( )
{
case ‘R’:
case ‘r’ : setBackground (new Color (255,0,0));
msg = “Red”;
break;
case ‘G’:
case ‘g’ : setBackground (new Color (0,255,0));
msg = “green”;
break;
case ‘B’:
112
case ‘b’: setBackground (new Color (0,0,255));
msg = “blue”
break;
}
repaint ( );
}
The MouseEvent class is used to handle the events generated by the mouse. There
are two types of mouse events. They are
Mouse click
The events associated with click of button or position of mouse pointer are listed
below.
mousePressed ()
mouseReleased ()
mouseClicked ()
mouseEntered ()
mouseExited ()
All the events use the MouseEvent object as parameter. The methods must
implement the MouseListener Interface.
Mouse Motion
There are two events associated with the movement of mouse. They are
mouseMoved ( )
mouseDragged ()
114
Review Questions
Part A (2 marks)
Part B (3 marks)
Part C (5 marks)
115
UNIT V - EXCEPTION HANDLING,MULTITHREADS AND I/OSTREAMS
OBJECTIVES
To know different types oferrors.
To understand the reasons & advantages ofexception
To understand how to handleexception
To know what ismultithreading
To know the lifecycle of athread
To know the different threadmethods
To know how to define and run athread
To understand what is thread priority, thread synchronization and threadscheduling
To know what is afile
To know what is stream and itstypes
To know the different streamclasses
To understand the methods used in fileoperations
try
{
Statements that causes an exception
}
catch(Exception class 1object1)
{
Statements that handles the exception
}
--------------------------
catch(Exception class nobjectn)
{
Statements that handles the exception
}
finally
{
Statements }
try block
It check the statements for exception. If exception occurs, it throws it.
catch block
The catch block follows the try block .It catches the exception thrown by the try block
and checks with the exception type. If match occurs, the statements inside the block will be
executed. A program may have multiple catch blocks.
finally block
It is an optional block. If it is present, it should after all the catch blocks. This block is
executed, If exception is thrown or not.
Example
public class Example6
{
public static void main(String args[ ])
{
int a=30,b=5,c=5,d;
try
{
d = a/(b-c);
System.out.println("d= "+d);
}
catch (ArithmeticException e)
{
System.out.println("Divide by zero ");
}
finally
{
System.out.println("Exception over");
}
}
}
117
5.1.5 tryblock
It check the statements for exception. If exception occurs, it throws it.
try
{
Statements that causes an exception
}
Eg:
try
{
Int a[ ]= {10,20,30};
System.out.println(a[3]);
}
118
5.1.8 finallystatement
It should be present after all the catch blocks. This block is executed, If exception is
thrown or not.
finally
{
Statements
}
Eg:
finally
{
System.out.println("Exception over");
}
5.2 Multithreading
A thread is the path followed when executing a program. All Java programs have at
least one thread known as the main thread. Every Java thread is created and controlled by
the java.lang.Thread class.
Java supports multithreading. Multithreading is the process of executing multiple
threads simultaneously.
5.2.1 CreatingThreads
There are two ways to create athread:
1. By extending Threadclass
2. By implementing Runnableinterface.
5.2.2 Life of athread
A thread can have five different states, during its life time a thread is always in any one of
these states and can move from one state to another. Followings are the states of a thread:
1. Newborn state
2. Runnable state
3. Runningstate
4. Blockedstate
5. Deadstate
119
1. Newbornstate: A newborn state is a state when a thread object is created, and is
not yet scheduled for running.It can move to runnable state using start() method or
move to dead state using stop()method.
2. Runnable state: The runnable state means the thread is ready for the execution
and waiting for processor.
3. Running state: In this state the processor has given the time to the thread for
execution. From this state, thread enters into blocked (whensuspend(),sleep(),
or wait() is called ) or dead state (when stop() is called).
5. Dead state: When a thread has completed its execution using run() method it is
called the natural death. And when we stopped or moved a thread to dead state bycalling
stop() method it causes a prematuredeath.
Object.start();
Example
class Even extends Thread
{
public void run()
{
for(int i=0; i<=10; i=i+2)
System.out.println("Even number: "+i);
}
120
}
class Odd extends Thread
{
public void run()
{
for(int j=1; j<=10; j=j+2)
System.out.println("Odd number: "+j);
}
}
public class Example7
{
public static void main(String args[ ])
{
Even e1 = new Even();
Odd o1 = new Odd();
e1.start();
o1.start();
}
}
5.2.4 Thread Methods
Method Use
void run() It is used to perform action for a thread
void start() It starts the execution of the thread
void sleep(long miliseconds) It stops the currently executing thread for the
specified number of milliseconds.
void suspend() It is used to suspend the execution of the
thread.
void yield() It is used to bring the thread to runnable
state.
void stop() It is used to stop the thread.
void resume() It is used to resume the suspended thread.
void wait() It stops the currently executing thread
temporarily.
void notify() It is used to bring the thread to runnable
state.
boolean isAlive() It tests if the thread is alive. If alive, it returns
true, otherwise false.
Each thread have a priority. Priorities are represented by a number between 1 and 10.
Default priority of a thread is 5 (NORM_PRIORITY). Normally the OS assigns same priority
to all threads. The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
Thread priorities are used by the thread scheduler to decide when each thread should be
allowed to run. Generally higher-priority threads get more CPU time than lower-priority
threads. Two methods are used to set and the priorities of the thread.
set_priority() method
To set a thread's priority, the setPriority( ) method is used.
121
The level specifies the new priority setting for the calling thread. The value of level must be
within the range MIN_PRIORITY and MAX_PRIORITY.
Eg: t1.setPriority(7);
get_priority() method
To get the current priority of the thread, getPriority( ) method is used.
Eg: t1.getPriority();
5.2.6 Synchronization
Synchronization in java is the capability to control the access of multiple threads to any
shared resource. Java Synchronization is better option where we want to allow only one
thread to access the shared resource.
Synchronization is achieved by using the concept monitor(semaphore). Only one thread can
own a monitor at a time. when a thread acquires a lock, it is said to be entered the
monitor.All other threads trying to acquire that lock are suspended until the first thread exists
the monitor. To achieve this, java uses synchronized keyword before the method.
Synchronized method is used to lock an object for any sharedresource.
}
Example
class Even extends Thread
{
synchronized public void run()
{
for(int i=0; i<=10; i=i+2)
System.out.println("Even number: "+i);
}
}
5.2.7 Implementing RunnableInterface
The thread can also be defined by implementing the runnable interface.
}
2. Override the run() method in allsubclasses.
public void run ( )
{
}
3. Create thread object in the main() method
classname object = newclassname();
122
class Even implements Runnable
{
public void run()
{
for(int i=0; i<=10; i=i+2)
System.out.println("Even number: "+i);
}
}
class Odd implements Runnable
{
public void run()
{
for(int j=1; j<=10; j=j+2)
System.out.println("Odd number: "+j);
}
}
public class Example8
{
public static void main(String args[ ])
{
Even e1 = new Even();
Odd o1 = new Odd();
new Thread(e1).start();
new Thread(o1).start();
}
}
5.2.8 ThreadScheduling
Scheduling is a process of allocating the CPU for execution of the threads. This allocation is
done based on the priority of the threads. This process is done with the help of operating
system.
The operating system selects the thread with highest priority and allocates the CPU for
execution, other threads are waiting until it completes its execution. After completing, the OS
gives chance to the next highest priority thread.
If two or more threads have the same priority ,the OS allocates the CPU in round robin
manner. This process is continued for all threads.
Eg:
Thread T1 T2 T3 T4 T5 T6
Priority 7 9 8 2 4 8
9 T2
T2
8 T3,T6
T3 T6
7 T1 T1
123
4 T5 T5
2 T4 T4
5.3 I/Ostreams
5.3.1 File
A file is a collection of related records. A record is the collection of fields. A
field is a group of characters.
Fields
5.3.2 Streams
A stream is the path along which data flows. There are two kinds of Streams:
1. Inputstream − The Inputstream reads data from a source and sends it to the
program.
Source Program
2. Outputstream − The Outputstream takes the data from the program and sends itto
thedestination.
Program Destination
5.3.3 Advantages
124
2. Characterstream ------- to perform input and output operationson
Characters
Stream Classes
Method Use
int available() It returns the number of bytes that can
be read from the current input stream.
int read() It reads the next byte of data from the
input stream. It returns -1 at the end of
file.
int read(byte[ ] b) It reads some number of bytes from the
input stream and stores them into the
buffer array b.
int read(byte[ ] b, int m, int n) It reads up to n bytes of data from the
125
mth position of the input stream into an
array of bytes.
void reset(). It moves the pointer to the beginning of
the input stream
long skip(long n) It skips n bytes of data from the input
stream.
void close() It closes the current input stream
OutputStream class
Method Use
void write(int) It is used to write a byte to the current
output stream
void write(byte[ ] b) It is used to write an array of byte to the
current output stream
void write(byte[ ] b ,int m, int n) It writes n bytes from buffer array of
data from the mth position.
void flush() It flushes the current output stream.
void close() It closes the current output stream
import java.io.*;
class Example11
{
public static void main(String args[])
{
int c;
126
try
{
FileOutputStream f1= new FileOutputStream("s1.dat");
System.out.println("Enter text at end pressctrl+z");
while (( c= System.in.read())!=-1)
f1.write(c);
f1.close();
}
catch(IOException e)
{
System.out.println("I/O error");
}
}
}
5.3.5 Characterstreams
Java character streams are used to perform input and output operation on characters.
Though there are many classes related to character streams but the most frequently used
classes are Reader and Writer.
Reader class
Reader class is an abstract class .It is the superclass of all classes representing an input
stream of characters. The methods in this class are given below:
Method Use
int available() It returns the number of characters that
can be read from the current input
stream.
int read() It reads the next character of data from
the input stream. It returns -1 at the end
of file.
int read(char [] b) It reads some number of characters
from the input stream and stores them
into the buffer array b.
int read(char[] b, int m, int n) It reads up to n characters of data from
the mth position of the input stream into
an array of bytes.
void reset(). It moves the pointer to the beginning of
the input stream
long skip(long n) It skips n characters of data from the
input stream.
void close() It closes the current input stream.
127
FileReader f1= new FileReader("s2.dat");
while (( c= f1.read())!=-1)
System.out.print((char)c);
f1.close();
}
catch(IOException e)
{
System.out.println("I/O error");
}
}
}
Writer class
Writer class is an abstract class. It is the superclass of all classes representing an output
stream of characters. The methods in this class are given below:
Method Use
void write(char) It is used to write a character to the
current output stream
void write(char[]) It is used to write an array of character
to the current output stream
void write(char[] ,int m, int n) It writes n bytes from character array of
data from the mth position
void flush() It flushes the current output stream.
void close() It closes the current output stream
128
Summary
Types of errors – Syntax ,Logical & Runtimeerrors
Exception – Error at the run time of aprogram
Handling exception -- using try catchblock
Multithreading –- Execution of more threads simultaneously
Life cycle of thread – 5states
Different thread methods –- run(),start(),stop(),yield(),wait()etc
Creating threads – using Thread class, Runnableinterface
Thread priority –- an integer number assigned by OS and used by the
thread scheduler to decide when the thread should be
allowed torun.
Thread Scheduling -- process of allocating the CPU for execution of the
threads
Thread Synchronization -- capability to control the access ofmultiple
threads to any shared resource
Stream – path along which the dataflows
Types of streams – Inputstream,outputstream
Stream classes – ByteStream,CharacterStream
129
QUESTIONS
PART - A (2 Marks)
1. Defineexception.
2. List the types oferror.
3. What are the limitations of errorhandling?.
4. What is exceptionhandling?.
5. What is the use of tryblock?.
6. Give the syntax of catchblock.
7. What is the use of finallystatement?.
8. Definemultithreading.
9. What are the different ways to create athread?.
10. List the states ofthread.
11. Write any two thread methods and state theiruse.
12. Which method is used to get the priority of thread?. Give itssyntax.
13. Define threadscheduling.
14. What is threadsynchronization?.
15. Definefile.
16. What is stream?.List istypes.
17. What isinputstream?.
18. What isoutputstream?.
PART - B (3 Marks)
1. Explain the use of setPriority()method.
2. List the advantages of exceptionhandling.
3. Explain about tryblock.
4. Explain about catchblock.
5. Explain about finallyblock.
6. List the advantages ofstreams.
7. Write any methods of OutputStream class and state theiruse.
8. Write any methods of Reader class and state theiruse.
PART - C (5/10Marks)
1. Explain in detail exceptionhandling.
2. Describe about threadmethods.
3. Explain the life cycle of thread with neatdiagram.
4. How you define and run a thread using Thread class?. Giveexample.
5. How you define and run a thread using Runnable interface?. Giveexample.
6. Explain about thread priority and threadscheduling.
7. Write short notes on threadsynchronization.
8. Explain about Bytestreamclasses.
9. Explain about Characterstream classes.
130