Chopra Rajiv Object Oriented Programming Using Scala and Java
Chopra Rajiv Object Oriented Programming Using Scala and Java
A I C T E
OBJECT ORIENTED
PROGRAMMING
( USING SCALA AND JAVA )
RAJIV CHOPRA
Get free access to e-books for 3 Months
Best Selling Textbooks in COMPUTER SCIENCE ENGINEERING
by
Renowned Authors from Prestigious Publishers
PHI
... & many more
RAJIV CHOPRA
Associate Professor
Department of Computer Science, GTBIT
GGSIPU, Delhi
AICTE
GLOBAL OFFICES
• New Delhi NEW AGE INTERNATIONAL (P) LIMITED, PUBLISHERS
7/30 A, Daryaganj, New Delhi-110002, (INDIA), Tel.: (011) 23253472, 23253771
E-mail: [email protected] • Visit us at www.newagepublishers.com
• Chennai 26, Damodaran Street, T. Nagar, Chennai-600 017, Tel.: (044) 24353401
E-mail: [email protected]
• Guwahati Hemsen Complex, Mohd. Shah Road, Paltan Bazar, Near Starline Hotel
Guwahati-781 008, Tel.: (0361) 2513881, E-mail: [email protected]
• Hyderabad 105, 1st Floor, Madhiray Kaveri Tower, 3-2-19, Azam Jahi Road, Near Kumar Theater
Nimboliadda Kachiguda, Hyderabad-500 027, Tel.: (040) 24652456
E-mail: [email protected]
• Kolkata RDB Chambers (Formerly Lotus Cinema) 106A, 1st Floor, S N Banerjee Road
Kolkata-700 014, Tel.: (033) 22273773, E-mail: [email protected]
• Mumbai 142C, Victor House, Ground Floor, N.M. Joshi Marg, Lower Parel, Mumbai-400 013
Tel.: (022) 24927869, 24915415, E-mail: [email protected]
• New Delhi 22, Golden House, Daryaganj, New Delhi-110 002, Tel.: (011) 23262368, 23262370
E-mail: [email protected]
ISBN: 978-93-89802-20-7
C-21-09-12826
Preface v
Acknowledgements vii
Syllabus viii
1. Introduction to Java.........................................................................................................1–25
1.0 Introduction 1
1.1 Abstract Data Types [ADTs] and their Specifications 1
1.2 How to Implement Abstract Data Types [ADTs]? 2
1.3 Concrete State Space and Concrete Invariant 7
1.4 Abstraction Function 7
1.5 Java History 7
1.6 How Java Works? 8
1.7 Java Virtual Machine (JVM) 11
1.8 Just In Time (JIT) Compiler 13
1.9 Java Features 13
1.10Java Tools 15
1.11Using Java with Other Tools 16
1.12Native Codes 21
1.13Java Application Types 22
1.14Java Comparisons with C and C++ 23
Exercise Questions 25
2. Java Fundamentals.......................................................................................................26–192
2.0 Introduction 26
2.1 My First Java Program—An Anatomy 26
2.2 Identifiers, Variables and Keywords 29
2.3 Data Types (in Java) 30
2.4 Literals (Constants) 34
2.5 Escape Sequences 37
2.6 Variables 38
2.7 Operators 42
2.8 String Concatenation 59
2.9 Operator Precedence and Associativity 61
x Contents
Introduction to Java
1.0 INTRODUCTION
Computers can perform different jobs as they are programmable. This important job of
programming is done by the programmers. It is an art as well as a science. It is also a science
because programs do not work properly the first time as they are written. It needs a lot of
analyzing (its space and time complexity), experimenting (with dry runs), redesigning, if
needed. The programs should be functional, efficient, powerful and easy to use. This adds
to its quality. The solution to any problem is written in form of a program now. A program is a
set of instructions written in a programming language. A programming language provides
a medium for conveying the instructions to the computer. A program transforms the inputs to
the outputs. To solve a problem, either bottom-up approach or top-down approach is followed.
In bottom-up approach or working backward approach the problem can be solved by starting
from the Goal state to the Start state. In top-down approach or the problem decomposition
technique, however, a problem is decomposed into smaller units over and over again until each
smaller unit is manageable. Please note that a complex problem is simplified and solved by
decomposing it into many simple problems. And then finding sub-solutions for all of these
sub-problems and finally combining these sub-solutions to get the solution as a whole.
This is known as divide-and-conquer strategy. This approach of program development is
also known as stepwise refinement or modular decomposition or structured approach or
algorithmic approach.
Ada Lovelace is considered to be the first computer programmer.
JAVA is a new object-oriented programming language that was developed by James Gosling
and his team at Sun Microsystems in California. The language was based on C and C++. The
language was first called as Oak, named after the oak tree outside of Gosling’s office. But
this name was already taken by someone so the team renamed it as JAVA. Also note that JAVA
is known as a web programming language because of its use in writing programs called as
applets (to be discussed later) that run within a web browser. Even complete applications
in Java can be written as we write in other programming languages. Many other object-
oriented programming languages also exist like C++, Simula, SmallTalk, ADA etc.
If we have to sort a set of numbers then we need an abstract model (an array, a sorting
algorithm) of a data structure. To develop a new model, we need to define abstract objects
2 Object Oriented Programming—Using Scala and Java
plus operations of them. Before we discuss further just keep the following points in mind
regarding ADTs: -
1. ADT is a mathematical model.
2. A set of values and a collection of operations on those values are defined on the model.
For example, int datatype in C is an implementation of ADT → INTEGER-ADT.
INTEGER-ADT Specifies two things—
(a) Range of numbers that will be represented.
(b) Operations that can be performed on integer numbers like addition, subtraction,
multiplication etc.
3. When we use ADTs, our program divides into two parts—
(a) Application part.
(b) Implementation part.
Where Application part –describes uses of ADT.
Implementation part- implements ADT.
4. ADT is a useful tool for specifying the logical properties of a datatype.
5. Data type =
6. ADT refers to basic mathematical concept that defines the data type.
7. ADTs are generalizations of basic (primitive) data types like integer, float etc. just as
procedures are generalizations of basic operations (additions, subtraction etc.).
8. Almost all programming languages support basic /primitive data types but they are not
sufficient. Java also supports a derived data type called as a class.
9. But by just defining a class type, the operations applicable to the objects of that type
cannot be specified. So, the concept of ADT is necessary.
10. Therefore, we can say that
Data type = permitted data values + operations
Data structure = organized data + allowed operations.
An ADT is a generalized description of a “concrete” data type such as int or string. The
flow diagram of ADT usage is as follows: -
From ADT → interface → class → objects
Introduction to Java 3
Object getNext( )
Returns: some element of this bag.
Post Condition: this bag is unchanged.
integer size( )
Post Condition: this bag is unchanged.
Return: number of elements in this bag.
This is an ADT for a Bag. It is different from an abstract class of JAVA as abstract class is
the one that has at least one abstract method. It is like a partial interface.
As per the flow diagram above, this ADT is now translated into a JAVA interface (just as an
algorithm is translated into a JAVA method). Hence, JAVA interface for Bag ADT is as follows:
public interface Bag {
public void add (Object object);
public boolean contains(Object object);
public Object getFirst( );
public Object getNext( );
public boolean remove (object, object);
public int size( );
}
Next we see its implementation in terms of classes.
//ArrayBag class implements Bag interface given above.
(d) Map.
Object
Abstract Set…………………Set
Abstract Map…………………Map
Fig. 1.1 (a)
Prefix ‘Abstract’ shows that they include abstract methods that are implemented by their
subclasses. A list is a collection of elements that are accessible sequentially. The List interface
in JCF (as shown in fig. 1.1(a), adds 10 methods to 15 methods specified by the Collection
interface that it extends. So, all of the List, Queue, Deque and Set classes implement the List
interface. Now, we can Test a List class.
public class TestStringList
{
public static void main(String [ ] args)
{
List<String> list = new ArrayList <string> ();
Collections. addAll (list, “GB”, “DE”, “FR”, “ES”);
System.out.println (list);
list.add (3, “DE”);
System.out.println(list);
System.out.println (“list.get(3): “ + list.get(3));
System.out.println (“list.indexof: “ + list.indexof(“DE”));
System.out.println (“list.sublist: “ + list.sublist(1,5));
list.remove (“DE”);
System.out.println (list);
}
}
OUTPUTS:
0 1 2 3
[GD, DE, FR, ES]
[GB, DE, FR, DE, ES]
0 1 2 3 4
6 Object Oriented Programming—Using Scala and Java
list.get (3) : DE
list.indexOf (“DE”) : 1 (returns 1st occurrence index)
list.get (IE) : -1 (not in list)
list.sublist (1, 5) =[DE, FR, DE, ES] (starting from 1st index up to 4th position i.e. < 5 elements)
list.remove (“DE”) = [GB, FR, DE, ES] (removes 1st occurrence of DE)
Even iterators can be used on these lists by creating an object (say “it”) of ListIterator class
of JFC like,
it. nextIndex ( ); //returns index of elem that will be returned by subsequent call
it. next ( ); //return next element in list
it. previousIndex ( );
it. previous ( ); //return prev elem in list
it. add (E e ); //inserts specified element into list
it. hasNext ( ); //returns true if list has more elements
it. remove ( ); //removes from list the last element
it. set (E e ); // replaces last element returned by next
We are in a position to solve an example now.
Example 1
Write an ADT to maintain a counter of number of persons arriving at the shopping mall.
Show how all steps are followed to get classes and objects.
Solution:
The following are the steps followed: -
Step-1: Create an ADT-counter, as follows-
void reset (int counter)
Post Condition: counter set to 0
void incre (object counter)
Post Condition: counter = counter + 1
void getval (int counter)
Post Condition: get current value of counter – no change in its value.
Step-2: Transform this ADT to interface now.
public interface count
{
void reset (int counter);
void incre (object counter);
void getval (int counter);
}
Introduction to Java 7
that 2 is part of the name and not the version number. So that version of the language was
known as Java 2 version 1.2. The next version was Java 2 version 1.3. The current version
is JDK 15, released on 15th Sept. 2020.
Let us show the history of JAVA in a tabular form.
Table 1.1: History of Java
Year Features and Versions of JAVA
1990 Sun Microsystems started Stealth project supporting applications of computers in the
consumer electronics market.
1991 Green project started with the members of Stealth project such as James Gosling, Patrick
Naughton and Mike Sheridan. New programming language called as Oak was created by
Gosling.
1992 An intelligent remote control called StarSeven was delivered. The Green project was
incorporated under the name FirstPerson.
1993 Mosaic web browser was introduced in the field of Internet.
1994 HotJava web browser was introduced by Sun Microsystems.
1995 Oak was renamed as Java.
1996 Sun released the first version 1.0 of JAVA with core features like I/O, utilities, network
programming, and user interfaces like AWT, Applets and multithreading introduced.
1997 Sun released JDK 1.1 with new features like inner classes, JavaBeans, JDBC (Java Database
Connectivity) and RMI (Remote Method Invocation).
1998 JAVA 2 platform, Standard Edition (J2SE) 1.2, code named as Playground, was released. It
replaced JDK and JVM was equipped with JIT (Just-in-Time) compiler.
2000 J2SE 1.3, code named as Kestral, was released with key features like JavaSound APIs like
audio playback, recording etc.
2002 J2SE 1.4, code named as Merlin, was released with key features like integrated XML parser,
image I/O etc.
2004 J2SE 5.0 , code named as Tiger, was released with new features like enhanced for-loop,
autoboxing/unboxing, enums, etc.
2006 JAVA SE 6.0, code named as Mustang, was released with new features like swing, JDBC
4.0 support etc.
2008 Java SE 7.0, code named as Dolphin, with native support for XML with its role in Web services.
2020 JDK 15
Unlike most other software systems that usually settle into a pattern of small, incremental
improvements, JAVA continued to evolve at an explosive space.
a java source file has .java extension similar to a word file that has an extension of .doc, a
Pascal file has an extension of .pas and a text file that has an extension of .txt
JAVA source codes (programs/files with .java extension) are compiled into a format
called as bytecode (i.e. files with .class extension) using Java compiler (javac.exe). If there
is any error then the java compiler announces it else its class file is created by the Java compiler.
Finally, this class file can be executed by a JAVA VIRTUAL MACHINE (java.exe) also known
as Java Interpreter. It is shown in Figure 1.1(b).
Editor/IDE
.java file
{
System.out.println(“My First Java Program”);
}
}
We save this file, compile it and run it using Java compiler (javac). Say, this program file
(first.java) is stored in a subdirectory—”c:\java”. Now go to the command prompt then go to
subdirectory java and compile this source program as follows: -
C:\java\javac first.java
Now if there is no error in this program then the javac compiler produces a file—first.class
in the same directory. This class file is the bytecode version of the java source file. The concept
of –“Write-once, Run anywhere” is possible in Java. The source file can be compiled on any
platform that has a javac compiler. The resulting class file can run on any type of platform, using
Java interpreter (java), that has a Java Virtual Machine (JVM) as follows: -
C:\java\java first.class
JAVA environment includes a large number of development tools and several classes and
methods. The development tools are the part of the system known as Java Development Kit
(JDK). The classes and methods are the part of Java Standard Library (JSL). They are also known
as Applications that are used to develop and run java programs as shown in Table 1.2 below.
Table 1.2: JDK Contents
TOOL USAGE
Appletviewer Allows us to run java applets without using any java compatible browser.
java Java Interpreter, which runs applets and applications by reading and interpreting byte
code files.
javac It is the java compiler that translates java source code to bytecode files that the
interpreter can understand.
javadoc Creates HTML format documentation from java source code files.
javah Produces header files for use with native methods.
javap Java disassembler, that enables you to convert bytecode files into a program description.
jdb Java debugger that helps you to find errors in your programs.
Please note that with most of the other programming languages, we either compile or
interpret a program so that we can run it on our system. However, in Java, a program is both
compiled as well as interpreted. Also note that with the compiler, we first of all translate a
program into an intermediate language called as Java Bytecodes i.e. platform-independent
codes interpreted by the interpreter on the Java platform. The interpreter parses and runs each
Java bytecode instruction on the computer. Compilation is done just once but interpretation
is done each time the program is executed. The entire concept is shown in Figure 1.2.
Get free access to e-books for 3 Months
Best Selling Textbooks in COMPUTER SCIENCE ENGINEERING
by
Renowned Authors from Prestigious Publishers
PHI
... & many more