Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views246 pages

Bca 3rd Java

The document provides an overview of Java programming and the principles of Object-Oriented Programming (OOP), including key concepts such as classes, objects, inheritance, polymorphism, and encapsulation. It highlights the benefits of OOP, such as code reusability and data security, and discusses Java's features, history, and its environment including the Java Development Kit (JDK) and Application Programming Interface (API). Additionally, it compares Java with C and C++, emphasizing its unique characteristics and advantages.

Uploaded by

sowmyarani912
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views246 pages

Bca 3rd Java

The document provides an overview of Java programming and the principles of Object-Oriented Programming (OOP), including key concepts such as classes, objects, inheritance, polymorphism, and encapsulation. It highlights the benefits of OOP, such as code reusability and data security, and discusses Java's features, history, and its environment including the Java Development Kit (JDK) and Application Programming Interface (API). Additionally, it compares Java with C and C++, emphasizing its unique characteristics and advantages.

Uploaded by

sowmyarani912
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 246

Java Programming

UNIT-1: Basic Concepts of Object-Oriented Programming

Programming: Programming is the process of creating a set of instructions that tell a


computer how to perform a task.

Software: is a set of instructions, data or programs used to operate computers and execute
specific tasks.

Programming Languages: The languages that are used to write a program or set of instructions
are called "Programming languages".

There are two different types of Programming paradigm:


 Procedural oriented programming
 Object oriented programming

Differences between Procedural Oriented Programming and Object-Oriented


Programming

Sr. No. Key OOP POP

Definition OOP stands for Object POP stands for Procedural Oriented
1
Oriented Programming. Programming.

Approach OOP follows bottom-up POP follows top-down approach.


2
approach.

Division A program is divided to A program is divided into functions


3
objects and their interactions. and they interact.

Inheritance Inheritance is supported. Inheritance is not supported.


4
supported

Access Access control is supported via No access modifiers are supported.


5
control access modifiers.

Data Hiding Encapsulation is used to hide No data hiding present. Data is


6
data. globally accessible.

7 Example C++, Java C, Pascal

Object oriented paradigm

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 1
Java Programming

 The object-oriented programming (OOP) paradigm in Java is a programming approach


that organizes software design around data, or "objects," rather than functions and logic.

 It emphasizes the concept of objects, which are instances of classes and encapsulate both
data (attributes) and behavior (methods).

 OOP allows us to decompose a problem into a number of entities called Objects and then
build data functions (known as methods in java) around these entities.

The combination of data and methods make up an object is shown in figure:

Method Method

Data

Method Method

Object = Data + Methods

Some of the features of object-oriented paradigm are:

 Emphasis is on data rather than procedure.


 Programs are divided into what are known as objects.
 Data structures are designed such that they characterize the objects.
 Methods that operate on the data of an object are tied together in the data structure.
 Data is hidden and cannot be accessed by external functions.
 Objects may communicate with each other through methods.
 New data and methods can be easily added whenever necessary.
 Follows bottom-up approach in program design.

BASIC CONCEPT OF OOPS (OBJECT-ORIENTED PROGRAMMING):

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 2
Java Programming

Object means a real word entity such as pen, chair, table etc.
Object-Oriented Programming is a methodology to design a program using classes and objects.

There are some basic concepts of object-oriented programming as follows:


1. Object
2. Class
3. Data abstraction
4. Data encapsulation
5. Inheritance
6. Polymorphism
7. Dynamic binding

1. Object: Any entity that has state and behavior is known as an object. For example: chair, pen,
table, keyboard, bike etc. It can be physical and logical.
“The instances (properties) of class is called object”

2. Class: Collection of objects is called class. It is a logical entity.


“A class is a set of objects with similar properties (attributes), common behavior
(operations), and common link to other objects.”
“A class is a plan or blue print which specifies what type of data and what type of the functions
which are including the objects of that class”

3. Data Abstraction: The act of representing essential features without including any
background details.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 3
Java Programming

Example1: A digital camera is used to capture a photograph. It simply provides a number of


buttons and switches to control the operations needed to take a photograph. In fact, these buttons
make the working so easy that anybody could operate the camera, even though he/she may not
be ware of the technology.

Example 2: The Car


As a driver you know how to start the car by pressing the start button and internal details of the
starting operations are hidden from you. So, the entire starting process is hidden from you
otherwise we can tell starting operation is encapsulated from you.

4. Data encapsulation: Data encapsulation (Data Hiding) combines data and functions into a
single unit called class. Data encapsulation will prevent direct access to data. The data can be
accessed only through methods present inside the class.
Example-1: The real-world examples of encapsulation is Capsule.
Example-2: Another real-world example of encapsulation can be your school or office bag.

5. Inheritance: In OOP, the concept of inheritance provides the ides of reusability.


The process of forming a new class from an existing class is known as inheritance. The objects
of one class acquire the properties of another class through inheritance. The existing class is
known as base class. The new class is known an derived class.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 4
Java Programming

6. Polymorphism: Polymorphism is a feature of object-oriented programming where a function


can take multiple forms based on the type of arguments, number of arguments and data type of
return value.

The ability of an operator and function to take multiple forms is known as Polymorphism. i.e.
Function overloading and Operator Overloading

Example: Suppose you want to save two numbers for one person. You must have a function,
which will take the two numbers and the person’s name is same.

7. Dynamic binding: Binding is the process of connecting one program to another.


 Dynamic binding means code associated with a procedure call is known only at the time
of program execution routine.
Dynamic binding is the connection between the function declaration and the function call

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 5
Java Programming

Benefits of OOP
OOPs offers several benefits to both the program designer and the user.

The advantages are:


 Through inheritance, we can eliminate redundant code and extend the use of existing
classes.
 We can build programs from the standard working modules that communicate with one
another rather than having to start writing the code from scratch. This leads to saving of
development time and higher productivity.
 The principle of data hiding helps the programmer to build secure programs that cannot
invaded by code in other parts of the program.
 It is easy to partition the work in a project based on objects.
 Object-oriented systems can be easily upgraded from small to large systems.
 Message passing techniques for communication between objects make the interface
descriptions with external systems much simpler.

Application of OOP
The areas for application of OOP include:
 Real-time systems
 Simulation and modeling
 Object-oriented databases
 Hypertext, hypermedia and expertext
 AI and expert system
 Neural networks and office automation systems
 CIM/CAD/CAM systems

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 6
Java Programming

JAVA VIRTUAL MACHINE:

As we know that all programming language compilers convert the source code to machine code.
Same job done by Java Compiler to run a Java program, but the difference is that Java compiler
converts the source code into Intermediate code is called as bytecode. This machine is called the
Java Virtual machine and it exits only inside the computer memory.
Following figure shows the process of compilation.

Java Program Java Compiler Virtual Machine

Source code Byte code


The Virtual machine code is not machine specific. The machine specific code is generated. By
Java interpreter by acting as an intermediary between the virtual machine and object code shown
below

Virtual Machine Java Interpreter Machine Code

Byte code Object Code

In below figure illustrates how java works on a typical computer. The java object frame work
(java API) acts as an intermediary between the user programs and the virtual machine which in
turns acts as the intermediary between the operating system and the java object frame work.
Real machine

Operating system
Java virtual machine

Java object framework (API)


Compiler Interpreter

User Application Programs

user
Fig: Layers of Interaction for Java Programs

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 7
Java Programming

JAVA FUNDAMENTALS

JAVA HISTORY:

• Java is a general-purpose, object-oriented programming language developed by sun


microsystems of USA in 1991.

• Originally called oak by James Gosling.

• Java was invented for the development of software for consumer electronic devices like
tvs, toasters, etc. The main aim had to make java simple, portable and reliable

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 8
Java Programming

FEATURES OF JAVA

1. Compiled and Interpreted


2. Platform Independent and portable
3. Object- oriented
4. Robust and secure
5. Distributed
6. Familiar, simple and small
7. Multithreaded and Interactive
8. High performance
9. Dynamic and Extensible

1. Compiled and Interpreted


 Basically, a computer language is either compiled or interpreted. Java comes together
both these approaches thus making java a two-stage system.
 Java compiler translates java code to byte code instructions and java interpreter generate
machine code that can be directly executed by machine that is running the java program.

2. Platform Independent and portable


 Java supports the feature portability. Java programs can be easily moved from one
computer system to another and anywhere.
 Java certifies portability in two ways.
 First way is, java compiler generates the byte code and that can be executed on any
machine.
 Second way is, size of primitive data type is machine independent.

3. Object- oriented
 Java is truly object-oriented language.
 In java, almost everything is an object.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 9
Java Programming

 All program code and data exist in objects and classes.

4. Robust and secure


 Java is a most strong language which provides many securities to make certain reliable
code.
 Java also includes the concept of exception handling, which detain serious errors and
reduces all kind of threat of crashing the system.

 Security is an important feature of java and this is the strong reason that programmer use
this language for programming on internet.

5. Distributed
 Java is called as distributed language for construct applications on networks which can
contribute both data and programs.
 Java applications can open and access remote objects on internet easily. That means
multiple programmers at multiple remote locations to work together on single task.

6. Simple and small


 Java is very small and simple language. Java does not use pointer and header files, goto
statements, etc.
 It eliminates operator overloading and multiple inheritance.

7. Multithreaded and Interactive


 Multithreaded means managing multiple tasks simultaneously.
 Java maintains multithreaded programs. That means we need not wait for the application
to complete one task before starting next task. This feature is helpful for graphic
applications

8. High performance
Java performance is very extraordinary for an interpreted language, majorly due to the use of
intermediate byte code.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 10
Java Programming

Java architecture is also designed to reduce overheads during runtime. The incorporation of
multithreading improves the execution speed of program.

9. Dynamic and Extensible


Java is also dynamic language. Java is capable of dynamically linking in new class, libraries,
methods and objects.
Java program is supporting functions written in other language such as c and c++, known as
native methods.

JAVA DIFFERS FROM C


 Java does not include the C unique statement keywords sizeof, and typedef
 Java does not contain the data types: struct and union
 Java does not define the type modifiers keywords auto, extern, register, signed and
unsigned
 Java does not support explicit pointer type
 Java does not have a preprocessor and therefore we cannot use #define, #include, and
#ifdef statements
 Java requires that the functions with no arguments must be declared with empty
parenthesis and not with the void keyword as done in C
 Java adds new operators such as instancesof and >>>
 Java adds labeled break and continue statements

JAVA differs from C++ (COMPARISON IN JAVA AND C++)


JAVA C++
1. Java is true Object-oriented language C++ is basically C with Object-oriented
extension
2 Java does not support operator- overloading C++ supports operator overloading
3 It supports labels with loops and statement It supports goto statement
blocks
4 Java does not have template classes as in C+ C++ has template classes.
+.
5 Java compiled into byte code for the Java Source code can be written to be platform

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 11
Java Programming

Virtual Machine. The source code is independent and written to take


independent on operating system. advantage of platform.C++ typically
compiled into machine code.
6 Java does not support multiple inheritance of C++ supports multiple inheritance of
classes but it supports interface classes.
7 Runs in a protected virtual machine Exposes low-level system facilities
8 Java does not support global variable. Every C++ support global variable.
variable should declare in class
9 Java does not use pointer. C++ uses pointer.
10 It Strictly enforces an object oriented It Allows both procedural programming and
Programming paradigm. object-oriented programming
11 There are no header files in Java We have to use header file in C++

Java Environment

Java environment includes a large number of development tools and hundreds of classes and
methods. The development tools are the part of the system known as Java Development Kit
(JDK) and the classes and methods are part of the Java standard Library (JSL), also called as the
Application Program Interface (AIP).

Java Development Kit

The Java Development Kit comes with a collection of tools that are used for developing and
naming Java programs. They include:

 appletviewer (for viewing java applets)


 javac (java compiler)
 java (java interpreter)
 javap (java disassembler)
 javah (for C header files)
 javadoc (for creating HTML documents)
 jdb (java debugger)

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 12
Java Programming

Java development tools


Tool Description

appletviewer Enables us to run java applets (without actually using a Java-compatible browser).

java Java Interpreter, which runs applets and applications by reading and interpreting
bytecode files.

javac The java compiler, which translates java source code to bytecode files that the
interpreter can understand.

javadoc Creates HTML-format documentation from java source code files.

javah Produces header files for use with native methods

javap Java disassembler, which enables us to convert bytecode files into a program
description

jdb Java debugger, which helps us to find errors in our programs.

Application Programming Interface


The Java Standard Library (or API) includes hundreds of classes and methods grouped into
several functional packages. Most commonly used packages are:
Language support package: A collection of classes and methods required for implementing
basic features of java.

Utility packages: A collection of classes to provide utility functions such as date and time
functions.

Input/Output package: A collection of classes required for input/output manipulators.

Networking packages: A collection of classes for communicating with other computers via
internet.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 13
Java Programming

AWT package: The Abstract Window Tool Kit package contains classes that implements
platform-independent graphical user interface.
Applet package: This includes a set of classes that allows us to create Java applets.

Overview Of Java Language

Java is a general purpose, object-oriented programming language. We can develop two types of
java programs:

 Stand-alone applications
 Web applets

Stand-alone applications are programs written in java programs to carry out certain tasks on a
stand-alone local computer.

Executing a stand-alone java program involves two steps:


1. Compiling source code into byte code using javac compiler.
2. Executing the byte code program using java interpreter.

Applets are the small java programs developed for internet applications. An applet located an
distant computer (server) can be downloaded via internet and executed on a local computer
(client) using java-enabled browser.

Stand-alone programs can read and write files and perform certain operations that applets cannot
do. An applet can only run within a web browser.

Java
Source
code

Java Compiler

Applet Type Application type

Java Enabled Java Interpreter


Browser

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 14
Java Programming

Output Output

Fig: Two ways of using java

Simple Java Program

class FirstProgram
{
public static void main(String args[ ])
{
System.out.println (“This is my first program”);
}
}
Class declaration:
The first line
class FirstProgram
declares a class, which is an object-oriented construct.
 The file must be named “FirstProgram.java” to equivalent the class name containing the
main method.
 Java is case sensitive. This program defines a class called “FirstProgram”.
 A class is an object-oriented term. It is designed to perform a specific task. A Java class
is defined by its class name, an open curly brace, a list of methods and fields, and a close
curly brace.
 The name of the class is made of alphabetical characters and digits without spaces; the
first character must be alphabetical.

Opening Brace:
Every class definition in java begins with an opening brace “{“ and ends with a matching closing
brace “}”.

The main Line:

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 15
Java Programming

The third line


public static void main (String args[ ] )

defines a method named main. Every java application program must include the main( ) method.
This is the starting point for the interpreter to begin the execution of the program.
A java application program can have any number of classes but only one of them must include
main method to initiate the execution.

This line contains the number of keywords: public, static and void.
 public: The keyword public is an access specifier that declares the main method as
unprotected and therefore making it accessible to all other classes.
 static: Next appears the keyword static, which declares this method as one that belongs
to the entire class and not a part of any objects of the class. The main must always be
declared as static since the interpreter uses this method before any objects are created.
 void: The type modifier void states that the main method does not return any value .

All parameters to a method are declared inside a pair of parentheses. Here, Strings args[ ]
declares parameter named args, which contains an array of objects of the class type Stirng.

The Output Line


The only executable statement in the program is
System.out. println ("This is my first program");
This is similar to the printf( ) statement of C or cout<< construct of C++. Since java is a true
object oriented language, every method must be part of an object. The println method is a
member of the out object, which is a static data member of System class. This line prints
This is my first program
Above explanation is about how to write program and now we have to learn where to write
program and how to compile and run the program.

For this reason, the next explanation is showing the steps.


1. Edit the program by the use of Notepad.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 16
Java Programming

2. Save the program to the hard disk.


3. Compile the program with the javac command.(Java compiler)
4. If there are syntax errors, go back to Notepad and edit the program.
5. Run the program with the java command.(Java Interpreter)
6. If it does not run correctly, go back to Notepad and edit the program.
7. When it shows result then stop.

Java Program Structure

A java program may contain many classes of which only one class defines a main method.
Classes contain data members and methods that operate on the data members of the class.
Methods may contain data type declarations and executable statements. To write a java program,
we first define classes and then put them together.

A java program may contain one or more section:


Documentation section
Suggested

Package statement Optional


Optional
Import statement

Interface statement Optional

Class definition Optional

Main method class


{
Main method definition
Essential
}

Documentation Section:

The documentation section comprises a set of comment lines giving the name of the program, the
author and other details, which the programmer would like to refer to at a late stage. Comments
must explain why and what of classes and how of algorithms. In additions to the two styles of

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 17
Java Programming

comments, java also uses a third style of comment /**……*/ known as documentation
comment. This form of comment is used for generating documentation automatically.

Package statement
The first statement allowed in a java file is package statement. This statement declares a
package name and informs the compiler that the classes defined here belong to this package.

Ex: package student;


The package statement is optional. i.e our classes do not have to be part of package.

Import statements
The next thing after a package statement may be a number of import statements. This is similar
to the #include statement in c.

Ex: import student.test;

This statement instructs the interpreter to load the test class contained in the package student.
Using import statements, we can have accesses that are part of other named packages.

Interface statements
An interface is like a class but includes a group of method declarations. This is also an optional
section and is used only when we wish to implement the multiple inheritance feature in the
program.

Class definitions
A java program may contain multiple class definitions. Classes are the primary and essential
elements of a java program. These classes are used to map the objects of real-world problems.
The number of classes used depends on the complexity of the problem.

Main method class


Since every java stand-alone program requires a main method as its starting point, this class is
the essential part of a java program. The main method creates objects of various classes and
established communications between them. On reaching the end of main, the program terminates
and the control passes back to the operating system.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 18
Java Programming

Implementing a java Program


Implementation of a java application program involves a series of steps. They include:
 Creating the program
 Compiling the program
 Running the program

Creating the program


We can create a program using any text editor. Assume that we have entered the following
program:
class Test
{
public static void main(String args[ ])
{
System.out.println(“Hellow”);
System.out.println(“Welcome to the worl”);
System.out.println(“ Let us learn java”);
}
}
We must save this program in a file called Test.java. This file is called the source file. Note that
all java source files will have the extension java. Note that if a program contains multiple classes,
the file name must be the class name of the class containing the main method.

Compiling the program


For compiling the program we have to use following command:
javac (Java compiler)
In java, we can use any text editor for writing program and then save that program with “.java”
extension. Java compiler convert the source code or program in bytecode and interpreter convert
“.java” file in “.class” file.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 19
Java Programming

Syntax:
C:\javac filename.java
To compile the program, we must run the java compiler javac, with the name of the source file
on the command line as shown below:
javac Test.java

Running the Program


For running the program, we have to use following command:
java(Java Interpreter)
As we learn that, we can use any text editor for writing program and then save that program with
“.java” extension. Java compiler convert the source code or program in bytecode and interpreter
convert “.java” file in “.class” file.
Syntax:
C:\java filename
we need to use the java interpreter to run a stand-alone program. At the command prompt, type
java test

JAVA TOKENS
A java program basically a collection of classes. A class is defined by a set of declaration
statements and methods containing executable statements.

“The smallest individual units in a program are known as tokens. A java program is a collection
of tokens, comments and white spaces”.

Java language includes five types of tokens:


 Keywords (Reserved words)
 Identifiers

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 20
Java Programming

 Literals
 Operators
 Separators

JAVA CHARACTER SET


The smallest units of java language are the characters used to write java tokens. These characters
are defined by the Unicode character set, an emerging standard that tries to create characters for
a large number of scripts worldwide.

The Unicode is a 16-bit character coding system and currently supports more than 34000 defined
characters. However, most of us use only the basic ASCII characters which include letters, digits
and punctuation marks, used in normal English.

Keywords
 Java language has reserved 50 words as keywords.
 These keywords, combined with operators and separators according to syntax, from the
definition of the java language.
 Since keywords have specific meaning in java, we cannot use them as names for variable,
classes, methods and so on.
 All keywords are to be written in lower-case letters.
 Since java is case-sensitive one can use these words as identifiers by changing one or
more letters to uppercase.

Identifiers
Identifiers are programmer designed tokens. They are used for naming classes, methods,
variables, objects, labels, packages and interfaces in a program.
Java identifiers follow the following rule:
 They can have alphabets, digits, and the underscore and dollar sign characters.
 They must not begin with a digit.
 Uppercase and lowercase letters are distinct
 They can be of any length

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 21
Java Programming

Identifier must be meaningful, short enough to be quickly and easily typed and long enough to be
descriptive and easily read. Java developers have followed some naming conventions.
 Names of all public methods and instances variables start with a leading lowercase letter.
Ex: average, sum
 When more than one words used in a name, the second and subsequent words are marked
with a leading uppercase letters. Ex: dayTemperature
totalMarks
 All private and local variables use only lowercase letters combined with underscores.
Ex: length, batch_strength
 All classes and interfaces start with a leading uppercase letters. Ex: Student, Vehicle.
 Variables that represent constant values use all uppercase letters and underscores between
words. Ex: TOTAL, F_MAX, PRINCIPAL_AMOUNT

Literals / Constants
Literals in java are a sequence of characters (digits, letters, and other characters) that represent
constant values to be stored in variables. Java language specifies five major types of literals.
They are:
 Integer literals
 Floating point literals
 Character literals
 String literals
 Boolean literals

Separators
Separators are symbols used to indicate where groups of code are divided and arranged. They
basically define the shape and function of our code.
Java separators:
Parenthesis ( ) used to enclose parameters in method definition and invocation, also used for
defining precedence in expression, containing expressions for flow control and surrounding cast
types.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 22
Java Programming

Braces { } used to contain the values of automatically initialized arrays and to define a block
of code for classes, methods, and local scopes
Brackets [ ] used to declare array types and for dereferencing array values.
Semicolon ; used to separate statements.
Comma , used to separate consecutive identifiers in a variable declaration, also used to
chain statements together inside a “for” statement
Period . used to separate package names from sub-package and classes; also used to
separate a variable or method from a reference variable.

JAVA STATEMENTS
A statement is an executable combination of tokens ending with a semicolon ( ; ) mark.
Statements are usually executed in sequence in the order in which they appear. However, it is
possible to control the flow of execution, if necessary using special statements.
Java implements several types of statements:
 Empty Statement : These do nothing and are used during program development as a
place holder.
 Labeled Statement : Any statement may begin with a label. Such labels must not be
keywords, already declared local variables or previously used labels in this module.
 Expression Statement : Most statements are expression statement. Java has seven
types of Expression statements: Assignment, Pre-Increment, Post-Increment, Pre-
decrement, Post-decrement, method call and allocation expression.
 Selection Statement : These select one of several control flows. There are three types of
selection statements in java: if , if-else, and switch.
 Iteration Statement : These specify how and when looping will take place. There are
three types of iteration statements: while, do-while and for.
 Jump statement : Jump statements pass control to the beginning or end of the
current block or to a labeled statement. Such labels must be in the same block, and
continue labels must be on an iteration statement. The four types of jump statements are
break, continue, return and throw.
 Synchronization statement: These are used for handling issues with multithreading.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 23
Java Programming

 Guarding Statements : Guarding statements are used for safe handling of code
that may cause exceptions. These statements use the keywords: try, catch, and finally.

CONSTANTS
Constant means fixed value which is not change at the time of execution of program. In Java, there
are two types of constant as follows:
 Numeric Constants
 Integer constant
 Real constant
 Character Constants
 Character constant
 String constant
Integer Constant:
An Integer constant refers to a series of digits. There are three types of integer as follows:

a) Decimal integer: consists of a set of digits, 0 through 9 preceded by an optional minus sign.
Embedded spaces, commas and characters are not allowed in between digits.
For example:
23 411
7,00,000

b) Octal integer: consists of any combination of digits from the set 0 through 7 with a leading 0.
For example:

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 24
Java Programming

011
00
0425

c) Hexadecimal integer It allows the sequence which is preceded by 0X or 0x and it also allows
alphabets from ‘A’ to ‘F’ or ‘a’ to ‘f’ (‘A’ to ‘F’ stands for the numbers ‘10’ to ‘15’) it is called
as Hexadecimal integer.
For example:
0x7
00X
0A2B

Real Constant:
Integer numbers inadequate to represent quantities that varies continuously. These quantities are
represented by numbers containing fractional parts. Such numbers are called real (or floating
point) constants.

It allows us fractional data and it is also called as floating point constant.


For example:
0.0234
0.777
-1.23
Single Character Constants
A single character constant contains a single character enclose within a pair of single quote mark.
For example:
‘A’, ‘7’ ,‘\’
String Constants
A string constant is a sequence of characters enclosed between double quotes. The characters
may be alphabets, digits, special symbols and blank spaces.
For example:
“WELCOME”

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 25
Java Programming

“END OF PROGRAM”

Backslash character constant:


Java supports some special backslash character constants that are used in output methods. Note
that each one of them represents one character, although they consist of two characters. These
character combinations are known as escape sequences.
Constant Importance
‘\b’ Back space
‘\t’ Tab
‘\n’ New line
‘\\’ Backslash
‘\” Single quote
‘\”’ Double quote

Data types
Every variable in java has a data type. Data types specify the size and type of values that the
variables can be stored. Java language is rich in its data types.

There are two types of data types


 primitive data type
 non-pimitive data type

In primitive data types, there are two categories


 numeric means Integer, Floating points
 Non-numeric means Character and Boolean

In non-primitive types, there are three categories


 classes
 arrays
 interface

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 26
Java Programming

Following table shows the datatypes with their size and ranges.
Data type Size (byte) Range
byte 1 -128 to 127
boolean 1 True or false
char 2 A-Z,a-z,0-9,etc.
short 2 -32768 to 32767
int 4 (about) -2 million to 2 million
long 8 (about) -10E18 to 10E18
float 4 -3.4E38 to 3.4E18
double 8 -1.7E308 to 1.7E308
Integer data type:
Integer data type can hold the numbers (the number can be positive number or negative number).
In Java, there are four types of integer as follows:
 byte
 short
 int
 long
We can make integer long by adding ‘l’ or ‘L’ at the end of the number.

Floating point data type:


It is also called as Real number and when we require accuracy then we can use it.
There are two types of floating point data type.
 float
 double
It is represent single and double precision numbers. The float type is used for single precision
and it uses 4 bytes for storage space. It is very useful when we require accuracy with small
degree of precision. But in double type, it is used for double precision and uses 8 bytes of storage
space. It is useful for large degree of precision.

Character data type:

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 27
Java Programming

It is used to store single character in memory. It uses 2 bytes storage space.

Boolean data type:


It is used when we want to test a particular condition during the execution of the program. There
are only two values that a Boolean type can hold: true and false. Boolean type is denoted by the
keyword Boolean and uses only one bit of storage.

Variables
A variable is an identifier that denotes a storage location used to store data value. These variables
can be changed during the execution of the program. A variable may take different values at
different times during the execution of the program.

A variable name can be chosen by the programmer in a meaningful way so as to reflect what is
represents in the program.

Rules for forming variable name:


 Use only the characters ‘a’ through ‘z’, ‘A’ through ‘Z’, ‘0’ through ‘9’, character ‘_’,
and character ‘$’.
 A name cannot include the space character.
 Do not begin with a digit.
 A name can be of any realistic length.
 Upper and lower case count as different characters.
 A name cannot be a reserved word (keyword).
 A name must not previously be in utilized in this block of the program.

Declaration of variables

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 28
Java Programming

In java, variables are the names of storage location. After designing suitable variable names, we
must declare them to the compiler. Declaration does three things:
1. It tells the compiler what the variable name is.
2. It specifies what type of data the variable will hold.
3. The place of declaration decides the scope of the variable.

The general form of the declaration of a variable is:

type variable1, variable2…………………………variable-n;

The first way to declare a variable: This specifies its data type, and reserves memory for it. It
assigns zero to primitive types and null to objects.
dataType variableName;

The second way to declare a variable: This specifies its data type, reserves memory for it, and
puts an initial value into that memory. The initial value must be of the correct data type.
dataType variableName = initialValue;

The first way to declare two variables: all of the same data type, reserves memory for each.
dataType variableNameOne, variableNameTwo;

The second way to declare two variables: both of the same data type, reserves memory, and puts
an initial value in each variable.
dataType variableNameI = initialValueI, variableNameII=initialValueII;

Giving values to variables


A variable must be given a value after it has been declared but before it is used in an expression.
This can be achieved in two ways:

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 29
Java Programming

1. By using an assignment statement


2. By using a read statement

1. Assignment statement
A simple method of giving value to a variable is through the assignment as follows:
VariableName= value;
Ex: initialValue= 0;
We can also assign string assignment expression as shown below:
X=Y=Z=0;
It is also possible to assign a value to a variable at the time of its declaration. This takes the form:
type variableName = value;
ex: int total = 75.32;
2. Read statement
We may also give the values to variables interactively through the keyboard using the method
readLine( )
The readLine( ) method read the input from the keyboard as a string which is then converted to
the corresponding data type using the data type wrapper classes.

The readLine ( ) method which is invoked using an object of the class DataInputStream.
Program:
import java.io.DataInputStream;
class cc2
{
public static void main(String args[ ]) throws Exception
{
Output:
DataInputStream s1=new DataInputStream(System.in); C:\cc>java cc2
byte rollno; Enter roll number:
07
int marks1,marks2,marks3; Enter marks m1, m2,m3:
float avg; 66
77
System.out.println("Enter roll number:"); 88
rollno=Byte.parseByte(s1.readLine()); Roll number is=7
Average is=77.0
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 30
Java Programming

System.out.println("Enter marks m1, m2,m3:");


marks1=Integer.parseInt(s1.readLine());
marks2=Integer.parseInt(s1.readLine());
marks3=Integer.parseInt(s1.readLine());
avg = (marks1+marks2+marks3)/3;
System.out.println("Roll number is="+rollno);
System.out.println("Average is="+avg);
}
}

Scope of Variables
Java variables are actually classified into three kinds:
 Instances variables
 Class variables
 Local variable

Instances and class variables are declared inside a class. Instance variables are created when
the objects are instantiated and therefore, they are associated with the objects. They take different
values for each object.

On the other hand, class variables are global to a class and belong to the entire set of objects that
class creates. Only one memory location is created for each class variable.

Variable declared and used inside methods are called local variables. They are called so because
they are not available for use outside the method definition. Local variables can also be declared
inside program blocks that are defined between an opening brace { and closing brace}.
“The area of the program where the variable is accessible is called its scope.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 31
Java Programming

We can have program blocks within other program blocks (called nesting) as shown in fig:

{
int x=0;
{ .
Block 1
.
int n=5;
. Block 2
}

{
.
int m=15; Block 3
}

Fig: Nested Program blocks

Symbolic Constant

We often use certain unique constant in a program. These constants may appear repeatedly in a
number of places in the program. One example of such a constant is 3.142, representing the
value of the mathematical constant “pi”. We face two problems in the subsequently use of such
programs. They are:

 Problem in modification of the program

 Problem in understanding the program

Modifiability
We may like change the value of “pi” from 3.142 to 3.14159 to improve the accuracy of
calculations or the number 50 to 100 to process the test results of another class. In both cases, we
will have to search throughout and explicitly change the value of the constant whenever it has
been used. If any value is left unchanged, the program may produce disastrous outputs.

Understandability

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 32
Java Programming

When a numeric value appears in a program, its use is not always clear, especially when the
same value means different things in different places. For example: the number 50 may mean the
number of students at one place and the ‘pass marks’ at another place of the same program.
A constant declared as follows:
final type symbolic_name= value;

ex: final int pass_mark=50;

Type Casting
We often encounter situations where there is a need to store a value of one into a variable of
another type. In such situations, we must cast the value to be stored by preceding it with the type
name in parenthesis.
The syntax is
type variable1 = (type) variable2 ;
The process of converting one data type to another is called casting.

Ex : int m = 50;
byte n = (byte) m;
long count=(long)m;

The below table list those casts, which are guaranteed to result in no loss of information.
Form To
byte short, char, int, long, float, double
short int, long, float, double
char int, long, float, double
int long, float, double
long float, double
float double

Automatic Conversion

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 33
Java Programming

For some types, it is possible to assign a value of one type to a variable of a different type
without a cast. Java does the conversion of the assigned value automatically. This is known as
automatic type conversion. Automatic type conversion only possible only if the destination
type has enough precession to store the source value.
For ex: byte b = 75;
int a= b;

The process of assigning a smaller type to a larger one is known as widening or promotion and
that of assigning a larger type to a smaller one is known as narrowing.

Getting Values of Variables


A computer program is written to manipulate a given set of data and to display or print the
results. Java supports two output methods that can be used to send the results to the screen.
 print( ) method // print and wait
 println( ) method // print a line and move to next line
The print( ) method sends information into a buffer. This buffer is not flushed until newline
character is sent. As a result, the print( ) method prints output on one line until a newline
character is encountered.
System.out.print (“Hello”);
System.out.print (“Java !);
Will display the words Hello Java! On one line and waits for displaying further information on
the same line. We may force the display to be brought to the next line by printing a newline
character as shown below:
System.out.print ( “\n”); Will display the output in two lines as follows:
For example: the statements Hello
System.out.print(“Hello”); Java!
System.out.print(“\n”);
System.out.print(“Java!”);
The println( ) method, by contrast, takes the information provided and displays it on a line
followed by a line feed(carriage-return). Will produce the following output.
System.out.println(“Hello”); Hello
Java!
System.out.println(“Java!);

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 34
Java Programming

Program: Getting the values to the screen


class Displaying
{ Screen display
public static void main (String args[ ]) 1
{ 22
System.out.println(Screen Display”); 333
for ( int i=1; i<=9; i++) 4444
{ 55555
for (int j=1; j<=i ; j++) 666666
{ 77 77777
System.out.print(“ ”); 88888888
System.out.print(i); 999999999
} Screen Display Done
System.out.print(“\n”);
}
System.out.println(“Screen display done”);
}
}

Standard Default Values


In Java, every variable has a default value. If we don’t initialize a variable when it is first
created. Java provides default value to that variable type automatically.
Type of variable Default value
byte zero
short zero
int zero
long zero
float 0.0f
double 0.0d
char null character
Boolean false
reference null

Operators and Expressions


Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 35
Java Programming

“An operator is a symbol that takes one or more arguments and operators on them to produce a
result.”

Java supports a rich set of operators. Such as +, -, =, *. An operator is a symbol that tells the
computer to perform certain mathematical or logical manipulations. Operators are used in
programs to manipulate data and variables.
Java operators can be classified into a number of related categories as below:
 Arithmetic operators
 Relational operators
 Logical operators
 Assignment operators
 Increment and Decrement operators
 Conditional operators
 Bitwise operators
 Special operators

 Arithmetic Operators
Java provides all the basic arithmetic operators. Such as +, -, *, and /. They can operate on any
built-in numeric data type of java. We cannot use these operators on Boolean type. The unary
minus operator multiplies its single operand by -1. Therefore, a number preceded by a minus
sign changes its sign.
Table: Arithmetic Operators
Operator Meaning
+ Addition or Unary plus
- Subtraction or Unary minus
* Multiplication
/ Division
% Modulo division (Remainder)

Arithmetic operators are used as shown below:


a-b a+b

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 36
Java Programming

a*b a/b
a%b -a*b
Here a and b may be variables or constants and are known as operands.

 Integer Arithmetic
When both the operand in a single arithmetic expression such as a+b are integers, the expression
is called an integer expression, and the operation is called integer arithmetic. Integer arithmetic
always yields an integer value. Ex: if a and b are integers, then for a=14 and b=4 we have the
following results: a – b =10
a + b =18
a * b =56
a / b =3 (decimal part truncated)
a % b=2 (remainder of integer division)
a/b, when a and b are integer types, gives the result of division of a by b after truncating the
divisor. This operation is called the integer division.

 Real Arithmetic
An arithmetic operation involving only real operands is called real arithmetic. A real operand
may assume values either in decimal or exponential form. Since floating point values are
rounded to the number of significant digits permissible, the final value is an approximation of the
correct result.

Ex: write a program to illustrate the floating point arithmetic.


class FloatPoint
{
public static void main(String args[ ])
{
float a = 20.5F, b=6.4F;
System.out.println(“ a = ” +a);
System.out.println(“ b = ” +b);
System.out.println(“ a+b = ” + (a+b));

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 37
Java Programming

System.out.println(“ a-b = ” + (a-b));


System.out.println(“ a*b = ” + (a*b));
System.out.println(“ a/b = ” + (a/b));
System.out.println(“ a%b = ” + (a%b));
}
}

The output of program is: a=20.5


b=6.4
a+b=26.9
a-b=14.1
a*b=131.2
a/b=3.20313
a%b=1.3

 Mixed Mode Arithmetic


When one of the operands is real and the other is integer, the expression is called a mixed-mode
arithmetic expression. If either operand is of the real type, then the other operand is converted to
read and the real arithmetic is performed. The result will be a real. Thus
15/10.0 produces the result 1.5
Where as
15/10 produces the result 1

 Relation Operators
We often compare two quantities, and depending on their relation, take certain decisions. These
comparisons can be done with the help of relational operators.

An expression such as
a<b or x < 20

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 38
Java Programming

containing a relational operator is termed as a relational expression. The value of relational


expression is either true or false. For example, if x=10, then
x < 20 is true
while
20 < x is false

Java supports six relational operators. These operators and their meanings are shown in table:
Relational Operators
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to

A simple relational expression contains only one relational operator and is of the following form:

ae1-1 relational operator ae2

ae-1 and ae-2 are arithmetic expressions, which may be simple constants, variables or
combination of them.

ex: 4.5 <= 10 TRUE


10<7+5 TRUE
4.5 < -10 FALSE

 Logical Operators
Java has three logical operators.
Logical Operators

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 39
Java Programming

Operator Meaning
&& logical AND
|| logical OR
! logical NOT

The logical operators && and || are used when we want to form compound conditions by
combining two or more relations. An example is:
A > B && x == 10

An expression of this kind which combines two or more relational expressions is termed as a
logical expression or compound relational expression.

Some examples of the usage of logical expressions are:


1. if( age > 55 && salary <1000)
2. if( number <0 || number>100)

Assignment Operators
Assignment Operators are used to assign the value of an expression to a variable. We have seen
the usual assignment operator, ‘=’. In addition, java has a set of ‘shorthand’ assignment operators
which are used in the form
v op = exp
where v is a variable, exp is an expression and op is a java binary operator. The operator op = is
known as the shorthand assignment operator.

The assignment statement


v op = exp;
is equivalent to
v = op(exp);
with v accessed only once. Consider an example
x += y+1;
this is same as the statement

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 40
Java Programming

x= x+(y+1);

The shorthand operator += means ‘add y+1 to x’ or ‘increment x by y+1’.

Shorthand assignment Operators


Statements with simple Statement with
Assignment operator shorthand operator
a= a+1 a += 1
a= a-1 a-=1
a= a*1 a *= 1
a= a /1 a/=1
a=a % b a %=b

The use of shorthand assignment operators has three advantages:


1. What appears on the left-hand side need not be repeated and therefore it becomes easier
to write.
2. The statement is more concise and easier to read.
3. Use of shorthand operator results in a more efficient code.

Increment and Decrement Operators


Java has two very useful operators not generally found in many other languages. These are the
increment and decrement operators:
++ and --

The operator ++ adds 1 to the operand while - - subtracts 1. Both are unary operators and are
used in the following form:
++m; or m++;
- - m; or m - -;

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 41
Java Programming

Here, ++m; is equivalent to m=m+1;


- -m ; is equivalent to m=m-1;

Conditional Operator
The character pair ? : is a ternary operator available in Java. This operator is used to construct
conditional expressions of the form
Exp1 ? Exp2 : Exp3

Where Exp1, Exp2 and Exp3 are expressions.

The Operator ? : works as follows: Exp1 is evaluated first. If it is nonzero (true), then the
expression Exp2 is evaluated and becomes the value of the conditional expression. If Exp1 is
false, Exp3 is evaluated and its value becomes the value of the conditional expression. Note that
only one of the expressions (either Exp2 or Exp3) is evaluated.

For example, consider the following statement:


a = 10;
b =15;
x = (a>b) ? a : b ;

Bitwise Operators
Java has a distinction of supporting special operators known as bitwise operators for
manipulation of data at values of bit level. These operators are used for testing the bits, or
shifting them to the right or left. Bitwise operators may not be applied to float or double.
Bitwise Operators
Operators Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 42
Java Programming

~ Bitwise complement
<< Shift left
>> Shift right
>>> Shift right with zero fill

Special Operators
Java supports some special operators of interest such as instanceof operator and member
selection operator (.).

 instanceof Operator
The instanceof is an object reference operator and returns true if the object on the left-hand side
is an instance of the class given on the right-hand side. This operator allows us to determine
whether the object belongs to a particular class or not.
Example: person instance student
is true if the object person belongs to the class student; otherwise it is false.

 Dot Operator
The dot operator (.) is used to access the instance variables and methods of class objects.
Examples: person1.age // reference to the variable age
Person1.salary( ) // reference to the member method salary( )

It is also used to access classes and sub-packages from a package.

Arithmetic Expressions
An arithmetic expression is a combination of variables, constants, and operators arranged as per
the syntax of the language. Java can handle any complex mathematical expressions. Some of the
examples of the java are:
Algebraic Expression Java Expressions
ab-c a*b-c

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 43
Java Programming

(m+n)(x+y) (m+n)*(x+y)
ab/c a*b/c

Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form
Variable = Expression;

Variable is any valid java variable name. When the statement is encountered, the expression is
evaluated first and the result then replaces the previous value of the variable on the left-hand
side. All variables used in the expression must be assigned values before evaluation is attempted.
X= a*b-c;
Y= b/c*a
Z= a-b/c+d;

Precedence of Arithmetic
An arithmetic expression without any parentheses will be evaluated from left to right using the
rules of precedence of operators. There are two distinct priority levels of arithmetic operators in
java.
High priority * / %
Low priority + -

The basic evaluation procedure includes two left-to-right passes through the expression. During
the first pass, the high priority operators are applied as they are encountered.

During the second pass, the low priority operators are applied as they are encountered.

Consider the following evaluation statement:


X = a-b/3+ c*2 -1

When a=9, b=12 and c=3, the statement becomes

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 44
Java Programming

X= 9-12/3+3*2-1

And is evaluated as follows:

First pass:
Step1: x=9 - 4+3*2-1 (12/3 evaluated)
Step2: x= 9 – 4+6-1 (3*2 evaluated)
Second pass:
Step3: x= 5+6-1 (9 – 4 evaluated)
Step4: x= 11 – 1 (5+6 evaluated)
Step5: x=10 (11-1 evaluated)
However, the order of evaluation can be changed by introducing parenthesis into an expression.
Consider the same expression with parenthesis as shown below:
9-12 / (3+3)*(2-1)

Whenever the parentheses are used, the expression within parentheses assumes highest priority.
If two or more sets of parentheses appear one after another as shown above, the expression
contained in the left-most set are evaluated first and the right-most in the last. Given below are
the new steps.
First pass:
Step1: 9-12/6*(2-1)
Step2: 9-12/6*1
Second pass:
Step3: 9-2*1
Step4: 9-2

Third pass:
Step5: 7

Operator Precedence and Associativity

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 45
Java Programming

Each operator in java has a precedence associate with it. This precedence is used to determine
how an expression involving more than one operator is evaluated. There are distinct levels of
precedence and an operator may belong to one of the levels. The operators at the higher level of
precedence are evaluated first. The operator of the same precedence are evaluated either from
left to right or from right to left, depending on the level. This is known as Associativity property
of an operator. Table shows a complete lists of operators, their precedence levels, their rules of
association. The groups are listed in the order of decreasing precedence (rank 1 indicates the
highest precedence level and 14 is the lowest).
Summary of java operators
Operator Description Associativity Rank

member selection left to right 1


. (dot) function call
()
[]

- Unary minus Right to left 2


++ Increment
-- Decrement
! Logical negation
~ One’s complement
(type) Casting

* Multiplication Left to right 3


/ Division
% Modulus

+ Addition Left to right 4


- Subtraction

<< Left shift Left to right 5

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 46
Java Programming

>>
>>> Right shift
Right shift with zero fill
< Less than Left to right 6
<= Less than or equal to
> Greater than
>= Greater than or equal to
instanceof Type comparison
== Equality Left to right 7
!= Inequality
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
?: Conditional operator Left to right 13
= Assignment operator Right to left 14
Op= Shorthand operator Right to left

Mathematical Functions
Mathematical functions such as cos, sqrt, log etc are frequently used in analysis of real-life
problems. Java supports these basic math functions through Math class defined in the java.lang
package. These functions should be used as follows:
Math.function_name( );

Math Functions
Function Action
sin(x) Returns the sine of the angle x in radians
cos(x) Returns the cosine of the angle x in radians
tan(x) Returns the tangent of the angle x in radians

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 47
Java Programming

asin(y) Returns the angle whose sine is y


acos(y) Returns the angle whose cosine is y
atan(y) Returns the angle whose tangent is y
atan2(x,y) Returns the angle whose tangent is x/y
pow(x,y) Returns x raised to y (xy)
exp(x) Returns e raised to x (ex)
log(x) Returns the natural logarithm of x
sqrt(x) Returns the square root of x
abs(a) Returns the absolute value of a
max(a,b) Returns the maximum of a and b
min(a,b) Returns the minimum of a and b

Decision making and branching


When a program breaks the sequential flow and jumps to another part of the code is called
branching. When the branching is based on a particular condition. It is known as conditional
branching. If branching takes place without any decision is called unconditional branching.

Java language possesses such decision-making capabilities and supports the following statements
called control or decision-making statements.
1. if statement
2. switch statement
3. conditional operator

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 48
Java Programming

Decision making with if statement


The if statement is a powerful decision-making statement and is used to control the flow of
execution of statements. It is basically two-way decision statement and is used in conjunction
with an expression. It takes the following form:
if (test expression)
Flowchart: Entry {
}
F
Test
expressio
n
T
It allows the computer to evaluate the expression first and then depending on whether the value
of the expression is true or false. It transfers the control to a particular statement.

The if statement may be implemented in different forms depending on the complexity of


condition to be tested.
1. Simple if statement
2. if ---else statement
3. Nested if statement
4. else if ladder
 Simple if statement:
Ex: if ((num[i]%2)==0)
The general form of a simple if statement is:
{
if (test expression) Even=Even+1;
{ }
Odd=Odd+1;
Statement-block;
}
Statement-x;

Flowchart:
Test
expressio
Prepared by: Sowmya Rani G S, Lecturer, Deptn of Computer Science, CTA Page 49
Java Programming

Statement-block
F
Statement-x

Next Statement

The statement block may be a single statement or group of statements. If the test expression is
true, the statement-block is executed; otherwise the statement-block will be skipped and the
execution will jump to the statement-x.

 The if-else statement

The if else statement is an extension of the simple if statement.

The general form is:


Ex: if(( num[i]%2)==0)
if (test expression)
{
{
even=even+1;
True-block statement;
}
}
else
else
{
{
odd=odd+1;
False-block statement;
}
}
Statement-x;
Flowchart:
T F
Test
expressio
n
True block statement False block statement

Statement-x

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 50
Java Programming

If the test expression is true, then the true block statement immediately following the if
statements are executed. Otherwise the false statements are executed.

 Nested if-else statement


When a series of decisions are involved. We may have to use more than oe if----else statement in
nested form as follows:

The general form is:


if (test condition1)
{
if (test condition2)
{
Statement1;
}
else
{
Statement2;
}
}
else
{
Statement-x;
}

If the test condition1 is true, it continues the second test. If the test condition2 is true, the
statement 1 will be evaluated. Otherwise the statement 2 will be evaluated and the condition 1 is
false, the statement 3 will be executed.

F
Test
condition
1
F T
Test
condition
2

Statement3
Prepared by: Sowmya Rani G S,Statement
Lecturer,2Dept of Computer Science, CTA
Statement1 Page 51

Statement-x
Java Programming

Ex: if (a>b)
{
if (a>c)
{
System.out.println(a);
}
else
{
System.out.println(c);
}
}
else
{
if(c>b)
{
System.ou.println(c);
}
else
{
System.out.println(b);
}
}
 The else if ladder
There is another way of putting ifs together when multipath decisions are involved. A multipath
decision is a chain of ifs in which the statement associated with each else is an if. It takes the
following general form: if (marks > 79)
if ( condition1) grade=”distinction”;
statement1 else if(marks>59)
grade=”first class”
else if (condition2) else if(marks>49)
statement2 grade=”secondclass”
else if(condition3 else if(marks>35)
grade=”pass”;
statement3 else
……….. grade=”fail”;

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 52
Java Programming

else if(condition n)
statement n;
else
default statement;
statement-x;

Flowchart:
T F
Condition
1

Statement1 T F
Condition
2
T F
Statement2
Condition
3

Statement3
Condition
n

Statement-x Default
Statement
Next statement
This construct is known as the else if ladder. The conditions are evaluated from the top (of the
ladder), downwards. As soon as the true condition is found, the statement associated with it is
executed and the control is transferred to the statement-x. when all the n condition becomes
false, then the final else containing the default statement will be executed.

The switch statement


Java has a built in multi-way decision statement known as switch. The switch statement test the
value of a given variable (expression) against a list of case values and when a match is found, a
block of statements associated with that case is executed.

The general form of the switch statement is:

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 53
Java Programming

switch (expression)
{
case value-1: block-1;
break;
case value-2: block-2;
break2;
case value-3: block-3;
break3;
………..
……….
default: default block;
break;
}
Statement-x;

Flowchart:

expressio
n

Exp=value1
Block1
…………………………..
Exp=value2
Block2

Default
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA block Page 54
Java Programming

default

Statement x

The expression is an integer expression or characters, value1, value2, -----value n are constants
expression and are known as case labels. Each of these values should be unique within a switch
statement. Block1, Block2 --------------Block-n are the statements lists and may contain zero or
more statements. There is no need to put braces around these blocks but it is important to note
that case labels end with a colon ( : ).

When the switch is executed, the value of the expression is successively compound against the
values value1, value2--- value-n.

The break statement at the end of each block signals the end of a particular case and causes an
exit from switch statement transferring the control to the statement-x following the switch.

Example:

switch ( i )
{
case 1: grade = “Distinction”;
break;
case 2: grade = “first class”;
break;
case 3: grade = “second class”;
break;

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 55
Java Programming

case 4: grade = “third class”;


break;
default: grade = “fail”;
break;
}
The ? : Operator
The java language has an unusual operator, useful for making two-way decisions. This operator
is a combination of ? and : and takes three operands. This operator is popularly known as the
conditional operator.
The general form of use of the conditional operator is
Conditional expression ? expressio1 : expression2;
The conditional expression is evaluated first. If the result is true, expression1 is evaluated and is
returned as the value of the conditional expression. Otherwise, expression2 is evaluated and its
value is returned.
Ex: if (x < 0)
flag=0;
else
flag=1;
it can also be written as
flag= (x < 0) ? 0 : 1;

Decision making and Looping


The process of repeatedly executing a block of statements is known as looping. The statements in
the block may be executed any number of times from zero to infinite number. If a loop continues
forever, it is called an infinite loop.

In looping, a sequence of statements is executed until some conditions for the termination of the
loop are satisfied. A program loop therefore consists of 2 segments, one known as the body of
the loop and other known as the control statement. The control statement tests certain conditions
and then directs the repeated execution of the statements contained in the body of the loop.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 56
Java Programming

Depending on the position of the control statements in the loop, a control structure may be
classified either as the entry controlled loop or as exit-controlled loop.

In entry-controlled loop, the control conditions are tested before the start of the loop execution.
If the conditions are not satisfied, then the body of the loop will not be executed.

In exit-controlled loop, the test is performed at the end of the body of the loop and therefore the
body is executed unconditionally for the first time.

Test statements
conditio
n

Body of the loop Test


conditio
n

a. Entry controlled loop b. Exit controlled loop

The java language provides for three constructs for performing loop operations. They are
1. While construct
2. Do while construct
3. for construct

1. while statement: The simplest of all the looping structures in java is the while statement.
The basic format of the while statement is:

initialization

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 57
Java Programming

while (condition)
{
Body of the loop;
}

The while is an entry controlled loop statement. The test condition is evaluated and if the
condition is true, then the body of the loop is executed. After execution of the body, the test
condition is once again evaluated and if it is true, the body is executed once again. This process
of repeated execution of the body continued until the test condition finally becomes false and the
control is transferred out of the loop. On exit, the program continues with the statement
immediately after the body of the loop.
Ex: …..
…..
Sum=0;
N=1;
while(N<=10)
{
Sum= Sum+ n*n;
N=N+1;
}

2. The do statement
In this statement the body of the loop is first executed before the test is performed. The general
form of do statement is:
Initialization
do
{
Body of the loop;
}
while (condition);

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 58
Java Programming

The do while statement is an exit-controlled loop statement. On reacting the do statement, the
program proceeds to evaluate the body of the loop first. At the end of the loop, the test condition
in the while statement is evaluated. If the condition is true, this program continues to evaluate the
body of the loop once again. This process continues as long as the condition is true. When the
condition becomes false, the loop will be terminated and the control goes to the statement that
appears immediately of the while statement.
Ex: ……
……
i= 1;
sum=0
do
{
sum=sum+1;
i=i+2;
}
while( sum < 40 || i<10);

3. The for statement


The for loop is entry controlled loop that provides a more concise loop control structure. The
general form of the for loop is
for ( initialization; test condition; increment)
{
Body of the loop
}

The execution of the for statement is as follows:


a. Initialization of the control variable is done first using assignment statements.
b. relational expression. If the condition is true. The body of the loop is executed; otherwise
the loop is terminated and the execution continues with the statement that immediately
follows the loop.
c. When the body of the loop is executed, the control is transferred back to the for statement
after evaluating the last statement in the loop. Now control variable is incremented using

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 59
Java Programming

an assignment statement and the new value of the control variable is again tested to see
whether it satisfies the loop condition. If the condition is satisfied, the body of the loop is
again executed. This process continues till the value of the control variable fails to satisfy
the test conditions.
Ex: for(x=0 ; x<=9; x=x+1)
{
System.out.println(x);
}

Nesting of for loops


Nesting of loops, that is, one for statement within another for statement is allowed in java.
Ex: for (i=0; i<10; i++)
{
for ( j=1; j<=i ; j++)
{ inner loop outer loop
}
}

Jumps in loops
Java permits a jump from one statement to the end or beginning of a loop as well as a jump out
of a loop.

 Jumping out of a loop: An early exit from a loop can be accomplished by using the
break statement. When the break statement is encountered inside a loop, the loop is immediately

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 60
Java Programming

exited and the program continues with the statement immediately following the loop. When the
loops are nested, the break would only exit from the loop containing it. i.e break will exit only a
single loop.
Ex: while(…..)
{
……
if (condition)
break;
}
……

Exit from the loop

 Skipping a part of loop: During the loop operation, it may be necessary to skip a part of
the body of the loop under certain conditions.

Java supports another statements called the continue statement. The continue, as the name
implies causes the loop to be continued with the next iteration after skipping any statements in
between.

The continue statements tells the compiler skips the following statement and continue with the
next iteration.

The general form of the continue statement is


continue;

ex: while (test condition)


{
if (..)
continue;

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 61
Java Programming

………
………
}
Labelled loops
In java, we can give a label to a block of statements. A label is any valid java variable name. to
give a label to a loop, place it before the loop with a colon at the end.
Ex: loop1: for (…….)
{
….
….
}
A block of statement can be labeled as shown below:
block1: {
….
}
block 2: {
……
}
{
…..
}
{
…..
}

Array in Java

An array refers to a data structure that contains homogeneous elements. This means that all the
elements in the array are of the same data type. Let's take an example:

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 62
Java Programming

This is an array of seven elements. All the elements are integers and homogeneous. The green
box below the array is called the index, which always starts from zero and goes up to n-1
elements. In this case, as there are seven elements, the index is from zero to six.

Define an Array in Java


Arrays in Java are easy to define and declare. First, we have to define the array. The syntax for it
is:

Here, the type is int, String, double, or long. Var-name is the variable name of the array.

Types of Arrays
There are three types of arrays. We use these types of arrays as per the requirement of the
program. These are:
1. One-dimensional Array
Also known as a linear array, the elements are stored in a single row. For example:

In this example, we have an array of five elements. They are stored in a single line or adjacent
memory locations.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 63
Java Programming

Look at this example in Java code. Here, the five elements are 1, 2, 3, 4, and 5. We use a for
loop to print the elements of the array. The output of this is as follows:

2. Two-dimensional Array
Two-dimensional arrays store the data in rows and columns:

In this, the array has two rows and five columns. The index starts from 0,0 in the left-upper
corner to 1,4 in the right lower corner.
In this Java code, we have a two-dimensional array. We have two rows and three columns.
Brackets separate the rows, and the number of elements separates the columns. For this, we use
two for loops: one for rows and one for each element in the row. When we execute this program,
the result will be as follows:

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 64
Java Programming

3. Multi-dimensional Array
This is a combination of two or more arrays or nested arrays. We can even use more than two
rows and columns using the following code:

Here, we are using three rows and three columns, but we are only using two for loops.
Regardless of how many rows and columns are entered, the number of for loops will always be
two.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 65
Java Programming

Chapter 3: Classes, Objects and methods

Class provides a convenient method for packing together a group of logically related data items
and functions that work on them. In java, the data items are called fields and the functions are
called methods. Calling a specific method in an object is described as sending the object a
message.

Defining a Class:
A class is a user-defined data type with a template that serves to define its properties. Once the
class type has been defined, we can create “variables” of that type using declarations that are
similar to the basic type declarations.

In java, these variables are termed as instances of classes, which are the actual objects.

The basic form of a class definition is:


class classname [extends superclassname]
{
[Fields declaration]
[Methods declaration]
}

Everything inside the square brackets is optional. classname and super classname are any valid
java identifier. The keyword extends indicates that the properties of the superclassname. Classes
are extended to the classname class. This concept is known as Inheritance.

Fields Declaration:

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 66
Java Programming

Data is encapsulated in a class by placing data fields inside the body of the class definition.
These variables are called instance variable because they are created whenever an object of the
class in instantiated. We can declare the instance variables exactly the same way as declare local
variables.
Ex: class Rectangle
{
int length;
int width;
}
The class Rectangle contains 2 integer type instance variables.
int length, width;

Instance variables are also known as member variables.

Method Declaration
Methods are declared inside the body of the class but immediately after the declaration of
instance variables.

The general form of a method declaration is:


type methodname (parameter_list)
{
Method-body;
}

Method declarations have four basic parts:


 The name of the method (method name)
 The type of the value the method returns (type)
 A list of parameters ( parameter_list)
 Method-body (Body of the loop)

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 67
Java Programming

The type specifies the type of the value the method would return. The methodname is a valid
identifier. The parameter_list is always enclosed in parenthesis. This list contains variable names
and types of all the values we want to give to the method as input. The variables in the list are
separated by comma.
(int m, float x, float y) // three parameter
( ) // empty list

The body actually describes the operations to be performed on the data.

Let us consider, the Rectangle class again and add a method getData( ) to it.
class Rectagle
{
int length;
int width;

void getData(int x, int y) // method declaration


{
length= x;
width=y;
}
}

Creating Objects
An object in java is essentially a block of memory that contains spaces to store the entire
instance variables. Creating an object is also referred to as instantiating an object.

Object in java are created using the new operator. The new operator creates an object of the
specified class and returns a reference to that object.
Ex: Rectangle rect1; //declare the object

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 68
Java Programming

rect1 = new Rectangle( ); // instantiate the object

The first statement declares a variable to hold the object reference and the second one actually
assigns the object reference to the variable.

Accessing class members


Now that we have created objects, each containing its own set of variables, we should assign
values to these variables in order to use them in our program. Remember, all variables must be
assigned values before they are used. Since we are outside the class, we cannot access the
instance variables and the methods directly. To do this, we must use the concerned object and dot
operators as shown in below:
objectname.variablename = value;
objectname.methodname (parameter_list);

Here objectname is the name of the object, variablename is the name of the instance variable
inside object that we wish to access, methodname is the method that we wish to call and
parameter_list is a comma separated list of actual values that must match in type and number
with the parameter list of the method name declared in the class.

The instance variable of the Rectangle class may be accessed and assigned values as follows:
rect1.length =15;
rect1.width = 10;
rect2.length= 20
rect2.width =12;

Write a program to illustrate the class and objects:


class Rectangle
{
int length, width; // declaration of variables
void getData(int x, int y) // definition of method
{

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 69
Java Programming

length =x;
width =y;
}
int rectArea( )
{
int area=length*width;
return(area);
}
}

class RectArea // class with main method


{
public static void main(String args[ ])
{
int area1, area2;
Rectangle rect1=new Rectangle( ); //creating objects
Rectangle rect2=new Rectangle( );
rect1.length=15; // Accessing variables
rect1.width=10;
area1=rect1.length*rect1.width;
rect2.getData(20, 12);
area2=rect2.rectArea( ); // Accessing methods
System.out.println(“Area1=”+area1);
System.out.println(“Area2=”+area2);
}
}

Constructors

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 70
Java Programming

Java supports a special type of method, called a constructor, that enable an object to initialize
itself when it is created.

Constructors have the same name as the class itself. Secondly, they do not specify a return type,
not even void. This is because they return the instance of the class itself.

Let us consider Rectangle class again. We can now replace the getData method by a constructor
method as shown below:

class Rectangle
{
int length;
int width;
Rectangle(int x, int y) // defining constructor
{
length = x;
width = y;
}
int rectArea( )
{
return (length*width);
}
}

class RectangleArea
{
public static void main(String args[ ])
{
Rectangle rect1=new Rectangle(15, 10); // calling constructor
int area1=rect1.rectArea( );
System.out.println(“Area1=”+area1);

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 71
Java Programming

}
}

Method Overloading
In java, it is possible to create methods that have the same name, but different parameters list and
different definitions. This is called method overloading.

Method overloading is used when objects are required to perform similar tasks but using
different input parameters. When we call a method in a object, java matches up the methodname
first and then the number and type of parameters to decide which one of the definitions to
execute. This process is known as polymorphism.

An example for creating an overloading method


class Room
{
float length;
float width;
Room(float x, float y) // constructor1
{
length=x;
width=y;
}
Room (float x) //constructor2
{
length = width = x;
}

int area( )
{
return (length * width);

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 72
Java Programming

}
}

Here, we are overloading the constructor method Room( ). An object representing a rectangular
room1 will be created as.

Room room1=new Room(25.0, 15.0); // using constructor1

On the other hand, if the room is square, then we may create the corresponding object as

Room room2=new Room(20.0); // using constructor2

Static members
We have seen that a class basically contains 2 sections. One declares variables and the other
declares methods. These variables and methods are called instance variables and instance
methods. This is because every time the class is instantiated, a new copy of each of them is
created. They are accessed using the objects (with dot operator).

Let us assume that we want to define a member that is common to all the objects and accessed
without using a particular object. i.e the member belongs to the class as a whole rather than the
objects created from the class. Such members can be defined as follows:

static int count;


static int max(int x, int y);

The members that are declared static as shown above are called static members. Since these
members are associated with the class itself rather than individual objects, the static variables
and static methods are often referred to as class variables and class methods.

Static variables are used. When we want to have a variable common to all instances of a class.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 73
Java Programming

We can define the static methods as shown in program:


class MethodOperation
{
static float mul( float x, float y)
{
return x*y;
}

static float divide(float x, float y)


{
return x/y;
}

class MathApplication
{
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);
}
}

Note that static methods are called using class names. Static methods have several restrictions:
1. They can only call other static methods.
2. They can only access static data.
3. They cannot refer to this or super in anyway.

Nesting of Methods
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 74
Java Programming

A method can be called by using its name by another method of the same class. This is known as
Nesting of methods.

Program to illustrate the nesting of methods inside a class


class Nesting
{
int m, n;
Nesting (int x, int y)
{
m=x;
n=y;
}

int largest( )
{
if (m>=n)
return m;
else
return n;
}

void display( )
{
int large = largest( ); // calling a method
System.out.println(“largest value=”+large);
}
}

class NestingTest
{
public static void main(String args[ ])

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 75
Java Programming

{
Nesting nest=new Nesting(50,40);
Nest.display( );
}
}

Inheritance: Extending a class


Reusability is another concept of OOP. The mechanism of deriving a new class from an old one
is called inheritance. The old class is called the base class or super class or parent class and the
new one is called sub class or derived class or child class.

The inheritance allows subclasses to inherit all the variables and methods of their parent classes.
Inheritance may take different forms:
 Single inheritance (only one super class)
 Multiple inheritance (several super classes)
 Hierarchical inheritance (one super class, many subclasses)

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 76
Java Programming

 Multilevel inheritance (Derived from a derived class)

Java does not directly implement multiple inheritance. However, this concept is implemented
using a secondary inheritance path in the form of interfaces.

A A

B B C D

a. Single inheritance b. Hierarchical inheritance

A B
A

B
C

c.Multilevel inheritance d. Multiple inheritance

fig : Forms of inheritance

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 77
Java Programming

Defining a Subclass
A subclass is defined as follows:
class subclassname extends superclassname
{
Variables declaration;
Method declaration;
}

The keyword extends signifies that the properties of the superclassname are extended to the
subclassname. The subclass will now contain its own variables and methods as well those of the
superclass.

Program to illustrate the single inheritance


class Room
{
int length;
int width;
Room( int x, int y)
{
length= x;
width =y;
}
int area( )
{
return(length * width);
}
}
class AnotherRoom extends Room // inheriting Room
{
int height;
AnotherRoom(int x, int y, int z)

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 78
Java Programming

{
super (x,y); // pass values to super class
height=z;
}
int volume( )
{
return (length*width*height);
}
}
class InherTest
{
public static void main(String args[ ] )
{
AnotherRoom room1=new AnotherRoom(14, 12, 10);
int area1= room1.area( ); // superclass method
int volume1 = room1.volume( ); // baseclass method
System.out.println(“Area1= “+area1);
System.out.println(“Volume=”+volume1);
}
}

Subclass constructor
A subclass constructor is used to construct the instance variables of both the subclass and the
superclass. The subclass constructor uses the keyword super to invoke the constructor method of
the superclass. The keyword super is used subject to the following conditions:
 super may only be used within a subclass constructor method
 The call to superclass constructor must appear as the first statement within the subclass
constructor
 The parameters in the super call must match the order and type of the instance variable
declaration in the superclass.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 79
Java Programming

Multilevel Inheritance
A common requirement in object-oriented programming is the use of a derived class as a super
class. Java supports this concept and use it extensively in building its class library.

A
Super class

B Intermediate Superclass

C Subclass

Fig : Multilevel Inheritance

The class A serves as a base class for the derived class B which in turn serves as a base class for
the derived class C. The chain ABC is known as inheritance path.

A derived class with multilevel base classes is declared as follows:


class A
{
….
….
}
class B extends A // First level
{

}
class C extends B // Second level
{

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 80
Java Programming

Hierarchical Inheritance
Another interesting application of inheritance is to use it as a support to the hierarchical design of
a program. Many programming problems can be cast into a hierarchy where certain features of
one level are shared by many others below the level.

B C D

Fig: Hierarchical inheritance

Overriding Methods
There may be the occasions when we want an object to respond to the same method but have
different behavior when that method is called. That means, we should override the method
defined in the superclass. This is possible by defining a method in the subclass that has the same
name, same arguments and same return type as a method in the subclass. Then, when that
methods is called, the method defined in the subclass is invoked and executed instead of the one
in the super class. This is known as overriding.

Program to illustrate the method overriding


class Super
{
int x;
Super ( int x)
{
this.x =x;
}

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 81
Java Programming

void display( ) // method defined


{
System.out.println(“Super x =” + x );
}
}
class sub extends Super
{
int y;
Sub (int x, int y)
{
Super (x);
this.y = y;
}
void display( )
{
System.out.println(“Super x=” +x);
System.out.println(“Sub y=” + y);
}
}
class OverrideTest
{
public static void main(String args[ ])
{
Sub s1= new Sub(100, 200);
s1.display( );
}
}

Final variables and methods

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 82
Java Programming

All methods and variables can be overridden by default in subclasses. If we wish to prevent the
subclasses from overriding the members of the superclass, we can declare them as final using the
keyword final as a modifier.
Ex: final int SIZE =100;
final void showstatus( );
Making a method final ensures that the functionality defined in this method will never be altered
in any way. Similarly, the value of a final variable can never be changed.
Final Classes
Sometimes we may like to prevent a class being further subclasses for security reasons. A class
that cannot be subclassed is called a final class. This can be achieved in java using the keyword
final as follows:
final class Aclass {…….}
final class Bclass extends Someclass {…….}

Finalizer
We have seen that a constructor method is used to initialize an object when it is declared. This
process is known as initialization. Similarly, java supports concept finalization, which is just
opposite to initialization. We know that java run-time is an automatic garbage collecting system.
It automatically frees up the memory resources used by the objects. But objects may hold other
non-object resources such as file descriptions or window system fonts. The garbage collector
cannot free these resources. In order to free these resources we must use a finalize( ) and can be
added to any class.

The finalizer method is simply finalize( ) and can be added to any class. Java calls that method
whenever it is about to reclaim the space for that object. The finalize method should explicitly
define the tasks to be performed.

Abstract Methods and Classes


We can indicate that a method must always be redefined in a subclass, thus making overriding
compulsory. This is done by using the modifier keyword abstract in the method definition.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 83
Java Programming

Ex: abstract class Shape


{
………
abstract void draw( );
……….
……….
}
When a class contains one or more abstract methods, it should also be declared abstract as
shown in above.

While using abstract classes, we must satisfy the following conditions:


 We cannot use abstract classes to instantiate objects directly.
Ex: Shape s = new Shape( );
is illegal because shape is an abstract class.
 The abstract methods of an abstract class must be defined in its subclass
 We cannot declare abstract constructor or abstract static methods

Methods with Varargs


Varargs represents variable length arguments in methods, which is one of the features introduced
by J2SE 5.0. It makes the java code simple and flexible. Varargs takes the following form:
<access specifier> <static> void method_name(Object …. Arguments)
{

In the above syntax, the method contains an argument called varargs in which object is the type
of an argument, ellipsis ( ) is the key to varargs and arguments is the name of the variables.

Visibility Control

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 84
Java Programming

The visibility modifiers is also known as access modifiers. Java provides three types of visibility
modifiers: public, private and protected. They provide different levels of protection.
 public Access: Any variable or method is visible to the entire class in which it is defined.
What if we want to make it visible to all classes outside this class? This is possible by simply
declaring the variable or method as public.
Ex: public int number;
public void sum( )

 friendly Access: In many of our examples, we have not used public modifier, yet they
were still accessible in other classes in the program. When no access modifier is specified, the
member defaults to a limited version of public accessibility known as “friendly” level of access.

The difference between the public access and the friendly access is that the public modifier
makes fields visible in all classes, regardless of their packages while friendly access makes fields
visible only in the same package, but not in other packages. A package is a group of related
classes stored separately.

 protected Access: The visibility level of a “protected” fields lies in between the public
access and friendly access. i.e the protected modifier makes the fields visible not only to all
classes in the same package but also to subclasses in other packages. Note-that non-subclasses in
other packages cannot access the “protected” members.

 private: private fields enjoy the highest degree of protection. They are accessible only
with their own class. They cannot be inherited by subclasses and therefore not accessible in
subclasses. A method declared as private behaves like a method declared as final. It prevents the
method from being subclasses. Also note that we cannot override a non-private method in a
subclass and then make it private.

 private protected Access: A field can be declared with two keywords private and
protected together.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 85
Java Programming

private protected int CodeNumber;

This gives the visibility level in between the “protected” access and “private” access. This
modifier makes the fields visible in all subclasses regardless of what package they are in.
Remember, these fields are not accessible by other classes in the same package.

Rules:

Given below are some simple rules for applying appropriate access modifiers.
 Use public if the field is to be visible everywhere.
 Use protected if the field is to be visible everywhere in the current package and also
subclasses in other packages.
 Use “default” if the field is to be visible everywhere in the current package only.
 Use private protected if the field is to be visible only in subclasses, regardless of
packages.
 Use private if the field is not to be visible anywhere except in its own class.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 86
Java Programming

Arrays, Strings and Vectors

Arrays:
An array is a group of contiguous or related items that share a common name A particular value
is indicated by writing a number called index number or subscript in brackets after the array
name.
For : students[10];

Represents the group of students. While the complete set of values is referred to as an array, the
individual values are called elements.

One-dimensional Array
A list of items can be given one variable name using only one subscript and such a variable is
called a single-subscripted variable or a one-dimensional array.

In java, single subscripted value xi can be expressed as


x[1], x[2], x[3] …………….. x[n]
The subscript can also be begin with number 0, that is,
x[0]

Ex: if we want to represent a set of five numbers, say (35, 40, 20, 57, 19), by an array variable
number, then we may create the variable Number as follows:
int Number [ ]= new int[5];

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 87
Java Programming

and the computer reserves five storage locations as shown below:

Number[0]
Number[1]
Number[2]
Number[3]
Number[4]

The values to the array elements can be assigned as follows:


Number[0]= 35; 35 Number[0]
Number[1]=40; 40 Number[1]
Number[2]=20; 20 Number[2]
Number[3]=57; 57 Number[3]
Number[4]=19; 19 Number[4]

Creating an array
Like any other variables, arrays must be declared and created in the computer memory before
they are used. Creation of an array involves three steps.
1. Declaring the array
2. Creating the array
3. Putting values into the memory locations

Declaration of Arrays:
Arrays in java may be declared in tow forms:
Form 1: type arrayname[ ];

Form2: type [ ] arrayname;

Examples: int number[ ];

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 88
Java Programming

float avg[ ];
int[ ] counter;
float[ ] marks;

Remember, we do not enter the size of the arrays in the declaration.

Creation of arrays:
After declaring an array, we need not create it in the memory. Java allows is to create arrays
using new operator only.
arrayname = new type[size];

Examples: number= new int [5];

This line create necessary memory locations for the arrays number as int type. Now the variable
number refers to an array of 5 integers.

It is also possible to combine the two steps- declaration and creation-into one as shown below:
int number[ ]= new int [5];

Initialization:
The final step is to put values into the array created. This process is known as initialization. This
is done using the array subscripts as shown below:
arrayname[subscript]=value;

Example: number[0]=35;

We can also initialize arrays automatically in the same way as the ordinary variables when they
are declared, as shown below:
type arrayname[ ]= {list of values};

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 89
Java Programming

The array initializer is a list of values separated by commas and surrounded by curly braces.
Note that no size is given. The compiler allocates enough space for all the elements specified in
the list.
Example: int number[ ]={35, 40, 20, 57, 19);

It is also possible to assign an array object to another.


Example: int a[ ]={1, 2, 3};
int b[ ];
b=a;

Array length
In java, all arrays store the allocated size in a variable named length. We can obtain the length of
the array a using a.length.

Example: int aSize=a.length;

W a program to illustrate the use of an array for sorting a list of numbers.


class NumberSorting
{
public static void main(String args[ ])
{
int number[ ]={55, 40, 80, 65, 71};
int n= number.length; //array length
System.out.println(“Given list:”);
for (int i=0;i<n; i++)
{
System.out.println(“ “+ number[i]);
}
System.out.println(“/n”);

// sort begins

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 90
Java Programming

for(int i=0;i<n;i++)
{
for(j=0;j<i+1;; j++)
{
if (number[i] < number [j])
{
int temp=number[i];
number[i]= number[j];
number[j]=temp;
}
}
}
System.out.println(“sorted list”);
for ( int i=0; i<n; i++)
{
System.out.println(“ “+number[i]);
}
System.out.println(“ “);
}
}

Two-dimensional Arrays
Java allows us to define tables of items by using two dimensional arrays. The table can be
represented in java as
Table[rowsize] [colsize] ;

Two dimensional array are stored in memory as shown below. Here the first index selects the
row and the second index selects the column within that row.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 91
Java Programming

Column1 column2 column3

[0][0] [0] [1] [0] [2]


Row1
[1] [0] [1] [1] [1] [2]
Row2
[2] [0] [2] [1] [2] [2]
Row3
[3] [0] [3] [1] [3] [2]
Row4

For creating the two dimensional arrays, we must follow the same steps that of simple arrays. We
may create a two-dimensional array,
int myArray[ ][ ];
myArray= new int[3][4];
or
int myArray[ ][ ] = new int[3][4];

Like one dimensional array, two-dimensional array may be initialized by following their
declaration with a list of initial values enclosed in braces.

For example: int table[2][3]={0, 0, 0, 1,1,1};


It initializes the elements t=of the first row to zero and the second row to one. The initialization
is done row by row.

The above statement can be equivalently written as


int table[ ][ ]={{0 , 0, 0} , {1, 1, 1}};
by surrounding the elements of each row by braces.

We can also initialize a two-dimensional array in the form of a matrix as shown below:
int table[ ][ ] = {
{0, 0, 0},
{1, 1, 1}
}

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 92
Java Programming

Note the syntax of the above statements. Commas are required after each brace that closes off a
row except in the case of the last row.

We can refer to a value stored in a two dimensional array by using subscripts for both the column
and row of the corresponding element.
Example: int value = table[1][2];

This retrieves the value stored in the second row and third column of table matrix.

Variable Size Arrays


Java treats multidimensional array as “arrays of arrays”. It is possible to declare a two
dimensional array as follows:
int x[ ][ ]=new int [3][ ];
x[0] = new int [2];
x[1] = new int [4];
x[2] = new int [3];

These statements create a two dimensional array as having different lengths for each row as
shown in fig:
x[0][1]
x[0]
x[1] x[1][3]
x[2] x[2][2]

Strings
Strings manipulation is the most common part of many java programs. A string represents a
sequence of characters enclosed within double quotes. The easiest way to represent a sequence of
characters in java is by using a character array.
Example: char charArray[ ] = new char[4];
charArray[0] = ‘J’;
charArray[1] = ‘A’;

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 93
Java Programming

charArray[2] = ‘V’;
charArray[3] = ‘A’;

In java, strings are class objects and implemented using two classes, namely String and
StringBuffer. A java string is an instantiated object of the string class.

Strings may be declared and created as follows:


String stringName;
stringName = new String (“string”);

Example:
String firstName;
firstName = new String(“smitha”);

These two statements may be combined as follows:


String firstName= new String (“smitha”);

Like arrays, it is also possible to get the length of strings using the length method of the String
class.
int m = firstName.length( );

Note the use of parentheses here. Java strings can be concatenated using the + operator.
Example:
String fullName = name1 + name2;
String city1 = “New” + “Delhi”;

String Array
We can also create and use arrays that contain strings. The statement

String itemArray[ ] = new String[3];

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 94
Java Programming

Will create an itemArray of size 3 to hold three string constants.

String Methods
The String class defines a number of methods that allow us to accomplish a variety of string
manipulation tasks.

Some most commonly used string methods


Method call Task Performed
S2= S1.toLowerCase; Converts the string s1 to all lowercase
S2= S1.toUpperCase; Converts the string s1 to all uppercase
S2=S1.replace(‘x’,’y’); Replace all appearances of x with y
S2 = S1.trim( ); Removes white spaces at the begging and end f the string S1
S1.equals(S2) Returns ‘true’ if S1 is equal to S2
S1.length( ) Gives the length of S1
S1.charAt(n) Gives nth character of S1
S1.compareTo( S2) Returns negative if S1<S2, positive if S1>S2, and zero if S1 is equal to S2
S1.concat( S2) Concatenates s1 and s2

StringBuffer class
StringBuffer is a peer class of String. While String creates of fixed _length. StringBuffer creates
strings of flexible length that can be modified in terms of both length and content.

Commonly used StringBuffer Methods


Method Task
S1.setCharAt(n, ‘x’) Modifies the nth character to x
S1.append(S2) Appends the string S2 to S1 at the end
S1.insert(n, S2) Inserts the string S2 at the position n of the string S1
S1.setLength(n) Sets the length of the string S1 to n. If n<S1.length( ) S1 is
truncated. If n>S1.length( ) zeros are added to S1

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 95
Java Programming

Write a program to illustrate the string methods and manipulating strings


class StringManipulation
{
public static void main(String arg[ ])
{
StringBuffer str = new StringBuffer(“Object language”);
System.out.println(“Original String: ” + str1);

//Obtaining string length


System.out.println(“Length of string : “+str.length( ));

//Accessing characters in a string


for (int i=0; i< str.length( ), i++);
{
int p= i+1;
System.out.println(“Character at position: “+ p + “is”+ str.charAt(i));
}
//Appending a string at the end
str.append(“improves security”);
System.out.println(“Appended string is:”+str);
}
}

Vectors
The vector class contained in the java.util package. This class can be used to create a generic
dynamic array known as vector that can hold objects of any type and any number. The objects
do not have to be homogeneous. Arrays can be easily implemented as vectors.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 96
Java Programming

Vectors are created like arrays as follows:


Vector intVect= new Vector( );
Vector list = new Vector(3);

Note that a vector can be declared without specifying any size explicitly. A vector without size
can be accommodating an unknown number of items. Even, when the size is specified, this can
be overlooked and a different number of items may be put into the vector. Remember, in
contrast, an array must always have its size specified.

Vectors possess a number of advantaged over arrays.

1. It is convenient to use vectors to store objects.


2. A vector can be used to store a list of objects that may vary in size.
3. We can add and delete objects from the list as and when required.

A major constraint in using vectors is that we cannot directly store simple data type in a vector.
We can only store objects. Therefore, we need to convert simple types to objects. This can done
by using wrapper classes.

Some important vector methods are


Method call Task Performed
list.addElement(item) Adds the item specified to the list at the end
list.elementAt(10) Gives the name of the 10th object
list.size( ) Gives the number of objects present
list.removeElement(item) Removes the specified item from the list
list.removeElementAt(n) Removes the item stored in the nth position of the list
list.removeAllElements( ) Removes all the element in the list
list.copyInto(array) Copies all items from list to array

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 97
Java Programming

list.insertElementAt(item,n) Inserts the item at nth position

w a p to illustrates the working with vectors and array


import java.io.*;
class LanguageVector
{
public static void main(String args[ ])
{
Vector list = new Vector( );
int length = args.length;
for(int i=0; i< length; i++)
{
list.addElement(args[ i]);
}
list.insertElementAt(“COBOL”,2);
int size = list.size( );
String listArray[ ] = new String[size];
list.copyInto(listArray);
System.out.println(“List of languages”);
for (int i=0; i<size; i++)
{
System.out.println(listArray[i]);
}
}
}

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 98
Java Programming

Wrapper classes
Vectors cannot handle primitive data types like int, float, long, char and double. Primitive data
types may be converted into object types by using the wrapper classes contained in the java.lang
package.

The below table shows the wrapper classes for converting simple types
Simple type wrapper class
boolean Boolean
char Character
double Double
float Float
int Integer
long Long

Interfaces : Multiple Inheritance


Java doesn’t support multiple inheritances. Java provides an alternate approach known as
interfaces to support the concept of multiple interfaces.

Defining Interfaces
An interface is basically a kind of class. Like class, interface contain methods and variables but
with a major difference. The difference is that interfaces define only abstract methods and final
fields. This means that interfaces do not specify any code to implement these methods and data
fields contain only constants.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 99
Java Programming

The syntax for defining an interface is very similar to that for defining a class. The general form
of an interface definition is:
interface InterfaceName
{
Variable declaration;
Method declaration;
}
Here, interface is the keyword and interface name is any valid java variable. Variables are
declared as follows:
static final type variableName= value;
Note that all variables are declared as constants. Methods declaration will contain only a list of
methods without anybody statements.

return-type methodName(parameter-list);

Ex: Here is an example of an interface definition that contain 2 variables and one method.

interface Item
{
static final int code=1001;
static final String name= “fan”;
void display( );
}

Note that the code for the method is not included in the interface and the method declaration
simply ends with a semicolon.

Extending Interfaces
Like classes, interface can also be extended. i.e an interface can be sub interfaced from other
interfaces. The new sub interfaces will inherit all the members of the super interface in the
manner similar to subclass. This can be achieved using the keyword extends as shown below:

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 100
Java Programming

interface name2 extends name1


{
Body of name2
}

Ex: interface ItemConstants


{
int code=1001;
String name=”fan”;
}

interface Item extends ItemConstants


{
void display( );
}

Implementing Interfaces
Interfaces are used as “super classes” whose properties are inherited by classes. It is therefore
necessary to create a class that inherits the given interfaces. This is done as follows:
class classname implements interfacename
{
Body of class name
}
Here the class name “implements” the interface interfacename. A more general form of
implementation is:
class classname extends superclass implements interface1, interface2,……
{
Body of classname

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 101
Java Programming

This shows that a class can extended another class while implementing interface.

W a program to illustrates the concept of implementing interfaces


interface Area
{
final static float pi=3.14F;
float compute (float x, float y);
}

class Rectangle implements Area


{
public compute(String args[ ])
{
return(x * y);
}
}

class circle implements Area


{
public float compute(float x, float y)
{
return (x*y);
}
}

class Interface
{
public static void main(String args[ ])

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 102
Java Programming

{
Rectangle rect=new Rectangle( );
Circle cir= new Circle( );
Area area; // interface object
area= rect; // area refers to rect object
System.out.println(“Area of Rectangle”+area.compute(10,20));
area= cir;
System.out.println(“Area of circle”+ area.compute(10,0));
}
}

Accessing Interface variables


Interfaces can be used to declare a set of constants that can be used in different classes. The
constants values will be available to any class that implements the interface. The values can be
used in any method, as part of any variable declaration or anywhere we can use a final value.

Ex: interface A
{
int m=10;
int n=50;
}
class B implements A
{
int x=m;
void method(int size)
{
……
if (size < n)
…….
}
}

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 103
Java Programming

W a p to illustrate the implementation of the concept of multiple inheritance using interface


class Student
{
int rollNumber;
void getNumber(int n)
{
rollNumber=n;
}
void putNumber( )
{
System.out.println(“Roll number:”+rollNumber);
}
}

class Test extends Student


{
float part1, part2;
void getMarks( float m1, float m2)
{
part1=m1;
part2 =m2;
}
void putMarks( )
{
System.out.println(“Marks obtained”);
System.out.println(“part1=”+part1);
System.out.println(“part2=”+part2);
}
}

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 104
Java Programming

interface Sports
{
float sportWt=6.0F;
void putWt( );
}

class Result extends Test implements Sports


{
float total;
public void putWt( )
{
System.out.println(“SportsWt=” + sportWt);
}
void display( )
{
total=part1+part2+sportWt;
putNumber( );
putMarks( );
putWt( );
System.out.println(“ Total Score=”+total);
}
}

class MultipleInheritance
{
public static void main(String args[ ] )
{
Result student1=new Result( );
student1.getNumber(1234);
student1.getMarks(27.5F, 33.0F);
student1.display( )

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 105
Java Programming

}
}

Chapter 11: Packages : Putting Classes Together

Packages are java’s way of grouping a variety of classes and/or interfaces together. The grouping
is usually done according to functionality. In fact, packages acts as “containers” for classes. By
organizing our classes into packages we achieve the following benefits:
1. The classes contained in the packages of other programs can be easily reused.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 106
Java Programming

2. In packages, classes can be unique compared with classes in other packages. i.e, two
classes in two different packages can have the same name. They may be referred by their
fully qualified name, comprising the package name and the class name.
3. Packages provide a way to hide classes thus preventing other programs or packages from
accessing classes that are meant for internal use only.
4. Packages also provide a way for separating “design” from “coding”. First we can design
classes and decide their relationships, and then we can implement the java code needed
for the methods. It is possible to change the implementation of any method without
affecting the rest of the design.

Java packages are classified into two types: the first category is known as Java API packages and
the second category is known as user defined packages.

Java API packages


Java API provides a large number of classes grouped into different packages according to
functionality. The below figure shows the functional breakdown of packages that are frequently
used in the program. The below table shows the classes that belong to each package.

Java

net apple
lang util io awt
t

Fig: Frequently used API packages

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 107
Java Programming

Java system packages and their classes


Package Name Contents
java.lang Language supports classes. These are classes that java compiler itself uses
and therefore they are automatically imported. They included classes for
primitive types, strings, math functions, threads and exception.
java.util Language utility classes such as vectors, hash tables, random numbers,
date etc
java.io Input/output support classes. They provide facilities for the input and
output of data.
java.awt Set of classes for implementing graphical user interface. They include
classes for windows, buttons, lists, menus and so on.
java.net classes for networking. They include classes for communicating with local
computers as well as with internet servers.
java.applet classes for creating and implementing applets.

Using System Packages


The packages are organized in a hierarchical structure as illustrated in figure. This shows that the
package named java contains the package awt, which in turn contains various classes required
for implementing graphical user interface.

Java
awt Package containing
awt package

Color

Graphics

package containing
Font:

Prepared by: Sowmya Rani G: S, Lecturer, Dept of Computer Science, CTA Page 108
Java Programming

classes

Image
classes containing
methods

Fig: Hierarchical representation of java.awt package

There are two ways of accessing classes’ stores in a package. The first approach is to use the
fully qualified class name of the class that we want to use. This is done by using the package
name containing the class and then appending the class name to it using the dot operator. For
example: if we want to refer to the class Color in the awt package, then we may do so as
follows.
java.awt.Color
Notice that awt is a package within the package java and the hierarchy is represented by
separating the levels with dots.

We might want to use a class contained in a package. We may achieve this easily as follows:

import packagename.classname;
or
import packagename.*;

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 109
Java Programming

These are known as import statements and must appear at the top of the file, before any class
declarations, import is a keyword.

The first statement allows the specified class in the specified package to be imported. For
Example, the statement
import java.awt.Color;

imports the class Color and therefore the class name can now be directly used in the program.
There is no need to use the package name to qualify the class.

The second statement imports every class contained in the specified package. For Example, the
statement
import java.awt.*;

will bring all classes of java.awt package.

Naming Conventions

Packages can be named using the standard java naming rules. By convention, however packages
begin with lowercase letters. This makes it easily for user to distinguish package names from
class names when looking at an explicit reference to a class. We know that all class names, again
by convention, begin with an uppercase letter. For example,
double y= java. lang . Math . sqrt(x);

package class method


name name name

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 110
Java Programming

This statement uses a fully qualified class name Math to invoke the method sqrt( ). Note that
methods begin with lowercase letters.

Creating Packages
Now, let us see how to create our own packages. We must first declare the name of the package
using the package keyword followed by a package name. This is must be first statement in a java
source file. Then we define a class, just as we normally define a class.
Here is an example: package firstPackage // package declaration
public class FirstClass // class definition
{
Body of class
}
Here the package name is firstPackage. The class FirstClass is now considered a part of this
package. This listing would be saved as a file called FirstClass.java, and located in a directory
named firstPackage. When source file is completed. Java will create a .class file and store it in
the same directory.

Creating our own package involves the following steps:


1. Declare the package at the beginning of a file using the form.
package package_name;
2. Define the class that is to be put in the package and declare it public.
3. Create a subdirectory under the directory where the main sources files are stored.
4. Store the listing as the classname.java file in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory.

Java also supports the concept of package hierarchy. This is done by specifying multiple names
in a package statement, separated by dots. Ex,
package firstPackage . secondPackage;

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 111
Java Programming

This approach allows us to group related classes into a package and then group related packages
into a larger package. Remember to store this package in a subdirectory named
firstPackage/secondPackage.

Accessing a Package
Java system packages can be accessed either using a fully qualified class name or using a
shortcut approach through the import statement. We use the import statement when there are
many references to a particular package or the package name is too long and unwieldy.

The import statement can be used to search a list of packages for a particular class. The general
form of import statement for searching a class is as follows:
import package1 [.package2] [.package3].classname;

Here package1 is the name of the top level package, package2 is the name of the package that is
the explicit classname is specified.

Note that the statement must be end with a semicolon (;). The import statement should appear
before any class definitions in a source file. Multiple import statements are allowed. The
following is an example of importing a particular class:

import firstPackage.secondPackage.Myclass;

Using a Package
The listing below shows a package named package1 containing a single class ClassA.

package package1;
public class ClassA
{
public void display( )
{

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 112
Java Programming

System.out.println(“Class A”);
}
}

This source file should be named as ClassA.java and stored in the subdirectory package1 as
stated earlier. Now compile this java file. The resultant ClassA.class will be stored in the same
subdirectory.

Now consider the listing shown below:

import package1.ClassA;
class PackageTest1
{
public static void main(Sting args[ ])
{
ClassA objectA = new ClassA( );
objectA.displayA( );
}
}

This listing shows a simple program that imports the class ClassA from the package package1.
The source file should be saved as PackageTest1.java and then compiled. The source file and
the compiled file would be saved in the directory of which package1 was a subdirectory

Now let us consider another package named package2 containing again a single class as shows
below:

package package2;
public class ClassB
{
protected int m=10;

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 113
Java Programming

public void displayB( )


{
System.out.println(“Class B”);
System.out.println(“ m = “ + m);
}
}

As usual, the source file and the compiled file of this package are located in the subdirectory
package2.

W a p to illustrate the importing classes from other packages


import package1.ClassA;
import package2.*;

class PackageTest2
{
public static void main(String args[ ])
{
ClassA objectA = new ClassA( );
ClassB objectB = new ClassB( );
objectA.dispalyA( );
objectB.displayB( );
}
}
This program may be saved as PackageTest2.java, compiled and run to obtain the results. The
output will be as under
Class A
Class B
M=10
Adding class to a package
It is simple to add a class to an existing package. Consider the following package:

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 114
Java Programming

package p1;
public ClassA
{
// body of A
}
The package1 contains one public class by name A. suppose we want to add another classB to
this package. This can be done as follows:

1. Define the class and make it public.


2. Place the package statement.
package p1;
before the class definition as follows:
package p1;
public class B
{
// body of B
}
3. Store this B.java file under the directory p1.
4. Compile B.java file. This will create a B.class file and place it in the directory p1.

Note that we can also add a non-public class to a package using the same procedure.

Now, the package p1 will contain both the classes A and B. A statement like
import p1. *;
will import both of them.

If we want to create a package with multiple public classes in it, we may follow the following
steps:
1. Decide the name of the package.
2. Create a subdirectory with this name under the directory where main source files are
stored.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 115
Java Programming

3. Create classes that are to be placed in the package in separate source files and declare the
package statement
package packagename;
at the top of each source file.
4. Switch to the subdirectory created earlier and compile each source file. When completed,
the package would contain .class files of all the source files.

Hiding classes
When we import a package using asterisk ( * ), all public classes are imported. However, we may
prefer to “not import” certain classes. i.e we may like to hide these classes from accessing from
outside of the package. Such classes should be declared “not public”.
Example:
package p1;
public class X // public class available outside
{
// body of x
}
class Y
{
// body of Y
}

Here, the class Y which is not declared public is hidden from outside of the package p1. This
class can be seen and used only by other classes in the same package.

Now, consider the following code, which imports the package p1 that contains classes X and Y.

import p1.*;
X objectX; // classX is available here
Y objectY; // Y is not available here

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 116
Java Programming

Static import
This feature eliminates the need of qualifying a static member with the class name. The static
import declaration is similar to that of import. We can use the import statement to import classes
from packages and use them without qualifying the package. Similarly, we can use the static
import static members from classes and use them without qualifying the class name.

The syntax for using the static import feature is:


import static package-name . subpackage-name . class-name . staticmember-name;
( or )
import static package-name . subpackage-name . class-name . * ;

Before introducing the static import feature, we had to use the static member with the qualifying
classname. For Example: consider the following code that contains the static member PI;

double area_of_circle = Math . PI * radius * radius;

In the above code, PI is the static member of the class, Math. So the static member PI is used in
the above program with the qualified class name called Math.

W a program to illustrate the use of static import

import static java.lang.Math.*;


public class MathOperation
{
public void circle(double r)
{
double area = PI * r * r;
System.out.println(“The Area Circle is:”+area);
}
public static void main(String args[ ])

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 117
Java Programming

{
MathOperation obj = new MathOperation( );
Obj.circle( 2.3);
}
}

Chapter 12: Multithreaded Programming

Multitasking is the ability to execute several programs simultaneously. In system terminology, it


is called multithreading.

Multithreading is a conceptual programming paradigm where a program (process) is divided into


two or more subprograms (processes), which can be implemented at the same time in parallel.

A thread is similar to a program that has a single flow of control. It has a beginning, a body, and
an end executes commands sequentially.

A unique property of java is its support multithreading. i.e java enables us to use multiple flows
of control in developing programs. Each flow of control may be thought of as a separate tiny
program (or module) known as thread that runs in parallel to others. A program that contains
multiple flows of control is known as multithreaded program.

In figure illustrates a java program with four threads, one main and three others. The main thread
is actually the main method module, which designed to create and start the other three threads,
namely A, B and C.
Main thread

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 118
Java Programming

…………………
…………………
………………… Main method module
…………………
………..

Start Start Start

………………… …………………
………………… ………………… …………………
………………… ………………… …………………
………………… Switching ………………… Switching …………………
……….. ……….. …………………
………..

Thread A Thread B Thread C

Fig: Multithreaded program

Once initiated by the main thread, the threads A, B, and C run concurrently and share the
resources jointly. The ability of a language to support multithreads is referred to as concurrency.
Since threads in java are subprograms of a main application program and share the same memory
space, they are known as light weight threads or lightweight process.
The java interpreter handles the switching of control between the threads in such a way that it
appears they are running concurrently.

Multithreading is useful in a number of ways. It enables programmers to do multiple things at


one time. They can divide a long program into threads and execute them in parallel.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 119
Java Programming

Creating Threads
Creating threads in java is simple. Threads are implemented in the form of objects that contain a
method called run( ). The run( ) methods is the heart and soul of any thread. It makes up the
entire body of a thread and is the only method in which the thread’s behavior can be
implemented. A typical run( ) would appear as follows:

public void run( )


{
………..
……….. // statements for implementing thread
…………
}

The run( ) method should be invoked by an object of the concerned thread. This can be achieved
by creating the thread and initiating it with the help of another thread method called start( ).

A new thread can be created in two ways:

1. By creating a thread class: Define a class that extends Thread class and override its
run( ) method with the code required by the thread.

2. By converting a class to a thread: Define a class that implements Runnable interface.


The Runnable interface has only one method, run( ), that is to be defined in the method
with the code to be executed by the thread.

Extending the Thread Class

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 120
Java Programming

We can make our class runnable as thread by extending the class java.lang.Thread. This gives
us access to all the thread methods directly. It includes the following steps:

1. Declare the class as extending the Thread class.

2. Implement the run( ) method that is responsible for execution the sequence of code that
the thread will execute.

3. Create a thread object and call the start( ) method to initiate the thread execution.

Declaring the class

The Thread class can be extended as follows:

class MyThread extends Thread


{
………
………
………
}

Now we have new type of thread MyThread.

Implementing the run( ) method

The run( ) method has been inherited by the class MyThread. We have to override this method
in order to implement the code to be executed by our thread. The basic implementation of run( )
will look like this.
public void run( )
{
…….
……. // thread code here

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 121
Java Programming

…….
}

When we start the new thread, java calls the thread’s run( ) method, so it is the run( ) where all
the action takes place.

Starting New Thread

To actually create and run an instance of our thread class, we must write the following:
MyThread aThread = new MyThread( );
athread.start( ); // invokes run( ) method

The first line instantiates the new object of class MyThread. Note that this statement just creates
the object. The thread will run this object is not running. The thread is in a newborn state.

The second line calls the start( ) method causing the thread to move into the runnable state. Then,
the java runtime will schedule the thread to run by invoking its run( ) method. Now, the thread
is said to be in the running state.

An example using Thread class

class A extends Thread


{
public void run( )
{

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 122
Java Programming

for ( int i=1; i<=5 ; i++)


{
System.out.println(“\t From Thread A: i = “ +i);
}
System.out.println(“Exit from A”);
}
}

class B extends Thread


{
public void run( )
{
for ( int j=1; j<=5; j++)
{
System.out.println(“\t From Thread B: j=” +j);
}
System.out.println(“Exit from B”);
}
}

class C extends Thread


{
public void run( )
{
for( int k=1; k<=5; k++)
{
System.out.println(“\t From Thread C: k=”+k);
}
System.out.println(“Exit from C”);
}
}

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 123
Java Programming

class ThreadTest
{
public static void main(String args[ ])
{
new A( ).start( );
new B( ).start( );
new C( ).start( );
}
}
Stopping and Blocking a Thread

Stopping a Thread:
Whenever we want to stop a thread from running further, we may do so by calling its stop( )
method, like:
aThread.stop( );

This statement causes the thread to move to the dead state. A thread will also move the dead
state automatically when it reaches the end of its method. The stop( ) method may be used
when the premature death of a thread is desired.

Blocking a Thread
A thread can also be temporarily suspended or blocked from entering into the runnable and
subsequently running state by using either of the following thread methods.
sleep( ) //blocked for a specified time
suspend( ) //blocked until further orders
wait( ) // blocked until certain condition occurs

These methods cause the thread to go into the blocked (or not-runnable) state. The threas will
return to the runnable state when the specified time is elapsed in the case of sleep( ), the

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 124
Java Programming

resume( ) method is invoked in the case of suspend( ), and the notify( ) method is called in the
case of wait( ).

Life cycle of a Thread


During the life time of a thread, there are many states it can enter. They include:
1. New born state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state

A thread is always in one of these five states. It can move from one state to another via a variety
of ways as shown in figure. New Born
New Thread
Start stop

Active stop
Running yield Runnabl Dead
Thread e killed
thread
suspend resume
sleep notify stop
wait
Blocked
Idle Thread
(not runnable)
Fig: State transition Diagram of a thread
Newborn State
When we create a thread object, the thread is born and is said to be in newborn state. The thread
is not yet scheduled for running. At this state, we can do only one of the following things with it:
 Schedule it for running using start( ) method
 Kill it using stop( ) method.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 125
Java Programming

Is scheduled, it moves to the runnable state. If we attempt to use any other method at this stage,
an exception will be thrown.

New
Born

start stop

Runnabl
Dead
e state
State

Fig: Scheduling a newborn thread

Runnable State
The runnable state means that the thread is ready for execution and is waiting for the availability
of the processor. i.e the thread has joined the queue of threads that are waiting for execution. If
all threads have equal priority, then they are given time slots for execution in round robin
fashion, ie, first come first serve. This process of assigning time to threads is known as time-
slicing.

However, if we want a thread to relinquish control to another thread to equal priority before its
turn comes, we can do so by using the yield( ) method

yeild

…. ……..

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 126
Java Programming

Running Thread Runnable Threads

Fig:Relinquishing control using yield( ) method

Running State

Running means that the processor has given its time to the thread for its execution. The thread
runs until it relinquishes control on its own or it is preempted by a higher priority thread. A
running thread may relinquish its control in one of the following situations:

1. It has been suspended using suspend( ) method. A suspended thread can be revived by
using the resume( ) method. This approach is useful when we want to suspend a thread
for some time due to certain reasons, but do not want to kill it.

suspend

resume

Running Runnable suspend

Fig: Relinquishing control using suspend( ) method

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 127
Java Programming

2. It has been made to sleep. We can put a thread to sleep for a specific time period using
the method sleep (time) where time is in milliseconds. This means that the thread is out
of the queue during this time period. The thread re-enters the runnable state as soon as
this time period is elapsed.

sleep(t)

after(t)

Running Runnable suspend

Fig: Relinquishing control using sleep( ) method

3. It has been told to wait until some event occurs. This is done using the wait( ) method.
The thread can be scheduled to run again using the notify( ) method.

wait

Running Runnable suspend

Fig: Relinquishing control using wait( ) method


Blocked State
A thread is said to be blocked when it is prevented from entering into the runnable state and
subsequently the running state. This happens when the thread is suspended, sleeping, or waiting
in order to satisfy certain requirements. A blocked thread is considered “not runnable” but not
dead and therefore fully qualified to run again.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 128
Java Programming

Dead State
Every thread has a life cycle. A running thread ends its life when it has completed executing its
run( ) method. It is a natural death. However, we can kill it by sending the stop message to it at
any state thus causing a premature death to it. a thread can be killed as soon it is born, or while it
is running, or even when it is in “not runnable” (blocked) condition.

Using Thread Methods


The Thread class methods can be used to control the behavior of a thread. We have used the
methods start( ) and run( ) in program. There are also methods that can move a thread from one
state to another. The below program illustrates the use of yield( ), sleep( ) and stop( ) methods.

W a p to illustrates the use of yield( ), stop( ) and sleep( )

class A extends Thread


{
public void run( )
{
for (int i=1; i<=5; i++)
{
if( i==1) yield( );
System.out.println(“\t From Thread A: i = “ +i );
}
System.out.println(“Exit from A”);
}
}

class B extends Thread


{
public void run( )

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 129
Java Programming

{
for (int j=1; j<=5; j++)
{
System.out.println(“\t From Thread B: j= “+j);
if ( j==3) stop( );
}
Sytem.out.println(“Exit from B”);
}
}

class C extends Thread


{
public void run( )
{
for (int k=1; k<=5; k++)
{
System.out.println(“\t From Thread C: k= “+k);
if ( k==1)
try
{
sleep(1000);
}
catch(Exception e)
{
}
}
Sytem.out.println(“Exit from C”);
}
}

class ThreadMethods

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 130
Java Programming

{
public static void main(String args[ ])
{
A threadA= new A( );
B threadB= new B( );
C threadC= new C( );

System.out.println(“Start thread A”);


threadA.start( );

System.out.println(“Start thread B”);


threadB.start( );

System.out.println(“Start thread C”);


threadC.start( );

System.out.prinln(“End of main thread”);


}
}

Thread Exceptions

Note that the call to sleep( ) method is enclosed in a try block and followed by a catch block.
This is necessary because the sleep( ) method throws an exception, which should be caught. If
we fail to catch the exception, program will not compile.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 131
Java Programming

Java run system will throw IllegalThreadStateException whenever we attempt to invoke a


method that a thread cannot handle in the given state.

Whenever we call a thread method that is likely to throw an exception, we have to supply an
appropriate exception handler to catch it. The catch statement may take one of the following
forms:

catch (ThreadException e)
{

… // killed thread
}

catch (InterruptedException e)
{

… // cannot handle it in the current state
}

catch(IllegalArgumentException e)
{

… // ileegal method argument
}

catch(Exception e)
{

… // Any other
}

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 132
Java Programming

Thread Priority

In java, each thread is assigned a priority, which affects the order in which it is scheduled for
running. The threads of the same priority are given equal treatment by the java scheduler and,
therefore, they share the processor on a first-come, first-serve basis.

Java permits us to set the priority of a thread using the setPriority( ) method as follows:
ThreadName.setPriority(intNumber);

The intNumber is an integer value to which the thread’s priority is set. The thread class defines
several priority constants:
MIN_PRIORITY =1
NORM_PRIORITY = 5
MAX_PRIORITY = 10

The intNumber may assume one of these constants or any value between 1 and 10. Note that the
default setting is NORM_PRIORITY.

Synchronization

We have seen threads that use their own data and methods provided inside their run( ) methods.
What happens when they try to use data and methods outside themselves? On such occasions,
they may compete for the same resources and may lead to serious problems. For example, one
thread may try to read a record from a file while another is still writing to the same file.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 133
Java Programming

Depending on the situation, we may get strange results. Java enables us to overcome this
problem using a technique known as synchronization.

In case of java, the keyword synchronized helps to solve such problems by keeping a watch on
such locations. For example, the method that will read information from a file and the method
that will update the same file may be declared as synchronized. Example:
synchronized void update( )
{
…. //code here is synchronized
….
}

When we declare a method synchronized, java creates a “monitor” and hands it over to the
thread that calls the method first time. As long as the thread holds the monitor, no other thread
can enter the synchronized section of code. A monitor is like a key and the thread that holds the
key can only open the lock.

It is also possible to mark a block of code as synchronized as shown below:


synchronized ( lock_object)
{
……
…… // code here is synchronized
}

Whenever a thread has completed its work of using synchronized method, it will hand over the
monitor to the next thread that is ready to use the same resources.
Thread A
synchronized method2( )
{
synchronized method1( )
{

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 134
Java Programming

…..
}
}
Thread B
synchronized method1( )
{
synchronized method2( )
{
…..
}
}

Implementing the “Runnable” interface


We can create the thread in two ways: one by using the extended Thread class and another by us
implementing the Runnable interface.

The Runnable interface declares the run( ) method that is required for implementing threads in
our programs. To do this, we must perform the steps listed below:
1. Declare the class as implementing the Runnable interface.
2. Implement the run( ) method.
3. Create a thread by defining an object that is instantiated from this “runnable” class as the
target of the thread.
4. Call the thread start( ) method to run the thread.

W a program to illustrate the implementation of the Runnable interface


class X implements Runnable
{
public void run( )
{
for ( int i=1; i<=10; i++)
{
System.out.println(“ \t ThreadX : “+i);
}
System.out.pritnln(“End of thread”);

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 135
Java Programming

}
}

class RunnableTest
{
public static void main(String args[ ])
{
X runnable=new X( );
Thread thread=new Thread (runnable);
threadX.start( );
system.out.println(“End of main thread”);
}
}

Chapter 6: Managing Errors and Exceptions

A mistake might lead to an error causing to program to produce unexpected results. Errors are
the wrongs that can make a program go wrong.

Types of Errors
Errors may broadly classify into two categories: Compile-time errors
Run-time errors

Compile-Time Errors
All syntax errors will be detected and displayed by the java compiler and therefore these errors
are known as compile-time errors. Whenever the compiler displays an error, it will not create the
.class file. It is therefore necessary that we fix all the errors before we can successfully compile
and run the program.

Ex: /* This program contains an error */

class Error1

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 136
Java Programming

{
public static void main(String arg[ ] )
{
System.out.println(“Hello Java!”) // missing ;
}
}

The java compiler does a nice job of telling us where the errors are in the program. For ex, if we
have missed the semicolon at the end of print statement in the program, the following message
will be displayed in the screen:

Error1.java :7: ‘:’ expected


System.out.println(“Hello Java!”)
^
1 error

Most of the compile-time errors are due to trying mistakes. Typographical errors are hard to find.
We may have to check the code word by word, or even character by character. The most
common problems are:
 Missing semicolons
 Missing or mismatch of brackets in classes and methods
 Misspelling of identifiers and keywords
 Missing double quotes in strings
 Use of undeclared variables
 Incompatible types in assignments / initialization
 Bad references to objects
 Use of = in place of = = operator
Run-time Errors
Sometimes, a program may compile successfully creating the .class file but may not return
properly. Such programs may produce wrong results due to wrong logic or may terminate due to
errors such as stack overflow.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 137
Java Programming

Most common run-time errors are:


 Dividing an integer by zero
 Accessing an element that is out of the bounds of an array
 Trying to store a value into an array of an incompatible class or type
 Trying to cast an instance of a class to one of its subclasses
 Passing a parameter that is not in a valid range or value for a method
 Trying to illegally change the state of a thread
 Attempting to use a negative size for an array

The below program illustrates how run time error causes termination of execution of the
program.

class Error2
{
public static void main(String args[ ])
{
int a=10;
int b=5;
int c=5;

int x=a/(b-c); // divisible by zero


System.out.println(“ x =”+x);

int x=a/(b+c);
System.out.println(“ y =”+y);
}
}

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 138
Java Programming

This program is syntactically correct and therefore does not cause any problem during
compilation. However, while executing, it displays the following message and stops without
executing further statements.

java.lang.ArithmeticException: / by zero
at Error2.main(Error2.java:10)

When java run-time tries to execute a division by zero, it generates an error condition, which
causes the program to stop after displaying an appropriate message.

Exceptions
An Exception is a condition that is caused by a run-time error in the program. When the java
interpreter encounters an error such as dividing an integer by zero, it creates an exception object
and throws it.

If the exception object is not caught and handled properly, the interpreter will display an error
message as shown in the output of program and will terminate the program. If we want the
program to continue with the execution of the remaining code, then we should try to catch the
exception object thrown by the error condition and then display an appropriate message for
taking corrective actions. This task is known as Exception Handling.

The purpose of exception handling mechanism is to provide a means to detect and report an
“exceptional circumstances” so that appropriate action can be taken. The mechanism suggests
incorporation on a separate error handling code that performs the following tasks:
1. Find the problem (Hit the exception)
2. Inform that an error has occurred ( Throw the exception)
3. Receive the error information (catch the exception)

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 139
Java Programming

4. Take corrective actions (Handle the exception)

The error handling code basically consists of two segments, one to detect errors and to throw
exceptions and the other to catch exceptions and to take appropriate actions,

When writing programs, we must always be on the lookout for places in the program where an
exception could be generated. Some common exceptions that we must watch out for catching are
listed in table below:

Common java Exceptions

Exception Type cause java Exception


ArithmeticException caused by math errors such as division by zero
ArrayIndexOutOfBoundsException caused by bad array indexes
ArrayStoreException caused when a program tries to store the wrong type of data
in an array
FileNotFoundException caused by an attempt to access a nonexistent file
IOException caused by general I/O failures, such as inability to read
from a file
NullPointerException caused by referencing a null object
NumberFormatException caused when a conversation between strings and number
fails
OutOfMemoryException caused when there’s not enough memory to allocate a new
object
SecurityException caused when an applet tries to perform an action not
allowed by the browser’s security setting
StackOverFlowException caused when the system runs out of stack space
StringIndexOfBoundsException caused when a program attempts to access a nonexistent
character position in a string
Syntax of Exception Handling Code

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 140
Java Programming

The basic concepts of exception handling are throwing an exception and catching it. this is
illustrated in figure:

try block

Statement that
Exception object
causes an exception
creator

catch block

Statement that Exception object


handles an exception Creator

Fig: Exception Handling Mechanism

Java uses a keyword try to preface a block of code that is likely to cause an error condition and
“throw” an exception. A catch block defined by the keyword catch “catches” the exception
“thrown” by the try block and handles it appropriately. The catch block is added immediately
after the try block.

The following example illustrates the use of simple try and catch statements.

……..
……..
try

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 141
Java Programming

{
Statement; // generates an exception
}
catch (Exception–type e)
{
Statement; // process the exception
}
…….
…….

The try block can have one or more statements that could generate an exception. If anyone
statement generates an exception, the remaining statements in the block are skipped and
execution jumps to the catch block that is placed next to the try block.

The catch block too can have one or more statements that are necessary to process the execution.
Remember that every try statement should be followed by at least one catch statement;
otherwise compilation error will occur.

W a p to illustrates the use of try and catch for exception handling

class Error3
{
public static void main(String args[ ])
{
int a = 10;
int b = 5;
int c = 5;
int x, y;
try
{
x= a / (b/c); // exception here

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 142
Java Programming

}
catch(ArithmeticException e)
{
System.out.println(“Division by Zero”);
}
y= a / (b+c);
System.out.println(“ y= “+y);
}
}
This displays the following output:
Divisible by zero
y=1

Multiple catch statements


It is possible to have more than one catch statement in the catch block.


try
{
statement; // generates an exception
}
catch (Exception-type-1 e)
{
Statement; // process exception type1
}
catch(Exception-type-2 e)
{
Statement; //process exception type 2
}
.
.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 143
Java Programming

.
catch(Exception-type-n e)
{
Statement; //process excpetion type n
}

….
….

When an exception in a try block is generated, the java treats the multiple catch statements. The
first statement whose parameter matches with the exception object will be executed, and the
remaining statements will be skipped.

Note that java does not require any processing of the exception at all. We can simply have a
catch statement with an empty block to avoid program abortion.

Example:
catch(Exception e);

The catch statement simply ends with a semicolon, which does nothing. This statement will catch
an exception and then ignore it.

W a p to illustrates Using multiple catch blocks


class Error4
{
public static void main(String args[ ])
{
int a[ ] ={5, 10};
int b = 5;
try
{

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 144
Java Programming

int x = a[2]/b – a[1];


}

catch(ArithmeticException e)
{
System.out.println(“Division by zero”);
}

catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array index error”);
}

catch(ArrayStoreException e)
{
System.out.println(“wrong data type”);
}
int y= a[1] / a[0];
System.out.println(“y= “ +y);
}
}

The above program uses a chain of catch blocks and, when run, produces the following output.
Array index error
y=2
Note that the array element a[2] does not exist because array a is defined to have only two
elements, a[0] and a[1]. Therefore, the index 2 is outside the array boundary thus causing the
block
catch(ArrayIndexOutOfBoundsException e)

to catch and handle the error. Remaining catch blocks are skipped.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 145
Java Programming

Using Finally Statement

Java supports another statement known as finally statement that can be used to handle an
exception that is not caught by any of the previous catch statements. finally block can be used to
handle any exception generated within a try block. It may be added immediately after the try
block or after the last catch block as shown below:
try try
{ {
….. ….
….. ….
} or }
finally catch(…..)
{ {
….. ….
….. ….
} }
catch( …. )
{
….
….
}
.
.
finally
{
…..
}
When finally block is defined, this is guaranteed to execute, regardless of whether or not in
exception is thrown. As a result, we can use it to perform certain house-keeping operations such
as closing files and releasing system resources.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 146
Java Programming

In program, we may include the last two statements include a finally block as shown below:
finally
{
int y= a[1] / a[0];
System.out.println(“y = “+y);
}

This will produce the same output.

Throwing Our Own Exceptions

When we would like to throw our own exceptions. We can do this by using the keyword throw
as follows:
throw new Throwable_subclass;

ex: throw new ArithmeticException( );


throw new NumberFormatException( );

The below program demonstrates the use of a user-defined subclass of Throwable class. Note
that Exception is a subclass of Throwable and therefore MyException is a subclass of
Throwable class. An object of a class that extends Throwable can be thrown and caught.

import java.lang.Exception;
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 147
Java Programming

class TestMyException
{
public static void main(String args[ ])
{
int x=5, y=1000;
try
{
float z=(float) x / (float) y;
if (z < 0.01)
{
throw new MyException(“Number is too small”);
}
}
catch (MyException e)
{
System.out.println(“ caught my exception”);
System.out.println(e.getMessage( ));
}
finally ( )
{
System.out.println(“I am always here”);
}
}
}

A run of program produces:


caught my exception
number is too small
I am always here

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 148
Java Programming

Using Exceptions for Debugging

The exception handling mechanism can be used to hide errors from rest of the program. It is
possible that the programmers may misuse this technique for hiding errors rather than debugging
the code. Exception handling mechanism may be effectively used to locate the type and place of
errors. Once we identify the errors, we must try to find out why these errors occur before we
cover them up with exception handlers.

Chapter 7: Applet Programming

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 149
Java Programming

Applets are small java programs that are primarily used in internet computing. They can be
transported over the internet from one computer to another and run using the Applet Viewer or
any web browser that supports java.

Local and Remote Applets

We can embed applets into web pages in two ways. One, we can write our own applets and
embed them into web pages. Second, we can download an applet from a remote computer system
and then embed it into a web page.

An applet developed locally and stored in a local system is known as a local applet.

A remote applet is that which is developed by someone else and stored on a remote computer
connected to the internet.

How Applets Differ From Applications

Although both the applets and stand-alone applications are java programs, there are significant
differences between them. Applets are not full-featured application programs. They are usually
written to accomplish a small task or a component of a task. Since they are usually designed for
use on the internet, they impose certain limitations and restrictions in their design.

 Applets do not use the main( ) method for initiating the execution of the code. Applets,
when loaded, automatically call certain methods of Applet class to start and execute the
applet code.

 Unlike, stand-alone applications, applets cannot be run independently. They are run from
inside a web page using a special feature known as HTML tag.

 Applets cannot read from or write to these files in the local computer.

 Applets cannot communicate with other servers on network.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 150
Java Programming

 Applets cannot run any program from the local computer.

 Applets are restricted from using libraries from other languages.

Preparing to Write Applets

Before we try to write applets, we must make sure that java is installed properly and also ensure
that either the java appletviewer or java enabled browser is available. The steps involved in
developing and testing in applet are:

 Building an applet code (.java file)


 Creating an executable applet (.class file)
 Designing a web page using HTML tags
 Preparing <APPLET> tag
 Incorporating <APPLET> tag into the web page
 Creating HTML file
 Testing the applet code

Building Applet Code


It is essential that our applet code uses the services of two classes, namely, Applet and Graphics
from the java class library. The Applet class which is contained in the java.applet package
provides life and behavior to the applet through its methods such as init( ), start( ) and paint( ).
Java automatically calls a series of Applet class methods for starting, running, and stopping the
applet code. The Applet class therefore maintains the lifecycle of an applet.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 151
Java Programming

The paint( ) method of the Applet class, when it is called, actually displays the result of the
applet code on the screen. The output may be text, graphics or sound. The paint( )method, which
requires a Graphics object as an argument is defined as follows:

public void paint (Graphics g)

This requires that the applet code imports the java.awt package that contains the Graphics class.

The general format of the applet code is:

import java.awt.*;
import java.applet.*;
………..
………..
public class appletclassname extends Applet
{
……….
public void paint(Graphics g)
{
…….
…….
}
…….
}

The appletclassname is the main class for the applet. When the applet is loaded, java creates an
instance of this class, and then a series of Applet class methods are called on that instance to
execute the code.

W a p to shows a simple HelloJava applet.

import java.awt.*;
import java.applet.*;

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 152
Java Programming

public class HelloJava extends Applet


{
public void paint(Graphics g)
{
g.drawString(“Hello Java”, 10, 100);
}
}

Applet Life Cycle

Every java applet inherits a set of default behaviors from the Applet class. As a result, when an
applet is loaded, it undergoes a series of changes in its state as shown in figure:

The applet states include:

Begin Born Initialization


(Load Applet)

start( )
stop( )

Runnin
g Idle
display stopped

paint( ) start( )
destroy( )

destroyed Dea End


d

Exit of Browser

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 153
Java Programming

Fig: An applet’s state transition diagram

 Born on initialization state


 Running state
 Idle state
 Dead or destroyed state

Initialization State

Applet enters the initialization state when it is first loaded. This is achieved by calling the init( )
method of Applet class. The applet is born. At this stage, we may do the following, if required.

 Creating objects needed by the applet


 Set up initial values
 Loaf images or fonts
 Set up colors

The initialization occurs only once in the applet’s life cycle. To provide any of the behaviors
mentioned above, we must override the init( ) method.

public void init( )


{
….. // Action
…..
}

Running State

Applet enters the running state when the system calls the start( ) method of Applet class. This
occurs automatically after the applet is initialized. Note that, unlike init( ) method, the start( )

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 154
Java Programming

method may be called more than once. We may override the start( ) method to create a thread to
control the applet.

public void start( )


{
…. // Action
….
}

Idle or Stopped State

An applet becomes idle when it is stopped from running. Stopping occurs automatically when
we leave the page containing the currently running applet. We can also do so by calling the stop(
) method explicitly. If we use a thread to run the applet, then we must use stop( ) method to
terminate the thread. We can achieve this by overriding the stop( ) method:

public void stop( )


{
…. // Action
….
}

Dead State

An Applet is said to be dead when it is removed from memory. This occurs automatically by
invoking the destroy( ) method when we quit the browser. Like initialization, destroying stage
occurs only once in the applet’s life cycle.

public void destroy( )


{

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 155
Java Programming

…. // Action
….
}

Display State

Applet moves to the display state whenever it has to perform some output operations on the
screen. This happens immediately after the applet enters into the running state. The paint( )
method is called to accomplish this task. Almost every applet will have a paint( ) method.

public void paint( )


{
….
…. // display statement
}

Creating an Executable Applet

Executable Applet is nothing but the .class file of the applet, which is obtained by compiling the
source code of the applet. Compiling an Applet is exactly the same as compiling an application.
Therefore, we can use the java compiler to compile the applet.

Let us consider the HelloJava applet created. this applet has been stored in a file called
HelloJava. Here are the steps required for compiling the HelloJava applet.

1. Move to the directory containing the source code and type the following command:
javac HelloJava.java

2. The compiled output file called HelloJava.class is placed in the same directory as the
source.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 156
Java Programming

3. If any error message is received, then we must check for errors, correct them and compile
the applet again.

Designing a Web Page

A web page is basically made up of text and HTML tags that can be interpreted by a Web
browser or an applet viewer. A Web page is also known as HTML page or HTML document.
Web pages are stored using a file extension .html such as MyApplet.html. Such files are
referred to as HTML files. HTML files should be stored in the some directory as the compiled
code of the applets.

A web page is marked by an opening HTML tag <HTML> and a closing HTML tag </HTML>
and is divided into the following three major sections:
1. Comment section (Optional)
2. Head section (Optional)
3. Body section

a. Comment section
This section contains comments about the web page. A comment line begins with a <! and ends
with a >. Web browsers will ignore the text enclosed between them.

b. Head section
The head section is defined with a starting <HEAD> tag and a closing </HEAD> tag. This
section usually contains a title for the web page as shown below:

<HEAD>
<TITLE> WELCOME TO JAVA APPLET </TITLE>

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 157
Java Programming

</HEAD>

The text enclosed in the tags <TITLE> and </TITLE> will appear in the title bar of the web
browser when it display the page. The head section is also optional.

<HTML>

<!
….
>

<HEAD>
Title tag
</HEAD>

</HTML>
<BODY>
Applet tag
</BODY>

Fig: A web page template


c. Body section
After the head section comes the body section. We call this as body section because this section
contains the entire information about the web page and its behavior. We can set up many options
to indicate how our page must appear on the screen. Shown below is a simply body section:

<BODY>
<CENTER>
<H1> Welcome to the World of Applets <H1>
<CENTER>

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 158
Java Programming

<BR>
<APPLET …>
</APPLET>
<BODY>

The body shown above contains instructions to display the message

Welcome to the World of Applets

Followed by the applet output on the screen.

Applet Tag

Note that we have include a pair of <APPLET…> and <APPLET> tag in the body section. The
<APPLET…> tag supplies the name of the applet to be loaded and tells the browser how much
space the applet requires. The ellipsis in the tag <APPLET…> indicates that it contain certain
attributes that must specified. The <APPLET> tag given below specifies the minimum
requirements to place the HelloJava applet on a web page:

<APPLET
CODE = HelloJava.class
WIDTH = 400
HEIGHT =200 >
</APPLET>

Note that <APPLET> tag discussed above specified three things:

1. Name of the applet


2. Width of the applet (in pixels)

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 159
Java Programming

3. Height of the applet (in pixels)

Adding Applet to HTML File

Now we can put together the various components of the Web page and create a file known as
HTML file. Insert the <APPLET> tag in the page at the place where the output of the applet
must appear. Following is the content of the HTML file that is embedded with the <APPLET>
tag of our HelloJava applet.

<HTML>
<! This page includes a welcome title in the title bar and also displays a welcome message. Then
it specifies the applet to be loaded and executed.
>
<HEAD>
<TITLE>
Welcome to Java Applets
</TITLE>
</HEAD>
<BODY>
<CENTER>
<H1> WELCOME TO THE WORLD OF APPLETS </H1>
</CENTER>
<BR>
<CENTER>
<APPLET
CODE = HelloJava.class
WIDTH = 400

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 160
Java Programming

HEIGHT = 200>
</APPLET>
</CENTER>
</BODY>
</HTML>

We must name this file as HelloJava.html and save it in the same directory as the compiled
applet.

Running the Applet


Now that we have created applet files as well as the HTML file containing the applet, we must
have the following files in our current directory:

HelloJava.java
HelloJava.class
HelloJava.html

To run an applet, we require one of the following tools:


1. Java-enabled Web browser (such as HotJava or Netscape)
2. Java appletviewer

If we use java-enabled Web browser, we will be able to see the entire Web page containing the
applet. If we use the appletviewer tool, we will only see the applet output.

We can use it to run our applet as follows:


appletviewer HelloJava.html

Note that the argument of the appletviewer is not the .java file or the .class file, but rather .html
file.

Passing Parameters to Applets


Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 161
Java Programming

We can supply user-defined parameter to an applet using <PARAM…> tag has a name attribute
such as color, and a value attribute such as red. Inside the applet code, the applet can refer to
that parameter by name to find its value. For example, we can change the color of the text
displayed to red by an applet using a <PARAM…> tag as follows:
<APPLET …..>
<PARAM = color VALUE = “red”>
</APPLET>

Similarly we can change the text to be displayed by an applet by supplying new text to the applet
through a <PARAM …> tag as follows:

<PARAM NAME = text VALUE = “JAVA PROGRAMMING”>

Passing parameters to an applet code using <PARAM> tag is something similar to passing
parameters to the main( ) method using command line arguments. To set up and handle
parameters, we need to do two things:
1. Include appropriate <PARAM..> tags in the HTML document.
2. Provide code in the applet to parse these parameters.

Parameters are passed on an applet when it is loaded. We can define the init( ) method in the
applet to get hold of the parameters defined in the <PARAM> tags. This is done by using the
getParameter( ) method, which takes one string argument representing the name of the
parameter and returns a string containing the value of that parameter.

The below program shows another version of HelloJava applet. Compile it so that we have a
class file.

import java.awt.*;
import java.applet.*;
public class HelloJavaParam extends Applet

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 162
Java Programming

{
String str;
public void init( )
{
str= getparameter(“String”):
if(str==null)
str = “Java”;
str= “Hello”+ str;
}
public void paint(Graphics g )
{
g.drawString(str, 10,100);
}
}

Now let us create HTML file that contains this applet. Program shows a web page that passes a
parameter whose NAME is “string” and whose VALUE is APPLET!” to the applet
HelloJavaParam.

<HTML>
< ! Parameterized HTML file>
<HEAD>
<TITLE> welcome to java applets</TITLE>
</HEAD>
<BODY>
<APPLET CODE = HelloJavaParam.class
WIDTH = 400
HIGHT = 200>
<PARAM NAME = “string”
VALUE = “Applet!”>
</APPLET>

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 163
Java Programming

</BODY>
</HTML>

Save this file as HelloJavaParam.html and then run the applet using the applet viewer as follows:
appletviewer HelloJavaParam.html

Aligning the Display

We can align the output of the applet using the ALIGN attribute. This attribute can have one of
the nine values:

LEFT, RIGHT, TOP, TEXT TOP, MIDDLE, ABSMIDDLE, BASELINE, BOTTOM,


ABSBOTTOM

For example: ALGN = LEFT will display the output at the left margin of the page.

More about HTML tags

The below table list important HTML tags and their functions:

Tags Function

<HTML> …</HTML> Signifies the beginning and end of a HTML file.

<HEAD> …</HEAD> This tag may include details about the web page. Usually contains
<TITLE> tag within it.

<TITLE>….</TITLE> The text contained in it will appear in the title bar of the browser.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 164
Java Programming

<BODY>….</BODY> This tag contains the main text of the web page. It is the place
where the <APPLET> tag is declared

<H1>….</H1> Header tags. Used to display headings. <H!> creates the largest
font header, while <H6> creates the smallest one.

<H6>….</H6>

<CENTER>….<CENTER> places the text contained in it at the center of the page.

<APPLET…> <APPLET…> tag declares the applet details as its attributes.

<APPLET>….</APPLET> may hold optionally user-defined parameter using <PARAM> tags.

<B>….</B> text between these tags will be displayed in bold type.

<BR> Line break tag. This will skip a line. Does not have an end tag.

<P> para tag. This tag moves us to the next line and starts a paragraph
of text. No end tag is necessary.

<IMG….> this tag declares attributes of an image to be displayed

<HR> Draws a horizontal rule.

<A…..> </A> Anchor tag used to add hyperlinks.

<FONT…> …</FONT> we can change the color and size of the text that lies in between
<FONT> and </FONT > tags using COLOR and SIZE attributes in
the tag <FONT…>

<!.....> Any text starting with a <! Mark and ending with a > mark is
ignored by the web browser. We may add comments here. A
comment tag may be placed anywhere in a web page.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 165
Java Programming

Displaying Numerical Values

In applets, we can display numerical values by first converting them into strings and then using
the drawstring( ) method of Graphics class. We can do this easily by calling the ValueOf( )
method of String class.

W a program to illustrates how an applet handles numerical values.


import java.awt.*;
import java.applet.*;
public class NumValues extends Applet
{
public void paint(Graphics g)
{
int value1 = 10;
int value2 = 20;
int sum = value1 + value2;
String s = “sum: ” + String.valueOf(sum);
g.drawString(s, 100 , 100);
}
}
The above applet program when run using the following HTML file displays the output.
<html>
<applet>
code = NumValues.class
width = 300
height = 300>
</applet>
</html>

Getting input from the user


Applets treat input as text strings. We must first create an area of the screen in which user can
type and edit input items. We can do this by using the TextField class of the applet package.
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 166
Java Programming

Once text fields are created for receiving input, we can type the values in the fields and edit
them.

Next step is to retrieve the items from the fields for display of calculations. Remember, the text
fields contain items in string form. They need to be converted to the right form, before they are
used in any computations. The results are then converted back to strings for display.

Program to demonstrate how these steps are implemented


import java.awt.*;
import java.applet.*;
public class USerIn extends Applet

{
TextField text1, text2;
public void init( )
{
text1= new TextField (8);
text2 = new TextFiled(8);
add (text1);
add (text2);
text1.setText(“0”);
text2.setText(“0”);
}
public void paint( Graphics g)
{
int x=0, y=0, z=0;
String s1, s2, s;
g.drawString(“Input a number in each box”. 10,50);
try
{
s1= text1.getText( );

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 167
Java Programming

x = Integer.parseInt(s1);
s2=text2.getText( );
y = Integer.parseInt(s2);
}
catch(Exception ex)
{
}
z=x+y;
s= String.valueOf(z);
g.drawString(“THE SUM IS :”, 10, 75);
g.drawString(s, 100, 75);
}
public Boolean action( Event e, Object o)
{
repaint( );
return true;
}
}
Run the applet UserIn using the following steps:
1. Type and save the program (.java file)
2. Compile the applet (.class file)
3. Write HTML document (.html file)
<html>
<applet
code= UserIn.class
width=300
height=200>
</applet>
</html>
4. Use the appletviewer to display the results.

Chapter 8: Graphics Programming


Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 168
Java Programming

Introduction

One of the most important features of java is its ability to draw graphics. We can write java
applets that draw lines, figures of different shapes, images, and text in different fonts and styles.
We can also incorporate different colors in display.

Every applet has its own area of the screen known as canvas, where it creates its display. The
size of an applet space is decided by attributes of the <APPLET…> tag. A java applet draws
graphical image inside its space using the coordinate system.

Java coordinate system has the origin(0,0) in the upper-left corner. Positive x values are to the
right, and positive y values are to the bottom. The values of coordinates x and y are in pixels.

The Graphics class

Java Graphics class includes methods for drawing many different types of shapes, from simple
lines to polygons to text in a variety of fonts. We have already seen how to display text using the
point( ) method and a Graphics object.

To draw a shape on the screen, we may call one of the methods available in the Graphics class.
The table shows the most commonly used drawing methods in the Graphics class. All the
drawing methods have arguments representing end points, corners, or starting locations of a
shape as values in the applet’s coordinate system.

(0,0) (80,0)

(20,20)

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 169
Java Programming

(60,60)

(0,80)

Fig: Coordinating system of java

The below table shows the drawing methods of the Graphics Class:

Method Description
clearRect( ) Erases a rectangle area of the canvas
copyArea( ) Copies a rectangular area of the canvas to another area
drawArc( ) Draws a hollow arc
drawLine( ) Draw a straight line
drawOval( ) Draw a hollow oval
drawPolygon( ) Draws a hollow polygon
drawRect( ) Draws a hollow rectangle
drawRoundRect( ) Draws a hollow rectangle with rounded corners
drawString( ) Draws a text string
fillArc( ) Draws a filled arc
fillOval( ) Draws a filled oval
fillPolygon( ) Draws a filled polygon
fillRect( ) Draws a filled rectangle
fillRoundRect( ) Draws a filled rectangle with rounded corners
getColor( ) Retrieves the current drawing color
getFont( ) Retrieves the currently used font
getFontMetrics( ) Retrieves information about the current font
setColor( ) Sets the drawing color
setFont( ) Sets the font

Lines and Rectangles


Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 170
Java Programming

 The simplest shape we can draw with the Graphics class is a line. The drawLine( )
method takes two pair of coordinates, (x1, y1) and (x2, y2) as arguments and draws a line
between them. For Example: the following statement draws a straight line from the coordinate
point (10,10) to (50,50).
g.drawLine(10,10, 50,50);

The g is the Graphics object passed to paint( ) method.

 Similarly, we can draw a rectangle using the drawRect( ) method. This method takes
four arguments. The first two represents the x and y coordinates of the top left corner of the
rectangle and remaining two represent the width and height of the rectangle. For example: the
statement with draw a rectangle starting at (10, 60) having a width of 40 pixels and a height of 30
pixels.
g.drawRect(10, 60, 40, 30);

(x, y) width
height

Rectangle

 We can draw a solid box by using the method fillRect( ). This also takes four parameters
corresponding to the starting point, the width and the height of the rectangle. For example: the
statement, g.fillRect(60, 10, 30, 80);

 We can also draw rounded rectangles, using methods drawRoundRect( ) and


fillRoundRect( ). These two methods are similar to drawRect( ) and fillRect( ) except that they
take two extra arguments representing the width and height of the angle of corners. These extra
parameters indicate how much of corners will be rounded. Example:

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 171
Java Programming

g.drawRoundRect(10, 100, 80, 50, 10, 10);

g.fillRoundRect(20, 110, 60, 30, 5 ,5);

W a program to drawing lines and rectangles

import java.awt.*;
import java.applet.*;
public class LineRect extends Applet
{
public void paint(Graphics g)
{
g.drawLine(10,10, 50,50);
g.drawRect(10,60, 40, 30);
g.fillRect(60, 10, 30, 80);
g.drawRoundRect(10, 100, 80, 50, 10, 10);
g.fillRoundRect(20, 110, 60, 30, 5,5);
g.drawLine(100, 10, 230, 140);
g.drawLine(100,140,230,10);
}
}

<APPLET
CODE=LineRect.class
WIDTH=250
HEIGHT=200>
</APPLET>

Circle and Ellipses

The drawOval( ) method can be used to draw a circle or an ellipses. The drawOval( ) methods
takes four arguments: the first two represent the top left corner of the imaginary rectangle and the

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 172
Java Programming

other two represent the width and height of the oval itself. Note that if the width and height are
the same, the oval becomes a circle. The oval’s coordinates are actually the coordinates of
enclosing rectangles.

height

width

Fig: Oval within an imaginary rectangle

Like rectangle methods, the drawOval( ) method draws outline of an oval, and the fillOval( )
method draws a solid oval. The code segment shown below draws a filled circle within an oval.

public void paint(Graphics g)


{
g.drawOval(20,20,200,120);
g. setColor(Color.green); // set color using this object
g.fillOval(70,30,100,100); // this is a circle
}

Drawing Arcs
An arc is a part of an oval. In fact, we can think of an oval as a series of arcs that are connected
together in an orderly manner. The drawArc( ) designed to draw arcs takes six arguments. The

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 173
Java Programming

first four are the same as the arguments for drawOval( ) method and the last two represents the
starting angle of the arc and the number of degrees around the arc.
90’

180’
180’ 0’

270’
Fig: Arc as a part of an oval

We can also draw an arc in backward direction by specifying the sweep angle as negative. For
example: if the last argument is -135’ and the starting angle is 45’, then the arc is drawn as
shown below:

45’

-135’

270’
Fig: Drawing an arc in clockwise directions

We can use the fillArc( ) method to fill the 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 center of the oval.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 174
Java Programming

W an applet program to draw a human face:


import java.awt.*;
import java.applet.*;
public class Face extends Applet
{
public void paint(Graphics g)
Output:
{
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); // pupil(left)
g.fillOval(121,81,10,10); //pupil(right)
g.drawOval(85,100,30,30) //nose
g.fillArc(60,125,80,40,180,180) //mouth
g.drawOval(25,92,15,30); // left ear
g.drawOval(160, 92, 15, 30) //right ear
}
}

Drawing Polygons
Polygons are shape with many sides. A polygon may be considered a set of lines connected
together. The end of the first line is the beginning of the second line, the end of the second line is
the beginning of the third and so on. This suggests that we can draw a polygon with a sides using
the drawLine( ) method n times succession. For example: the code given below will draw a
polygon of three sides.

public void paint(Graphics g)

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 175
Java Programming

{
g.drawLine(10,20,170,40);
g.drawLine(170,40,80,140);
g.drawLine(80,140, 10,20);
}
We can draw polygons more conveniently using the drawPolygon( ) method of Graphics class.
This method takes three arguments:
 An array of integers containing x coordinates
 An array of integers containing y coordinates
 An integer for the total number of points

It is obvious that x and y arrays should be of the same size and we must repeat the first point at
the end of the array for closing the polygon.
Ex: public void paint(Graphics g)
{
int xPoints [ ] = {10,170,80,10};
int yPoints [ ] = {20, 40, 140, 20};
int nPoints [ ] = xPoints.length;
g.drawPolygon (xPoints, yPoints , nPoints);
}
We can also draw a filled polygon by using the fillPolygon( ) method.
W an applet to draw polygons
import java.awt.*;
import java.applet.*;
public class Poly extends Applet
{
public void paint(Graphics g)
int x1 [ ] = {20, 120, 220, 20};
{
int y1 [ ] = {20, 120, 20, 20}; g.drawPolygon(x1,y1,n1);
int n1 =4; g.fillPolygon(x2,y2,n2);
}
int x2 [ ] ={120, 220, 220, 120};
}
int y2 [ ] = {120, 20, 220, 120};
int n2 = 4;

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 176
Java Programming

Chapter 9: Managing Input / Output Files in Java

Introduction
A file is a collection of related records placed in a particular area on the disk. A record is
composed of several fields and a field is a group of characters. Characters in java are Unicode
characters composed of two bytes, each byte containing eight binary digits, 0 or 1.

Concept of Streams
Java uses the concept of streams to represent the ordered sequence of data, a common
characteristic shared by all the input/output devices. A stream presents a uniform, easy-to-use,
object oriented interface between the program and the input/output devices.

A stream in java is a path along which data flows. It has a source(of data) and a destination (for
that data). Both the source and the destination may be physical devices or programs or other
streams in the same program.

The concept of sending data from one stream to another has made streams in java a powerful tool
for file processing. We can build a complex file processing sequence using a series of simple
stream operations. This feature can be used to filter data along the pipeline of streams so that we
obtain data in a desired format.

Input stream Reads Program


Source

a. Reading data into a program

Writes Output stream


Program Destination

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 177
Java Programming

b. Writing data to a destination


Fig: Using Input and output streams

Java streams are classified into two basic types: namely, input stream and output stream. An
input stream extracts (reads) data from the source file and sends it to the program. Similarly, an
output stream takes data from the program and sends it to the destination file.

Stream classes
The java.io package contains large number of classes that provide capabilities for processing all
types of data. These classes may be categorized into two groups based on the data type on which
they operate.
1. Byte stream classes that provide support for handling I/O operations on bytes.
2. Character stream classes that provide support for managing I/O operations on characters.

These two groups may further be classified based on their purpose.

Java Stream
Classes

Byte Stream Character


Classes Stream Classes

Input Output stream Reader Writer


stream Classes classes classes
Prepared
classesby: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 178

Input
Java Programming

Memor File Pipe Memor File Pipe


y y

Fig: classification of java stream classes

Byte Stream Classes


Byte stream classes have been designed to provide functional features for creating and
manipulating streams and files for reading and writing bytes. Since the streams are
unidirectional, they can transmit bytes in only one direction and, therefore java provides two
kinds of byte stream classes: input stream classes and output stream classes.

Input stream classes: Input stream classes that are used to read 8-bit bytes include a super class
known as InputStream and a number of sub classes for supporting various input-related
functions.

Object

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 179
Java Programming

InputStream

FileInputStream SequenceInputStream

PipeInputStrea ObjectInputStream
m

ByteArrayInputStream StringBufferInputStream

FilterInputStream

BufferedInputStream PushbackInputStream

DataInputStream

DataInput

Fig: Hierarchy of input stream classes

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 180
Java Programming

The super class InputStream is an abstract class, and, therefore, we cannot create instances of
this class. Rather, we must use the subclasses that inherit from this class.

The InputStream class defines methods for performing input functions such as
 Reading bytes

 Closing streams

 Marking positions in streams

 Skipping ahead in a stream

 Finding the number of bytes in a stream

Summary of input stream methods

Method Description

1. read( ) Reads a byte from the input stream

2. read( byte b[ ]) Reads an array of bytes into b

3. read (byte b[ ], int n, int m) Reads m bytes into b starting from the nth byte

4. available( ) Gives number of bytes available in the input

5. skip ( n ) Skips over n bytes from the input stream

6. reset( ) goes back to the beginning of the stream

7. close( ) Closes the input stream

Output Stream Classes: Output stream classes are derived from the base class OutputStream.
The output stream is an abstract class and therefore we cannot instantiate it. The several
subclasses of the OutputStream can be used for performing the output operations.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 181
Java Programming

The OutputStream includes methods that are designed to perform the following tasks:

 writing bytes

 closing streams

 flushing streams

Object

OutputStream

FileOutputStream ObjectOutputStream

PipedOutputStream ByteArrayOutputStream

FilterOutputStream

BufferedOutputStream PushbackOutputStream

DataOutputStream

DataOutput
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 182
Java Programming

Fig: Hierarchy of output stream classes

Summary of OutputStream Methods

Method Description

1. write( ) writes a byte to the output stream

2. write(byte[ ] b) writes all bytes in the array b to the output steam

3. write(byte b[ ], int n, int m) writes m bytes from array b starting from nth byte

4. close( ) closes the output stream

5. flush( ) flushes the output stream

Character Stream Classes

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 183
Java Programming

Character stream classes were not a part of the language when it was released in 1995. They
were added later when the version 1.1 was announced. Character streams can be used to read and
write 16-bit Unicode characters. Like byte streams, there are two kinds of character stream
classes, namely, reader stream classes and writer stream classes.

Reader Stream Classes

Reader stream classes are designed to read character from the files. Reader class is the base
class for all other classes in this group. These classes are functionally very similar to the input
stream classes, expect input streams use bytes as their fundamental unit of information, while
reader streams use characters.

Object

Reader

BufferedReader StringReader

CharArrayReade PipeReader
r
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 184
Java Programming

InputStreamReader FilterReader

FileReader PushbackReader

Fig: Hierarchy of reader stream classes

The Reader class contains methods that are identical to those available in the InputStream
class, except Reader is designed to handle characters. Therefore, reader classes can perform all
the functions implemented by the input stream classes.

Writer Stream Classes

Like output stream classes, the writer stream classes are designed to perform all output
operations on files. Only difference is that while output stream classes are designed to write
bytes, the writer stream classes are designed to write characters.

The writer class is an abstract class which acts as a base class for all the other writer stream
classes. This base class provides support for all output operations by defining methods that are
identical to those in OutputStream class.

Object

writer

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 185
Java Programming

PrintWriter
BufferedWriter

CharArrayWriter StringWriter

FilterWriter PipeWriter

OutputStreamWriter

FileWriter

Fig: Hierarchy of writer stream classes

Using Streams

The various types of input and output stream classes used for handling both the 16-bit characters
and 8-bits bytes. Although all the classes are known as i/o classes, not all of them are used for
reading and writing operations only. Some perform operations such as buffering, filtering, data
conversion, counting and concatenation while carrying out i/o tasks.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 186
Java Programming

Other Useful I/O Classes

The java.io package supports many other classes for performing certain specialized functions.
They include among others:

 Random Access File

 Stream Tokenizer

The RandomAccessFile enables us to read and write bytes, text and java data types to any
location in a file (when used with appropriate access permissions). This class extends object
class and implements DataInput and DataOutput interfaces. This forces the
RandomAccessFile to implement the methods described in both these interfaces.

Object
Interface Interface

DataInput DataOutput

RandomAccessFile

Fig: Implementation of the RandomAccessFile

The class Stream Tokenizer, a subclass of object can be used for breaking up a stream of text
from an input text file into meaningful pieces called tokens. The behavior of the Stream
Tokenizer class is similar to that of the String Tokenizer class (of java.util package) that
breaks a string into its component tokens.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 187
Java Programming

Using the File Class

The java.io package includes a class known as the File class that provides supports for creating
files and directories. The class includes several constructs for instantiating the File objects. This
class also contains several methods for supporting the operations such as

 Creating a file
 Opening a file
 Closing a file
 Deleting a file
 Getting the name of a file
 Getting the size of a file
 Checking the existence of a file
 Renaming a file
 Checking whether the file is writable
 Checking whether the file is readable

Input / Output Exceptions

When creating files and performing i/o operations on them, the system may generate i/o related
exceptions.

Important i/o related exception classes and their functions:

I/O Exception class Function

EOFException signals that an end of the file or end of stream has been reached
unexpectedly during input

FileNotFoundException Informs that a file could not be found

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 188
Java Programming

InterruptedIOException Warms that an I/O operations has been interrupted

IOException Signals that an I/O exception of some sort has occurred

Each i/o statement or group of i/o statements must have an exception handler around it as shown
below or the method must declare that it throws an IOException.

try
{
…………
………… // I/O statements
}
catch(IOException e)
{
………….. // Message output statement
}
Creation of Files

If we want to create and use a disk file, we need to decide the following about the file and its
intended purpose:
 Suitable name for the file
 Data type to be stored
 Purpose (reading, writing, or updating)
 Method of creating the file

A filename is a unique string of characters that helps identify a file on the disk. The length of a
filename and characters allowed are dependent on the OS on which the Java program is
executed. A filename may contain two parts, a primary name and an optional period with
extension. Examples:
input.dat salary
test.doc student.txt
Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 189
Java Programming

inventory rand.dat

Data type is important to decide the type of file stream classes to be used for handling the data.
We should decide whether the data to be handled is in the form of characters, bytes or primitive
type.

The purpose of using a file must also be decided before using it. For example, we should know
whether the file is created for reading only, or writing only, or both the operations.

As we know, for using a file, it must be opened first. This is done by creating a file stream and
then liking it to the filename. A file stream can be defined using the classes of
Reader/InputStream for reading data and Writer/OutputStream for writing data.

Common Stream Classes used for I/O Operations

Source or
Destination Characters Bytes
Read Write Read Write
Memory CharArrayReader CharArrayWriter ByteArrayInputStream ByteArrayOutputStream
File FileReader FileWriter FileInputStream FileOutputStream
Pipe PipedReader PipedWriter PipedInputSttream PipedOutputStream

There are two ways of initializing the file stream objects. All of the constructors require that we
provide the name of the file either directly, or indirectly by giving a file object that has already
been assigned a filename.

The following code segment illustrates the use of direct approach.

FileInputStream fis; // Declare a file stream object


try
{

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 190
Java Programming

// Assign the filename to the file stream object


fis = new FileInputStream (“test.dat”);
……
}
catch (IOException e)
……
……

The indirect approach uses a file object that has been initialized with the desired filename. This
is illustrated by the following code:

…………
…………
File inFile; //declare a file object
InFile = new File(“test.dat”) // Assign the filename to

FileInputStream fis; // the file object


try
{
//Give the value of the file object
// to the file stream object
fis = new FileInputStream (infile);
……….
}
catch (………)
…………
…………

The code above includes five tasks:


 Select a filename
 Declare a file object

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 191
Java Programming

 Give the selected name to the file object declared


 Declare a file stream object
 Connect the file to the file stream object’

fis “test.dat”

Stream object Filename

fis inFile “test.dat”

Stream object File object Filename

Fig: Instantiating file stream objects

Reading / Writing Characters


The subclasses of Reader and Writer implement streams that can handle characters. The two
subclasses used for handling characters in files are FileReader (for reading characters) and
FileWriter (for writing characters).

Program : Copying Characters


// copying characters from one file into another
import java.io.*;
class CopyCharacters
{
public static void main(String args[ ])
{

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 192
Java Programming

//Declare and create input and output files


File inFile = new File (“input.dat”);
File outFile = new File (“output.dat”);
FileReader ins = null;
FileWriter outs = null;
try
{
ins = new FileReader (inFile);
outs = new FileWriter (outFile);

int ch;
while ( (ch = ins.read( )) != -1)
{
outs.write(ch);
}
}
catch (IOException e)
{
System.out.println(e);
System.exit(-1);
}
finally
{
try
{
ins.close( );
outs.close( );
}
Catch(IOException e)
{}
}

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 193
Java Programming

}
}

Concatenating and Buffering Files

It is possible to combine two or more input stream into a single input stream. This process is
known as concatenation of files and is achieved using the SequenceInputStream class. One of
the constructors of this class takes two InputStream objects as arguments and combines them to
construct a single input stream.

Java also supports creation of buffers to store temporarily data that is read from or written to a
stream. The process is known as buffere i/o operation. A buffer sits between the program and the
source or destination and functions like a filter. Buffers can be created using the
BufferedInputStream and BufferedOutputStream.

Random Access Files

The Random Access File class supported by the Java.io package allows us to create files that
can be used for reading and writing data with random access. That is, we can “jump around” in
the file while using the file. Such files are known as random access files.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 194
Java Programming

A file can be created and opened for random access by giving a mode string as a parameter to the
constructor when we open the file. We can use one of the following two mode strings:
 “r” for reading only
 “rw” for both reading and writing

An existing file can be updated using the “rw” mode

Reading / Writing using a random access file


import java.io.*;
class RandomIO
{
public static void main (String args[ ])
{
RandomAccessFile file = null;
try
{
file = new RandomAccessFile(“rand.data”, “rw”);
file.writeChar(‘X’);
file.writeInt(555);
file.writeDouble(3.1412);
file.seek(0);

System.out.println(file.readerChar( ));
System.out.println(file.readInt( ) );
System.out.println(file.readDouble( ));

file.seek(2);
System.out.println(file.length( ));
File.writeBoolean(false( );

file.seek(4);

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 195
Java Programming

System.out.println(file.readBoolean( ));
file.close( );
}
catch(IOException e)
{
System.out.println(e);
}
}
}

Interactive Input and Output


The process of reading data from the keyboard and displaying output on the screen is known as
interactive i/o. There are two types of interactive i/o. First one is referred to as simple interactive
i/o which involves simple input a=from the keyboard and simple output in a pure text form. The
second type is referred to as graphical interactive i/o which involves input from various input
devices and output to a graphical environment on frames and applets.

Simple Input and Output


The System class contains three i/o objects, namely System.in, System.out and System.err
where in, out, err are static variables. The variable in is of InputStream type and the other two
are of PrintStream type. We can use these objects to input from the keyboard, output to the
screen, and display error messages. System class is stored in java.lang package which is
imported into a java program automatically.

Graphical Input and Output


The program uses the TextField class to create text fields that receive information from the user
at the keyboard and then writes the information to a file.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 196
Java Programming

Other Stream Classes


Java supports many other input/output stream that we might find useful in some situations. A
brief discussion of some of these streams is given as follows:

 Object Streams: we can read and write characters, bytes and primitive data types. It is
also possible to perform input and output operations on objects using the object streams.
The object streams are created using the ObjectInputStream and ObjectOutputStream
classes. In this case, we may declare records as objects and use the object classes to write
and read these objects from files. As mentioned in the beginning, this process is known as
object serislization.

 Piped Stream: Piped stream provide functionality for threads to communicate and
exchange data between them. There are two threads use pipes for communication. The
write thread sends data to the read thread through a pipeline that connects an object of
PipedInputStream to an object of PipedOutputStream. The objects inputPipe and
outputPipe are connected using the connect( ) method.

 Pushback Streams: The pushback stream created by the classes PushbackInputStream


and PushbackReader can be used to push a single byte or a character back into the input
stream so that it can be reread. This is commonly used with parsers. When a character
indicating a new input token is read, it is pushed back into the input stream until the
current input token is processed. It is then reread when processing of the next input token
is initiated.

 Filtered Streams: Java supports two abstract classes, namely, FilterInputStream and
FilterOutputStream that provide the basic capability to create input and output streams
for filtering input/output in a number of ways. These streams, known as filters, sits
between an input stream and an output stream and perform some optional processing on
the data they transfer.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 197
Java Programming

Chapter 10: Java Database Connectivity

Event handling

Basics of Event Handling:


• Event handling is a basic concept of graphical user interfaces.
• What is event handling?
– It is the way we capture events in Java. Java GUI programmers are particularly
interested in events like:
• mouse clicks
• keyboard entries

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 198
Java Programming

• time intervals
– We can also implement simple GUI objects in Java such as buttons.
• The way event handling works is this:
– Any operating system that supports GUIs constantly monitors events such as
keystrokes and mouse clicks.
– The operating system reports these events to programs that are running.
– The programs decide what, if anything, they want to do with these events.
• In Java, you control how to handle these events by setting up event source objects and
event listener objects.
• Event sources are objects like buttons and scroll bars.
• Event listeners can be any object.
• Here is how to set up event sources and listeners:
– A listener object is an instance of a class that implements a listener interface.
– An event source is an object that can register listener objects and send them event
objects.
– The event source sends out event objects to all the registered listeners when that
event occurs.
– The listener objects will then use information in the event object to determine
their reaction to the event.

Registering Listeners
• So, how do you set this up in Java.
• First, you create an event source object like a button.
– JButton button = new JButton(“Ok”);
• Second, instantiate an object that implements a listener interface.
– ActionListener listener = new ColorAction(Color.red);
– where ColorAction implements ActionListener
• Third, register the listener object with the event source object.
– button.addActionListener(listener);

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 199
Java Programming

• Note: JButton objects require an ActionListener interface. Other objects may require
different interfaces
– The ActionListener interface requires the programmer to override the
actionPerformed method that accepts an Event object.
• So, now when the button is clicked, the JButton object creates an ActionEvent object
(which is a subclass of an Event object) and calls the actionPerformed method in listener
object (ColorAction).
• Note, multiple listeners can be registered to one event source.

Revisiting Inner Classes


• Listener objects are often strategically placed as inner classes inside the class whose state
the listener should modify.
– Again, inner classes have access to the private data of the outer class.
• You can also use anonymous inner classes to dramatically reduce the amount of code
needed.

Capturing Window Events


• To capture window events (such as when the user closes a window), you must have an
object that implements the WindowListener interface. The JFrame is the source of a
WindowEvent.
– e.g. WindowListener listener = …;
frame.addWindowListener(listener);
• The WindowListener interface has seven distinct events that can happen. That means you
must override seven abstract methods.

• An object that implements the WindowListener interfact must override these methods:
– void windowOpened(WindowEvent e);
– void windowClosing(WindowEvent e);
– void windowClosed(WindowEvent e);

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 200
Java Programming

– void windowIconified(WindowEvent e);


– void windowDeiconified(WindowEvent e);
– void windowActivated(WindowEvent e);
– void windowDeactivated(WindowEvent e);
• This can obviously be a real pain if you only care about one event.

• To make it easier for programmers, the designers of Java supplied adapter classes.
– Each AWT listener interface with more than one method comes with a companion
adapter class.
– These adapter classes implement all the methods in the interface but does nothing
with them.
– This means that the adapter classes satisfy all the technical requirements for
implementing the listener interface.
– You can then just extend your class from these adapter classes if you don’t need
to extend it from anything else.

Adapter Classes

• The adapter class for the WindowListener interface is WindowAdapter. You can use it
like this:
– class Terminator extends WindowAdapter {…}
• Creating a listener class that extends the WindowAdapter is even easier than that. There is
no need to give a name to the listener object.
– frame.addWindowListener(new Terminator());
• You can go even further by using an anonymous inner class:
– frame.addWindowListener(new
WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0)

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 201
Java Programming

}
});
• You can see how much less code there is.

Semantic and Low-Level Events


• Semantic events express what the user is doing.
– e.g. clicking a button
• Low-level events are those that make semantic events possible.
– e.g. mouse moves, mouse clicks, keyboard strokes etc.
• The 4 semantic event classes in java.awt.event package
– ActionEvent
• (for button clicks, menu selections, ENTER typed in text field, selecting a
list item)
– AdjustmentEvent
• (the user adjusted a scroll bar)
– ItemEvent
• (the user made a selection from a set of checkboxes or list items)
– TextEvent
• (the contents of a text field or text area were changed)

• The 7 low-level event classes in java.awt.event package


– ComponentEvent
• (the component was resized, moved, shown, or hidden)
– KeyEvent
• (key was pressed or released)
– MouseEvent
• (the mouse button was pressed, released, moved, or dragged)
– MouseWheelEvent
• (the mouse wheel was rotated)
– FocusEvent
• (a component got focus or lost focus)

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 202
Java Programming

– WindowEvent
• (the window state changed)
– ContainerEvent
• (a component has been added or removed)

Java – Networking
The term network programming refers to writing programs that execute across multiple devices (computers),
in which the devices are all connected to each other using a network.

The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the low-
level communication details, allowing you to write programs that focus on solving the problem at hand.

The java.net package provides support for the two common network protocols:

 TCP: TCP stands for Transmission Control Protocol, which allows for reliable communication
between two applications. TCP is typically used over the Internet Protocol, which is referred to as
TCP/IP.

 UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of
data to be transmitted between applications.

This tutorial gives good understanding on the following two subjects:

 Socket Programming: This is most widely used concept in Networking and it has been explained in
very detail.

 URL Processing: This would be covered separately. Click here to learn about URL Processing in
Java language.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 203
Java Programming

Socket Programming:
Sockets provide the communication mechanism between two computers using TCP. A client program creates
a socket on its end of the communication and attempts to connect that socket to a server.

When the connection is made, the server creates a socket object on its end of the communication. The client
and server can now communicate by writing to and reading from the socket.

The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for
the server program to listen for clients and establish connections with them.

The following steps occur when establishing a TCP connection between two computers using sockets:

 The server instantiates a ServerSocket object, denoting which port number communication is to occur
on.

 The server invokes the accept() method of the ServerSocket class. This method waits until a client
connects to the server on the given port.

 After the server is waiting, a client instantiates a Socket object, specifying the server name and port
number to connect to.

 The constructor of the Socket class attempts to connect the client to the specified server and port
number. If communication is established, the client now has a Socket object capable of
communicating with the server.

 On the server side, the accept() method returns a reference to a new socket on the server that is
connected to the client's socket.

After the connections are established, communication can occur using I/O streams. Each socket has both an
OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and
the client's InputStream is connected to the server's OutputStream.

TCP is a twoway communication protocol, so data can be sent across both streams at the same time. There are
following usefull classes providing complete set of methods to implement sockets.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 204
Java Programming

ServerSocket Class Methods:


The java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests

The ServerSocket class has four constructors:

SN Methods with Description

1 public ServerSocket(int port) throws IOException

Attempts to create a server socket bound to the specified port. An exception occurs if the port is
already bound by another application.

2 public ServerSocket(int port, int backlog) throws IOException

Similar to the previous constructor, the backlog parameter specifies how many incoming clients
to store in a wait queue.

3 public ServerSocket(int port, int backlog, InetAddress address) throws IOException

Similar to the previous constructor, the InetAddress parameter specifies the local IP address to
bind to. The InetAddress is used for servers that may have multiple IP addresses, allowing the
server to specify which of its IP addresses to accept client requests on

4 public ServerSocket() throws IOException

Creates an unbound server socket. When using this constructor, use the bind() method when you
are ready to bind the server socket

If the ServerSocket constructor does not throw an exception, it means that your application has successfully
bound to the specified port and is ready for client requests.

Here are some of the common methods of the ServerSocket class:

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 205
Java Programming

SN Methods with Description

1 public int getLocalPort()

Returns the port that the server socket is listening on. This method is useful if you passed in 0 as
the port number in a constructor and let the server find a port for you.

2 public Socket accept() throws IOException

Waits for an incoming client. This method blocks until either a client connects to the server on
the specified port or the socket times out, assuming that the time-out value has been set using the
setSoTimeout() method. Otherwise, this method blocks indefinitely

3 public void setSoTimeout(int timeout)

Sets the time-out value for how long the server socket waits for a client during the accept().

4 public void bind(SocketAddress host, int backlog)

Binds the socket to the specified server and port in the SocketAddress object. Use this method if
you instantiated the ServerSocket using the no-argument constructor.

When the ServerSocket invokes accept(), the method does not return until a client connects. After a client
does connect, the ServerSocket creates a new Socket on an unspecified port and returns a reference to this
new Socket. A TCP connection now exists between the client and server, and communication can begin.

Socket Class Methods:


The java.net.Socket class represents the socket that both the client and server use to communicate with each
other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object from
the return value of the accept() method.

The Socket class has five constructors that a client uses to connect to a server:

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 206
Java Programming

SN Methods with Description

1 public Socket(String host, int port) throws UnknownHostException, IOException.

This method attempts to connect to the specified server at the specified port. If this constructor
does not throw an exception, the connection is successful and the client is connected to the
server.

2 public Socket(InetAddress host, int port) throws IOException

This method is identical to the previous constructor, except that the host is denoted by an
InetAddress object.

3 public Socket(String host, int port, InetAddress localAddress, int localPort) throws
IOException.

Connects to the specified host and port, creating a socket on the local host at the specified
address and port.

4 public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws
IOException.

This method is identical to the previous constructor, except that the host is denoted by an
InetAddress object instead of a String

5 public Socket()

Creates an unconnected socket. Use the connect() method to connect this socket to a server.

When the Socket constructor returns, it does not simply instantiate a Socket object but it actually attempts to
connect to the specified server and port.

Some methods of interest in the Socket class are listed here. Notice that both the client and
server have a Socket object, so these methods can be invoked by both the client and server.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 207
Java Programming

SN Methods with Description

1 public void connect(SocketAddress host, int timeout) throws IOException

This method connects the socket to the specified host. This method is needed only when you
instantiated the Socket using the no-argument constructor.

2 public InetAddress getInetAddress()

This method returns the address of the other computer that this socket is connected to.

3 public int getPort()

Returns the port the socket is bound to on the remote machine.

4 public int getLocalPort()

Returns the port the socket is bound to on the local machine.

5 public SocketAddress getRemoteSocketAddress()

Returns the address of the remote socket.

6 public InputStream getInputStream() throws IOException

Returns the input stream of the socket. The input stream is connected to the output stream of the
remote socket.

7 public OutputStream getOutputStream() throws IOException

Returns the output stream of the socket. The output stream is connected to the input stream of the
remote socket

8 public void close() throws IOException

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 208
Java Programming

Closes the socket, which makes this Socket object no longer capable of connecting again to any
server

InetAddress Class Methods:


This class represents an Internet Protocol (IP) address. Here are following usefull methods
which you would need while doing socket programming:

SN Methods with Description

1 static InetAddress getByAddress(byte[] addr)

Returns an InetAddress object given the raw IP address .

2 static InetAddress getByAddress(String host, byte[] addr)

Create an InetAddress based on the provided host name and IP address.

3 static InetAddress getByName(String host)

Determines the IP address of a host, given the host's name.

4 String getHostAddress()

Returns the IP address string in textual presentation.

5 String getHostName()

Gets the host name for this IP address.

6 static InetAddress InetAddress getLocalHost()

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 209
Java Programming

Returns the local host.

7 String toString()

Converts this IP address to a String.

Socket Client Example:


The following GreetingClient is a client program that connects to a server by using a socket and sends a
greeting, and then waits for a response.

// File Name GreetingClient.java

import java.net.*;

import java.io.*;

public class GreetingClient

public static void main(String [] args)

String serverName = args[0];

int port = Integer.parseInt(args[1]);

try

System.out.println("Connecting to " + serverName

+ " on port " + port);

Socket client = new Socket(serverName, port);

System.out.println("Just connected to "

+ client.getRemoteSocketAddress());

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 210
Java Programming

OutputStream outToServer = client.getOutputStream();

DataOutputStream out =

new DataOutputStream(outToServer);

out.writeUTF("Hello from "

+ client.getLocalSocketAddress());

InputStream inFromServer = client.getInputStream();

DataInputStream in =

new DataInputStream(inFromServer);

System.out.println("Server says " + in.readUTF());

client.close();

}catch(IOException e)

e.printStackTrace();

Socket Server Example:


The following GreetingServer program is an example of a server application that uses the Socket class to
listen for clients on a port number specified by a command-line argument:

// File Name GreetingServer.java

import java.net.*;

import java.io.*;

public class GreetingServer extends Thread

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 211
Java Programming

private ServerSocket serverSocket;

public GreetingServer(int port) throws IOException

serverSocket = new ServerSocket(port);

serverSocket.setSoTimeout(10000);

public void run()

while(true)

try

System.out.println("Waiting for client on port " +

serverSocket.getLocalPort() + "...");

Socket server = serverSocket.accept();

System.out.println("Just connected to "

+ server.getRemoteSocketAddress());

DataInputStream in =

new DataInputStream(server.getInputStream());

System.out.println(in.readUTF());

DataOutputStream out =

new DataOutputStream(server.getOutputStream());

out.writeUTF("Thank you for connecting to "

+ server.getLocalSocketAddress() + "\nGoodbye!");

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 212
Java Programming

server.close();

}catch(SocketTimeoutException s)

System.out.println("Socket timed out!");

break;

}catch(IOException e)

e.printStackTrace();

break;

public static void main(String [] args)

int port = Integer.parseInt(args[0]);

try

Thread t = new GreetingServer(port);

t.start();

}catch(IOException e)

e.printStackTrace();

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 213
Java Programming

The Tour of Swing


Swing is a set of classes this provides more powerful and flexible components than are possible
with the AWT. In addition to the familiar components, such as buttons, check boxes, and labels,
Swing supplies several exciting additions, including tabbed panes, scroll panes, trees, and tables.
Even familiar components such as buttons have more capabilities in Swing. For example, a
button may have both an image and a text string associated with it. Also, the image can be
changed as the state of the button changes.
Unlike AWT components, Swing components are not implemented by platform-specific code.
Instead, they are written entirely in Java and, therefore, are platform-independent. The term
lightweight is used to describe such elements. The number of classes and interfaces in the Swing
packages is substantial. Swing is the set of packages built on top of the AWT that provide us
with a great number of pre-built classes that is, over 250 classes and 40 UI components.

The Swing component classes that are shown below:

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 214
Java Programming

The Swing family tree

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 215
Java Programming

Swing Features
Besides the large array of components in Swing and the fact that they are lightweight, Swing
introduces many other innovations.

Borders
We can draw borders in many different styles around components using the setborder( ) method.

Graphics Debugging

We can use setDebuggingGraphicsOptions method to set up graphics debugging which means


among the other things, that you can watch each line as its drawn and make it flash.

Easy mouseless operation

It is easy to connect keystrokes to components.

Tooltips
We can use the setToolTipText method of JComponent to give components a tooltip, one of
those small windows that appear when the mouse hovers over a component and gives
explanatory text.

Easy Scrolling

We can connect scrolling to various components-something that was impossible in AWT.

Pluggable look and feel

We can set the appearance of applets and applications to one of three standard looks. Windows,
Motif (Unix) or Metal (Standard swing look).

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 216
Java Programming

New Layout Managers

Swing introduces the BoxLayout and OverlayLayout layout managers.

One of the differences between the AWT and Swing is that, when we redraw items on the screen
of AWT, the update method is called first to redraw the item’s background and programmers
often override update method to just call the paint method directly to avoid flickering. In Swing,
on the other hand the update method does not redraw the item’s background because components
can be transparent; instead update just calls paint method directly.

Japplet

Fundamental to Swing is the JApplet class, which extends Applet. Applets that use Swing must
be subclasses of JApplet. JApplet is rich with functionality that is not found in Applet. For
example, JApplet supports various “panes,” such as the content pane, the glass pane, and the root
pane.

When adding a component to an instance of JApplet, do not invoke the add( ) method of the
applet. Instead, call add( ) for the content pane of the JApplet object. The content pane can be
obtained via the method shown here:

Container getContentPane( )
The add( ) method of Container can be used to add a component to a content pane. Its form is
shown here:
void add(comp)
Here, comp is the component to be added to the content pane.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 217
Java Programming

Icons and Labels


In Swing, icons are encapsulated by the ImageIcon class, which paints an icon from an image.
Two of its constructors are shown here:

ImageIcon(String filename)
ImageIcon(URL url)

The first form uses the image in the file named filename. The second form uses the image in the
resource identified by url. The ImageIcon class implements the Icon interface that declares the
methods shown here:

Swing labels are instances of the JLabel class, which extends JComponent. It can display text
and/or an icon. Some of its constructors are shown here:

JLabel(Icon i)
Label(String s)
JLabel(String s, Icon i, int align)

Here, s and i are the text and icon used for the label. The align argument is either LEFT,
RIGHT,CENTER, LEADING, or TRAILING. These constants are defined in the
SwingConstants interface, along with several others used by the Swing classes. The icon and text
associated with the label can be read and written by the following methods:
Icon getIcon( )
String getText( )

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 218
Java Programming

void setIcon(Icon i)
void setText(String s)

Here, i and s are the icon and text, respectively. The following example illustrates how to create
and display a label containing both an icon and a string. The applet begins by getting its content
pane. Next, an ImageIcon object is created for the file IC.jpg. This is used as the second
argument to the JLabel constructor. The first and last arguments for the JLabel constructor are
the label text and the alignment. Finally, the label is added to the content pane.

import java.awt.*;
import javax.swing.*;
/* <applet code="JLabelDemo" width=250 height=150> </applet> */
public class JLabelDemo extends JApplet
{
public void init()
{
Container contentPane = getContentPane();
ImageIcon ii = new ImageIcon("IC.jpg");
JLabel jl = new JLabel("IC", ii, JLabel.CENTER);
contentPane.add(jl);
}
}

Text Fields
The Swing text field is encapsulated by the JTextComponent class, which extends JComponent.
It provides functionality that is common to Swing text components. One of its subclasses is
JTextField, which allows us to edit one line of text. Some of its constructors are shown here:

JTextField( )
JTextField(int cols)
JTextField(String s, int cols)

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 219
Java Programming

JTextField(String s)

Here, s is the string to be presented, and cols is the number of columns in the text field. The
following example illustrates how to create a text field. The applet begins by getting its content
pane, and then a flow layout is assigned as its layout manager. Next, a JTextField object is
created and is added to the content pane.

import java.awt.*;
import javax.swing.*;
/*
<applet code="JTextFieldDemo" width=300 height=50>
</applet>
*/
public class JTextFieldDemo extends JApplet
{
JTextField jtf;
public void init()
{
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
jtf = new JTextField(15);
contentPane.add(jtf);
}
}

Buttons
Swing buttons provide features that are not found in the Button class defined by the AWT. For
example, we can associate an icon with a Swing button. Swing buttons are subclasses of the

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 220
Java Programming

Abstract Button class, which extends JComponent. Abstract Button contains many methods that
allow us to control the behavior of buttons, check box and radio buttons. For example, we can
define different icons that are displayed for the component when it is disabled, pressed, or
selected. Another icon can be used as rollover icon, which is displayed when the mouse is
positioned over that component. The following are the methods that control this behavior:
void setDisabledIcon(Icon di)
void setPressedIcon(Icon pi)
void setSelectedIcon(Icon si)
void setRolloverIcon(Icon ri)
Here, di, pi, si, and ri are the icons to be used for these different conditions. The text associated
with a button can be read and written via the following methods:
String getText( )
void setText(String s)
Here, s is the text to be associated with the button. Concrete subclasses of AbstractButton
generate action events when they are pressed. Listeners register and un-register for these events
via the methods shown here:
void addActionListener(ActionListener al)
void removeActionListener(ActionListener al)
Here, al is the action listener. Abstract Button is a superclass for push buttons, check boxes, and
radio buttons.
JButton Class
The JButton class provides the functionality of a push button. JButton allows an icon string, or
both to be associated with the push button. Some of its constructors are shown here:
JButton(Icon i)
JButton(String s)
JButton(String s, Icon i)
Here, s and i are the string and icon used for the button. The following example displays four
push buttons and a text field. Each button displays an icon that represents the flag of a country.
When a button is pressed, the name of that country is displayed in the text field. The applet
begins by getting its content pane and setting the layout manager of that pane. Four image
buttons are created and added to the content pane.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 221
Java Programming

Next, the applet is registered to receive action events that are generated by the buttons. A text
field is then created and added to the applet. Finally, a handler for action events displays the
command string that is associated with the button. The text field is used to present this string.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JTextFieldDemo" width=250 height=300>
</applet>
*/
public class JButtonDemo extends JApplet
implements ActionListener
{
JTextField jtf;
public void init()
{
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
ImageIcon france = new ImageIcon("green.jpg");
JButton jb = new JButton(france);
jb.setActionCommand("Green");
jb.addActionListener(this);
contentPane.add(jb);
ImageIcon germany = new ImageIcon("red.jpg");
jb = new JButton(germany);
jb.setActionCommand("Red");
jb.addActionListener(this);
contentPane.add(jb);
ImageIcon italy = new ImageIcon("yellow.jpg");
jb = new JButton(italy);
jb.setActionCommand("Yellow");
jb.addActionListener(this);

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 222
Java Programming

contentPane.add(jb);
ImageIcon japan = new ImageIcon("black.jpg");
jb = new JButton(japan);
jb.setActionCommand("Black");
jb.addActionListener(this);
contentPane.add(jb);
jtf = new JTextField(15);
contentPane.add(jtf);
}
public void actionPerformed(ActionEvent ae)
{
jtf.setText(ae.getActionCommand());
}
}

Check Boxes

The JCheckBox class, which provides the functionality of a check box, is a concrete
implementation of Abstract Button. It is immediate super -class is JToggleButton, which
provides support for two -state buttons. Some of its constructors are shown here:

JCheckBox(Icon i)
JCheckBox(Icon i, boolean state)
JCheckBox(String s)
JCheckBox(String s, boolean state)
JCheckBox(String s, Icon i)
JCheckBox(String s, Icon i, boolean state)

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 223
Java Programming

Here, i is the icon for the button. The text is specified by s. If state is true, the check box is
initially selected. Otherwise, it is not. The state of the check box can be changed via the
following method:

void setSelected(boolean state)

Here, state is true if the check box should be checked. The following example illustrates how to
create an applet that displays four check boxes and a text field. When a check box is pressed, its
text is displayed in the text field the content pane for the JApplet object is obtained, and a flow
layout is assigned as its layout manager. Next, four check boxes are added to the content pane,
and icons are assigned for the normal, rollover, and selected states.

The applet is then registered to receive item events. Finally, a text field is added to the content
pane. When a check box is selected or deselected, an item event is generated. This is handled by
itemState Changed( ). Inside item State Changed( ), the getItem( ) method gets the JCheckBox
object that generated the event. The getText( ) method gets the text for that check box and uses it
to set the text inside the text field.

import java.awt.*;
import javax.swing.*;
/*
<applet code="JTextFieldDemo" width=400 height=50>
</applet>
*/
public class JCheckBoxDemo extends JApplet
implements ItemListener
{
JTextField jtf;
public void init()
{
Container contentPane = getContentPane();

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 224
Java Programming

contentPane.setLayout(new FlowLayout());
JCheckBox cb = new JCheckBox("C", true);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("C++", false);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("Java", false);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("Perl", false);
cb.addItemListener(this);
contentPane.add(cb);
jtf = new JTextField(15);
contentPane.add(jtf);
}

public void itemStateChanged(ItemEvent ie)


{
JCheckBox cb = (JCheckBox)ie.getItem();
jtf.setText(cb.getText());
}
}

Radio Buttons

Radio buttons are supported by the JRadioButton class, which is a concrete implementation of
Abstract Button. Its immediate super -class is JToggle Button, which provides support for two-
state buttons. Some of its constructors are shown here:

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 225
Java Programming

JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s)
JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, boolean state)

Here, i is the icon for the button. The text is specified by s. If state istrue, the button is initially
selected. Otherwise, it is not. Radio buttons must be configured into a group. Only one of the
buttons in that group can be selected at any time. For example, if a user presses a radio button
that is in a group, any previously selected button in that group is automatically deselected. The
ButtonGroup class is instantiated to create a button group. Its default constructor is invoked for
this purpose. Elements are then added to the button group via the following method:

void add(AbstractButton ab)

Here, ab is a reference to the button to be added to the group. The following example illustrates
how to use radio buttons. Three radio buttons and one text field are created. When a radio button
is pressed, its text is displayed in the text field. First, the content pane for the JApplet object is
obtained and a flow layout is assigned as its layout manager. Next, three radio buttons are added
to the content pane. Then, a button group is defined and the buttons are added to it.

Finally, a text field is added to the content pane. Radio button presses generate action events that
are handled by action Performed(). The get Action Command() method gets the text that is
associated with a radio button and uses it to set the text field.

import java.awt.*;
import javax.swing.*;

/*
<applet code="JTextFieldDemo" width=400 height=50>

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 226
Java Programming

</applet>

*/

public class JRadioButtonDemo extends JApplet


implements ActionListener
{
JTextField tf;
public void init()
{
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
JRadioButton b1 = new JRadioButton("A");
b1.addActionListener(this);
contentPane.add(b1);
JRadioButton b2 = new JRadioButton("B");
b2.addActionListener(this);
contentPane.add(b2);
JRadioButton b3 = new JRadioButton("C");
b3.addActionListener(this);
contentPane.add(b3);
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
bg.add(b3);
tf = new JTextField(5);
contentPane.add(tf);
}
public void actionPerformed(ActionEvent ae)
{
tf.setText(ae.getActionCommand());

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 227
Java Programming

}
}

Combo Boxes
Swing provides a combo box (a combination of a text field and a dropdown list) through the
JComboBox class, which extends JComponent. A combo box normally displays one entry.
However, it can also display a drop -down list that allows a user to select a different entry. We
can also type our selection into the text field. Two of JComboBox’s constructors are shown here:

JComboBox( )
JComboBox(Vector v)
JComboBox(Objects obj[])

Here, v is a vector that initializes the combo box and obj is the array of objects. Items are added
to the list of choices via the addItem( ) method, whose signature is shown here:

void addItem(Object obj)

Here, obj is the object to be added to the combo box.

Important Methods:

public void setEditable(boolean aFlag)

It determines whether the JComboBox field is editable or not?

public boolean isEditable()

It returns true if the JComboBox is editable. By default, a combo box is not editable.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 228
Java Programming

public void setMaximumRowCount(int count)

It sets the maximum number of rows the JComboBox displays. If the number of objects in the
model is greater than ‘count’, the combo box uses a scrollbar.

public void setSelectedItem(Object anObject)

It sets the selected item in the combo box display area to the object in the argument. If anObject
is in the list, the display area shows anObject selected.

public void insertItemAt(Object anObject, int index)

It inserts an item ‘anObject’ into the item list at a given ‘index’. public void remove Item(Object
anObject)

It removes an item ‘anObject’ from the item list.

public void removeItemAt(int anIndex)

It removes the item at ‘anIndex’.


The following example contains a combo box and a label. The label displays an icon. The combo
box contains entries for colors Green, Red, Yellow and Black. When a country is selected, the
label is updated to display the color for that particular color. Color jpeg images are already stored
in the current directory.

import java.awt.*;
import javax.swing.*;
/*
<applet code="JTextFieldDemo" width=300 height=100>
</applet>
*/

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 229
Java Programming

public class JComboBoxDemo extends JApplet


implements ItemListener
{
JLabel jl;
ImageIcon green, red, black, yellow;
public void init()
{
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
JComboBox jc = new JComboBox();
jc.addItem("Green");
jc.addItem("Red");
jc.addItem("Black");
jc.addItem("Yellow");
jc.addItemListener(this);
contentPane.add(jc);
jl = new JLabel(new ImageIcon("green.jpg"));
contentPane.add(jl);
}
public void itemStateChanged(ItemEvent ie)
{
String s = (String)ie.getItem();
jl.setIcon(new ImageIcon(s + ".jpg"));
}
}

Java Collections Framework


Prior to Java 2, Java provided ad hoc classes such as Dictionary, Vector, Stack,
andProperties to store and manipulate groups of objects. Although these classes were quite
useful, they lacked a central, unifying theme. Thus, the way that you used Vector was different from
the way that you used Properties.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 230
Java Programming

The collections framework was designed to meet several goals.

 The framework had to be high-performance. The implementations for the fundamental


collections (dynamic arrays, linked lists, trees, and hashtables) are highly efficient.

 The framework had to allow different types of collections to work in a similar manner and
with a high degree of interoperability.

 Extending and/or adapting a collection had to be easy.

Towards this end, the entire collections framework is designed around a set of standard interfaces.
Several standard implementations such as LinkedList, HashSet, and TreeSet, of these interfaces
are provided that you may use as-is and you may also implement your own collection, if you
choose.

A collections framework is a unified architecture for representing and manipulating collections. All
collections frameworks contain the following:

 Interfaces: These are abstract data types that represent collections. Interfaces allow
collections to be manipulated independently of the details of their representation. In object-
oriented languages, interfaces generally form a hierarchy.

 Implementations, i.e., Classes: These are the concrete implementations of the collection
interfaces. In essence, they are reusable data structures.

 Algorithms: These are the methods that perform useful computations, such as searching
and sorting, on objects that implement collection interfaces. The algorithms are said to be
polymorphic: that is, the same method can be used on many different implementations of
the appropriate collection interface.

In addition to collections, the framework defines several map interfaces and classes. Maps store
key/value pairs. Although maps are not collections in the proper use of the term, but they are fully
integrated with collections.

The Collection Interfaces:


The collections framework defines several interfaces. This section provides an overview of each
interface:

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 231
Java Programming

SN Interfaces with Description

1 The Collection Interface

This enables you to work with groups of objects; it is at the top of the collections
hierarchy.

2 The List Interface

This extends Collection and an instance of List stores an ordered collection of


elements.

3 The Set

This extends Collection to handle sets, which must contain unique elements

4 The SortedSet

This extends Set to handle sorted sets

5 The Map

This maps unique keys to values.

6 The Map.Entry

This describes an element (a key/value pair) in a map. This is an inner class of Map.

7 The SortedMap

This extends Map so that the keys are maintained in ascending order.

8 The Enumeration

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 232
Java Programming

This is legacy interface and defines the methods by which you can enumerate (obtain
one at a time) the elements in a collection of objects. This legacy interface has been
superceded by Iterator.

The Collection Classes:


Java provides a set of standard collection classes that implement Collection interfaces. Some of the
classes provide full implementations that can be used as-is and others are abstract class, providing
skeletal implementations that are used as starting points for creating concrete collections.

The standard collection classes are summarized in the following table:

SN Classes with Description

1 AbstractCollection

Implements most of the Collection interface.

2 AbstractList

Extends AbstractCollection and implements most of the List interface.

3 AbstractSequentialList

Extends AbstractList for use by a collection that uses sequential rather than random
access of its elements.

4 LinkedList

Implements a linked list by extending AbstractSequentialList.

5 ArrayList

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 233
Java Programming

Implements a dynamic array by extending AbstractList.

6 AbstractSet

Extends AbstractCollection and implements most of the Set interface.

7 HashSet

Extends AbstractSet for use with a hash table.

8 LinkedHashSet

Extends HashSet to allow insertion-order iterations.

9 TreeSet

Implements a set stored in a tree. Extends AbstractSet.

10 AbstractMap

Implements most of the Map interface.

11 HashMap

Extends AbstractMap to use a hash table.

12 TreeMap

Extends AbstractMap to use a tree.

13 WeakHashMap

Extends AbstractMap to use a hash table with weak keys.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 234
Java Programming

14 LinkedHashMap

Extends HashMap to allow insertion-order iterations.

15 IdentityHashMap

Extends AbstractMap and uses reference equality when comparing documents.

The AbstractCollection, AbstractSet, AbstractList, AbstractSequentialList and AbstractMapclasses


provide skeletal implementations of the core collection interfaces, to minimize the effort required to
implement them.

The following legacy classes defined by java.util have been discussed in previous tutorial:

SN Classes with Description

1 Vector

This implements a dynamic array. It is similar to ArrayList, but with some differences.

2 Stack

Stack is a subclass of Vector that implements a standard last-in, first-out stack.

3 Dictionary

Dictionary is an abstract class that represents a key/value storage repository and


operates much like Map.

4 Hashtable

Hashtable was part of the original java.util and is a concrete implementation of a


Dictionary.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 235
Java Programming

5 Properties

Properties is a subclass of Hashtable. It is used to maintain lists of values in which the


key is a String and the value is also a String.

6 BitSet

A BitSet class creates a special type of array that holds bit values. This array can
increase in size as needed.

The Collection Algorithms:


The collections framework defines several algorithms that can be applied to collections and maps.
These algorithms are defined as static methods within the Collections class.

Several of the methods can throw a ClassCastException, which occurs when an attempt is made
to compare incompatible types, or an UnsupportedOperationException, which occurs when an
attempt is made to modify an unmodifiable collection.

Collections define three static variables: EMPTY_SET, EMPTY_LIST, and EMPTY_MAP. All
are immutable.

SN Algorithms with Description

1 The Collection Algorithms

Here is a list of all the algorithm implementation.

How to use an Iterator ?


Often, you will want to cycle through the elements in a collection. For example, you might want to
display each element.

The easiest way to do this is to employ an iterator, which is an object that implements either the
Iterator or the ListIterator interface.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 236
Java Programming

Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator
extends Iterator to allow bidirectional traversal of a list and the modification of elements.

SN Iterator Methods with Description

1 Using Java Iterator

Here is a list of all the methods with examples provided by Iterator and ListIterator
interfaces.

How to use a Comparator ?


Both TreeSet and TreeMap store elements in sorted order. However, it is the comparator that
defines precisely what sorted order means.

This interface lets us sort a given collection any number of different ways. Also this interface
can be used to sort any instances of any class (even classes we cannot modify).

SN Iterator Methods with Description

1 Using Java Comparator

Here is a list of all the methods with examples provided by Comparator Interface.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 237
Java Programming

The java.util package

Objective :The collection classes/interfaces

Make appropriate selection of collection classes/interfaces to suit specified behavior


requirements.

Note on this Objective

Although it does not mention it specifically, this objective involves one of the new objectives for
the Java2 version of the exam, a knowledge of the collection classes. The exam questions on
these new collections are fairly basic, requiring a knowledge of where and how you might use
them, rather than a detailed knowledge of the fields and methods.

The old collections

The Java 2 API includes new interfaces and classes to enhance the collections available. Earlier
versions of Java included

vector

hashtable

array

BitSet

Of these, only array was included in the objectives for the 1.1 certification exam. One of the
noticeable omissions from Java 1.1 was support for sorting, a very common requirement in any
programming situation,

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 238
Java Programming

The new collections

At the root of the Collection API is the Collection interface. This gives you a series of common
methods that all collection classes will have. You would probably never create your own class
that implements Collection as Java supplies a series of sub-interfaces and classes that uses
the Collection interface.

The Java2 API includes the following new collection interfaces

Sets

Maps

Classes that implement the Collection interface store objects as elements rather than primitives.
This approach has the drawback that creating objects has a performance overhead and the
elements must be cast back from Object to the appropriate type before being used. It also means
that the collections do not check that the elements are all of the same type, as an object can be
just about anything.

A Set

A Set is a collection interface that cannot contain duplicate elements. It thus matches nicely onto
concepts such as a record set returned from a relational database. Part of the magic of
the Set interface is in the add method.

add(Object o)

Any object passed to the add method must implement the equals method so the value can be
compared with existing objects in the class. If the set already contains this object the call
to add leaves the set unchanged and returns false. The idea of returning falsewhen attempting to
add an element seems more like the approach used in C/C++ than Java. Most similar Java
methods would seem to throw an Exception in this type of situation.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 239
Java Programming

A List

A list is a sorted collection interface that can contain duplicates

Some important methods are

add

remove

clear

The JDK documentation gives the example of using List to manage an actual GUI list control
containing a list of the names of the Planets.

A Map

Map is an interface, classes that implement it cannot contain duplicate keys, and it is similar to a
hashtable.

Why use Collections instead of arrays?.

The big advantage of the collections over arrays is that the collections are growable, you do not
have to assign the size at creation time. The drawback of collections is that they only store
objects and not primitives and this comes with an inevitable performance overhead. Arrays do
not directly support sorting, but this can be overcome by using the static methods of the
Collections. Here is an example.

import java.util.*;

public class Sort{


public static void main(String argv[]){
Sort s = new Sort();
}

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 240
Java Programming

Sort(){
String s[] = new String[4];
s[0]="z";
s[1]="b";
s[2]="c";
s[3]="a";
Arrays.sort(s);
for(int i=0;i< s.length;i++)
System.out.println(s[i]);
}
}

Using Vectors

The following example illustrates how you can add objects of different classes to a Vector. This
contrasts with arrays where every element must be of the same type. The code then walks
through each object printing to the standard output. This implicitly access the toString() method
of each object.

import java.awt.*;
import java.util.*;
public class Vec{
public static void main(String argv[]){
Vec v = new Vec();
v.amethod();
}//End of main

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 241
Java Programming

public void amethod(){


Vector mv = new Vector();
//Note how a vector can store objects
//of different types
mv.addElement("Hello");
mv.addElement(Color.red);
mv.addElement(new Integer(99));
//This would cause an error
//As a vector will not store primitives
//mv.addElement(99)
//Walk through each element of the vector
for(int i=0; i< mv.size(); i++){
System.out.println(mv.elementAt(i));
}
}//End of amethod
}

Prior to Java2 the Vector class was the main way of creating a re-sizable data structure. Elements
can be removed from the Vector class with the remove method.

Using Hashtables

Hashtables are a little like the Visual Basic concept of a Collection used with a key. It acts like
a Vector, except that instead of referring to elements by number, you refer to them by key.
The hash part of the name refers to a math term dealing with creating indexes. A hashtable can
offer the benefit over a Vector of faster look ups.

BitSet

A BitSet as its name implies, stores a sequence of Bits. Don't be misled by the "set" part of its
name its not a set in the mathematical or database sense, nor is it related to the Sets available in

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 242
Java Programming

Java2. It is more appropriate to think of it as a bit vector. A BitSet may useful for the efficient
storage of bits where the bits are used to represent true/false values. The alternative of using
some sort of collection containing Boolean values can be less efficient.

According to Bruce Eckel in "Thinking in Java"

It’s efficient only from the standpoint of size; if you’re looking for efficient access, it is slightly
slower than using an array of some native type.

The BitSet is somewhat of a novelty class which you may never have a need for. I suspect that it
might be handy for the purposes of cryptography or the processing of images. Please let me
know if you come across a question relating to it in the Java2 exam.

JDBC ARCHITECTURE

INTRODUCTION TO JDBC
JDBC stands for Java Database Connectivity. It is set of Java API’s(application programming
interface) used for executing SQL statements. This API consists of a set of classes and interfaces
to enable programmers to write pure Java Database applications.

JDBC is a software layer that allows developers to write real client –server projects in Java.
JDBC does not concern itself with specific DBMS functions. JDBC API defines how an
application opens a connection, communicates with a database, executes SQL statements, and

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 243
Java Programming

retrieves query result. Following fig. will illustrate the role of JDBC. JDBC is based on the
X/OPEN call level interface (CLI) for SQL.

Call Level Interface is a library of function calls that supports SQL statements. CLI requires
neither host variables nor other embedded SQL concepts that would make it less flexible from a
programmer’s perspective. It is still possible, however, to maintain and use specific functions of
a database management system when accessing the database through a CLI.

JDBC Architecture

The JDBC API supports both two-tier and three-tier processing models for database access.

Figure 1: Two-tier Architecture for Data Access.

In the two-tier model, a Java application talks directly to the data source. This requires a JDBC driver that
can communicate with the particular data source being accessed. A user's commands are delivered to
the database or other data source, and the results of those statements are sent back to the user. The
data source may be located on another machine to which the user is connected via a network. This is
referred to as a client/server configuration, with the user's machine as the client, and the machine housing
the data source as the server. The network can be an intranet, which, for example, connects employees
within a corporation, or it can be the Internet.

In the three-tier model, commands are sent to a "middle tier" of services, which then sends the
commands to the data source. The data source processes the commands and sends the results back to
the middle tier, which then sends them to the user. MIS directors find the three-tier model very attractive
because the middle tier makes it possible to maintain control over access and the kinds of updates that

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 244
Java Programming

can be made to corporate data. Another advantage is that it simplifies the deployment of applications.
Finally, in many cases, the three-tier architecture can provide performance advantages.

Figure 2: Three-tier Architecture for Data Access.

Until recently, the middle tier has often been written in languages such as C or C++, which offer fast
performance. However, with the introduction of optimizing compilers that translate Java bytecode into
efficient machine-specific code and technologies such as Enterprise JavaBeans™, the Java platform is
fast becoming the standard platform for middle-tier development. This is a big plus, making it possible to
take advantage of Java's robustness, multithreading, and security features.

With enterprises increasingly using the Java programming language for writing server code, the JDBC
API is being used more and more in the middle tier of a three-tier architecture. Some of the features that
make JDBC a server technology are its support for connection pooling, distributed transactions, and
disconnected rowsets. The JDBC API is also what allows access to a data source from a Java middle tier.

JAVA AND JDBC


The combination of java with JDBC is very useful because it lets the programmer run
his/her program on different platforms, Java programs are secure, robust, automatically
downloaded from the network and java is a good language to create database applications.
JDBC API enables Java applications to interact with different types of database. It is
possible to publish vital information from a remote database on a web page using a java

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 245
Java Programming

applet. With increasing inclination of programmers towards Java, knowledge about JDBC is
essential.

Some of the advantages of using Java with JDBC are as follows:


 Easy and economical
 Continued usage of already installed databases
 Development time is short
 Installation and version control simplified

How does JDBC work


JDBC defines a set of API objects and methods to interact with the underlying database. A
Java program first opens a connection to the database, makes a statement object, passes
SQL statements to the underlying database management system (DBMS) through the
statement object and retrieve the results as well as information about the result set.

There are two types of interfaces – low –level interface and high-level interface. While high
level interfaces are user-friendly, low-level interfaces are not. JDBC is a low-level API
interface, ie. It used to invoke or call SQL commands directly. The required SQL statements
are passed as strings to Java methods.

Some of the current trend that are being developed to add more features to JDBC are
embedded SQL for java and direct mapping of relational database to java classes.

Embedded SQL enables mixing of java into SQL statements. These statements are
translated into JDBC calls using SQL Processor. In this type of direct mapping of relational
database tables to java, each row of the table becomes an instance of the class and each
column value corresponds to an attribute of that instance. Mapping is being provided that
makes rows of multiple tables to form a java class.

Prepared by: Sowmya Rani G S, Lecturer, Dept of Computer Science, CTA Page 246

You might also like