Professional Documents
Culture Documents
B.A/B.Com/B.Sc
THIRD YEAR SEMESTER-V
DESCIPLINE SPECIFIC CORE COURSE-DSC-5
COMPUTER APPLICATIONS
“We may forgo material benefits of civilization, but we cannot forgo our right
and opportunity to reap the benefits of the highest education to the fullest
extent as the education is the greatest material benefit”
All rights reserved. No part of this book may be reproduced in any form without the permission
in writing from the University.
Web: www.braou.ac.in
E-mail: info@braou.ac.in
Lr. No.-
Printed at: .................................................................................................................................
ii
PREFACE
This book on “Programming wth Java” is prepared for the Under Graduate Students
of B.A./B.Com/B.Sc studying in Dr. B. R. Ambedkar Open University. This course is offered
as a Discipline Specific Core Course (DSC) under CBCS being offered in V Semester as four
credit course. For the convenience of the students, the entire syllabus is organized in to four
blocks. Each block consists of three units. Each block covers a specific area of the subject.
The Units are prepared by the expert in accordance with a format so designed as to enable the
student to read and understand them without much difficulty. Each unit begins with a statement
of the Objectives followed by an introduction, self-check exercises in between and at the end
model examination questions intended to test the student’s comprehension of its subject matter.
“Programming with Java” course aims at gaining the knowledge of evolution of Java Language,
application of Java, comparisons with other languages like C and C++, advantages ofJava,
input and output, data types, operators, type casting, type conversion,classes,objects, garbage
collection, inheritance, encapsulation. And also enable the students to gain the knowledge of
using package; setting class path, access protection, importing packages, defining, implementing,
nested interfaces, applying interfaces, default interface methods, using static method in an
interface It enables all the students to learn basics to advanced features of Java language.
Today, we carry more computing power on our smart phones and tabs than was available in the
early models. The past decade has seen the revolutionary development in the hardware and
computer infrastructure. The software such as High level languages, Middleware, mobile
operating systems, GPS and deep learning software enhanced the skills of the people in solving
the challenging problems and living with emerging technologies. There is no doubt that the
intelligent computing technologies has helped to change the world. Most websites are hosted
on servers running free software. Even the mighty IBM, Google and Amazon also have their
walls placed in the rock-solid foundations of AI &ML, data mining, Big Data Analysis.
This course consists of four blocks and 12 units. Block-1 describesthe basic features
of Java which are History of java, downloading java, installing java, comparing java with C
and C++, Java vocabulary, variables, data types, type conversions, operators, literals, reading
input from keyboard, writing output to console. Block-II introduces the classes, objects new
operator, object references, methods, box class, types of constructors, this key word,. instance
variable hiding, garbage collection, finalize method, stack class, overloading methods and
constructors, access controls, final method, static method, static variables nested and inner
classes, string class, command line arguments with vararg. super class, second use for super,
multi-level hierarchy, method overriding, dynamic method dispatching, abstract classes, and
using final with inheritance. . Block-III explains Defining package, setting class path, access
protection, importing packages. Interfaces – defining, implementing, nested interfaces, applying
interfaces, default interface methods, use static method in an interface, Frame work, types of
exceptions, uncaught exceptions, try and catch, nested catch, multiple try, throw, throws, finally,
java built-in exceptions, user-defined exceptions, chained exceptions, recently added 3
exceptions. Collection Frame Work, Collection Classes- Array List, HaspMap, user defined
data in collections, using for each loop to iterate collections. . Block – IV describes the JDBC
definition, JDBC structure, registering and calling JDBC drivers, JDBC URL and the
connection, using JDBC drivers, Using meta-data, Transaction management with JDBC, event
handling mechanism, event classes, key event class, source of events, event listener interfaces,
using delegation event model, adaptor classes, inner classes-Examples of event handling with
AWT container and component classes and Java Swing.
The University hopes that this material will help the student to get clear concepts of
the Java, the power of java OOPs, Exception handling, Event handling,GUI API which enables
the world progress to modern era with the emerging computing technologies. iii
iv
CONTENTS
v
vi
BLOCK - I
1
2
UNIT-1: INTRODUCTION TO JAVA LANGUAGE
Contents
1.0 Objectives
1.1 Introduction
1.2 History, Evolution, Features of Java
1.3 Comparing with C++, Java SE 8, Phases of Execution
1.4 Sample Java programs
1.5 Summary
1.6 Check your progress – model answers
1.7 Model Examination Questions
1.8 Glossary
1.0. OBJECTIVES
After studying this unit, you should be able to understand
• the history, evolution and features of Java Programming Language
• the similarities and differences between Java and C/C++
• Features of Java SE8
• the structure of Java program along with how to read and print data
1.1. INTRODUCTION
Java language project, which was originally called Oak, was initiated by James Gosling, Mike
Sheridan, and Patrick Naughton in June 1991. Later the project went by the name Green and
was finally renamed Java. At that time Coke was the most favoured drink in software circles,
followed by Java coffee, the coffee from Indonesia. Since Coke is a brand already owned by a
company, Java was preferred. C/C++ style syntax are adopted in Java so that programmers
would be comfortable. Most of the features of Java language were also taken from C++ language
with suitable modifications, additions and omissions. Sun Microsystems (which is now acquired
by Oracle Corporation) released the first public implementation as Java 1.0 in 1996 as Free
and Open Source Software (FOSS). Java is generally available as Java Development Kit (JDK)
from its download site.Java is supported by a lot of open source libraries which can be used for
free to build applications. There are many tools and IDEs (Integrated Development Environment)
that makes your Java development easier. There are many frameworks that help you build
highly reliable applications quickly and easily since these frameworks already implements
common code pertaining to the applications.The Java community is huge and mature which
makes support easy in tight situations. Help on any topic is almost always available on Internet
how hard the problem may be.
5
1.3 COMPARING WITH C++, JAVA SE 8, PHASES OF EXECUTION
Comparison with c and c++
Java language borrowed the syntax from C and features from C++ language with minor changes.
This helped programmers to quickly learn Java and migrate to this modern language since
they need not relearn syntax. Almost all the language features are supported in Java which are
the strength of C and C++ like static variables, recursive functions, variable argument functions
etc. Object oriented paradigm is supported totally just like C++. However there are some
distinct differences among these languages.
First and foremost of them is the removal of the pointers which is the source of many errors in
software particularly with memory leakages.
Further Java also removed support for multiple inheritance, which creates confusion. Instead
of this it introduced the concept of Interfaces to mimic the multiple inheritance.
Operator overloading is also removed from Java since it is unsafe because the implementation
may be misleading in some cases. For example, a library may implement a + symbol for doing
something else like say formatting the disk!
In C and C++ the “main” method is outside all the classes and structures, but in Java, it should
be within a class, which is the pure object oriented since no definition should be outside the
classes.
While C and C++ use “include” statement, java uses “import” statement which is more natural.
Some of the important feature comparisons are given in the following table:
C C++ Java
Structured code with its Compatible with C source Mostly follows C++/C
original syntax rules code, except for a few special syntax
cases
6
Has multiple binary Same as C Has one binary
compatibility standards compatibility standard,
cross-platform for OS and
compiler.
Supports struct and union only Supports class, struct and Supports class only
union
8
Java Code
Java Code Compiler
Compiler Byte
Byte Code
Code
Test java
Test.java java
java Test.class
Test Class
Java
Java Byte Code
Byte Code Class loader
Class loader
Internreter
Interpreter Verifier
Verifier
Machine
Machine Specific
Specific Output
Output
Runtime
Runtime
Figure 1.1
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
2. What is Java SE8?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
9
It opens up the window of system properties as shown below:
Here click on the CLASSPATH variable if exists or click on new button if it doesn’t exist. This
opens up the System variable edit window with variable name and variable value. The class
path value is a series of directories separated by semicolons in windows (by colons in Linux).
Add all the paths to the jar files separated by semicolons and click OK button. This adds the
various jar files to the CLASSPATH environment variable, which are automatically scanned
for any missing classes by Java compiler during compilation and running.
10
Open any text editor (notepad.exe on Windows or vi or some other editor in Unix) and type the
following code without the preceding numbers and space.
1 import java.lang.*; // Import statement(s) here
2 public class HelloWorld// class declaration
3 {
// class block begin
4 public static void main(String args[]) // main method
5 { // main block begin
6 System.out.println(“Hello World”); // output
7 } // main block end
8 } // class block end
Save this file at a convenient location as “HelloWorld.java”. For convenience create a folder
for all the java files say at “D:\javacode” on Windows or “./javacode” in Unix platform.Note
that the class name should be same as file name (with a .java extension) always.
Though the program takes only a few lines of code, it provides an insight into the Java program.
The 1stline is an import statement that instructs the compiler to add code from all library files
from the package java.lang. This java.lang package is automatically imported and need not be
explicitly imported. This is only for illustration purpose and in real programs it is never used.
More details on packages will be given later.
The 2nd line declares a new class called “HelloWorld” with public scope.
The 3rd and 8th lines declare a block of code within which the main method is written.
The 4th line declares the standard main method. This should be declared as public static void
method with an array of strings as parameters. Here the parameter name is taken as “args”
arbitrarily.
Lines 5 and 7 declare the block for the method “main”.
Line 6 uses the println method of the “out” object declared inside the built-in System class.
This outputs the string given as parameter, which is “Hello World” in this case. The System.out
object generally refers the standard output device (screen).
Additionally comments can be added anywhere in the document using either // (line comments),
“/* comment here */” (multiline block comment) or “/** comments here */ (multiline document
comment). These comments are ignored during compile time. All the text after the // to the end
of that line are ignored in case of line comments or all the content between /* and */ is ignored
in case of block or document comments.
11
Observe that the code is indented to make each block clearly identified. Java removes all
unnecessary spaces and tabs before compiling the code. This indentation is important for
readability of the code which in turn improves maintainability of the code.
The name of the file should be the name of the class including the case with an extension of
“.java” in lower case. Note that file names are case insensitive in Windows where as they may
be case sensitive in other operating systems.
Now open a command window (by running cmd in Windows or by firing a console session in
Unix systems). Move to the folder where the file is stored with cd command. For example, on
windows issue the following two command if the folder of the java file is “D:\javacode”.
D:
cdjavacode
Now the command prompt changes to (D:\javacode>) from where the program is run.
Run the compiler on HelloWorld.java with the following command:
javac HelloWorld.java
If there are no errors, the HelloWorld.class file will be generated in the same folder. If there
are errors (most likely some kind of typo error), it shows the error along with line number and
so correct it in the Java file with text editor and rerun the javac command.
Once the class file (ByteCode) is generated, it is ready to be run with the interpreter under
JVM. This is done with the java command.
javaHelloWorld.class
If everything goes well, the output is printed on the screen. If any change is made to the source
code, the javac and java commands should be repeated.
Separators: There are certain characters which are used as separators in Java.
( ) Parenthesis: Used to contain list of parameters and to change the precedence in expressions.
[ ] Brackets: Used to declare array type and to access an element in an array.
{ } Braces: Used to define a block of code.
; Semicolon: Used to separate statements or statement terminator.
, Comma: Separates consecutive identifiers and chains statements.
White spaces: The tab, space, newline and carriage return characters are treated as white space
characters.
Java program that reads input and prints output
In the previous example, there is no input required and only there is an output statement
(System.out.println). However, in many cases a program requires some input from the user.
The input can be from various devices like keyboard, file, network etc.. In the next example
We consider reading input from keyboard and shows an output to the screen. The standard
input device (keyboard in this case) is accessed by the built-in System.in object. As was
mentioned earlier, the import of java.lang.* is omitted since it is automatically imported.
Consider the following example that reads a name from the keyboard and prints a hello message.
The keyboard is generally attached to an input stream and the methods from the stream are
used to get input from keyboard. The easiest way is to use a scanner object which is defined in
java.util package. Hence, the java.util.Scanner is imported first and then it is instantiated with
the System.in as its input. The Scanner class has methods for reading various data types which
12 are given below:
intnextInt() Returns the next token as an int.
float nextFloat() Returns the next token as a float.
double nextDouble() Returns the next token as a long.
String next() Returns the next token as a string terminated by a blank.
String nextLine() Returns the rest of the current line, excluding any line separator at the
end.
The next program reads a name and salary from the keyboard and shows the read values on the
screen.
importjava.util.Scanner;
publicclass Test{
publicstaticvoid main(String[] args)
{
Scanner scn = newScanner(System.in);
System.out.print(“Enter Name: “);
String name = scn.nextLine();
System.out.print(“Enter Salary: “);
intsalary = scn.nextInt();
scn.close(); // Close Scanner
System.out.println(
“Hello “ + name +
“ Your salary is: “+ salary);
}
}
In the above program, the Scanner class is imported first. Then the class Test is declared as
public. Then the main method is declared within the class. In the main, an object of type
Scanner is declared and instantiated with System.in as its input. Now there are a couple of
prompt messages followed by two scanner input methods (nextLine() and nextInt()) to read
required input from keyboard. The last print statement prints the information by adding the
string literals and the read values. The plus sign with strings will concatenate them.
Check Your Progress
b) Compare your answers with the one given at the end of the unit
3. What is Scanner?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
13
1.5 SUMMARY
This unit aims at introducing the Java language and explains how a program can be entered
into computer, compiled and run. It gives a brief history of Java language, its features which
made them the most popular language and a small introduction to the structure of a Java
program. The input can be from various devices like keyboard, file, network etc.. In the next
example We consider reading input from keyboard and shows an output to the screen. The
standard input device (keyboard in this case) is accessed by the built-in System.in object. As
was mentioned earlier, the import of java.lang.* is omitted since it is automatically imported.
Consider the following example that reads a name from the keyboard and prints a hello message.
The keyboard is generally attached to an input stream and the methods from the stream are
used to get input from keyboard. The easiest way is to use a scanner object which is defined in
java.util package. Hence, the java.util.Scanner is imported first and then it is instantiated with
the System.in as its input. The Scanner class has methods for reading various data types.
1.8.GLOSSARY
Class Method : A method that is invoked without reference to a particular
object. Class methods affect the class as a whole, not a
particular instance of the class.
Class Variable : A data item associated with a particular class as a whole—not
with particular instances of.
Classpath : An environmental variable which tells the Java virtual
machine Where to find the class libraries, including user-
defined class libraries
Declaration : A statement that establishes an identifier and associates
attributes with it, without reserving its storage (for data) or
providing the implementation (for methods).
Default : A Java keyword optionally used after all case conditions in
a switch statement. If all case conditions are not matched by
14
the value of the switch vari
UNIT-2: DATA TYPES
Contents
2.0 Objectives
2.1 Introduction
2.2 Java Data Types
2.3 Keywords and Type Conversions
2.4 Summary
2.5 Check your progress – Model Answers
2.6 Model Examination Questions
2.7 Glossary
2.0 OBJECTIVES
After studying this unit, you should be able to understand
• various data types available in Java
• how to declare variables and literals,
• casting of one data type to another and automatic conversion of data types
• some special characters defined in Java
2.1 INTRODUCTION
In Java, all the variables are objects except the primitive types. If any object is to be created, it
should be created with the “new” keyword and should be assigned to a variable (known as
handle). The syntax for the creation of objects is given in the example below, which defines an
object of type String and assigns it to a variable of type String named s along with an initial
value for the string.Stack and heap are two different areas in memory to store variables. The
heap space variables are available throughout the application while the stack space variables
are available only during that block. The heap space contains all objects that are created, while
stack space contains any reference to those objects and primitive values. A variable is a name
given to a storage area which a program can manipulate. Each variable in Java is associated
with a data type, which is required to determine the size required in memory. A variable name
should start with an alphabet (a-z, A-Z), a $ or an underscore (_) followed by any number of
alphabets or digits or underscores
Backspace \b 8
TAB \t 9
NUL character \0 0
newline \n 10
carriage control \r 13
double quote \” 34
single quote \’ 39
backslash \\ 92
Examples:
Stingstr = “Double quote (\”) is escaped”; // double quote is escaped
charch = ‘\’’; // single quote is escaped
String str=”10\t20\30\n”; // Tab separated data terminated by newline
TYPE CASTING
There are cases where one data type is to be converted into another data type (for example, an
integer into a float). There are two cases while converting from one data type to another viz.,
implicit automatic conversion (known as type conversion) and explicit conversion (know as
casting). The explicitly conversion is possible using the casting, which is done using the
following syntax.
(new data type) <data or variable of old type>
Consider the following code piece:
int x=10;
long y;
float z=12.34f;
y = x;// Legal since int is promoted as long (conversion)
y = (long)x;// Legal since int is promoted as long (casting)
x=y;// Illegal since long is demoted as int
x= (int) y;// Legal since explicit casting is used (casting)
x = (int) z; // Legal since explicit casting is used with data loss
It is important to note that there may be data loss during casting, since the data is narrowed
sometimes. Further, the two data types must be compatible for type conversion. For example, 19
the following is not possible and gives an error:
int t = (int)”10"; // String cannot be directly converted to int
TYPE CONVERSION
Automatic conversion of data type is taken care when a variable of one data type is assigned a
value of other data type following the rules that the two data types are compatible and the new
data type is large enough to hold all the old data without any loss of bits and bytes. The
promotion rules are given in the “Type Promotion” section.
Examples:
NtintVal = 10;
LonglongVal = intVal; // Automatic conversion from int to long (data widening)
FloatfloatVal = longVal; // Automatic conversion from long to float (promotion)
TYPE PROMOTION
Java tries to convert the data automatically into the other data type if it is a promotion where
the two data types are compatible and the new data type is larger than the original data type.
Following are automatically converted (promoted) by compiler
· From a byte to a short, an int, a long, a float, or a double
· From a short to an int, a long, a float, or a double
· From a char to an int, a long, a float, or a double
· From an int to a long, a float, or a double
· From a long to a float or a double
· From a float to a double
The promotion from byte ->short->int->long is also known as widening since the basic data
type is still integer. Similarly float->double is also widening since the basic data type is still a
float value. However, conversion like int->float is promotion since the basic data type itself is
changed where the nature of int and float are different. Following is a simple program that
shows different conversions:
public class TestCasting{
public static void main(String[] args){
bytebval = 10;
charcval = ‘A’;
floatfval = 1.23f;
intival = bval; // Ok, promotion
System.out.println(“ival: “ + ival);
ival = 300;
bval = (byte) ival; // Value = 300%256 = 44 (data lost)
System.out.println(“bval: “ + bval);
ival = (int) fval; // Value = 1 (data lost)
System.out.println(“ival: “ + ival);
20
ival = cval; // Value = 65 (ASCII Value of ‘A’)
System.out.println(“ival: “ + ival);
}
}
Conversion from String to Numeric value
Java provides methods for converting a string into its equivalent number with wrapper classes.
For example the Integer class provides a method called parseInt to convert a string to integer.
Similar methods are available for converting to appropriate data type in other wrapper classes
like Float, Double, Long etc.
Examples:
String x = “123”; // sequence of characters ‘1’,’2' and ‘3’
String y = “234.567”; // sequence of characters ‘2’,’3',’4',’.’,’5',’6' and ‘7’
int i = Integer.parseInt(x); // Converts String x to integer
long l = Long.parseLong(x); // Converts String x to long number
float f = Float.parseFloat(y); // Converts string y to float
double d = Double.parseDouble(y); // Converts y to double
Converting Numeric Value to String
Any numeric value can be converted to String in different ways:
Method 1: The value may be added to an empty string (“”) to promote it as string.
String p = “”+i;
String q = “”+d;
Method 2: The String.valueOf() method may be used.
String p = String.valueOf(i);
String q = String.valueOf(d);
Method 3: The Wrapper class’s toString() method may be used.
String p = Integer.toString(i);
String q = Integer.toString(d);
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
2. What is type casting?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
2.4 SUMMARY
Data type defines the values that a variable can take, for example if a variable has int data
type, it can only take integer values. In java we have two categories of data type: 1) Primitive
data types 2) Non-primitive data types – Arrays and Strings are non-primitive data types, we 21
will discuss them later in the coming tutorials. Here we will discuss primitive data types and
literals in Java.
Java is a statically typed language. A language is statically typed, if the data type of a variable
is known at compile time. This means that you must specify the type of the variable (Declare
the variable) before you can use it.n Java, we have eight primitive data types: boolean, char,
byte, short, int, long, float and double. Java developers included these data types to maintain
the portability of java as the size of these primitive data types do not change from one operating
system to another.The promotion from byte ->short->int->long is also known as widening
since the basic data type is still integer. Similarly float->double is also widening since the
basic data type is still a float value. However, conversion like int->float is promotion since the
basic data type itself is changed where the nature of int and float are different
2.7.GLOSSARY
Class Method : A method that is invoked without reference to a
particular object. Class methods affect the class as a
whole, not a particular instance of the class.
Class Variable : A data item associated with a particular class as a
whole—not with particular instances of.
Classpath : An environmental variable which tells the Java virtual
machine Where tofindthe class libraries, including user-
defined class libraries
Declaration : A statement that establishes an identifier and associates
attributes with it, without reserving its storage (for data)
or providing the implementation (for methods).
Default : A Java keyword optionally used after all case conditions
in a switch statement. If all case conditions are not
matched by the value of the switch vari
22
UNIT-3: JAVA OPERATORS AND CONTROL
STATEMENTS
Contents
3.0 Objectives
3.1 Introduction
3.2 Operators
3.3 Cotrol Statements
3.4 Summary
3.5 Check your progress Model Answers
3.6 Model Examination Questions
3.7 Glossary
3.0. OBJECTIVES
After studying this unit, you should be able to
• understand Java language program constructs and expressions
• explain howto write and execute Java programs with simple to medium complexity,
• describe various operators in Java
• understand various control statements in Java
3.1. INTRODUCTION
Java provides various operators for various purposes. These operators can be classified broadly
into 4 categories according to their usage. These four groups are explained below. These
operators are useful when more than one condition is to be tested simultaneously. For example,
if there are two subjects, and a student is declared passed only when he clears both subjects.
That is, the student has to pass in first subject AND has to pass in second subject. This condition
is called AND condition. Similarly there are cases where we will be satisfied with either of the
given two choices (for example, coffee or tea). This is called OR condition. Following is the
full list of the logical operators available in Java. Java provides a rich set of bitwise operators,
which can be used to manipulate individual bits of a byte. This is necessary in case we are
representing data with only one bit (for example, the status of a file can be indicated with just
one bit(for example, 1 means file already in use and 0 means it is not in use). Similarly, in
embedded systems which have very small memory generally in the order of hundreds of bytes
to a few kilobites (compared to the order of GBs in PCs), each bit is valuable and hence bit
operations are a must if the target program is for embedded systems. Java is originally targeted
to be an embedded platform and hence fully supports the bit operations. Following is the list of
bitwise operators:
3.2. OPERATORS
Java provides various operators for various purposes. These operators can be classified broadly
into 4 categories according to their usage. These four groups are explained below:
23
Mathematical operators:
Mathematical operators are required for representing or computing mathematical formulae.
The various mathematical operators that are available in Java are:
+ (addition) - (subtraction / unary minus) * (multiplication)
/(division) % (modulus) ++ (increment)
—(decrement) += , -=, *=, /=, %= (arithmetic assignment operators)
The unary operators are attached to a variable as +x, -y, +10, -20 etc.
The assignment operators are shortcuts. For example, x +=10 is equivalent to x =x+10.
Increment and decrement operators have double syntax. They can be used on either side of a
variable, which, then decides whether it is used as post-operator or pre-operator.
Consider, x=10 and y = x++
In this case y is assigned the value of x first, and then x is incremented (y=10 and x=11). Here
++ is used as post-increment operator. It is equivalent to two statements as y=x; x++;
Now consider x=10 and y= ++x, which means first increment x and then assign the value to y
(x=11 and y=11). Here ++ is used as pre-increment operator. It is equivalent to x++; y=x;
Other operators are used for normal arithmetic operations. The set of arithmetic assignment
operators is a short form of the actual operation. For example, x +=2 is equivalent to x = x+2.
Following is a full example for pre and post increment operators
// Demonstrates the ++ and — operators
public class AutoInc {
public static void main(String args[]) {
int i = 1;
System.out.println(“i : “ + i);
System.out.println(“++i : “ + ++i); // Preincrement
System.out.println(“i++ : “ + i++); // Postincrement
System.out.println(“i : “ + i);
System.out.println(“—i : “ + —i); // Predecrement
System.out.println(“i— : “ + i—); // Postdecrement
System.out.println(“i : “ + i);
}
}
The output for this program is:
i:1
++i : 2
i++ : 2
i:3
—i : 2
24
i— : 2
i:1
Relational Operators
There is a set of operators in Java, which are used to compare two operands and return a
boolean true or false. These are
== (Equal), != (not equal), < (less than), > (greater than) <= (less than or equal), >= (greater
than or equal).
x (operator) y returns either TRUE or FALSE depending on the comparison that is used. For
example, if x=10 and y=20, then x>y returns FALSE while, y >x returns TRUE.
Logical Operators
These operators are useful when more than one condition is to be tested simultaneously. For
example, if there are two subjects, and a student is declared passed only when he clears both
subjects. That is, the student has to pass in first subject AND has to pass in second subject.
This condition is called AND condition. Similarly there are cases where we will be satisfied
with either of the given two choices (for example, coffee or tea). This is called OR condition.
Following is the full list of the logical operators available in Java.
! logical NOT
|| Logical OR
&& Logical AND
Following program gives examples for various logical operators:
importjava.util.*;
public class Bool {
public static void main(String args[]) {
int i = 10;
int j = 20;
System.out.println(“i = “ + i);
System.out.println(“j = “ + j);
System.out.println(“i > j is “ + (i > j));
System.out.println(“i < j is “ + (i < j));
System.out.println(“i >= j is “ + (i >= j));
System.out.println(“i <= j is “ + (i <= j));
System.out.println(“i == j is “ + (i == j));
System.out.println(“i != j is “ + (i != j));
System.out.println(“(i < 10) && (j < 10) is “
+ ((i < 10) && (j < 10)) );
System.out.println(“(i < 10) || (j < 30) is “
+ ((i < 10) || (j < 30)));
}
} 25
Output listing looks like this:
i = 10
j = 20
i > j is false
i < j is true
i >= j is false
i <= j is true
i == j is false
i != j is true
(i< 10) && (j < 10) is false
(i< 10) || (j < 30) is true
Note that a boolean value is automatically converted to “true” or “false”if it is printed as
string. Variable i can be replaced with any other primitive data type except boolean. Be aware,
that the comparison of floating-point numbers for equality is not guaranteed due to the nature
of storing a floating point number. Even a tiniest fraction difference is still “not equal”.
Bitwise operators
Java provides a rich set of bitwise operators, which can be used to manipulate individual bits
of a byte. This is necessary in case we are representing data with only one bit (for example, the
status of a file can be indicated with just one bit(for example, 1 means file already in use and
0 means it is not in use). Similarly, in embedded systems which have very small memory
generally in the order of hundreds of bytes to a few kilobites (compared to the order of GBs in
PCs), each bit is valuable and hence bit operations are a must if the target program is for
embedded systems. Java is originally targeted to be an embedded platform and hence fully
supports the bit operations. Following is the list of bitwise operators.
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ exclusive OR (XOR)
>> Shift right
<< Shift left
>>> Shift right zero fill
&=, |=, ^=, >>=, <<=, >>>= Operate and then assign
The bitwise AND operator (&) results in 1 if both input bits are 1, otherwise results in 0. The
bitwise OR operator (|) results in 1 if either input bit is 1 andresults in 0 only if both input bits
are 0s. The bitwise XOR (^) results in 1 if only one of the input bits is 1, but not both. The
bitwise NOT (~) is a unary operator and invert the bit (1 is made 0 and 0 is made 1).
Bitwise operators can be clubbed with the = sign to operate and then assign: &=, |= and ^= are
all legitimate. (Since ~ is a unary operator itcannot be combined with the = sign.)
The boolean type is treated as a single bit value and hence it is treated differently. Bitwise
AND, OR and XOR can be performed but a bitwise NOT can’t be performed to prevent
duplication with the logical NOT. Using shift expressions is not allowed on boolean values
26
since there only one bit.
Shift operators
The shift operators can be used only on primitive integer types. These operators shift the bits
of the number to left(<<) or right (>>) by a number of bits given after the operator. When the
bits are shifted some bits are overflowed and some empty bits will be added. The overflowed
bits are ignored and empty bits are replaced with zeros. There is an unsigned right shift
operator (>>>) which shifts the sign bit also to the right which not available in C/C++.
Shifts can be combined with the equal sign (<<=,>>=,>>>= etc.). The left value is replaced by
the left value shifted by the right value. Here’s an example that demonstrates the use of all the
operators involving bits:
// Using the bitwise operators
public class BitManipulation {
public static void main(String args[]) {
int i = 59081716;
int j = 198850956;
intmaxpos = 2147483647;
intmaxneg = -2147483648;
printBinary(“-1”, -1);
printBinary(“+1”, +1);
printBinary(“maxpos”, maxpos);
printBinary(“maxneg”, maxneg);
printBinary(“i”, i);
printBinary(“~i”, ~i);
printBinary(“-i”, -i);
printBinary(“j”, j);
printBinary(“i & j”, i & j);
printBinary(“i | j”, i | j);
printBinary(“i ^ j”, i ^ j);
printBinary(“i << 5”, i << 5);
printBinary(“i >> 5”, i >> 5);
printBinary(“(~i) >> 5”, (~i) >> 5);
printBinary(“i >>> 5”, i >>> 5);
printBinary(“(~i) >>> 5”, (~i) >>> 5);
}
static void printBinary(String message, intval)
{System.out.print( message + “: “ + val + “ Binary: “);
String str = Integer.toBinaryString(val);
String x = “”;
for(int i=0; i<32-str.length(); i++) x += “0”;
27
x += str;
System.out.println(x);
}
}
Note the use of System.out.print() instead of System.out.println(). The print() method continues
on the same line until a println() or a newline (“\n”) is printed. The leftmost bit represents the
sign, 0 means positive and 1 means negative. To print the bits, the built-in function from
Integer class is used along with logic to fill zeros before the actual value. The output looks like
this:
-1: -1 Binary: 11111111111111111111111111111111
+1: 1 Binary: 00000000000000000000000000000001
maxpos: 2147483647 Binary: 01111111111111111111111111111111
maxneg: -2147483648 Binary: 10000000000000000000000000000000
i: 59081716 Binary: 00000011100001011000001111110100
~i: -59081717 Binary: 11111100011110100111110000001011
-i: -59081716 Binary: 11111100011110100111110000001100
j: 198850956 Binary: 00001011110110100011100110001100
i& j: 58720644 Binary: 00000011100000000000000110000100
i | j: 199212028 Binary: 00001011110111111011101111111100
i ^ j: 140491384 Binary: 00001000010111111011101001111000
i<< 5: 1890614912 Binary: 01110000101100000111111010000000
i>> 5: 1846303 Binary: 00000000000111000010110000011111
(~i) >> 5: -1846304 Binary: 11111111111000111101001111100000
i>>> 5: 1846303 Binary: 00000000000111000010110000011111
(~i) >>> 5: 132371424 Binary: 00000111111000111101001111100000
Ternary if-else operator (?:)
This operator is unusual because it has three operands. It is truly an operator because it produces
a value, unlike the ordinary if-else statement that you’ll see later in this chapter. The expression
is of the form
boolean-exp ?value0 : value1
If boolean-exp evaluates to true, value0 becomes the value produced by the operator. If boolean-
exp is false, value1 is produced by the operator.
Here’s an example:
Staticintmax(int x, int y)
{
return x > y ? x: y;
}
Another example that limits a value to a maximum of 10
28
int x = (y<10)?y:10; // either y or maximum 10
The code is more compact than using if else structure:
Staticintmax(intx, int y)
{
if (x > y)
returnx;
else
returny;
}
Though the ternary operator is used for efficiency reasons and for compact code, it is advised
to use the second method if clarity of the program is important.
The comma operator
The comma is used in C and C++ and Java as an operator for sequential evaluation. The sole
place that the comma operator is used in Java is in for loops. Comma operator can be used as
follows:
for(i=0,j=1; i<20; i++, j—) {….}
Here for loop expects only one initialization, where as two initializations are given here with
a comma operator. Similarly it expects one increment or decrement, but two operations are
given here (i++ and j—) with a comma operator.
String operator +
There’s one special usage of an operator in Java: the + operator can be used to concatenate
strings, as was seen in previous examples. The + operator seems normal for strings, though it
doesn’t fit with the traditional way that + is used. If an expression begins with a String, then all
operands that follow will be converted to strings automatically using their internal “toString()”
method.
int x = 0, y = 1, z = 2;
String sString = “x, y, z “;
System.out.println(sString + x + y + z);
Here, the Java compiler will convert x, y, and z into their String representations instead of
adding them together first.
Operator Precedence
Operator precedence determines how the given expression should be evaluated. For example,
10/2+3 may give 8 if the equation is evaluated as 10/2 and then add 3 to it. On the other hand,
if the equation is considered as 10 divided by (2+3), the answer is 2. In such cases, the compiler
first evaluates the operator that has higher precedence. The list of operators with precedence
from highest to lowest is as follows:
29
() []
++ — ~ !
* / %
+ -
>>>>><<
>>= <<=
== !=
&
^
|
&&
||
?:
= operator= (+=, *= , ...)
It is advised to use the parenthesis for safety in case of complex expressions to avoid wrong
interpretation by the compiler.
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
1. List the relational operators in Java?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
3.3. SUMMARY
This chapter introduces the data types and control structures available in Java. Data conversion
from one type to another type is explained along with promotion rules and precautions to be
taken to prevent possible data loss. Various examples are given for each control structure.The
goto keyword has been present in programming languages from the beginning which has its
genesis from assembly language (in the form of jump). “if condition A, then jump here, otherwise
jump there”. Although goto is a reserved word in Java, it is not used in the language; Java has
no gotobut it has a similar but restricted jump around statement in the form of named break
and continue statements. In java a lable can be declared as unique label name followed by a
colon, lSelector is an expression that produces an integer or string value. C/C++ doesn’t support
string as a selector and Java started supported it from version 5. The switch compares the
result of selector to each value defined in case statements. If it finds a match, the execution
starts at the corresponding statement (simple or compound).If no match occurs, the default
statement is executed.
39
3.5. MODEL EXAMINATION QUESTIONS
I. Answer the following questions in about 30 lines each
1. Write a java program that reads the percentage of marks and declares the grade following
the rule (Distinction: >=70%, First class: >= 60%, Second class: >= 50% and fail
otherwise)
2. Write a program that prints a triangle with stars from 1 to 5 using (a) for loop and (b)
while loop as shown below (stars must be centered vertically by calculating the space
required before the stars):
*
***
*****
3. Write a program that reads two names from keyboard and prints them alternatively for
10 times (if count is odd, print first name, otherwise print second name).
II. Answer the following questions in about 15 lines each
1. Write a program that reads a value and tells if it is an even or odd number.
2. Read 10 numbers from keyboard and print the maximum, minimum and average of
these numbers
3. Describe Bitwise operators with an example java program.
3.6. GLOSSARY
Class Method : A method that is invoked without reference to a
particular object. Class methods affect the class as a
whole, not a particular instance of the class.
Break : Exit from the loop
Continue : Skip the iteration which meets certain conditon
Operator Precedence : List the operators in the order of priority for evaluating
expressions.
String Operator : Print the values of numeric variables as characters
40
BLOCK - II
41
42
UNIT-4: INTRODUCTION TO CLASSES AND OBJECTS
Contents
4.0 Objectives
4.1 Introduction
4.2 Java classes and objects
4.3 Box and Unbox, Constructors
4.4 Garbage collection and Finalize Method
4.5 The Stack Class
4.6 Summary
4.7 Check your progress Model Answers
4.8 Model Examination Questions
4.9 Glossary
4.0. OBJECTIVES
After studying this unit, you should be able to
• Explain how classes are declared in Java and how to create objects of this class
• Descr9he some important implementations specific to object oriented programming
• Understand this keyword.
• The garbage collection feature of Java is also explained in this chapter.
4.1. INTRODUCTION
In object oriented programming, classes are the definition of an entity which contains data and
operations that can be performed with the data. This is unlike C which is procedural language
where data and methods to manipulate data are defined independently. When a class is defined,
it is like a blueprint for a design or a plan for a building. A class can hold two types of elements:
data members and method (function) members. Methods in classes have access to the object
data directly. The code of the method is shared among all objects of the same class but data
part is different for each object. A method is same as a function definition in C/C++. A member
has a name, parameters and a return type. For example, the Box class may contain methods to
access data or process and return data. In programming, when a variable is created, memory is
allocated and these must be destroyed to release the memory. Programmers know about the
importance of initialization, but often forget the importance of cleanup. In C or C++ this is
done by the use of free or delete. Java has the garbage collector to reclaim the memory of
objects that are no longer used. The garbagecollector is automatically initiated by the runtime
environment whenever it feels apt. Since the finalize method is called just before garbage
collector is run, it may not be called if garbage collector is not run because there is plenty of
memory available making garbage collection unnecessary.
/**
* Method that initializes the data
*@param h height of the box
48 *@param w Width of the box
*@param d Depth of the box
*/
public void setSize(int h, int w, int d){
height= h;
width = w;
depth = d;
}
// Returns the volume of the rectangle
public int getVolume() {
return length*width*height;
}
// Main method that tests the class
public static void main(String args[]){
Box b1=new Box();// Create Box object and assign it to b1
Box b2 = new Box();
b2.setSize(10,20,5);
System.out.println(“B1 Volume: “ + b1.getVolume());
System.out.println(“B2 Volume: “ + b2.getVolume());
}
}
Now, when an object is created by the syntax “new Box(); “, storage is allocated and the
constructor is called. It is guaranteed that the object will be properly initialized (height, width
and depth to 5 each) before anything is done with the object.
Like any method, the constructor can have arguments to specify how an object is created.
These arguments provide a way to initialize an object. For example, if the Box has a constructor
that takes height, width and height as arguments/parameters, a Box object can be created as
shown in the example.
Constructor with parameters (arguments)
Here’s the Box class that implements constructor with arguments:
/**
* This class shows the use of constructor with arguments
*/
public class Box {
int width, height, depth; // Variables to hold data
/**
* Constructor with parameters
*@param h Height of the box
49
*@param w Width of the box
*@param d Depth of the box
*/
public Box(int h, int w, int d) {
width = w;
height= h;
depth = d;
}
// Returns the volume of the rectangle
public int getVolume() {
return length*width*height;
}
// Main method that tests the class
public static void main(String args[])
{
Box b1 = new Box (5,10,15); // Create Box object b1
Box b2 = new Box (2,3,4); // Create Box b2
System.out.println(“B1 Volume: “ + b1.getVolume());
System.out.println(“B2 Volume: “ + b2.getVolume());
}
}
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
2. What is constructor?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
4.6.SUMMARY
This chapter introduces the concept of classes, objects, data and member elements, constructor
etc. The method and constructor overloading is illustrated with simple examples. Java’s unique
garbage collection feature and its associated finalize method are also explained.To guaranty
that a variable is initialized, an automatic function, which will be run immediately when an
object is created, should be written. In Java, the class designer can guarantee initialization of
every object by providing a special method called a constructor. If a class has a constructor,
Java automatically calls that constructor when an object is created, before users can even get
their hands on it. So initialization is guaranteed. The name of the constructor is the same as the
name of the class. It makes sense that such a method will be called automatically on
initialization.Programmers know about the importance of initialization, but often forget the
importance of cleanup. In C or C++ this is done by the use of free or delete. Java has the
garbage collector to reclaim the memory of objects that are no longer used. The garbage collector
is automatically initiated by the runtime environment whenever it feels apt. Since the finalize
method is called just before garbage collector is run, it may not be called if garbage collector
is not run because there is plenty of memory available making garbage collection unnecessary.
Java provides a static method
54
4.7. CHECK YOUR PROGRESS MODEL ANSWERS
1. If a local variable exists in a method with same name as that of an instance variable,
then the local variable hides or shadows the instance variable
2. Method whose name is the class name without return type that guarantees data members.
3. . The Stack is a “Last In First Out” mechanism, just like a stack of plates arranged for a
buffet.
4.9. GLOSSARY
Constructor : Method whose name is the class name without return type
that guarantees data members.
Box and Unbox : Primitive to wrpper and vice versa
Hiding a variable : If a local variable exists in a method with same name as that
of an instance variable, then the local variable hides or
shadows the instance variable
Garbage : All the memory allocated for unused objects and variables.
Instance Variable : Variable which is instantiated for each object of a class.
55
UNIT-5: ADDITIONAL FEATURES OF JAVA OOPs
Contents
5.0 Objectives
5.1 Introduction
5.2 Overloading methods and constructors, Access controls
5.3 The final method, Static Variables and Methods
5.4 Nested and inner classes, String class
5.5 Command line arguments with vararg
5.6 Summary
5.7 Check your progress Model Answers
5.8 Model Examination Questions
5.9 Glossary
5.0. OBJECTIVES
After studying this unit, you should be able to
• Explain object oriented programming concepts like overloading, access controls.
• Describe static classes, static members and methods
• Understandinner and anonymous classes.
• Gain knowledge on command line arguments
5.1 INTRODUCTION
In many cases it is required to use the same function name for different purposes to maintain
intuitive naming convention. For example, the method name ‘add’ is apt for adding integers,
real numbers or other data types.Access control to variables and members of a class is one of
the key features of any OOP as it results in more robust and safe code. For example in the stack
class the array defined to store values is supposed to be accessed or modified only by its two
methods push and pop where the top is properly modified. If a user directly accesses the ‘top’
variable and sets its value say to 5 when there is only one value on stack, the program behaves
oddly by showing “stack full” message. To avoid this danger, the user should not be permitted
to access the variables array and top. Object oriented programming encourages the extension
of an existing class by the user to provide additional or different functionality. In some cases
the designer of a class may feel that a specific method should not be modified any further. In
such a case, the method may be declared as ‘final’ in Java. Once a method is made final, its
derived classes cannot modify or override this method
/**
* No parameter Constructor
*/
public Box() {
width = 5;
height= 5;
depth = 5;
}
/**
* Constructor with parameters (overloaded)
*@param h Height of the box
*@param w Width of the box
*@param d Depth of the box
*/
public Box(int h, int w, int d) {
width = w;
height= h;
depth = d;
}
57
/**
* Returns the volume of the rectangle
*/
public int getVolume() {
return length*width*height;
}
/**
* This method sets the values and returns volume
*/
public int getVolume(int h, int w, int d) {
height = h;
width = w;
depth = d;
return h*w*d;
}
66
public static void main(String args[]){
System.out.println(“You have sent “+ args.length +
“ arguments and they are: “);
for (int i=0;i<args.length;i++){
System.out.println(i+”: “ + args[i]);
}
}
}
The result of the same program for two different argument lists is shown below:
java Test one two three
You have sent 3 arguments and they are:
0: one
1: two
2: three
java Test one two three four five six seven
You have sent 7 arguments and they are:
0: one
1: two
2: three
3: four
4: five
5: six
6: seven
Methods with Variable Arguments (Varargs) in Java
Since JDK 5, Java has included support for methods with variable arguments just like variable
arguments to main method. A variable-length argument is specified by three periods(…) known
as ellipses. For Example,
public static void sum(int ... a) { // code } takes any number of integers as arguments.
Internally the compiler takes these arguments as an array of int values. Following Java program
demonstrates the use of varargs
class Test{
static void sum(int ...a){
int sum = 0;
System.out.println(“Number of arguments: “ + a.length);
// using for each loop to get sum of contents of a
for (int i : a){
sum +=i;
}
67
System.out.println(“Sum: “ + sum);
}
// Driver code
public static void main(String args[]){
sum(); // no parameter
sum(100, 200); // two parameters
sum(1, 2, 3, 4, 5); // five parameters
}
}
Output:
Number of arguments: 0
Sum: 0
Number of arguments: 2
Sum: 300
Number of arguments: 5
Sum: 15
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
4. What do you mean by method VARARGS?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
5.6. SUMMARY
This chapter introduced the basic concepts of classes and objects and some features of Java
language like variable arguments to main and user defined methods. An introduction to the
String class is given. Command line arguments are useful when some data is to be supplied to
the program when the program is run. This is done by giving the arguments along with the
command separated by spaces. Java takes the arguments that are passed by the user as an array
of strings which is passed to the main(). That is the reason for declaring the main with String
array as a parameter. These arguments can be processed by accessing the parameter to main.
Since JDK 5, Java has included support for methods with variable arguments just like variable
arguments to main method. A variable-length argument is specified by three periods(…) known
as ellipses. For Example,public static void sum(int ... a) { // code } takes any number of
integers as arguments. Internally the compiler takes these arguments as an array of int values.
Following Java program demonstrates the use of varargs
68
5.7. CHECK YOUR PROGRESS MODEL ANSWERS
1. Public, private, default, protected
2. It initializes static variables
3. string.length()
4. Any method can variable arguments using syntax data type ….. arg_name
5.9. GLOSSARY
Access Control : Control the how a member of class is accessible in
side,out side of the class.
Inner Class : A class whihch is defined inside another class
Static Variable : A variable which is shared by all methods with class
scope or object scope
Final Mehtod : A static method which can’t be modified
compareTo(String s) : Compares two strings and returns an integer
69
UNIT-6: INHERITANCE AND ABSTRACT CLASSES
Contents
6.0 Objectives
6.1 Introduction
6.2 Inheritance, Super Class and Subclass
6.3 Abstract Classes and Methods
6.4 Summary
6.5 Check your progress Model Answers
6.6 Model Examination Questions
6.7 Glossary
6.0. OBJECTIVES
After studying this unit, you should be able to
• Understand the concept of inheritance
6.1. INTRODUCTION
Inheritance is the feature that makes software more reusable. When a class is developed for a
particular application, and there is a need to develop a similar class with minor modifications,
inheritance comes handy. When a class is inherited from another, some or all the methods of
the base class can be retained or overridden or some extra methods can be added. That means,
without editing the source code of the original class, one can enhance the capabilities of the
class by deriving a new class from the existing class. The super is a keyword in java which
references parent class object. It is generally used to access the specific variable of a superclass.
A special function called super() also exists, which calls the constructor of an object’s superclass.
The super() function should be used only in the subclass constructors and it should be the first
line of that constructor. A reference (variable of a class type) to an object of a subclass can be
used just like any reference without inheritance. However, a reference of superclass (base
class) type can also be used to refer a subclass. For example, consider the above example
given in the multi level hierarchy. Class A is the parent of B which is the parent of C. Normally
if objects of type A, B and C are to be created, the same data type variables are declared with
new
VideoCD
Movie
77
6.3. ABSTRACT CLASSES AND METHODS
Abstract Method
Consider a simple class called Shape with a, b, c as data members which can store the dimensions
of different shapes. For example, a rectangle stores length and breadth in ‘a’ and ‘b’. A triangle
stores its sides in ‘a’, ‘b’ and ‘c’. A circle just stores the radius in ‘c’. Now if area of the shape
is to be found, there is no generic formula for all these three shapes. The formula will vary
with the shape and hence, while designing the Shape class, there is no way to implement the
method area() meaningfully. The subclasses of Shape must implement their own version of
area() method properly.
Suppose that a program uses a base class and calls the area() method expecting that the subclass
has implemented it, where as the subclass actually doesn’t implement it. This gives an error
during runtime. This situation can be avoided by enforcing or compelling the subclass to
implement the method area(). This is done using the abstract method. An abstract method is
declared by prefixing the keyword abstract before the method signature and removing the
body of the method i.e., just declaring the signature.
access_modifier abstract methodName(parameters …);
The access_modifier can be empty (default), private, protected or public. A non-abstract child
class inherits the abstract method and must define a non-abstract method that matches the
abstract method.
Abstract Class
A class can be declared just by prefixing the keyword abstract before the class definition.
Once, declared as abstract, objects of that type cannot be created. If any method is declared as
abstract in a class, the class must be declared as abstract since there is no code for the abstract
method. The class declaration in such a case must also be preceded by abstract keyword.
Access modifiers such as public can be placed before abstract. Even though it cannot be
instantiated, an abstract class can define methods and variables that children classes inherit.
access_modifier abstract class ClassName{
. . . . . // definitions of methods and variables with at least
// one abstract method
}
Consider the Test class that tests Abstract classes of type Shape:
public class Test{
public static void main(String[] args){
Shape a = new Rect(10,20);
Shape b = new Triangle(10,20,30);
Shape c = new Circle(10);
System.out.println(“Area of Rect: “ + a.area());
System.out.println(“Area of Triangle: “ + b.area());
System.out.println(“Area of Circle: “ + c.area());
}
78 }
abstract class Shape{
double a,b,c;
Shape(){
a = b = c = 0.0; // Chained assignment
}
public Shape(double val1, double val2, double val3)
{
a=val1;
b=val2;
c=val3;
}
abstract double area();
}
class Rect extends Shape{
public Rect(double width, double height){
super(width, height, 0); // 0 will be promoted to double
}
public double area(){
return a*b;
}
}
class Triangle extends Shape{
public Triangle(double side1, double side2, double angle){
super(side1, side2, angle);
}
public double area(){
return (a*b*Math.sin(c*Math.PI/180)/2.0);
}
}
class Circle extends Shape
{
public Circle(double radius) {
super(0f,0f,radius);
}
public double area(){
79
return (double)(Math.PI * c*c);//
}
}
In the above example, a test class is defined with three references to the abstract Shape class,
which is assigned to a Rect, Triangle and Circle respectively. The Shape class is declared
abstract since it defines at least one abstract method (only one in this case). The respective
classes implement the area method appropriately.
Observe that all the subclasses of class Shape should implement all the abstract methods of the
Shape class (in this case there is only one abstract method).
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
2. How do you define abstract base class?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
6.4. SUMMARY
This chapter introduces the important concept of object oriented program called inheritance,
which allows reuse of classes by extending the functionality. Method overriding, importance
of abstract methods and classes is also highlighted. Sometimes, for security or design reasons,
a class should not be sub classed (extended) or a method within a class should not be overridden.
In Java, either of these goals can be achieved by declaring the class or the method as final. Any
class or method can be made final by adding a keyword “final” in front of its definition. A
class, or a method or a variable, once it is declared as a final, it cannot be overridden, or
altered. Many of the Java standard methods are final and hence they cannot be modified.A
class can be declared just by prefixing the keyword abstract before the class definition. Once,
declared as abstract, objects of that type cannot be created. If any method is declared as abstract
in a class, the class must be declared as abstract since there is no code for the abstract method.
The class declaration in such a case must also be preceded by abstract keyword. Access modifiers
such as public can be placed before abstract. Even though it cannot be instantiated, an abstract
class can define methods and variables that children classes inherit.
6.7. GLOSSARY
Inheritance : Is OOPs concept using which reusability, extensibility
is implemented.
Multilevel Inheritance : Heirarchy of nase class and derived classes
Super() : Is a function which calls base class constructor.
Abstract Method : A method that will be just declared in abstract base class.
Dynamic Method Dispatching: is a mechanism by which Java can select proper method
based on the object’s data type using a reference of its
base (super) class.
81
82
BLOCK - III
83
84
UNIT-7: PACKAGES AND INTERFACES
Contents
7.0 Objectives
7.1 Introduction
7.2 Packages In Java
7.3 Interfaces In Java
7.4 Summary
7.5 Check your progress Model Answers
7.6 Model Examination Questions
7.7 Glossary
7.0. OBJECTIVES
After studying this unit, you should be able to
• Understand how to build packages that can be used anywhere.
• Describe foundation of interfaces.
• Explain how to use existing packages..
• Understand using interfacesin GUI programming.
7.1. INTRODUCTION
In any programming language, intuitive names should be given for easy identification and
understanding of code without any clash of names. For methods it works with method
overloading. But class names cannot be overloaded. If the name clash in classes is envisaged,
the programmer must somehow limit the scope of the variables (namesapce) where a package
comes handy. Package in Java is a way to organize classes into groups and subgroups. Internally
packages are organized into folders with the same names used in packages. In java, package is
a unit where one can pack various classes together. For example, “io” is a package in java
which contains various input/output related classes. Now, for example, the class name
“DataInputStream” becomes something like “java.io.DataInputStream”. It is a good practice
to use a package for the programs, though java takes the current folder as default package if no
package statement appears at the top. An interface declared within another class or interface is
known as nested interface. The nested interfaces are used to group related interfaces. The
nested interface cannot be accessed directly. Nested interface must be public if it is declared
inside the interface but it can have any access modifier if declared within the class. Since Java
8, interfaces can have a default implementation of an abstract method, which was not possible
with earlier versions. Consider that a class X used an interface Y and therefore has implemented
the methods declared in Y. Now if a new method is to be added in the interface Y for any
enhancement, then X should also implement it which was not done so far.
87
Access Protection
Package controls the access of how the components are bundled together into a cohesive library
unit. Access specifiers are affected by whether a class is in the same package or in a separate
package. Following table gives the possible access levels with respect to packages:
private default protected public
same class yes yes yes yes
same package subclass no yes yes yes
same package non-subclass no yes yes yes
different package subclass no no yes yes
different package non-subclass no no no yes
Importing Packages:
A package is what becomes available when the import keyword is used like:
import java.util.*;
This brings in entire utility library that is a standard part of Java. If a specific class from this
package is required (say a class called Hashtable), it can be imported exclusively with “import
java.util.Hashtable;” statement in which case no other class in java.util is available. The
programmer may directly refer to it in the program with its fully qualified name
java.util.Hashtable without the import statement. However, if it is referred to it with full name,
every time when the class is used, full name must be used which is cumbersome. If the package
is imported, it can be referred simply as Hashtable.
When a package is imported as a whole using * (as in java.util.*), Java compiler is smart
enough to include only the used classes from the package into the compilation unit thus
optimizing the byte code. Hence using “import java.util.*;” and “import java.util.Hashtable;”
have the same output if Hashtable is the only class that is used. The only overhead is the
compilation time, which takes a small extra time in searching for used classes which is negligible
considering the power of the machines today.
Check Your Progress
• A variable of interface type can be used to reference the implemented class type object
just like a base class variable can reference a subclass type object
Differences between interface and class
• Interface cannot be instantiated.
• Interface does not have any constructors.
• All of the methods in an interface are abstract.
• All data members must be static final.
• An interface cannot be extended by classes. Only another interface can extend it.
• A class can implement multiple interfaces.
Defining an Interface
The definition of an interface looks somewhat like a class definition. But no objects can be
constructed from it. Objects can be constructed from a class that implements an interface. The
definition of an interface is as below:
interface InterfaceName{
constant definitions
method declarations (without implementations)
}
A method declaration is simply an access modifier, return type, and method signature followed
by a semicolon.
Here is an example interface definition:
interface MyInterface{
public static final int aConstant = 32; // constant
public static final double pi = 3.14159; // Constant
public void methodA( int x ); // Method declaration
double methodB(); // Method declaration
}
A method in an interface cannot be made private. A method in an interface is public by default.
In the example methodB is public even though it does not say so. A constant is automatically
taken as static if ‘static’ keyword is missing in the definition.
Variables in Interfaces 89
An interface is a collection of constants and method declarations only. It cannot contain variables
like normal classes. However, constants can be declared in the interfaces, but must be declared
as static and final. Also by default, the variables and methods that are defined are public. It
cannot contain other access modifiers.
Implementing Interfaces
A class definition that implements an interface must specifically use the keyword “implements”
in its definition as below. Note that a class always extends just one parent but may implement
several interfaces.
class SomeClass extends SomeParent implements interfaceName{
………
}
Following rules are applicable for interfaces:
• A class that implements an interface must implement each method in the interface.
• Each method must be public (this happens by default).
• Constants from the interface can be used as if they had been defined in the class.
• Constants should not be redefined in the class.
• Multiple interfaces can be given with comma separator.
Nested Interfaces
An interface declared within another class or interface is known as nested interface. The nested
interfaces are used to group related interfaces. The nested interface cannot be accessed directly.
Nested interface must be public if it is declared inside the interface but it can have any access
modifier if declared within the class.
Syntax of nested interface which is declared within the interface
interface ifaceName{
...
interface nestedIfaceName{
...
}
}
Syntax of nested interface which is declared within the class
class class_name{
...
interface nestedIfaceName{
...
}
}
Example of nested interface which is declared within the interface:
interface Display{
90
void show();
// Nested Interface
interface Message{
void msg();
}
}
// Now define the main class that implements both
public class Test implements Display, Display.Message{
public void show(){
System.out.println(“Hello display interface”);
}
public void msg(){
System.out.println(“Hello nested message interface”);
}
95
7.7. GLOSSARY
Interface : Contains constants, method declaratons, default
methods.
Constant : Final variables such as pi=3.1414.
Package : Container which contains classes and interfaces to
reuse names.
Defualt Method : A method that is implemented in an interface.
Nested Interface : Interface with in another interface.
96
UNIT-8: JAVA EXCEPTION HANDLING
Contents
8.0 Objectives
8.1 Introduction
8.2 Java Exception Handling frame work
8.3 Chained exceptions
8.4. Exceptions added in Java 8
8.5 Summary
8.6 Check your progress Model Answers
8.7 Model Examination Questions
8.8 Glossary
8.0. OBJECTIVES
After studying this unit, you should be able to
• Understand the Java exception handling framework.
• Describegracefully using this framework.
• Explain how to handle different types of exceptions..
• Understand newly addedexceptins in Java 8.
8.1. INTRODUCTION
An exception is an abnormal condition that arises in a code sequence during runtime. A program
often encounters problems as it executes such as trouble reading data, illegal characters in the
data, or an array index might go out of bounds etc. Java Errors and Exceptions enable the
programmer deal with such problems. Java provides a neat way to recovers from errors and
keeps on running the program by handling these error conditions gracefully. This is very
important as far as a program is concerned since the program should be robust and should not
crash when the user makes an error. Java classifies these kinds of errors into two types, viz.
exceptions and errors. The difference between error and exception in Java is that exceptions
can be handled at the run time whereas errors cannot be handled. An Error is a critical condition
that cannot be handled by the user most of the time and the program is terminated eventually
97
Java classifies these kinds of errors into two types, viz. exceptions and errors. The difference
between error and exception in Java is that exceptions can be handled at the run time whereas
errors cannot be handled. An Error is a critical condition that cannot be handled by the user
most of the time and the program is terminated eventually. The rest of this chapter discusses
how to handle the Exceptions in Java programs.
Exception Class Hierarchy
Class Exception and class Error both descend from the class Throwable which in turn is descend
from the Object. The Error class is final and nothing can be done with this since these are
catastrophic failures. The Exception class is further extended with RuntimeException. The
following diagram represents the class hierarchy implemented by Java.
Object
Throwable
Error Exception
Runtime
Exception
Figure 8.1
Often the problem is caused by circumstances outside the control of the program, for example,
bad user input or a bad sector in a disk file or a network failure etc. A Java program provides
five statements to manage the exceptions which are ‘try’, ‘catch’, ‘throws’, ‘throwable’ and
‘finally’.
When an exception occurs, the Java virtual machine creates an object of the class Exception,
which holds information about the problem like line number, location within that line, type of
error, statement that caused the error etc. The Exception object is used to recover from the
problem.
Broadly the exception framework can be defined as follows:
The code that may generate any error is enclosed in a try block (try{ …}). If an error arises
anywhere within the block, the execution is stopped there and directly proceeds to the catch
block (catch(Exception e) {…}). The code in the exception block is executed where the
programmer can take corrective measures or gracefully exits from the program. If the user
wishes to generate a custom Exception and wish to throw it, the throw can be used. If the user
wishes to move out of the method on exception, the method can be declared as throwable.
Consider the following example that reads a number and prints it.
import java.util.Scanner;
public class Test{
public static void main(String[] args){
Scanner scn = new Scanner(System.in);
System.out.print(“Enter a Number: “);
99
Java’s Built-in Exceptions
Java has a rich set of built-in exceptions. Some of them are given below:
Unchecked Exception Meaning
ArithmeticException Arithmetic Errors such as divided by zero
ArrayIndexOutOfBounds Array index is outside the size of the array
ClassCastException Invalid Cast operation
IlligalArgumentException Wrong arguments in calling a method
IlligalThreadStateException Operation is not compatible with current thread state
IndexOutOfBoundsException Array index is out of bound
NullPointerException Invalid use of null pointer for reference
NumberFormatException Invalid conversion of a string to a number
SecurityException violation of security
StringIndexOutOfBounds Attempt to index outside the bounds of a string
UnsupportedOperationException Unsupported operation was encountered
Note the multiple catch blocks are allowed in Java which is explained shortly. After the catch{}
block is executed, execution continues with the statement that follows the catch{} block
(Execution does not return to the try{} block.).
Nested Try Catch
Nesting of try catch blocks is allowed in Java where the inner ‘try’ block uses its own ‘catch’
block first and if it doesn’t match the exception type, then it goes to the catch block of outer
try. The general syntax of a nested try catch is as follows:
....
try{
outer try block statement(s);
...
try{
inner try block statement(s);
...
}
catch(Exception e){
inner catch block statement(s)
}
outer try block statement(s);
...
}
catch(Exception e){
outer catch block statement(s)
}
....
Multiple Catch Blocks
There can be zero or more catch blocks for a single try block. The compiler will choose the
appropriate block depending on the exception type. If there is no match found in the catch
block(s), the default system exception handler will take control which prints the stack trace
and then terminates the program. Following is the modified code of the above example with
try catch blocks added to handle the errors:
public class Test{
public static void main(String[] args){
101
try{
int a[]=new int[10];
int x = 0;
String s=null;
//System.out.println(a[100]);//1.Generates Exception
//System.out.println(10/x);//2.Generates Exception
System.out.println(s.toUpperCase());//3.Generates Exception
}
catch(ArithmeticException e){
System.out.println(“ArithmeticException occured”);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println(“ArrayIndexOutOfBoundsException occured”);
}
catch(Exception e){
e.printStackTrace(System.out);
}
System.out.println(“End of code”);
}
}
In the above example, there are three System.out.println statements, each of which is designed
to generate a different kind of exception which are an ArrayIndexOutOfBounds exception, an
Arithemetic exception and a NullPointer exception respectively. Comment any two lines and
the third line generates that particular exception.
There are some important points to observe here. The first is that the program doesn’t have a
catch block explicitly for the NullPointerException type. However, Exception is the base class
for all the exceptions and matches any kind of exception. Hence, any unmatched exception
will be automatically finds a match here and this block will be executed.
Hence, if the catch(Exception e) block is placed as the first catch block, it matches everything
and no other catch block is executed. Hence the generic catch block must be the last.
The other statement that is used is the “e.printStackTrace(Stream s)” in the last catch block.
This is a built-in method in the Exception class that prints possible elaborated error message
on the given stream (in this case the System.out which defaults to screen).
User Defined Exceptions with Throw and Throws
User defined exceptions can be created by extending the Exception built-in class of Java. The
user just needs to override the toString() method apart from any initialization work. Following
example gives an idea of how a user defined exception can be created.
// User defined Exception class
Class MyException extends Exception{
102
String msg;
MyException (String message){
this.msg = new String (message);
}
public String toString(){
return “Error: “ + msg;
}
}
// Class that uses the user defined exception
class ExceptionDemo{
static square(int a) throws MyException{
if (a < 0) throw new MyException(“Negative Value” +
“cannot be given here”);
System.out.println(“Square of “ + a + “= “ + a*a “);
}
public static void main (String args[]){
try{
square(1);
square(-1); // Generates an error
}
catch (MyException e){
System.out.println(“Exception caught: “ + e); }
}
}
In the above example, when a negative number is passed to method ‘square()’, it returns an
exception which is handled by catch block in the main. The throws keyword after any method
indicates the compiler that this method may generate the exception of given type and must be
caught when this method is called. The throw keyword is used to manually generate and trigger
an exception. For example, to generate an exception even though there is no error, a statement
like “throw new ArithmeticException();” may be added anywhere in the program. When the
execution reaches here, the exception is generated and the program will be terminated, if not
handled properly.
The Finally{} Block
If an exception occurs in a program, it is immediately thrown to the method that called it
which may terminate the program or goes to the catch block. In some cases a resource like a
file may be opened and if an exception occurs, the resource might not be closed properly,
leaving the resource unusable by others or may corrupt it. Similar clean up may be needed in
many cases, where graceful exit is required. In such case, after all the catch blocks, a finally{}
block may be used which ensures that statements within that block will always run, no matter
how the try{} block was exited. Here is the try/catch/finally{} structure.
103
try{
// statements, some of which might throw an exception
}
catch(ExceptionType_1 e){
// statements to handle this type of exception
}
.... // more catch blocks
finally{
// statements which will execute no matter
// how the try block was exited.
}
// Statements following the structure
There can only be one finally{} block, and it must follow the catch{} blocks if any. If the try{}
block exits with or without exceptions, the control goes to the catch block and catch block
takes care that the finally{} block is executed before it takes an action. The finally block will
not be run if a system error occurs which cannot continue the program in any way (like a stack
overflow) or the catch block explicitly terminates the program with “System.exit()” statement.
Following example illustrates the finally block.
public class Test
{
public static void main(String[] args)
{
Try
{
//System.out.println(10/0);// ArithmeticException
}
catch(NullPointerException e) {
// do nothing
}
finally {
System.out.println(“End of code”);
}
System.out.println(“Last Line”);
}
}
In this example, the main throws an ArithmeticException, which is not caught by the program.
Hence, the default system handler will intervene and terminates the program. However, before
it terminates the program, the finally block is executed and the last line will not be executed
104
since it is outside the finally block. The output will be like this:
End of code
Exception in thread “main” java.lang.NullPointerException
at Test.main(Test.java:9)
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
1. What is an exception?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
106
FileOutputStream fout= new FileOutputStream(“outfile.txt”);
)
{
int i;
do{
i=fin.read(); // Reads one byte from fin
if(i!= -1) {
fout.write(i); // If not end of file (-1), write it
}
}while(i != -1);
System.out.println(“File Copied”);
}
catch(IOException e){
System.out.println(“Error Occurred. “+e);
}
}
}
In the above example, fin.close() and fout.close() statements must be present in earlier versions
of Java. Howver, in this case since these resources are declared within try block scope, they
are automatically closed even when an exception occurs.
Multi-Catch blocks
In many cases, there will be common code for some exceptions where each exception type
must be handled with a separate catch block or a generic “Exception” type catch block must be
used. However, in Java 8, multiple exception types can be given for catch block with a pipe (|)
symbol. Following example explains the use of multi-catch block in Java 8.
import java.util.*;
public class Test {
public static void main(String[] args) {
try {
int x;
Scanner scn = new Scanner(System.in);
System.out.println(“Enter a Number:”);
x = scn.nextInt();
scn.close();
System.out.println(“10/x = “ + (10/x));
}
catch(InputMismatchException | ArithmeticException ex){
System.out.println(“Error Occurred. “+ex);
} 107
}
}
The above example can throw two types of exceptions. When the user given a non number
(like abc) as input, it throws “InputMismatchException” and when a zero is given, it throws
“ArithmeticException” error. Both are handled with a single catch block using the multi-catch
feature of Java 8.
The Final Rethrow
The catch block can throw an exception from within it. This is known as rethrow, which was
supported since early versions of Java. However, the final Throwable type is introduced since
Java 7. If a catch block handles all exceptions, makes several operations and then rethrow it, it
can be implemented just by using an Exception type catch block. The big problem is that the
method must add a throws clause to the method signature to manage the new exception launched
by this code where the type is to be defined which is hard to get. This can be done with the
final Throwable without adding an exception throws clause:
try {
// some code
} catch (final Throwable ex)
{
// some more code
throw ex;
}
Using the final keyword allows to throw an exception of the exact dynamic type that will be
throwed. So if an IOException occurs, an IOException will be throwed. However, this feature
is not preferred by many programmers as it will not give any leverage since Exception type
catch and throw is enough for that.
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
3. What are three exceptions added newly?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
8.5. SUMMARY
This chapter introduces the Exception handling framework implemented in Java. The use of
try-catch blocks, multiple catch blocks, nested and chained exception handlings are briefed.
Java built-in Exceptions and their classification is also explained.Java classifies these kinds of
errors into two types, viz. exceptions and errors. The difference between error and exception
in Java is that exceptions can be handled at the run time whereas errors cannot be handled. An
Error is a critical condition that cannot be handled by the user most of the time and the program
is terminated eventually. The rest of this chapter discusses how to handle the Exceptions in
Java programs.Chained Exceptions allows one exception describes cause of another exception.
108
For example, an integer is read from keyboard and it is used as a divisor in another statement.
Suppose that the read failed and the value is set to zero. Here the exception will be an
ArithmeticException because the denominator is zero but the actual cause of exception was an
I/O error which caused the divisor to be zero.There are three features added in Java 8, which
are sometimes useful in reducing the code and making the program robust. These three are
Automatic resource release (called try with resource), Multiple Exceptions in a single catch
block (called multi-catch),Rethrow of Exception (called rethrow or final rethrow)
8.8. GLOSSARY
Exception : An exception is an abnormal condition that arises in a
code during runtime
Changed Exception : allows one exception describes cause of another
exception
Cheked Exception : The compiler will not flag any error even if these are
not handled by the programmer..
IOException : Error occurred in I/O operations
ArithmeticException : Arithmetic Errors such as divided by zero.
109
UNIT-9: JAVA COLLECTIONS
Contents
9.0 Objectives
9.1 Introduction
9.2 Java Collections Frame Work
9.3. Important Collection Classes
9.4 Summary
9.5 Check your progress Model Answers
9.6 Model Examination Questions
9.7 Glossary
9.0. OBJECTIVES
After studying this unit, you should be able to
• Understand Java collection framework.
• Describe java util package components.
• Explain how to use different types of objects defined in this framework...
• Understand important colectio of classes.
9.1. INTRODUCTION
Power of any language comes from its representation and organization of data in the program.
Java exceeds in this respect with its powerful collections framework, which defines many new
data containers. These containers can handle almost any type of data. These containers have
enough methods in each class to manage the data they hold like insert, delete, modify and
retrieve apart from many other methods like querying, comparing and sorting data. Java has a
rich collection of various general purpose interfaces and classes. These classes are very generic
and cater to almost all the day to day needs of programming. These classes are packed in the
‘java.util’ package, which should be imported if one of the classes is used in the program. The
list interface provides some important methods which are essential in handling and manipulating
the lists of objects. ArrayList is one of the most used implementation of the List
interface.HashMap is another important tool in programming. It is not derived from the
Collection interface, but it has Map interface as the base class. The HashMap stores data as
Key-Value pairs, where key and value can be objects of any type, though generally key is
limited to primitive data types like integers and strings. Here the map does not allow duplicate
keys.
Table 9.2
Enumeration:
This interface enumerates the values of a container. The implementing class must declare two
functions
boolean hasMoreElements()
Object nextElement();
Generally a while loop is used to iterate through each object as
while(en.hasMoreElements){ en.nextElement(); }
112
List Interface
The list interface provides some important methods which are essential in handling and
manipulating the lists of objects. ArrayList is one of the most used implementation of the List
interface. Some of the methods are as follows:
Method Description
void add(int index, E element) Inserts the element at the given position in a list.
boolean add(E e) Appends the specified element at the end of a list.
boolean addAll(Collection c) Appends all of the elements in the given collection to the end
of a list.
void clear() Removes all elements from this list.
boolean equals(Object o) Compare the given object with the elements of a list.
E get(int index) Returns the element at the index
boolean isEmpty() Returns true if the list is empty, otherwise false.
int lastIndexOf(Object o) Return the index of the last occurrence of the given element,
or -1 if the list does not contain this element.
T[] toArray(T[] a) Return an array containing all of the elements in this list in
the same order.
boolean contains(Object o) Returns true if the list contains the given element or false
otherwise
int indexOf(Object o) Returns the index of the first occurrence of the given element,
or -1 if the List does not contain this element.
E remove(int index) Removes the element at the given position.
boolean remove(Object o) Removes the first occurrence of the given element.
boolean remove All(Collection c) removes all the elements of the collection
from the list.
void sort(Comparator c) Sorts the elements of the list on the basis of given comparator.
List<E> subList Returns a sub list of elements within the given range.
(int fromIndex, int toIndex) Returns the number of elements present in the list.
int size()
Table 9.3
All the methods from various interfaces are available in the classes that implement those
interfaces. Collection interface methods are available to all the Classes:
113
Some of the important classes that implement the Collection framework are given below
ArrayList Container for sequential data just like an array but expandable
HashMap Extends AbstractMap and provides a hash table
implementation
HashSet Provides a collection of keys which can be queries for available
or not. It implements AbstractSet interface.
LinkedList Linked list implementation of the List and Abstract
Sequential List interfaces.
TreeSet It extends AbstractSet and implements a set stored in a tree
structure.
TreeMap Extends AbstractMap to provide tree structured hash table.
Table 9.4
Other Important Classes in java.util Package
Following is a list of important classes other than Collection framework components. Again
the list is large and only important components are presented here. For full list, the reference
manual may be referred.
Arrays This class contains various methods for manipulating arrays
(such as sorting and searching).
BitSet This class implements a vector of bits that grows as needed
and provides bit operations.
Date The class Date represents a specific instant in time, with
millisecond precision.
GregorianCalendar GregorianCalendar is a concrete subclass of Calendar and
provides the standard calendar used by most of the world.
Hashtable This class implements a hashtable, which maps keys to values.
Observable This class represents an observable object, or “data” in the
model-view paradigm.
Random An instance of this class is used to generate a stream of
pseudorandom numbers.
Stack The Stack class represents a last-in-first-out (LIFO) stack of
objects.
StringTokenizer The string tokenizer class allows an application to break a
string into tokens.
TimeZone TimeZone represents a time zone offset, and also figures out
daylight savings.
Scanner Parser class that parses any input stream like System.in, Files and
Strings
Table 9.5
114
Following figure gives a partial hierarchy of the interfaces, abstract classes and implemented
classes purely for the purpose of understanding the collection framework. It is by no means, a
full list. Since the collection has large set of components within it, it is almost impossible to
give the entire picture. However, the user may understand that all the methods available in
Iterable and Collection are available to all the classes. In addition to these, any base class or
base interface methods are also available to the implemented classes. This brings uniformity
of methods and variables across all the collection classes.
Figure.9.1
The full documentation is available with Oracle Corporation’s website.
Some legacy classes like Vector, Hashtable etc. are reengineered to implement these interfaces,
so that they follow the new standards.
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
A hash map can be created with one of its constructors given below:
HashMap<keyType, valueType>( ) - creates a default empty HashMap with keyType object as
key and valueType object as its value.
HashMap<keyType, valueType> (Map m) - Creates a new HashMap with initial data containing
all key-value pairs from map m.
HashMap<keyType, valueType> (int cap) - Creates a HashMap with initial capacity of cap.
HashMap<keyType, valueType> (int capacity, float fillRatio) - Creates a HashMap with given
capacity and fill ratio.
Here fill ratio decides when to expand or shrink memory. For example, for a fill ratio of 0.8,
with capacity of 10 will expand the capacity to 20 when the number of elements reaches 8.
Some of the useful methods of Map interface are given below:
Method Description
Void put(Object key, Object value) inserts an entry in the map.
void putAll(Map map) inserts the given elements from a map
remove(Object key) deletes an entry for the specified key.
void clear() removes all elements from map.
boolean containsKey(Object key) returns true if key exists within the map, else
return false.
boolean containsValue(Object value) returns true if value exists anywhere in the map,
else return false.
V get(Object key) returns the value object for the given key or null.
V getOrDefault(Object key,VdefaultValue) returns the value for a given key, or defaultValue
if the map does not contain the key.
boolean isEmpty() returns true if the map is empty, false otherwise
V replace(K key, V value) replaces the specified value for a given key.
Collection values() returns a collection of all the values in the map.
Table 9.6
Following table gives some important methods defined in HashMap in addition to methods
inherited from its parent classes:
118
Method Description
Set keySet() Returns a set of the keys contained in this map.
int size() This method returns the number of entries in the map.
Following example creates a HashMap, adds some key-value pairs into it, and then removes
some keys based on value or key. Listing of all elements of a HashMap is a little tricky without
iterators (which will be explained shortly). First all the keys are obtained into a Set using
getSet() method and then it is converted to an array. Now using the keys from array, each value
is obtained using get() method.
import java.util.*;
publicclass HashMapTest{
publicstaticvoid main(String args[]) {
int i;
HashMap<String,String> hm = new HashMap<>();
System.out.println(“Initial Size: “ + hm.size()); // size = 0
hm.put(“key0”, “abcd”);
hm.put(“key1”,”def”);
hm.put(“key2”,”ghij”);
hm.put(“key3”,”jklmn”);
System.out.println(“Size Now is: “ + hm.size()); // size = 4
System.out.println(“Contents of hm are: “ + hm);
hm.put(“key1”,”pqr”); // replaces key1
System.out.println(“Contents of hm are: “ + hm);
hm.remove(“key3”); // remove element at index 1
hm.remove(“def”); // Remove element “def”
System.out.println(“Contents of hm are: “ + hm);
// Listing all elements from list
Set<String> keys = hm.keySet();
String k[] = keys.toArray(new String[0]);
for(i=0;i<k.length; i++) {
System.out.println(“Value[“+k[i]+”]=”+ hm.get(k[i]));
}
System.out.println(“——————————”);
}
}
Output of the program is:
Initial Size: 0
Size Now is: 4
Contents of hm are: {key1=def, key2=ghij, key0=abcd, key3=jklmn} 119
Contents of hm are: {key1=pqr, key2=ghij, key0=abcd, key3=jklmn}
Contents of hm are: {key1=pqr, key2=ghij, key0=abcd}
Value[key1]=pqr
Value[key2]=ghij
Value[key0]=abcd
——————————
Accessing Data from Collections
In the previous examples, traversing all the elements of a collection was done using a for loop
either by getting the size of the collection or by getting all the keys. However, the collection
framework provides an easier method through its super class – Iterable, which defines a single
method “iterator()”. This can be used to traverse through all the elements of a collection.
Modern versions of Java supports the simpler ‘for-each’ structure as well.
Accessing Collection with an iterator
Every class that implements Collection interface, has the iterator() method which gives an
iterator object. The iterator object has two methods viz., hasMoreElements() and nextElement()
methods. Using these two methods, any collection can be traversed. Following is an example
for traversing all the elements of an ArrayList. The process is as follows:
Iterator itr = col.iterator(); // Get iterator for the collection col.
while(itr.hasNext()) {
System.out.println(itr.next()); // get value using next() method of iterator
}
Accessing Collection With for-each Loop
In the previous case, an iterator is obtained and a while loop is used to iterate through the
elements. Java has simplified the process with for-each variant of the for loop. For any collection,
the for-each loop is as follows:
for (DataType var:col) { use var here } where var is a variable that will be given next element’s
value every time in the for loop
The variable should be declared within the ‘for’ loop and any variable declared outside the
brackets cannot be used here. Following example demonstrates the use of both iterator and
for-each loop:
import java.util.ArrayList;
import java.util.Iterator;
class ArrayListTest {
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<>();
al.add(“abcd”);
al.add(“def”);
al.add(“ghij”);
al.add(“jklmn”);
120 System.out.println(“———— Using iterator —————”);
Iterator<String> itr = al.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
System.out.println(“———— Using for-each —————”);
for(String s:al) {
System.out.println(s);
}
}
}
The data of the array list is printed by both methods correctly when the program is run.
Arrays Class:
Arrays class is added to java.utils in Java 2 and has various static methods for manipulation of
arrays. It has a huge collection of methods (over hundred) where most of them are overloaded
for different data types and generics. Some of the useful functions are given below:
static List asList(Object array[]) - Returns List object from the Array
static int binarySearch(array, value) - Searches for the value in array and returns index if
found or negative value otherwise.
static <T> T[] copyOf(T original[], int newLength) – Copies newLenght elements or nulls if
newLength is greater than the number of elements in the original array and returns a duplicate
array.
static boolean equals(arr1, arr2) - Returns true if both arrays have same elements
static void fill(array, value) - Fills the array with the given value
static void fill(array, start, end, value) - Fills partial array with value
static void sort(array) - Sorts the entire array
static void sort(array, start, end) - Sorts partial array from start to end
static <T> void sort(T arr[], Comparator comp) – Sorts the arr using comparator comp
Following example illustrates the use of Arrays static methods on an array.
import java.util.*;
public class ArrayDemo {
static void display(String msg, int arr[]) {
int i;
System.out.print(msg+”: “);
for(i=0;i<arr.length; i++){
if(i>0){
System.out.print(“, “);
}
System.out.print(arr[i]); 121
}
System.out.println();
}
public static void main(String args[]){
int arr[] = new int[5];
arr[0]= 10; arr[1] = 2; arr[2] = 8; arr[3] = 4; arr[4] = 1;
display(“Initial array”,arr);
Arrays.sort(arr);
display(“After Sort”,arr);
Arrays.fill(arr,2,3,5);
display(“After Fill”,arr);
Arrays.sort(arr);
display(“After Sort”,arr);
int res = Arrays.binarySearch(arr,8);
System.out.println(“Value 8 is at Location “ + res);
}
}
————— Output —————
Initial array: 10, 2, 8, 4, 1
After Sort: 1, 2, 4, 8, 10
After Fill: 1, 2, 5, 8, 10
After Sort: 1, 2, 5, 8, 10
Value 8 is at Location 3
Using User Defined Data in Collections
Collection framework is designed and implemented using Java generics where the data type
can be any object. User defined objects can be managed the same way as with the standard
data types. Following example uses a user defined data type called student with the following
definition:
class Student
{
String rollno, name, course;
public Student(String rollno, String name, String course){
this.rollno = rollno;
this.name = name;
this.course = course;
}
public String toString(){
122
return (rollno+”, “ + name + “, “ + course);
}
}
Now this data type can be used in any Collection class. As an example, the following program
uses the Student data in the ArrayList:
import java.util.ArrayList;
class ArrayListTest {
public static void main(String args[]) {
ArrayList<Student> al = new ArrayList<>();
ArrayListTest alt = new ArrayListTest();
al.add(alt.new Student(“20A102”, “Bhanu”, “M.A (Economics)”));
al.add(alt.new Student(“20A104”, “Ananda Rao”, “M.C. A”));
al.add(alt.new Student(“20A101”, “Keerthana”, “M.Sc. (Physics)”));
al.add(alt.new Student(“20A103”, “Ranjan”, “M.Sc. (Physics)”));
System.out.println(“———— Using for-each —————”);
for(Student s:al) {
System.out.println(s);
}
}
public class Student{
String rollno, name, course;
public Student(String rollno, String name, String course){
this.rollno = rollno;
this.name = name;
this.course = course;
}
public String toString(){
return (rollno+”, “ + name + “, “ + course);
}
}
}
Observe how the generic collection is used with user data (<Student>). The output is as follows:
———— Using for-each —————
20A102, Bhanu Kumar, M.A (Economics)
20A104, Ananda Rao, M.C. A
20A101, Keerthana, M.Sc. (Physics)
20A103, Ranjan, M.Sc. (Physics) 123
Observe how the Student objects are created using an object of type ArrayListTest. This is
necessary when a program uses an inner class. To avoid this type of instantiation, the Student
class may be defined as a separate class with its own file. The data is printed using the toString
method defined in the Student class.
Sorting User Defined Data in Collections
Consider the above example where four objects of type Student are defined and are printed.
The data is printed in the same order as they were added. However, consider that the data must
be printed in sorted order. Now there is an ambiguity on what field the data should be sorted.
In this case, the user has to define how the compare should work using a special interface
called Comparator or extending the class Comparable. Extending Comparable is not
recommended since it increases the depth of hierarchy of classes and already a class may be
extending another class. Hence, implementing Comparator is the best option.
The Comparator interface declares just one method which is as follows:
class MyComparator implements Comparator<T>{
public int compare (T obj1, T obj2); // where T is any data type
}
Here the compare method should return
negative value if obj1 < obj2
0 if obj1 = obj2
positive value if obj1 > obj2
Mathematically it should return the difference (obj1-obj2). For example, if strings are compared,
the method can use String’s compareTo() method (return obj1.compareTo(obj2);) or if numeric
values are compared, it can use direct difference (return obj1-obj2;)
Following example declares the Comparators based on the name and rollno and sorts data
based on roll number and name.
import java.util.*;
class ArrayListTest {
public static void main(String args[]) {
ArrayList<Student> al = new ArrayList<>();
ArrayListTest alt = new ArrayListTest();
al.add(alt.new Student(“20A102”, “Bhanu Kumar”, “M.A (Economics)”));
al.add(alt.new Student(“20A104”, “Ananda Rao”, “M.C. A”));
al.add(alt.new Student(“20A101”, “Keerthana”, “M.Sc. (Physics)”));
al.add(alt.new Student(“20A103”, “Ranjan”, “M.Sc. (Physics)”));
System.out.println(“———— Unsorted data —————”);
for(Student s:al) {
System.out.println(s);
}
al.sort(new RollnoComparator());
124 System.out.println(“———— Sorted on Roll Number —————”);
for(Student s:al){
System.out.println(s);
}
al.sort(new NameComparator());
System.out.println(“———— Sorted on Name —————”);
for (Student s:al){
System.out.println(s);
}
}
public static class RollnoComparator implements Comparator<Student>{
public int compare(Student s1, Student s2){
return s1.rollno.toUpperCase().compareTo(s2.rollno.toUpperCase());
}
}
public static class NameComparator implements Comparator<Student>{
public int compare(Student s1, Student s2){
return s1.name.toUpperCase().compareTo(s2.name.toUpperCase());
}
}
public class Student{
String rollno, name, course;
public Student(String rollno, String name, String course){
this.rollno = rollno;
this.name = name;
this.course = course;
}
public String toString(){
return (rollno+”, “ + name + “, “ + course);
}
}
}
In the above program two additional classes (‘RollnoComparator’ and ‘NameComparator’)
are defined and in each sort call, one of the object is created and passed as parameter. The sort
method uses the compare method of this object for sorting the data. The output is as follows:
———— Unsorted data —————
20A102, Bhanu Kumar, M.A (Economics)
125
20A104, Ananda Rao, M.C. A
20A101, Keerthana, M.Sc. (Physics)
20A103, Ranjan, M.Sc. (Physics)
———— Sorted on Roll Number —————
20A101, Keerthana, M.Sc. (Physics)
20A102, Bhanu Kumar, M.A (Economics)
20A103, Ranjan, M.Sc. (Physics)
20A104, Ananda Rao, M.C. A
———— Sorted on Name —————
20A104, Ananda Rao, M.C. A
20A102, Bhanu Kumar, M.A (Economics)
20A101, Keerthana, M.Sc. (Physics)
20A103, Ranjan, M.Sc. (Physics)
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
2. What is the Array Class?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
9.4. SUMMARY
This chapter introduced the use of Collection framework and java.util package. Some important
classes are explained and examples were given wherever necessary. With this introduction,
the candidate should be in a position to learn about other classes of the package. HashMap
uses a hash function to determine if the given key exists in the map, which makes it very
efficient compared to a list, where elements are searched sequentially. HashMap is a kind of
lookup table for the data where each data item is associated with a key (as the keywords in
dictionary).Every class that implements Collection interface, has the iterator() method which
gives an iterator object. The iterator object has two methods viz., hasMoreElements() and
nextElement() methods. Using these two methods, any collection can be traversed. Following
is an example for traversing all the elements of an ArrayList.Arrays class is added to java.utils
in Java 2 and has various static methods for manipulation of arrays. It has a huge collection of
methods (over hundred) where most of them are overloaded for different data types and
generics.the data must be printed in sorted order. Now there is an ambiguity on what field the
data should be sorted. In this case, the user has to define how the compare should work using
a special interface called Comparator or extending the class Comparable. Extending Comparable
is not recommended since it increases the depth of hierarchy of classes and already a class may
be extending another class. Hence, implementing Comparator is the best option.
126
9.5. CHECK YOUR PROGRESS MODEL ANSWERS
1. Provides some important methods which are essential in handling and manipulating the
lists of objects. 2. It implemnets the array with huge number of built in methods
9.7 GLOSSARY
HashMap : HashMap stores data as Key-Value pairs, where key and
value can be objects of any type,
TreeMap : Implements Tree heirachy and derived from SortedMap
Enumeration : This interface enumerates the values of a container. The
implementing class must declare two functions
ArrayList : Is a collection which stoes, iterte array of objects
Collection : Container class which contains various types of objects or
primitive types.
127
128
BLOCK - IV
129
130
UNIT-10: JAVA DATABASE CONNECTIVITY
Contents
10.0 Objectives
10.1 Introduction
10.2 Java Data Base Connectivity
10.3. Using Meta Data
10.4. Transaction Management
10.5. Summary
10.6. Check your progress Model Answers
10.7. Model Examination Questions
10.8. Glossary
10.0. OBJECTIVES
After studying this unit, you should be able to
• Understandimportant concept called Java Database Connectivity (JDBC)
• Describe transaction management.
• Explain how to execute queries on that database through Java programs.
10.1. INTRODUCTION
Java provides a robust API (Application Programming Interface) for connecting and managing
databases of almost all important brands known as JDBC API. It is a part of JavaSE (Java
Standard Edition). JDBC API uses JDBC drivers to connect with the database. JDBC Driver is
a software component that enables java application to interact with the database.The
executeQuery statement returns a ResultSet Object which contains the results and acts as an
iterator for the data. A null indicates that the execution failed. The data from the resultSet
object is retrieved using a while loop with its built-in method next() which advances the current
location to the next record within result set object. The individual columns of a record are
fetched with the getString(), getInt(), getFloat(), … methods with column index that starts
with 1 (not with zero) or with column name in the database.Finally the database connection,
statement, result set etc are closed with their respective close() method. Transaction represents
a single unit of work which may contain one or more SQL statements. If a transaction is
successful, all the statements are executed. If at any stage, one statement fails, all the successful
statements so far should be undone. This process of undoing in case any statement in the
transaction fails, is known as “rollback”.
132
JDBC offers a uniform procedure and syntax for connecting and querying the database,
irrespective of the vendor and type of database. Following are the entities used in JDBC enabled
programs.
• DriverManager: This class manages a list of database drivers. This is used to establish
a database Connection.
• Driver: This interface handles the communications with the database server which is
transparent to the user.
• Connection: This interface is the handle for all communication with the connected
database.
• Statement: This object is created from the connection which is used to submit the
SQL statements to the database.
• ResultSet: This object holds data retrieved from a database after an SQL query is
executed using Statement object. Result data is retrieved using this object.
• SQLException: This exception is thrown on any errors that occur in a database
application.
Installing JDBC Driver
In normal cases, when database software is installed, it also installs the drivers for that. However,
it is possible to exclusively download the packaged (jar) jdbc driver from the vendor’s website.
In this chapter, MySQL is considered as the database since it is freely available and one of the
most popular databases. The MySQL JDBC driver can be downloaded from the website, which
has a name similar to “mysql-connector-java-5.1.39-bin.jar” where the version number may
vary. The driver may be placed in any directory but the path of the jar file should be in the
CLASSPATH.
Registering and Calling JDBC Drivers
Once the driver is available in the CLASSPATH, it can be used in any Java program. Each
vendor specifies a String for their product. Following are the Strings specified by some of the
popular vendors:
• MySQL - “com.mysql.jdbc.Driver”.
• Oracle - “oracle.jdbc.driver.OracleDriver”
• MS SQL Server - “com.microsoft.sqlserver.jdbc.SQLServerDriver”
Once the driver string is identified, that should be registered using Class.forName() method as
follows:
Class.for Name (“com.mysql.jdbc.Driver”);
For other data databases the appropriate strings may be used. Every JDBC or SQL statement
may throw an exception of type SQL Exception. Hence, all the JDBC connection statements
are inside a try catch block or the method is declared to throw the SQLException with throws
keyword.
JDBC URL and the Connection
After registering the Driver with Class.forname(), the next step is to establish a connection to
the database using its connection ULR. Again each vendor specifies different connection URLs
for their products. The following are URL strings for some popular vendors. Values in square
brackets are optional.
• MySQL - “jdbc:mysql://host[:port]/myDB” where default port is generally 3306
133
• Oracle: “jdbc:oracle:thin:@host[:port]:myDB” where default port is 1521
• MS SQL Server: “jdbc:sqlserver://host[:port];databaseName=uDB;
user=uName;password=uPWD;” where default port is 1433
A connection to MySQL database can be obtained with:
Connection con = DriverManager.getConnection(url,username, userPassword);
The driver manager has two methods to get a connection:
i. public static Connection getConnection(String url)
ii. public static Connection getConnection(String url,String userName,String password)
One of them can be used depending on whether the database supports user name and password
as separate arguments or as a single argument like in Microsoft SQL server.
Using JDBC Drivers
After a connection is established without any problem, the next step is to create a statement
from the connection.
Statement smt = con.createStatement();
Now this statement object is used to execute the query using either executeQuery(“sql
statement”) if it is a data retrieval statement, or executeUpdate(“sql statement”) if it is an
update statement (update, insert or delete).
For updateQuery statements, the result returned will be an integer that tells how many records
are affected by the query. A value of negative indicates an SQL error, 0 indicates no records
were modified and any positive number indicates that many number of records are updated.
The execute Query statement returns a ResultSet Object which contains the results and acts as
an iterator for the data. A null indicates that the execution failed. The data from the resultSet
object is retrieved using a while loop with its built-in method next() which advances the current
location to the next record within result set object. The individual columns of a record are
fetched with the getString(), getInt(), getFloat(), … methods with column index that starts
with 1 (not with zero) or with column name in the database.
Finally the database connection, statement, result set etc are closed with their respective close()
method.
The process steps can be summarized as follows:
Step 1: Import required classes
Step 2: Register the Driver with Driver Manager using Class.forName()
Step 3: Get a connection from the DriverManager
Step 4: Create a Statement from the connection
Step 5: Execute an SQL statement with the statement
Step 6: Process results if it is a Query statement or get number of records affected otherwise
Step 7: Close resources
The following example extracts all records from the table and shows them on the screen.
//STEP 1. Import required packages
import java.sql.*;
134
public class JdbcExample{
public static void main(String[] args){
String driver = “com.mysql.jdbc.Driver”;
String url = “jdbc:mysql://localhost/mydb”;
String user = “guest”;
String pass = “guest123”;
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName(driver);
//STEP 3: Open a connection
conn = DriverManager.getConnection(url,user,pass);
//STEP 4: Create Statement
stmt = conn.createStatement();
String sql = “SELECT name, phno FROM test”;
//STEP 5: Execute a query
ResultSet rs = stmt.executeQuery(sql);
//STEP 6: Extract data from result set
while(rs.next()){
//Retrieve by column name
System.out.print(“Name: “ + rs.getString(1) +
“ Ph: “ + rs.getString(2));
}
//STEP 7: Close/release resources
rs.close();
stmt.close();
conn.close();
}
catch(Exception se){
//Handle errors for JDBC
se.printStackTrace();
}
finally{
//finally block used to close resources
try{
135
if(stmt!=null)
stmt.close();
if(conn!=null)
conn.close();
}
catch(Exception se2){
se.printStackTrace();
}// nothing we can do
}//end try
System.out.println(“Exiting the program”);
}//end main
}//end JdbcExample
To execute this program the MySQL server should be running and the database mydb should
be created. Within the mydb database, there should be a table named ‘test’ should exist. Table
test contains two columns viz., the name of type varchar(20) and the phno of type varchar(10).
Assume that the user name for the database is “guest” and the password is “guest123”.
To create a database with MySQL and a table, refer to any help (either internet or MySQL
documentation or User Guide). Following is a brief list of commands that should be given at
the mysql command prompt and the output from the server:
mysql> create database mydb;
Query OK, 1 row affected (0.00 sec)
mysql> use mydb;
Database changed
mysql> create table test(name varchar(20), phno varchar(10)) ENGINE = InnoDB;
Query OK, 0 rows affected (0.01 sec)
mysql> insert into test values(‘Bhanu’,’12345678');
Query OK, 1 row affected (0.00 sec)
mysql> insert into test values(‘Pratap’,’23456789');
Query OK, 1 row affected (0.00 sec)
mysql> select * from test;
name phno
Bhanu 12345678
Pratap 23456789
136
Prepared Statement
When a query is submitted by the program to the server, the query is first translated into
appropriate query that is understood by the server (compiled). If a query is repeatedly submitted
with different data, the translation step can be reused by converting the data into parameters.
This saves considerable time from second query onwards and results in performance
improvement. For example, consider an insert query that is used to insert 10 records. Instead
of compiling and executing the query 10 times, the prepared statement just compiles it once,
and each time new data is sent as parameters.
Following steps are necessary for using prepared statements in JDBC.
As a first step, a prepared statement is obtained from Connection object using
PreparedStatement ps = con.preparedStatement(sql); where con is the connection object and
sql is the SQL string where each variable data item is denoted with a question (?) symbol.
String sql=”insert into mydb.test values(?,?)”;
Here the two question marks represent the two parameters (name and phno) where both are
string type in Java. These parameters will be supplied actual values by calling the setter methods
of PreparedStatement like setInt(paramIndex, int Value) or setString(paramIndex, String value)
or setFloat(paramIndex, float value) … Similar to the statement, prepared statement also has
the two methods executeUpdate(String sql) for update, delete or insert and executeQuery(String
sql) for retrieving results into a ResultSet.
The parameter index is counted from 1 (unlike Java array index which starts with 0). Once
statement is created, the same procedure is followed for both statement and prepared statement.
Example
The following example inserts two records into the mydb.test table using prepared statement.
import java.sql.*;
class InsertPrepared{
public static void main(String args[]){
String driver = “com.mysql.jdbc.Driver”;
String url = “jdbc:mysql://localhost/mydb”;
String uname = “dbUser”; // Replace with actual user name
String pwd = “password”;// Replace with actual password
String sql = “insert into test values(?,?)”;
try{
Class.forName(driver);
Connection con = DriverManager.getConnection(url,uname,pwd);
PreparedStatement stmt= con.prepareStatement(sql);
// Add record using prepared statement
stmt.setString(1, “Rupa”);// first parameter in the query
stmt.setString(2,”33445566"); // Second parameter
intres = stmt.executeUpdate();
System.out.println(res+” records inserted”);
137
// Add One more record
stmt.setString(1, “Hari”);
stmt.setString(2,”33556677");
res = stmt.executeUpdate();
System.out.println(res+” records inserted”);
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
After running this program check the records from mysql command prompt again:
mysql> select * from test;
name phno
Bhanu 12345678
Pratap 23456789
Rupa 33445566
Hari 33556677
4 rows in set (0.00 sec)
The same procedure that is used to retrieve records can be applied to execute select query with
prepared statements also. The partial code gives an idea of how to retrieve data using prepared
statement.
PreparedStatement stmt=con.prepareStatement(“select * from test”);
ResultSet rs=stmt.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1)+” “+rs.getString(2));
}
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
2. What an Execute Query method does?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
139
The output of the run will be as follows:
Total columns: 2
Column 1 Name:name
Column 1 Type: VARCHAR
Column 2 Name:phno
Column 2 Type: VARCHAR
Database Meta Data
DatabaseMetaData interface provides methods to get metadata of a database such as database
product name, database product version, driver name, name of total number of tables, name of
total number of views etc. Some commonly used methods of DatabaseMetaData interface are
given below:
• String getDriverName():Returns the name of JDBC driver.
• String getDriverVersion(): Returns the version of JDBC driver.
• String getUserName(): Returns the user name of database.
• String getDatabaseProductName(): Returns the product name of the database.
• String getDatabaseProductVersion(): Returns the product version of the database.
• ResultSet getTables(String catalog, String schemaPattern, String table Name Pattern,
String[] types): Returns the description of the tables of the specified catalog where the
table type can be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.
The database metadata object can be obtained using connection object’s getMetaData method:
DatabaseMetaData dmd = con.getMetaData();
Following example presents the metadata of the mydb database.
import java.sql.*;
class JdbcTest{
public static void main(String args[]){
String driver = “com.mysql.jdbc.Driver”;
String url = “jdbc:mysql://localhost/mydb”;
String uname = “root”; // Replace with actual user name
String pwd = “pwd123”;// Replace with actual password
try{
Class.forName(driver);
Connection con = DriverManager.getConnection(url,uname,pwd);
DatabaseMetaData dbmd=con.getMetaData();
System.out.println(“Driver Name: “+dbmd.getDriverName());
System.out.println(“Driver Version: “+dbmd.getDriverVersion());
System.out.println(“UserName: “+dbmd.getUserName());
System.out.println(“Database Product Name: “+
140
dbmd.getDatabaseProductName());
System.out.println(“Database Product Version: “+
dbmd.getDatabaseProductVersion());
String types[]={“TABLE”,”VIEW”};
ResultSet rs=dbmd.getTables(null,null,null,types);
while(rs.next()){
System.out.println(rs.getString(3));
}
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Typical output of the program will be similar to the following:
Driver Name: MySQL Connector Java
Driver Version: mysql-connector-java-5.1.39(Revision: 3289a357………)
UserName: root@localhost
Database Product Name: MySQL
Database Product Version: 5.7.14
Test
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
2. What is JDBC?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
10.6. SUMMARY
This chapter introduced the basics of Database connectivity from a Java program to any DBMS
engine. It also introduced the concept of JDBC support for transaction management and metadata
retrieval, with simple examples.In this chapter, MySQL is considered as the database since it
is freely available and one of the most popular databases. The MySQL JDBC driver can be
downloaded from the website, which has a name similar to “mysql-connector-java-5.1.39-
bin.jar” where the version number may vary. The driver may be placed in any directory but the
path of the jar file should be in the CLASSPATH.Java application that connects to a database
will use JDBC API and registers a Driver corresponding to the database, which the vendor will
supply. Using this driver, the program connects to the database and executes queries.When a
query is submitted by the program to the server, the query is first translated into appropriate
query that is understood by the server (compiled). If a query is repeatedly submitted with
different data, the translation step can be reused by converting the data into parameters. This
saves considerable time from second query onwards and results in performance improvement.
For example, consider an insert query that is used to insert 10 records. Instead of compiling
and executing the query 10 times, the prepared statement just compiles it once, and each time
new data is sent as parameters.
10.8 GLOSSARY
JDBC : Java Data Base Connectivity
Connector/j : Java Connector Driver to Connect to MySQL
database
Meta Data : Data about Data
Prepared Statement : Uses parameters to execute the updating of database
Transacion : Represents a single unit of work which may contain
one or more SQL statements.
144
UNIT-11: JAVA AT AND EVENT HANDLING
Contents
11.0 Objectives
11.1 Introduction
11.2 Java Event Handling
11.3. Adaptor Classes and Inner Classes
11.4. Summary
11.5. Check your progress Model Answers
11.6. Model Examination Questions
11.7. Glossary
11.0. OBJECTIVES
After studying this unit, you should be able to
• Understandimportant concept called Java event handling
• Describe adaptor classes.
• Explain how to use inner clasees.
11.1. INTRODUCTION
An event is a signal received by a program from the operating system as a result of some action
taken by the user, or because something else has happened within a graphical user interface.
Examples of events are:
The user pressed a key, The user clicked the Button or Menu item, The user closed or resized
a window.There are three entities in the event handling, viz., the event, the source of the event,
and an event listener. The delegation event model relates these three entities with a well defined
standard process. Whenever the source generates an event it is sensed or noticed by the listener
and the listener handles the event immediately.The program has to implement all the methods
since it is implementing that listener where code is written only in the windowClosed() method
and all the others are written with empty code like “void windowActivated(WindowEvent e){}”.
This is unnecessarily increasing the complexity of the code. The dummy implementations can
be observed in the examples given above.
Java provides adapter classes, which simplify the creation of event handlers in such situations.
An adapter class provides an empty implementation of all methods in an event listener interface.
The user can define a new class to act as an event listener by extending one of the adapter
classes and implementing only those events of interest.
146
java.lang.Object
java.util.Event Object
java.awt.AWT Event
Action Event Adjustment Event Component Event Item Event Text Event
The EventObject, in java.utilis the superclass for all events. It has one constructor and defines
two methods as shown below:
• EventObject(Object src) where, srcis the object that generates this event.
• Object getSource( ) – Returns the source of the event
• String toString( ) – Returns the string equivalent of the event
The AWTEvent class is a subclass of EventObject which is the superclass of all AWTbased
events used by the delegation event model.
Key Event Class
As an example of an Event class, the ‘KeyEvent’ class is considered here. A KeyEventis
generated when keyboard input occurs. There are three types of key events, which are defined
as three integer constants: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED. The first
two events are generated when any key is pressed or released. The KEY_TYPED event is
generated only when a character is generated (for example, pressing SHIFT or CTRL key does
not generate a character and hence KEY_TYPED is not generated). The KeyEvent class defines
device independent ASCII characters constants like VK_0 through VK_9 and VK_A through
VK_Z, where VK stands for virtual key. These key codes are fixed even with modifiers (Shift,
alt, ctrl or any combination). The KeyEvent has one constructor:
• KeyEvent(Component src, int type, long time, int modifiers, int code, char ch)
Where,
src is a reference to the source component of the event.
type is the type of the event
time is the system time at which the key was pressed
modifiers indicates which modifiers were pressed
code is the virtual key code, such as VK_UP, VK_DOWN, VK_A etc.
ch is the character equivalent or contains CHAR_UNDEFINED.
Commonly used methods of KeyEvent class are given below: defines several methods, but
probably the most commonly used ones are getKeyChar( ), which returns the character that
was entered, and getKeyCode( ), which returns the key code. Their general forms are shown
147
here.
• char getKeyChar() – returns character entered
• int getKeyCode() – returns key code
If no valid character is available, then getKeyChar( ) returns CHAR_UNDEFINED. When a
KEY_TYPED event occurs, getKeyCode( ) returns VK_UNDEFINED.
Each type of event generates an event with its own methods and constructor. The system uses
this constructor and constructs an event object appropriate for that event and sends it to the
listener.
Source of Events
Source is the object which undergoes state change and generates an event. It also provides
information about the event to the listener. A source can register listeners so that it can send
notifications to the listeners when an event occurs. Each type of event has its own registration
method which has a generic form:
public void addTypeListener (TypeListener el )
Where Type is the name of the event, and el is a reference to the event listener. For example,
the method that registers a keyboard event listener is called addKeyListener() and the method
for mouse motion listener is addMouseMotionListener(). The Key and MouseMotion are the
event type.
When an event occurs, all registered listeners are notified and sent a copy of the event object
which is known as multicasting the event.
Some sources may allow only one listener to register and if another listener tries to register for
this event, the add method throws java.util.TooManyListenersException. This is known as
unicasting the event.
Every source provides a method to unregister a listener which is as follows:
public void removeTypeListener(TypeListener el )
Where Type is the name of the eve-nt, and el is a reference to the event listener. For example,
to remove a keyboard listener removeKeyListener().is called.
The Component class (super class of all GUI components) provides methods to add and remove
keyboard and mouse event listeners.
Following table shows some of the event classes and source of the event
Following table shows some of the event classes and source of the event
Event Class Generated when
ActionEvent A button Is pressed, a list item is double clicked, or a
menu item is selected.
AdjustmentEvent A scroll bar is manipulated.
ComponentEvent A component is hidden, moved, resized, or becomes
visible.
ItemEvent A check box, list item, selection, or menu is clicked
TextEvent Value of a text area or text field is changed.
ContainerEvent A component is added to or removed from a container.
FocusEvent A component gains or loose keyboard focus.
148
WindowEvent A window is activated, closed, deactivated, deiconified,
iconified, opened, or quit.
KeyEvent An input is received from the keyboard.
MouseEvent Mouse is dragged, moved, clicked, pressed, released,
entered or exited
MouseWheelEvent Mouse wheel is moved.
Event Listener Interfaces
The class that implements a listener (also called event handler) is the actual handler of the
event. A listener is an object that will be notified when an event occurs. It must have been
registered with one or more sources to receive notifications about specific types of events. It
must also implement methods as defined in the listener interface to receive and handle these
notifications.
For example a listener that handles mouse events must implement the
MouseMotionListenerinterface which defines two methods to receive notifications when the
mouse is dragged or moved.
An event handler should not take too much time to process the event. Otherwise, some events
may be missed or program appears sluggish. Following is a list of some of the event listeners.
In the above image the left side window shows the initial screen and when the user clicks the
button, the message is shown in the text field by calling the action listener’s actionPerformed()
method. Read the comments carefully for an understanding of the process.
Other Examples of Event Handling:
Mouse Example:
Following example uses the mouse events.
import java.awt.*;
import java.awt.event.*;
class Test implements MouseListener{
Frame f=null;
Test(){
f = new Frame(“Mouse Test”);
f.setPreferredSize(new Dimension(200,150)); // Set size of the window
150
f.addMouseListener(this);
f.pack();
f.setVisible(true);
}
public void mouseClicked(MouseEvent e){
f.getGraphics().clearRect(0, 0, 200, 150);
f.getGraphics().drawString(“Mouse Clicked”, e.getX(), e.getY());
}
// Other dummy methods of the listener
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public static void main(String args[]){
new Test();
}
}
This program listens for mouse events and takes action when the mouse is clicked, ignoring
other events. When the mouse is clicked the location is filled in the event object that is passed
to the method. The string is printed starting at that location after clearing the screen first. A
screenshot of the output is shown below:
Keyboard Example:
Following program uses the key event to count the characters and words. The words are counted
whenever there is a space.
import java.awt.*;
import java.awt.event.*;
class KeyEventTest implements KeyListener{
Frame f=null;
Label l;
TextArea area;
KeyEventTest(){
f=new Frame(“Key Listener”);
151
l=new Label();
l.setBounds(20,50,200,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
f.add(l);f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void keyReleased(KeyEvent e) {
String text=area.getText();
String words[]=text.split(“ *”);
l.setText(“Words: “+words.length+” Characters:”+text.length());
}
public void keyTyped(KeyEvent e){}
public void keyPressed(KeyEvent e){}
public static void main(String args[]){
new KeyEventTest();
}
}
When a key is released, the keyReleased() method is called with KeyEvent which contains the
key pressed. The method just gets the string so far typed and splits it based on the space into
words array. The length of the array is the words and the length of the string is the number of
characters. This is set to the Label component’s text.
words:9 Characters : 40
this is a test string to test key events
152
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
1. What is an event handler?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
154
public void mouseClicked(MouseEvent e){
f.getGraphics().clearRect(0, 0, 200, 150);
f.getGraphics().drawString(“Mouse Clicked”, e.getX(), e.getY());
}
// Other dummy methods of the listener are removed
public static void main(String args[]){
new Test();
}
}
Inner Classes and Anonymous Classes
The examples with and without adapters shown before use the same class as a listener
and hence must implement all the required methods within the same class. This is what was
done in Java version 1.0 which was discarded for the very same reason. Hence, it is always
better to use a separate class that handles the events. If the class is implemented outside the
class code, it cannot access the variables of the original class of importance. Hence, the event
handler class is implemented within the main class since any inner class can access all the data
of the parent class. The structure of such a design is as follows:
class Outer {
… code here …
evtSource.addTypeListener(new EventHandler());
… code …
class EventHandler implements TypeListener {
… event handling methods here …
}
}
Mouse Example with Inner Class:
import java.awt.*;
import java.awt.event.*;
class Test{
Frame f=null;
Test(){
f = new Frame(“Mouse Test”);
f.setPreferredSize(new Dimension(200,150)); //Set window size
f.addMouseListener(new MyMouseAdapter()); // Add listener
f.pack();
f.setVisible(true);
}
// This is an inner class that handles mouse events
155
class MyMouseAdapter extends MouseAdapter {
public void mouseClicked(MouseEvent e){
f.getGraphics().clearRect(0, 0, 200, 150);
f.getGraphics().drawString(“Mouse Clicked”,e.getX(),e.getY());
}
}
public static void main(String args[]){
new Test();
}
}
In the above example, an adapter class is defined within the main class which is set as the
listener for the mouse events. Here the event code is separated from main code by means of an
inner class. In this specific case, the definition of a separate class is used only once, during the
addMouseListener() call. Java provides anonymous classes where the definition is given along
with the parameter, which is used only within the method. The above code can be modified to
send the adapter class during the call itself without declaring it explicitly. The modified code
is presented below:
import java.awt.*;
import java.awt.event.*;
class Test{
Frame f=null;
Test(){
f = new Frame(“Mouse Test”);
f.setPreferredSize(new Dimension(200,150)); //Set window size
f.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
f.getGraphics().clearRect(0, 0, 200, 150);
f.getGraphics().drawString(“Mouse Clicked”,e.getX(),e.getY());
}
}); // Add listener
f.pack();
f.setVisible(true);
}
public static void main(String args[]){
new Test();
}
}
156
Observe that the MouseAdapter’s code is written within the brackets () of method
addMouseListener().
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
2. What is an anonymous class?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
11.4. SUMMARY
This chapter introduces the event handling mechanism that is one of the essentials in GUI
programs in Java. . Events were handled in Java 1.0 by implementing a set of methods for that
event within the user class. However this monolithic implementation was deprecated and will
be removed from future versions of Java and hence not recommended to be used. Since Java
1.1, the system has been modified and an event delegation model is followed. The delegation
event model defines standard and consistent mechanisms to generate and process events. Events
should be handled by all new programs using this delegation model.
.The class that implements a listener (also called event handler) is the actual handler of the
event. A listener is an object that will be notified when an event occurs. It must have been
registered with one or more sources to receive notifications about specific types of events. It
must also implement methods as defined in the listener interface to receive and handle these
notifications.For example a listener that handles mouse events must implement the
MouseMotionListenerinterface which defines two methods to receive notifications when the
mouse is dragged or moved. An event handler should not take too much time to process the
event. Otherwise, some events may be missed or program appears sluggish
11.7 GLOSSARY
Event : Java Data Base An event is a signal received by a program
from the operating system as a result of some action taken by
the user
Event Hanlwe : The class that implements a listener (also called event handler)
is the actual handler of the event.
Delegation Model : Separating event handlng mechanism into event, source,
handler
Adapter class : An adapter class provides an empty implementation of all
methods in an event listener interface.
Anonymous class : The method whose parameter is passed the code that handles
the Window event
158
UNIT-12: JAVA VISUAL PROGRAMMING WITH SWING
Contents
12.0. Objectives
12.1. Introduction
12.2. Swing Packages
12.3. Swing GUI Components-Lable,Imagge Icon, Button, Text Field, Text Area
12.4 . Swing GUI Components-Check Boz, Radio Button, Combo Box, List, Tabbed Pane,
Scroll Pane, Table, Tree
12.5. Summary.
12.6. Check your progress Model Answers
12.7. Model Examination Questions
12.8. Glossary
12.0. OBJECTIVES
After studying this unit, you should be able to
• Understand GUI programming with Java Swing components.
• Describe Swing packages.
• Explain how to write programs using Swing event handling.
12.1. INTRODUCTION
Java originally incorporated the AWT components which translate each graphical instruction
to corresponding native call specific to the platform. As a result, the behavior of the GUI
components are platform specific which was against the “run anywhere” principle of Java,
since the GUI looks different on different platforms. Further there was overhead of converting
each call to machine specific call. These drawbacks lead to the development of swing which
uses pure Java implementation of the entire GUI stack. Swing components appear and behave
alike on all platforms.
Swing uses the AWT and replaced the native code with Java code. The same event handling
used by AWT is used in swing as well. However, there are some important changes in the
design of the swing components. The swing components are pure Java implementation unlike
AWT which uses native code. Hence, swing components have the same look and feel on all
platforms. Furthermore, the user can change the look and feel within the program.
Swing Components
Swing has a considerably large set of components. Following is a list of some important
components supported by swing:
160
Component Name Description
JButton Push button that can display text, images, or both
JCheckBox Toggle button for displaying choices (allows multiple
selection)
JColorChooser Component that allows the user to select a color
JComboBox Combination of a text entry field and a drop-down list of
choices
JEditorPane Customizable text editor component for displaying and
editing text and HTML
JFileChooser Component that allows the user to select a file or directory
JLabel Component that displays text, an image, or both
JList Component that displays a selectable list of choices
JMenu Pull-down menu in a JMenuBar or a submenu within another
menu
JMenuBar Component that displays a set of pull-down menus
JMenuItem Selectable item within a menu
JOptionPane Customizable dialog box for display simple messages
JPasswordField Text input field that displays the text as stars or dots
JPopupMenu Window that pops up to display a menu
JProgressBar Component that displays the progress of an operation
JRadioButton Toggle button for displaying mutually exclusive choices
JScrollBar Horizontal or vertical scrollbar
JSeparator Component that draws a horizontal or vertical line
JSlider Component that simulates a slider control
JTable A complex and powerful component for displaying and
editing tables
JTextArea Component for displaying and editing multiple lines of plain
text
JTextField Component for the display, input, and editing of a single
line of plain text
JToolBar Component that displays a set of user-selectable tools or
actions
JToolTip Lightweight pop-up window that displays simple tips when
the mouse pointer hovers over a component
JTree Component for the display of tree-structured data.
161
Swing Containers
Swing components must be placed inside a container before they are shown. There are two
types of containers available in swing. The first one is the top level containers, which are
JFrame, JDialog, JWindow and JApplet. A top level container cannot be contained by another
container. Any other components can be directly added to this category of containers. The
JApplet is deprecated and may be removed in future and hence not recommended to be used.
The second category of containers is the JPanel, which can contain other components and
even other JPanels. This is very useful since the nested panels can yield any design requirement
as far as component layout is concerned.
Layout Managers
When components are added to a container, the order or place where these components should
be added is controlled by a layout manager. Swing provides layout managers defined by AWT
which are FlowLayout, BorderLayout, GridLayout, GridbagLayout and CardLayout. If the
user wants to take control of the layout, the layout may be set to null. Each layout adds the
components in a specified way.
FlowLayout: It places the components left to right and top to bottom order if components
overflow from one row.
BorderLayout: It places components in 5 places (top – NORTH, bottom – SOUTH, right (EAST),
left (WEST) or center – CENTER).
GridLayout: It places components in rows and columns (right to left, top to bottom)
CardLayout: It places each component on a layer and the order can be changed programmatically.
GridBagLayout: It uses FlowLayout but with horizontal and vertical constraints.
By default the JFrame uses BorderLayout and the JPanel uses FlowLayout.
Swing Packages
Swing components are organized into different packages. Some packages generally used are
given here:
javax.swing javax.swing.text javax.swing.border
javax.swing.text.html javax.swing.colorchooser javax.swing.event
javax.swing.filechooser javax.swing.tree javax.swing.table
Appropriate package should be imported to use a component. To avoid clashing with existing
names, swing uses javax.swing as its base package directory. Every component is a part of
“javax.swing” package directly.
Check Your Progress
Image Icon,
The class ImageIcon is an implementation of the Icon interface that paints Icons from Images.
An object of type ImageIcon can be created using any of its constructors. Here are the important
and very useful constructors:
ImageIcon() – Creates an empty icon
ImageIcon(Image image) – Creates an icon from an image
ImageIcon(String filename) – Creates an icon from given JPG or PNG file
ImageIcon(URL locationURL, String description) – Creates an icon from a remote location
Some of the important methods that are useful are:
int getIconHeight(): Gets the height of the icon.
int getIconWidth(): Gets the width of the icon.
165
Image getImage(): Returns this icon’s Image.
void setImage(Image image): Sets the image displayed by this icon.
Example:
For this example, an image is required, which can be created with any
graphics editor like paint. In this case an image called myicon.png is
created and is placed in the same directory as that of the code. The
image looks as shown. Following example uses the image to create an
icon and shows it along with a label.
import java.awt.*;
import javax.swing.*;
publicclass IconTest
{
JFrame jf;
JLabel jl;
public IconTest(){
jf = new JFrame(“Icon Test”);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLayout(new FlowLayout());
jf.setSize(300,300);
ImageIcon ico = new ImageIcon(“myicon.png”);
jl = new JLabel(“Icon Demo:”, ico, JLabel.LEFT);
jf.add(jl);
jf.setVisible(true);
}
publicstaticvoid main(String[] args)
{
new IconTest();
}
}
The output of the program is as shown below:
166
JButton
JButton class provides functionality of a button. JButton supports ActionEvent, i.e., when a
button is pressed an ActionEvent is generated. JButton class has three constructors which
allow a button to be created using icon, a string or both:
JButton(Icon ic)
JButton(String str)
JButton(String str, Icon ic)
When a button is clicked, an ActionEvent is generated and is passed to the actionPerformed()
method as parameter. This action event contains the source of the event which can be used to
differentiate different button clicks, though both will generate the same action event.
Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
publicclass ButtonTest{
JFrame jf;
JButton jb1, jb2;
JLabel jl;
public ButtonTest(){
jf = new JFrame(“Button Test”);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(300,300);
jf.setLayout(new FlowLayout());
jb1 = new JButton(“Upper”);
jb1.addActionListener(new ButtonEventHandler());
jb2 = new JButton(“Lower”);
jb2.addActionListener(new ButtonEventHandler());
jl = new JLabel(“Test Message”);
jf.add(jb1);
jf.add(jb2);
jf.add(jl);
jf.setVisible(true);
}
publicstaticvoid main(String[] args){
new ButtonTest();
}
167
class ButtonEventHandler implements ActionListener {
publicvoid actionPerformed(ActionEvent ae) {
if(ae.getSource() == jb1) {
jl.setText(jl.getText().toUpperCase());
}
else {
jl.setText(jl.getText().toLowerCase());
}
}
}
}
The program attaches the same handler class to both buttons. ActionEvent’s getSource() method
that gives the reference to the source which is used to distinguish the buttons. That reference
is compared with jb1 and jb2 to know which object (Button) is clicked. Output of the program
when the first button was clicked is as shown below:
password
password ****
User OK OK
JTextArea
JTextArea works just like a JTextField, but can take multi-line input like address, feedback
etc. It can be created with its constructor JTextArea(int rows, int cols) where rows and cols are
integers that represent the minimum number of rows and number of columns on the screen.
Following example uses a JTextArea.
import java.awt.*;
import javax.swing.*;
public class TextAreaTest{
JFrame jf;
JScrollPane jsp;
public TextAreaTest() {
jf = new JFrame(“TextArea Test”);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(300,300);
JTextArea jta = new JTextArea(5, 30); // 5 rows x 30 columns area
jf.add(new JLabel(“Enter some text”), BorderLayout.NORTH);
jf.add(jta, BorderLayout.CENTER);// Add to the content pane.
jf.setVisible(true);
}
public static void main(String[] args){
new TextAreaTest();
}
}
170 A typical output of the program is shown below:
Enter some text
This is a !text area than can take
multi-line input
from the user!
172
JRadioButton
Radio buttons work like check boxes except that, when grouped, only one out of them can be
selected making them mutually exclusive. Radio buttons are created with one of its constructors.
Two important constructors are given below:
• JRadoiButton(String str) – Creates a radio button object with the given string as its
value
• JRadioButton(String str, boolean selected) – Creates and selects it if selected is true
Once the buttons are created they can be grouped logically with ButtonGroups. A ButtonGroup
is created for each group, and add each radio button to appropriate group. Once, grouped, only
one out of the group can be selected. Following application selects the gender and handles the
event.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RadioTest {
JFrame jf;
JLabel jl;
JRadioButton jr1, jr2;
public RadioTest() {
jf = new JFrame(“TextArea Test”);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(300,300);
jf.setLayout(new FlowLayout());
jr1 = new JRadioButton(“Male”);
jr2 = new JRadioButton(“Female”);
MyListener ml = new MyListener();
jr1.addItemListener(ml);
jr2.addItemListener(ml);
ButtonGroup bg = new ButtonGroup();
bg.add(jr1);
bg.add(jr2);
jl = new JLabel(“Selected: “);
jf.add(jr1);
jf.add(jr2);
jf.add(jl);
jf.setVisible(true);
}
173
public static void main(String[] args){
new RadioTest();
}
class MyListener implements ItemListener{
public void itemStateChanged(ItemEvent e)
{
if(e.getSource()== jr1) {
jl.setText(“Selected: Male”);
}
else if(e.getSource()==jr2)
{
jl.setText(“Selected: Female”);
}
else {
jl.setText(“Selected: None”);
}
}
}
}
The output of the program with ‘Female’ selected is shown below:
JList
In Java, Swing toolkit contains a JList Class. It is under package javax.swing.JList class. It is
used to represent a list of items together. One or more than one item can be selected from the
list. A JList object can be created with one of its constructors:
JList()
JList(ary[] listData)
While declaring a JList variable, a data type should be given within angular brackets since a
list uses Java generics feature, where the user can define what type of data it contains. Observe
how it is defined and how it is instantiated in the following example. The example shows a list
with some colors to select from. When the user selects a color, the list selection event is
triggered and it is handled by the inner anonymous class which sets the color to the label. Note
that JList generates events defined in javax.swing.event.ListSelectionListener, not from the
standard java.awt.event. Following is an example of a list:
import java.awt.*;
import javax.swing.*;
174
import javax.swing.event.*;
public class ListTest{
JFrame jf;
JList<String> jl;
String items[]={“Red”, “Green”, “Blue”, “Pink”,
“Yellow”, “White”, “Black”};
JLabel jlb;
public ListTest(){
jf= new JFrame();
jf.setSize(400,400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLayout(new FlowLayout());
jl = new JList<>(items);
jl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jf.add(jl);
jlb = new JLabel(“Selected: “);
jf.add(jlb);
jf.setVisible(true);
jl.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e){
String sel = jl.getSelectedValue();
jlb.setText(“Selected: “ + sel);
}
});
}
public static void main(String args[]){
new ListTest();
}
}
The output is as shown below. For every change in selection, the label is reset to that color.
Red
GREEN
Blue
Pink Selected : Green
Yellow
White
Black
175
JCombobox
Combo box is a combination of text fields and drop-down list. A combo box is created with
one of the following constructors:
JComboBox() – Creates an empty combo box which will be populated later.
JComboBox(String arr[]) – Creates a combo box with the elements of the array
When a combo box is created, items can be added to or removed from it with addItem() and
removeItem() respectively. When an item is selected, it generates an action event which can be
handled by creating a handler with actionPerformed() method. Following example shows a
simple JcomboBox with its handling mechanism. Following is an example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
JScrollPane
JScrollPane is an advanced component which adds functionality of scrolling to any component
by adding scrollbars. The scroll pane object is created with its constructor
JScrollPane(Component cp). The scrollbars can be selectively added or can be made automatic.
Following program adds scroll capability to a panel which is populated with 20 x 20 labels as
a grid.
import java.awt.*;
import javax.swing.*;
public class ScrollTest {
JFrame jf;
JScrollPane jsp;
public ScrollTest() {
jf = new JFrame(“Scroll Test”);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(300,300);
JPanel jp = new JPanel();
jp.setLayout(new GridLayout(20,20));
for(int i = 0; i < 20; i++){
for(int j = 0; j < 20; j++) {
jp.add(new JLabel(“Label (“ + i+”,”+j+”)”));
}
}
JScrollPane jsp = new JScrollPane(jp);// Create Scroll Pane
jf.add(jsp, BorderLayout.CENTER);// Add Scroll pane at center
jf.setVisible(true);
}
177
public static void main(String[] args){
new ScrollTest();
}
}
The output of the program is as shown below, with horizontal and vertical scrollbars.
JTabbedPane
JTabbedPane provides an advanced view for the components, where the components are
organized into different screens with tabs. Each tab contains a panel which will be shown
when that tab is clicked. The panel acts as the container for components. A JTabbedPane can
be created with its constructor JTabbedPane(). Once, a tabbed pane object is created, it can be
populated with different panels using its add(String tabName, Component cp) method. Following
example creates a tabbed pane with three tabs where each tab is attached with a different panel
and each panel is populated with different items.
Example:
import javax.swing.*;
JTable
JTable is an advanced container component that shows a two dimensional array of elements as
a table. It can be used to display data in tabular format including a header line. The JTable
contains two constructors:
JTable()
JTable(Object[][] data, Object[] headers)
Example:
import javax.swing.JFrame;
import javax.swing.JScrollPane;
179
import javax.swing.JTable;
public class TableTest{
JFrame jf;
// Initialize column headings.
String[] heading = { “Name”, “Phone”, “Ext” };
// Initialize data.
String[][] data = {
{“Anand”, “11223344”, “865”}, {“Bhanu”, “11223344”, “565”},
{“Charles”, “11223344”, “578”}, {“Dharma”, “22334455”, “111”},
{“Eeswar”, “22334455”, “333”}, {“Fathima”, “22334455”, “222”},
{“Gangaram”, “33445566”, “111”}, {“Hari”, “33445566”, “444”},
{“Irfan”, “33445566”, “222”}, {“Jagan”, “33445566”, “333”},
{“Krishna”, “11111111”, “111”}, {“Lakshmi”, “11111111”, “112”},
{“Malini”, “11111111”, “113”}
};
public TableTest() {
jf = new JFrame(“Table Test”);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(300,300);
//jf.setLayout(new FlowLayout());
JTable table = new JTable(data, heading); // Create the table.
JScrollPane jsp = new JScrollPane(table); // Add to a scroll pane.
jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jf.add(jsp); // Add the scroll pane to the content pane.
jf.setVisible(true);
}
public static void main(String args[]) {
new TableTest();
}
}
The output of a table example is given below:
180
JTree
JTree is an advanced container introduced in swing to create and manage a hierarchical view
of data. A JTree starts with one root node, which contains sub-root nodes and their children
nodes. The tree can be expanded or collapsed similar to a file explorer in windows.
When a node is selected from the JTree, it generates a TreeSelectionEvent which can be handled
by implementing TreeSelectionListener interface. A JTree object can be constructed using one
its constructors :
• public JTable() - Creates a JTree with a sample model.
• public JTree(TreeModel newModel) - Creates a JTree using TreeModel.
• public JTree(TreeNode root) - Creates a JTree with the specified TreeNode as its root.
Some useful methods in JTree are as shown below:
• public TreeModel getModel() - Gets the TreeModel whose data is displayed by JTree.
• public int getRowCount() - Gets the total number of the rows in the JTree.
• public void addTreeSelectionListener(TreeSelectionListener tsl) - Adds a listener for
TreeSelectionEvents with JTree.
An example of a simple JTree is given below.
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
public class TreeTest{
JFrame jf;
JTree tree;
JLabel jlab;
public TreeTest(){
jf = new JFrame(“Tree Test”);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(300,300);
// Create top node of tree.
DefaultMutableTreeNode root = new DefaultMutableTreeNode(“Root”);
// Create subtree of “A”.
DefaultMutableTreeNode st1 = new
DefaultMutableTreeNode(“Language”);
root.add(st1);
DefaultMutableTreeNode t11 = new DefaultMutableTreeNode(“Java”);
st1.add(t11);
DefaultMutableTreeNode t12 = new DefaultMutableTreeNode(“Python”);
st1.add(t12); 181
// Create subtree of “B”.
DefaultMutableTreeNode st2 = new DefaultMutableTreeNode(“Hobbies”);
root.add(st2);
DefaultMutableTreeNode t21 = new DefaultMutableTreeNode(“Sports”);
st2.add(t21);
DefaultMutableTreeNode t22 = new DefaultMutableTreeNode(“Movies”);
st2.add(t22);
DefaultMutableTreeNode t23 = new
DefaultMutableTreeNode(“Reading”);
st2.add(t23);
// Create the tree.
tree = new JTree(root);
// Add the tree to a scroll pane.
JScrollPane jsp = new JScrollPane(tree);
// Add the scroll pane to the content pane.
jf.add(jsp);
// Add the label to the content pane.
jlab = new JLabel();
jf.add(jlab, BorderLayout.SOUTH);
// Handle tree selection events.
tree.addTreeSelectionListener(new TreeSelectionListener(){
public void valueChanged(TreeSelectionEvent tse){
jlab.setText(“Selection is “ + tse.getPath());
}
});
jf.setVisible(true);
}
public static void main(String[] args) {
new TreeTest();
}
}
The output of the tree example is given below. Whenever the user selects a node, the label at
the bottom is set to the new path.
182
Check Your Progress
Note: a) Space is given below for writing your answers
b) Compare your answers with the one given at the end of the unit
3. What is a JTree?
............................................................................................................................................................
............................................................................................................................................................
............................................................................................................................................................
12.5. SUMMARY
This chapter introduced the major components of swing GUI programming along with procedure
to handle different events. Swing is a large subsystem of GUI programming. It has a considerably
large set of components and containers to accommodate these components. Almost every
possible screen can be designed with swing components and an appropriate container. Swing
adds J for each component to distinguish it from AWT equivalent like JFrame for Frame,
JButton for Button and so on. Similarly swing is organized into a large set of packages which
are different from AWT packages.When components are added to a container, the order or
place where these components should be added is controlled by a layout manager. Swing
provides layout managers defined by AWT which are FlowLayout, BorderLayout, GridLayout,
GridbagLayout and CardLayout. If the user wants to take control of the layout, the layout may
be set to null. Each layout adds the components in a specified way.JTable is an advanced
container component that shows a two dimensional array of elements as a table. It can be used
to display data in tabular format including a header line. The JTable contains two constructors.
JTree is an advanced container introduced in swing to create and manage a hierarchical view
of data. A JTree starts with one root node, which contains sub-root nodes and their children
nodes. The tree can be expanded or collapsed similar to a file explorer in windows. When a
node is selected from the JTree, it generates a TreeSelectionEvent which can be handled by
implementing TreeSelectionListener interface. A JTree object can be constructed using one its
constructors
183
12.6. CHECK YOUR PROGRESS MODEL ANSWERS
1. Swing uses model view controller (MVC) architecture which gives a clean separation
among the three components.
2. JTextArea works just like a JTextField, but can take multi-line input like address, feedback
etc.
3. JTree is an advanced container introduced in swing to create and manage a hierarchical
view of data.
12.8 GLOSSARY
MVC : Swing uses model view controller (MVC) architecture which
gives a clean separation among the three components.
JTabbedPane : Provides an advanced view for the components, where the
components are organized into different screens with tabs.
Delegation Model :Separating event handlng mechanism into
event, source, handler
JTree : An advanced container introduced in swing to create and
manage a hierarchical view of data.
Image Icon : Is an implementation of the Icon interface that paints Icons
from Images.
Layout Manager : When components are added to a container, the order or place
where these components should be added is controlled by a
184 layout manager.
Dr. B.R. Ambedkar Open University
B.Sc / B.Com./ B.A.
th
3rd Year 5 Semester (3 year degree course)
MODEL QUESTION PAPER
COMPUTER APPLICATIONS DSCC-4
DATA BASE MANAGEMENT SYSTEM
[Time: 3 hours] [Max. Marks: 80]
Section – A
[Short Answer Questions]
[Marks: 4x5=20]
Note: a) Answer any four of the following in about 10 lines each
b) Each question carries 5marks
1. [Block-I] Describe the steps to set the path and class path of Java 8..
2. [Block-I] Write a java program to print the size of various data types..
3. [Block-II] Write a java program to demonstrate box and Unbox int data type.
4. [Block-II] Describe final key word with inheritance in Java..
5. [Block-III] Describe the try catch finally blocks.
6. [Block-III] What is Array class? Write a program to demonstrate Array class.
7. [Block-IV] What is prepared statement? Describe with an example.
8. [Block-IV] Write a java program to close the awt window using adapter class
Section –B
[Essay type]
[Marks: 4x10=40]
Note: a) Answer any four of the following in about 30 lines each
b) Each question carries 10marks
9. [Block-I] Explain bitwise operators with suitable code examples in Java..
(Or)
10. [Block-I] Write program to find the prime numbers in a given range.
11. [Block-II] Explain static variables, static methods.static block with examples
(Or)
12. [Block-II] Explain multilevel inheritance with an example java program.
186
III. Fill in the blanks (5 marks)
1. Full form of JVM Java Virtual Machine
2. Full form ofJava SE 8 is Java Standard Edition 8
3. Full form ofJava JDK 8 is Java Development Kit 8
4. A member function with class name which initialize members is Constructor.
5. In Java members of classes are by default private
187