Preview 9789387284913
Preview 9789387284913
Third Edition
Yashavant Kanetkar
THIRD REVISED AND UPDATED EDITION 2018
Second Edition 2016
All Rights Reserved. No part of this publication can be stored in a retrieval system
or reproduced in any form or by any means without the prior written permission
of the publishers.
The Author and Publisher of this book have tried their best to ensure that the
programmes, procedures and functions described in the book are correct.
However, the author and the publishers make no warranty of any kind,
expressed or implied, with regard to these programmes or the documentation
contained in the book. The author and publisher shall not be liable in any event of
any damages, incidental or consequential, in connection with, or arising out of the
furnishing, performance or use of these programmes, procedures and functions.
Product name mentioned are used for identification purposes only and may be
trademarks of their respective companies / owners and are duly acknowledged.
Distributors:
BPB PUBLICATIONS BPB BOOK CENTRE
20, Ansari Road, Darya Ganj 376 Old Lajpat Rai Market,
New Delhi-110002 Delhi-110006
Ph: 23254990/23254991 Ph: 23861747
MICRO MEDIA
Shop No. 5, Mahendra Chambers, 150
DN Rd. Next to Capital Cinema, V.T.
(C.S.T.) Station, MUMBAI-400 001 Ph:
22078296/22078297
Published by Manish Jain for BPB Publications, 20, Ansari Road, Darya Ganj, New Delhi-
110002 and Printed him at Akash Press, New Delhi
Dedicated to
Nalinee and Prabhakar Kanetkar
- Yashavant Kanetkar
iii
About The Author
Through his books and Quest Video Courseware DVDs on C, Java, C++,
Data Structures, VC++, .NET, Embedded Systems, etc. Yashavant
Kanetkar has created, moulded and groomed lacs of IT careers in the last
two decades. Yashavant’s books and Quest DVDs have made a
significant contribution in creating top-notch IT manpower in India and
abroad.
Yashavant’s books are globally recognized and millions of students /
professionals have benefitted from them. Yashavant's books have been
translated into Hindi, Gujarati, Japanese, Korean and Chinese languages.
Many of his books are published in India, USA, Japan, Singapore, Korea
and China.
Yashavant is a much sought after speaker in the IT field and has
conducted seminars/workshops at TedEx, IITs, RECs and global software
companies.
Yashavant has recently been honored with the prestigious
“Distinguished Alumnus Award” by IIT Kanpur for his entrepreneurial,
professional and academic excellence. This award was given to top 50
alumni of IIT Kanpur who have made significant contribution towards
their profession and betterment of society in the last 50 years.
In recognition of his immense contribution to IT education in India, he
has been awarded the "Best .NET Technical Contributor" and "Most
Valuable Professional" awards by Microsoft for 5 successive years.
Yashavant holds a BE from VJTI Mumbai and M.Tech. from IIT Kanpur.
iv
Acknowledgments
Let Us Java is not an outcome of my work alone. A book on such a
dynamic language required inputs, help and suggestions from several
people. Topmost amongst them were our students at Nagpur training
centre and the participants in various seminars and workshops. Their
inputs have gone a long way in getting this book in the shape and form
in which you are holding it.
Over the years, I have used Java to build many applications. All these
practical experiences and usage scenarios are factored into Let Us Java.
I am indebted to Manish Jain of BPB Publications who had a faith in this
book idea, believed in my writing ability, whispered the words of
encouragement and made helpful suggestions from time to time. I hope
every author gets a publisher who is as cooperative, knowledgeable and
supportive as Manish.
I thank my family for enduring the late nights, the clicking keyboard and
mostly for putting up with yet another marathon book effort.
v
Contents
1. An Overview of Java 1
The Evolution 3
The Birth of Java 4
What is Java? 5
Traditional Programming Model 6
How is Java Different? 7
How Java Addresses Security? 8
Java or C++? 9
The Java Environment 10
Tools of the Trade 10
Exercise 12
KanNotes 14
2. Getting Started 17
Java Data Types 19
Rules for Constructing Constants 21
Rules for Constructing Variable Names 22
Java Keywords 23
The First Java Program 23
Compilation and Execution 28
One More Program 28
Exercise 30
KanNotes 32
vi
Constant Variables 49
Console Input/Output in Java 50
readLine( ) Function 50
println( )and format( ) Functions 51
Control Instructions in Java 53
Exercise 54
KanNotes 57
vii
KanNotes 109
7. Functions 111
What is a Function? 113
Why use Functions? 118
Passing Values between Functions 118
Exercise 123
KanNotes 127
viii
11. Arrays 185
What are Arrays 187
A Simple Program using Array 187
More on Arrays 189
Array Initialization 189
Bounds Checking 190
Passing Array Elements to a Function 191
Passing Array Reference to a Function 192
Returning an Array 193
Common Array Operations 193
Array of Objects 195
Multi-Dimensional Arrays 197
Passing and Returning 2-D Array 198
Jagged Array 200
Resizing of Arrays 202
Exercise 205
KanNotes 207
ix
Abstract Classes and Functions 252
Abstract Functions – Practical Example 256
Interfaces 258
Practical Uses of Interfaces 260
Interfaces–Focused View 261
Interfaces–Different Implementation 264
Interfaces–Unrelated Inheritance 266
Exercise 269
KanNotes 271
x
Launching Threads 332
Launching Multiple Threads 335
Another Way to Launch Threads 338
A Practical Multithreading Example 340
Synchronization 343
The Synchronized Block 346
Inter-thread Communication 346
Thread Priorities 347
Exercise 348
KanNotes 350
xi
Common Database Operations 405
Database Operations through Java 407
JDBC Architecture 407
JDBC Driver Types 408
MySQL Database Installation 409
Common JDBC API Components 409
Putting it to Work 410
Exercise 416
KanNotes 418
Index 421
xii
An Overview
of Java
1
You remain well-grounded when
you know your roots. Same is true
about Java. So a look at how it came
into existence and where it stands
amongst other programming
languages…
1
2 Let Us Java
Chapter Contents
The Evolution
The Birth of Java
What is Java?
Traditional Programming Model
How is Java Different?
How Java addresses Security?
Java or C++?
The Java Environment
Tools of the Trade
Exercise
KanNotes
Chapter 1: An Overview of Java 3
The Evolution
Approaches to programing keep evolving all the time. These approaches
are more or less driven by the computing needs of those times. When
these needs cannot be addressed by languages of that era, a need is felt
for a new language. These needs have become more and more complex
over the years.
In the early days of computing when the need was that a machine
should somehow be able to execute instructions, programming was
done by manually keying in the binary machine instructions. So long as
the programming task was small, programmers were ready to take the
pains of keying in instructions in binary.
As the tasks became more complex and the program lengths increased,
need was felt for a new language that makes it easier to write programs.
That’s when Assembly language was invented. In Assembly, instead of
binary, small abbreviations were used to write instructions. These
abbreviations were nothing but representations of binary instructions.
This made life much easier for the programmer. The assembly language
programs were very efficient.
As the demands of computing increased it was felt that learning and
using Assembly language is not very easy. To address this need, many
languages were invented. These included FORTRAN, BASIC and COBOL.
But these turned out to be suitable for specific domains. For example,
FORTRAN found widespread acceptance in scientific and engineering
applications, whereas, COBOL was typically used for building business
applications like payrolls, inventory management, etc.
These languages suffered from three important limitations. They are as
follows:
(a) They could not be used across the domains that they were
supposed to serve. So a change in domain necessitated a
programmer to learn a new language.
4 Let Us Java
(b) They could not be used to write system-level code that could
interact with hardware easily.
(c) All these languages were not designed around structured
programming principles. Hence, in programs of sizeable length it
became difficult to follow the flow of control.
What is Java?
Java is a programming language developed at Sun Microsystems in 1995.
It was designed by James Gosling. The language derives much of
its syntax from C++ (and its predecessor, C), but is simpler to use than
C++. Java’s reputation has spread wide and far and has captured the
imagination of most software professionals. Literally thousands of
applications are being built today in Java for different platforms
including desktop, web and mobile.
Possibly why Java seems so popular is because it is reliable, portable and
easy to use. It has modern constructs that are required to represent
today’s problems programmatically. Java, like C++ makes use of a
principle called Object-Oriented Programming (OOP) to organize the
program. This organizing principle has lots of advantages to offer. We
would be discussing this in detail in Chapter 8.
Let us now try to understand how Java achieves portability and
reliability.
6 Let Us Java
C Program
Figure 1.1
Any running program needs to make use of services of an Operating
System (OS) during its execution. These include services like performing
input/output, allocating memory, etc. You must be aware of the fact
that on the same microprocessor, different OS can be used. For
example, suppose there are two laptops having same Intel Pentium
microprocessor. On one laptop one can run Windows, whereas on the
other one can run Linux. But since the way these OSs offer different
Chapter 1: An Overview of Java 7
services is different, during conversion to machine language these
changes have to be accommodated. So for the same program, machine
language instructions for Intel + Windows combination would be
different than those for Intel + Linux combination. This is shown in
Figure 1.2.
C Program
Figure 1.2
Figure 1.1 and Figure 1.2 depict a scenario called “write once, compile
anywhere”. It means to make the same program work on a different
microprocessor + OS combination we are not required to rewrite the
program, but are required to recompile the program for that
microprocessor + OS combination. This is the approach taken by popular
traditional languages like C and C++.
Java Compiler
Interpreter/JIT Compiler
Figure 1.3
Java or C++?
After learning C, it is often a question whether one should migrate to
Java or C++. Answer is both; and that too in any sequence that you want.
Though both are Object Oriented programming languages, neither is an
advanced version of the other. Learning one before the other would
naturally help to learn the second.
It is important to note that both address different sets of problems. C++
primarily addresses complexity, whereas Java addresses portability and
security. In my opinion both languages would continue to rule the hearts
of programmers for many years to come.
As you start learning Java, you would find that there are many features
in it that are similar to C and C++. This is not by accident, but by intent.
Java designer knew that he has to provide a smooth transition path to
learners of Java language. That is why Java uses a syntax which is similar
in many ways to that of C and it follows many of the object oriented
features of C++, though in a refined fashion.
10 Let Us Java
JDK
JRE
Java
JVM Compiler
Interpreter / JIT Compiler Java API
Java
Debugger
Figure 1.4
Exercise
[A] Match the following:
(a) Structured
(b) Object Oriented
(c) Portable
Chapter 1: An Overview of Java 13
(d) Secure
(e) Suitable for Internet programming
(f) Simple syntax
(g) Architecturally neutral
(h) Management of complexity
14 Let Us Java
2 categories of software :
- System software - OS, Compilers, Device Drivers
- Application software - software for desktop/laptop, Web, Mobile
Technologies used in Java world for different platforms :
- Desktop - J2SE, Mobile - J2ME, Web - J2EE
Reasons of popularity of Java :
- Same language for varied applications
- Rapid Application Development (RAD) possible
- Easy development cycle
- Easy to manage large projects
Acronymns:
- API = Application Programming Interface JVM = Java Virtual
Machine
- JRE = Java Runtime Environment JDK = Java
Development Kit
API = Library of classes in form of packages
17
18 Let Us Java
Chapter Contents
Java Data Types
Rules for Constructing Constants
Rules for Constructing Variable Names
Java Keywords
The First Java Program
Compilation and Execution
One More Program
Exercise
KanNotes
Chapter 2: Getting Started 19
F our important aspects of any language are the way it stores data, the
way it operates upon this data, how it accomplishes input and
output, and how it lets you control the sequence of execution of
instructions in a program. We would discuss the first three of these
building blocks in this chapter.
For example, an integer data type can take values in the range
-2147483648 to +2147483647, and operations like addition, subtraction,
multiplication, division, etc., can be performed on it. Similarly, a boolean
data type can take a value true or false, and permits comparison
operations on it.
Based on where a data type can be created in memory, it is called a
primitive type (often also known as a value type) or a reference type.
Java forces primitive data types to get created only in stack and
reference types only on heap. For example, an integer (like say, 2341)
always gets created in stack, whereas a string (like say "Quest") always
gets created in heap. The guiding principle on the basis of which Java
does this decision making is—all data types that are small in size are
created in stack, and all those that occupy bigger memory chunks are
created in heap.
A primitive type as well as a reference type can be further categorized
into pre-defined and user-defined categories. Here pre-defined means
the data types that Java provides ready-made, whereas, user-defined
means the one that a common user like us can create. For example,
integer is a pre-defined primitive data type, whereas an Enumeration is
a user-defined value type. Figure 2.1 shows the different categories of
data types available in Java. Note that the pre-defined value types are
often also called Primitives.
20 Let Us Java
Primitive Types
Reference Types
(Value Types)
Reals Interfaces
Booleans
Figure 2.1
Amongst all the data types shown in Figure 2.1, to begin with, we would
concentrate on the pre-defined value data types. To use the data types
in a Java program we have to create constants and variables. A constant
is nothing but a specific value from the range of values offered by a data
type, whereas a variable is a container which can hold a constant value.
The container is typically a memory location and the variable is the
name given to the location in memory. For example, if we use an
expression x = 5, then the constant value 5 would be stored in a memory
location and a name x would be given to that location. Whenever, we
wish to retrieve and use 5, we just have to use the variable name x. This
is shown in Figure 2.2.
x 3 x 5
Figure 2.2
Chapter 2: Getting Started 21
As the name suggests, a constant’s value cannot change (fixed),
whereas, a variable's value can change (vary). A constant is often called
a literal, whereas, a variable is also known as an identifier. Figure 2.3
gives list of commonly used pre-defined primitive data types along with
the range of values that they can take and the numbers of bytes they
occupy in memory.
char 0 to 65535 2
int -2147483648 to +2147483647 4
float -3.4e38 to +3.4e38 4
Figure 2.3
There are certain rules that one needs to observe while creating
constants and variables. These are discussed below.
(c) The bytes occupied by each constant are fixed and do not change
from one compiler to another.
(d) Variable names are case-sensitive. So, abc, ABC, Abc, aBc, AbC are
treated as different variables.
(a) A variable name usually begins with an alphabet. Ex. speed, average
(c) If a variable name containing multiple words the words are either
connected using underscore or follow a camel-case notation. Ex.
current_speed, currentSpeed, avg_salary, avgSalary.
While following these rules and conventions one must avoid the
temptation of creating long variable names, as it unnecessarily adds to
the typing effort.
The rules remain same for constructing variables of any type. Naturally,
the question follows—how is Java able to differentiate between these
variables? This is a rather simple matter. Java compiler makes it
compulsory for us to declare the type of any variable name that we wish
to use in a program. Here are a few examples showing how this is done.
Java Keywords
Keywords are the words whose meaning has already been explained to
the Java compiler. When we make the declaration
int age ;
Figure 2.4
instead of this, we would write our first Java program now. Once we
have done that we would see in detail the instructions that it made use
of.
Before we begin with our first Java program do remember the following
rules that are applicable to all Java programs:
(b) Blank spaces may be inserted between two words to improve the
readability of the statement. However, no blank spaces are allowed
within a variable, constant or keyword.
Let us now write our first Java program. It would simply calculate simple
interest for a set of values representing principal, number of years and
rate of interest.
Java Program
Package1 Package2
class1 class2
function1 function1
{ {
instruction1 instruction1
instruction2 instruction2
... ...
} }
function2 function2
{ {
instruction1 instruction1
instruction2 instruction2
... ...
} }
class3 class4
function1 function1
{ {
instruction1 instruction1
instruction2 instruction2
... ...
} }
Figure 2.5
main( ) is a function. A function contains a set of statements.
Though a Java program can contain multiple functions, to begin
with, we would concentrate on only those programs which have
only one function. All statements that belong to main( ) are
enclosed within a pair of braces { } as shown below.
public static void main ( String[ ] args )
{
statement 1 ;
statement 2 ;
statement 3 ;
}
Chapter 2: Getting Started 27
The way functions in a calculator return a value, similarly, functions
in Java also return a value. Since we do not wish to return any value
from main( ) function we have to specify this using the keyword
void before main( ). main( ) is always preceded by the keyword
static. The purpose of this keyword and detailed working of
functions would be discussed in Chapters 9 and 7 respectively.
Any variable used in the program must be declared before using it.
For example,
int p, n ; /* declaration */
float r, si ; /* declaration */
si = p * n * r / 100 ; /* usage */
Any Java statement always ends with a semicolon ( ; ). For example,
float r, si ;
r = 15.5f ;
In the statement,
si = p * n * r / 100 ;
(b) Select File | New Project from the File menu. Select ‘Java’ from
‘Categories’ list box and ‘Java Application’ from ‘Projects’ box. Click
on ‘Next’ button.
(c) Give a proper name for the project in ‘Project Name’ text box (say
CalOfSi). Choose suitable location for the project folder, then click
on Finish.
/* Calculation of average */
package calofavg ;
public class CalOfAvg
Chapter 2: Getting Started 29
{
public static void main ( String[ ] args )
{
int x, y, z, avg ;
x = 73 ;
y = 70 ;
z = 65 ;
avg = ( x + y + z ) / 3 ;
System.out.println ( avg ) ;
}
}
30 Let Us Java
Exercise
[A] Which of the following is invalid variable name and why?
[B] Point out the errors, if any, in the following Java statements:
(a) int = 314.562f * 150 ;
(e) k = ( a * b ) ( c + ( 2.5fa + b ) ( d + e ) ;
(j) k = ( ( a * b ) + c ) ( 2.5f * a + b ) ;
(k) a = b = 3 = 4 ;
(b) Assume a suitable value for distance between two cities (in km.).
Write a Java program to convert and print this distance in meters,
feet, inches and centimeters.
(e) Assume suitable values for length and breadth of a rectangle, and
radius of a circle. Write a Java program to calculate the area and
perimeter of the rectangle, and the area and circumference of the
circle.
32 Let Us Java
Primtive types :
- Char - 2 bytes
- Integers - byte, short, int, long ( sizes - 1, 2, 4, 8 bytes)
- Real - float, double ( sizes - 4, 8 bytes respectively)
- Boolean - true / false (1 bit)
Derived types (classes) :
- Library : String, System, Exception, etc.
- User-defined : CalOfSi, CalOfAvg, etc.
Variable names are case-sensitive and should begin with an alphabet
3 types of comments :
- Single line - //
- Multiline - /* … */
- Documentation - /** …. */