0% found this document useful (0 votes)
94 views

Chapter-1: Introduction To Java

This document provides an introduction to Java programming and abstract data types (ADTs). It discusses how ADTs provide a mathematical model for defining data types and their operations. An ADT for a bag is defined, showing the collection of values and operations. This ADT is then implemented using a Java interface and class. The document also discusses lists as a type of Java collection and provides an example of using an ArrayList.

Uploaded by

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

Chapter-1: Introduction To Java

This document provides an introduction to Java programming and abstract data types (ADTs). It discusses how ADTs provide a mathematical model for defining data types and their operations. An ADT for a bag is defined, showing the collection of values and operations. This ADT is then implemented using a Java interface and class. The document also discusses lists as a type of Java collection and provides an example of using an ArrayList.

Uploaded by

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

CHAPTER-1: 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
banalyzing (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.

1.1 Abstract Data Types [ADTs] and their Specifications

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 plus operations of them. Before we discuss further
just keep the following points in kind 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 =
[collection of values] + [ set of operations on those
values]

That collection + those operations

Form a mathematical model that is implemented using a


specific data structure.
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.

1.2 How to implement Abstract Data Types [ADTs]?

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

For example, for a Bag, its ADT definition will be-

A bag is a collection of objects.

void add (Object object)


Post Condition: given object is in bag.

boolean contains (Object object)


Post Condition: this bag is unchanged.

object getFirst ( ) Is an ADT


Returns: an element of this bag. for a bag

Object getNext( )
Returns: some element of this bag.
Post Condition: this bag is unchanged.

boolean remove(Object object)


Returns: true iff this bag was changed.

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.

public class ArrayBag implements Bag


{
private Object[ ] objects = new Objects[1000];
private int size, i;

public void add (Object object)


{
objects [size ++] = object;
}

public boolean contains (Object object)


{
for (int i = 0; i < size; i++)
if(objects[i] == object)
return true;
return false;
}
public object getFirst( )
{
i = 0;
return objects [i++];
}

………………
………………

public int size( )


{
return size;
}
}

Final step is to create objects of this class like

Bag bag = new ArrayBag( );

bag.add (“MERCURY LEARNING”);


bag.add (“USA”);

…………………….
…………………….

What are Lists?

Java collection Framework (JCF) is a group of classes and interfaces in


java.util.package. Collection means an object that contains other objects i.e.
elements.

Four main types of JCF are-

a) Lists.
b) Queue.
c) Set.
d) Map.
Object

AbstractCollection …………………………….Collection

AbstractList………………..List

ArrayList
Vector

AbstractQueue…………….Queue

AbstractSet…………………Set

AbstractMap…………………Map

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. ), 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

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 1: 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);
}

Step-3: Transform this interface to class now.

public counter implements count


{
//body also appears now
}

Step-4: Finally, objects are created.

counter c = new counter ( );


………………..
……………….
c. method-1( );
c. method-2( );

Hence, we can say that first of all ADT is created, then it is transformed
to an interface, which is then transformed into a class and finally the
objects are created. This is shown in steps-1 to step-4 above.

1.3 Concrete State Space and Concrete Invariant

A concrete class is a type of class that has methods defined in it.


Otherwise, the class is an empty class/stub. For a given problem we have
many solutions. This forms a state space. Now instead of trying to
symbolically analyze the whole state space, such an application could be
executed in concrete mode until a certain condition. It is basically concrete
state space exploration with matching on abstract states. A concrete model
may be built which can be further used to design and test it.

1.4 Abstraction Function

The following points may be remembered regarding abstraction function: -

1. It separates interface and implementation.


2. It provides access to a specific part of data.
3. It gives coherent picture of what the user wants. High cohesion is
achieved by means of good abstraction.
4. Abstraction is defined as a datatype called as a class which separates
interface from implementation.
5. The ability to encapsulate and isolate design from execution
information is known as abstraction.

1.5 JAVA History

Several versions of Java exist today ever since Sum Microsystems released
the first version of Java i.e. JAVA 1.0. This was followed by an updated
version, JAVA 1.1. When Sun released the next version, Java 1.2, they
changed the name of the language to JAVA 2. Please remember 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 Java 2 version 1.4.

Let us show the history of JAVA in a tabular form.

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.
Table-1: History of Java

Unlike most other software systems that usually settle into a pattern of
small, incremental improvements, JAVA continued to evolve at an explosive
space. We shall be studying the latest version JAVA 2 Platform
Standard Edition with JAVA DEVELOPMENT KIT 5.0 (JDK1.4.2_07)
in this book.

1.6 How Java Works?

JAVA is an object-oriented programming language similar to C++. It has


been, however, simplified to eliminate language features that cause common
programming errors. the source code is developed in either a plain text editor
like a Notepad or Wordpad or an Integrated development Environment
(IDE) like Netbeans IDE 7.0, JAVA creator or Gel or jEdit. Please note
that 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.
Editor/IDE

.java file

JAVA COMPILER javac.exe

.class file (byte codes)

JAVA VIRTUAL MACHINE


(INTERPRETER) Java.exe

Figure 1: JAVA’s Working

Compiled Java code can run on most computers because Java


interpreters and runtime environments (known as Java Virtual
Machine (JVM)) exists for most operating systems (including UNIX and
windows). Bytecodes can also be converted directly into machine
language instruction by Just-in-Time (JIT) compiler. In nutshell, the
process of compilation involves two steps: -

Step-1: Source code is converted to bytecode i.e. the instructions for an


imaginary machine called as the JAVA VIRTUAL MACHINE.

Step-2: This virtual machine is emulated by all Java interpreters. This


allows us to execute a compiled java program among different platform.
Notes:
1. Java is a general purpose programming language with a number of features that make the
language well suited for its use on WWW.
2. Small Java applications are called as Java Applets. They run on the system by a Java-
compatible web browser like Netscape Navigator or Microsoft Internet Explorer.
For example,

Create a java source file named as first.java as follows:-

//Program1—first.java

class first
{
public static void main (String args[ ] )
{
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-2 below.

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.

Table-2: JDK Contents


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-2.

Figure-2: Overall Flowchart


Thus, we can think of Java bytecodes as the machine code instructions
for the Java Virtual Machine (JVM). Every Java interpreter, whether it
is a development tool or a web browser that can run applets, is an
implementation of the JVM. Also understand that these bytecodes
make “write once, run anywhere” also possible. This means that you
can compile your program into bytecodes on any platform that has a
Java compiler. Then the bytecodes can be run on any implementation of
the JVM. This means that as long as a computer has a JVM, the same
program written in Java Programming language can be run on
WINDOWS 2K, A SOLARIS WORKSTATION or on an iMAC.

1.7 JAVA VIRTUAL MACHINE (JVM)

Java platform consists of a JAVA VIRTUAL MACHINE and a package


of ready-made software components. It is shown in figure-3. This package
is known as Java Application Programming Interface (API).

Figure-3: JVM

As we know that all programming languages use compilers to convert source


code into machine code for a specific computer. But Java is somewhat
different because Java produces a bytecode of a source code and this
bytecode is run by this JAVA VIRTUAL MACHINE (JVM). Also
understand that JVM is actually software and not a hardware unit. Its
job is to convert bytecode into machine code for a specific computer.
Thus, we can say that JVM is an interpreter for a bytecode. Java
bytecodes were made machine-independent so that they could be run on
a variety of machines. That is why, you need only JVM for each
platform. Also note that these bytecodes are not machine specific.

From figure-3, it is crystal clear that Java platform has two main
components: -
a) JVM—JAVA VIRTUAL MACHINE.
b) JAVA API—JAVA APPLICATION PROGRAMMING
INTERFACE.

JVM is the base for the Java platform and is ported onto various hardware-
based platforms. While Java API is a large collection of ready-made
software components that provides many useful capabilities like GUI
(Graphical User Interface). The Java API is grouped into libraries of related
classes and interfaces and these libraries are known as packages (to be
discussed later). Figure-4 shows a program running on the Java platform.

Figure-4: Snapshot of Java Running Program

From figure-4, it is crystal clear that the JAVA API and the virtual machine
insulate the program from the hardware. Native code is the code that after
you compile it, the compiled code runs on a specific hardware platform.
But as a platform-independent environment, the Java platform can be a
bit slower than the native code. But smart compilers, smart interpreters and
just-in-time bytecode compilers can bring performance closer to that of
native code without threatening portability.

Before we discuss further, please answer the following questions:-

Q1. What is a compiler?


Q2. Define a bytecode.
Q3. What is JVM?
Q4. Name some runtime data areas of JVM.
[Hint: Heap, Stack, Registers, Method area, Runtime constant Pool]
Q5. What was the earlier name of Java?
Ans. Oak.
Q6. What actually JVM is—Interpreter or Compiler?
Q7. What is the difference between JDK and JRE? How Java is platform
independent in case of JRE?

Q8. Briefly explain JVM, JDK and JRE?

1.8 Just In Time Compiler (JIT)

Each web browser that supports Java has a JAVA VIRTUAL


MACHINE (JVM) built right into it and it loads .class file. It is
also evident that when a program is interpreted, it generally runs
substantially slower than it would run if compiled to an
executable code. But remember that the use of bytecode
enables the Java run-time system to execute programs faster.
Sun has introduced Just In Time Compiler (JIT) for bytecode.
Just In Time Compiler (JIT compiler) is a part of JVM. Its job
is to take the generic i.e. cross-platform bytecodes and compile
them into more machine-specific instructions allowing the
program to run faster. Even though it is referred to as a JIT
compiler, it is the part of the virtual machine. When JIT is a part of
JVM, it compiles bytecode into executable code in real-time, on
demand basis. This is so because JVM performs various run-time
checks that can be done only at the run-time. Instead, JIT compiles
the code as it is needed during execution. JVM code is designed so
that it is easy to translate it into machine instructions for real
machines, so the second part of the translation to real machine
instructions is done in the browser on the user’s machine. Please
understand that the browser takes the applet JVM code that it
gets from the server and translates from JVM code to the
machine code the browser is using like a Pentium. And this
compiler in the browser is often called as a JIT compiler. Also
understand that JIT means that the last part of the compilation
is done before running the program.

1.9 JAVA Features


When JAVA was released publicly by Sun Microsystems in 1996 (USA)
then its authors also wrote a white paper in US magazine that explains their
design goals and some of them are discussed below.

1. Simple: JAVA is simple and easy to understand. Peter Naughton,


one of the authors of Java quoted that-“We wanted to build a
system that could be programmed easily without a lot of erotic
training and which leveraged today’s standard practice. So,
even though we found that C++ was unsuitable, we designed
Java as closely to C++ as possible in order to make the system
more comprehensible. Java omits many rarely used, poorly
understood confusing features of C++ that, in our experience,
brings more grief than benefit” [2]. From these statements, we
find that Java inherits the C/C++ syntax and many of the object-
oriented features of C++. Java is simple as compared to C++
because:-
a) Unstructured goto statement has been removed.
b) Java has no preprocessor.
c) No structures and unions.
d) Pointers are not supported.

2. Object-oriented: The authors of Java quoted that-“Object-


oriented design is a technique for programming that focuses on
the data (=objects) and on the interfaces to that object. To
make an analogy with carpentry, an “object-oriented”
carpenter would be mostly concerned with the chair he was
building and secondarily with the tools used to make it. A non
object-oriented carpenter would think primarily of the tools.
The object-oriented facilities of Java are essentially those of C+
+” [2]. There are no global functions in java rather all
functions are invoked through an object. Thus, Java is a pure
object-oriented programming language. Java believes that
everything is an object. It provides features like abstraction,
encapsulation, inheritance and polymorphism. Please understand
that anything in Java is embedded into a class.
3. Compiled and Interpreted: Java source programs are translated
into bytecode by Java compiler and this bytecode is interpreted by
the JAVA interpreter. Thus, Java is both compiled and
interpreted. When a java source program is compiled, it lists all
errors in that program. And when this program is error free, it is
interpreted by the interpreter which executes it line by line. It takes
some extra time for debugging a program. Please understand that
the Java interpreter can execute Java bytecode directly on any
machine to which the interpreter has been posted. Also note
that as linking is more incremented and lightweight process,
the development process can be much more rapid and
exploratory.

4. Portable: Java is portable because the bytecode produced by a


Java compiler can be run on any platform that has Java
interpreter. This portability is because of Java wide library---the
libraries that are a part of the system defined portable interfaces.
For example, there is an abstract windows class and
implementation of it for UNIX, windows and the Macintosh.
Java authors quoted that-“unlike C and C++, there is no
implementation-dependent aspect of the specification. The
sizes of the primitive’s data types are specified, as is the
behavior of arithmetic on them”.

5. Robust: Java is a strictly types language. It checks your code at


compile time as well as at the run-time. Thus, Java programs are
less error prone. Java provides an easy and wide exception
handling package to make it more robust language. Authors of
Java once quoted-“Java is intended for writing programs that
must be reliable in a variety of ways. Java puts a lot of
emphasis on early checking for possible problems, later
dynamic checking and eliminating situations that are error-
prone. The single bigger difference between Java and C++ is
that Java has a pointer model that eliminates the possibility of
overwriting memory and corrupting data.”

6. Multithreading: Java supports multithreading programming


environment that allows you to write programs that do many things
simultaneously. Please note that even the core of Java is
multithreaded.
7. Secure: Java does not allow a programmer to manipulate the
memory of a system. Authors of Java once quoted—“Java is
intended to be used in network distributed environments;
towards that end a lot of emphasis has been placed on security.
Java enables that construction of virus-free, tamper-free
systems.”
8. Distributed: Java programs can access data across a network. So,
it is distributed. Java is a complete language to build distributed
application. The authors of Java once quoted-“Java has an
extensive library of routines for coping with TCP/IP protocols
like HTTP and FTP. Java application can open and access
objects across the Net via URL with some ease when accessing
a local file system.” There is now a separate architecture, the Java
2 Enterprise Edition (J2EE) that supports very large scale of
distributed applications.
9. Architectural Neutral: Java first converts s source program into
bytecode which can be run on a variety of computers having
different operating systems. For example, if Java programs are
written on WINDOWS-XP and we want to use it on LINUX or
any other platform then without any modification, it can be
run on LINUX platform; just needed is Linux compatible
JVM. The authors of Java once quoted—“The compiler
generates an architecture-neutral object file format—the
compiled code is executable on many processors, given the
presence of the Java runtime system. The Java compiler does
this by generating bytecode instruction, which has nothing to
do with particular computer architecture. Rather they are
designed to be both easy to interpret on any machine and easily
translated into native machine code on the fly.”
10.High Performance: Java programs are faster as compared to
programs written in other interpreter-based programming
languages.
11.Dynamic: Java provides an efficient way for maintaining different
versions of an application. In many ways, JAVA is more dynamic
language than C++. It was designed to adapt to an evolving
environment. Libraries can freely add new methods and instance
variable without any effect on their clients.

1.10 JAVA TOOLS


JDK stands for JAVA DEVELOPMENT KIT. To write rapid Java
applications or applets, we need a tool to write, test and debug our programs.
All of these activities are the part of JDK only. Some vital Java tools are as
follows:-

1. The javac Compiler: Java programs are created in any text editor like
Notepad. We just need to open the text editor, type our program and save
this program with the extension .java. Every Java source file must have one
public class definition. This source file is converted to bytecode by the java
compiler, javac. The javac compiler converts this .java file that you
create to a .class file which contains bytecode.

Syntax is:

javac filename.java

Please note here that filename.java is the name of the java source file.
After execution of this statement, we get a bytecode file—filename.class,
which is interpreted by the Java interpreter, java.

2. The java Interpreter: The Java interpreter, java, is used to execute the
java class file produced by the javac compiler.

Syntax is:

Java filename.class

3. The jdb tool: It is used to debug a java program.

Syntax is:

Jdb filename.class

4. The javap Disassembler: To get back the java code from the bytecode,
we can use java disassembler called as javap.

Syntax is:

Javap filename.class
Please note that you can also get back the Java codes of more than one
file using a java disassembler as follows: -

javap file1.class file2.class file3.class

Also note that the filenames must be separated by spaces.

5. The javadoc tool: It is a document generator that creates HTML page


documentation for the classes that you create. To use javadoc, you have
to embed the statements between /** and */.

Syntax is:

javadoc filename.java

Again if you specify more than one file then they must be separated by
spaces.

6. The javah tool: It creates header and stub files that let you extend your
java code with the C language.

Syntax is:

javap filename.class

7. The Appletviewer: Applets are small programs that are not executed on
its own rather they are first embedded into web pages and then they are
executed using a Java enabled web browser. We can also run these
applets using the appletviewer. We can also test our applets using the
appletviewer.

Syntax is:

Appletviewer filename.html

1.11 Using Java with Other Tools


Java can be made to work with internet and with WWW. Let us now discuss
these two cases.

Case 1: Java and Internet.


Case 2: Java and WWW.

Case 1: Java and Internet

The first application written in Java was HotJava. It is a web browser to


run applets on Internet. Java is strongly associated with Internet. Internet
users can use Java to create applet programs and run them locally using a
Java enabled web browser. We can even download an applet from a remote
(far off) computer. We can, thus say that Java applets have made the Internet
a true extension of the storage system of the local computer. Internet users
can also create their own site containing java applets that could be used by
other users of the Internet. It is this ability that makes Java a unique
programming language for the Internet. This is the reason as to why Java
is known as Internet programming language.

Case 2: Java and WWW

WWW stands for WORLD WIDE WEB. It provides a consistent means to


access any type of information in a much more simplified manner. Please
note that WWW is different from an Internet because WWW is just one
of the many technologies that the Internet makes possible. WWW
contains web pages. A web browser is required to retrieve these web pages.
The first web browser was Mosaic. Others are like Netscape navigator,
Microsoft’s Internet Explorer. These are graphical web browsers meaning
that they can display graphics as well as text. A web page contains HTML
tags that enable us to find, retrieve, manipulate and display document world
wide.

Note: JAVA made the web more interactive and dynamic as it can be easily used in
web page.

Please remember the following points now: -


1. Internet is a massive network of networks, a networking
infrastructure. It collects millions of computers together globally.
Information that travels over the Internet does so via a variety of
languages known as protocols.

2. WWW or World Wide Web or simply a web is a way of accessing


information over the medium of the Internet. It is an information
sharing model that is built on top of the Internet. Web uses HTTP
protocol to transmit data. Web services, that use HTTP to allow
applications to communicate in order to exchange business logic, use
the web to share information. Web also uses browsers to access web
documents called as web pages that are linked to each other via
hyperlinks. Web documents also contain graphics, sounds, text and
video.

3. Web is just one of the ways that information can be disseminated over
the Internet.

4. The Internet (not the web), is also used for email, which relies on
SMTP, Usenet news groups, instant messaging and FTP.

5. So, web is just a portion of Internet but the two terms are not same
and should not be confused.

We are in a position to answer the following questions now.

Q1. What do you mean by Internet, Intranet and Extranet?

[Hint: Intranet is a network that operates locally by sung one or more Internet services
like email, www etc. Thus, we can say local Internet is an Intranet.
Internet is the network of networks which operates globally and connect local network
outside for everyone. It uses a common set of rules or protocols like TCP/IP suite.

Extranet is the combination of Internet and Intranet. When we connect our Intranet to
Internet, on authentication for special users that is compulsory for company is called as
Extranet. For example, VPN-virtual private networks.]

Q2. What do you mean by ISP?

[Hint: ISP or Internet Service Provider is a company that operates Internet facility
globally or locally and makes money monthly or yearly for it.
For example, Reliance, BSNL, Primus and Bharti (Airtel).]

Q3. The java compiler generates ________________.

Q4. JVM stands for ___________________________.

Q5. What are bootstrap class loader and user-defined class loader?

[Hints: The main task of JVM is to load .class files and to execute the bytecode they
contain. JVM contains a class loader which loads .class files, that are compiled versions
of the user programs and JAVA APIs. Please understand that only the mandatory
.class files from JAVA APIs are loaded into JVM. Java application can use 2 types of
class loaders:-

a) Bootstrap loader or primordial or system or default class loader—


that loads classes in default way from the local disk, usually.
b) User-defined class loader—is not the part of JVM implementation.
During execution, a Java application can install a user-defined class
loader like other .class files.]

Q6. Distinguish between structured programming and OOP.


[Hint: The differences are given in the tabular form below:-

Structured Programming Object-oriented Programming


1. Top-down is followed. 1. Bottom-up approach is followed.
2. The main focus is on algorithm and 2. The main focus is on objects and classes.
control flow.
3. A program is divided into a number of 3. A program is organized by having a
sub-modules or functions or procedures. number of classes and objects.
4. Functions are independent of each other. 4. Each class is related in a hierarchical
manner.
5. It views data and functions as two 5. It views data and functions as a single
separate entities. entity.
6. Software reuse is not possible. 6. Software reuse is possible.
7. Functions call is used. 7. Message passing is used.
8. Function abstraction is used. 8. Data abstraction is used.
9. Data-driven technique is used. 9. It is driven by delegation of
responsibilities.
10. Algorithm is given importance. 10. Data is given more importance.
11. No encapsulation—data and functions 11. Encapsulation is done here and it treats
are separate. code and data as a single unit called as a
class.
12. Costlier maintenance. 12. Cheaper maintenance.
Q7. Distinguish between abstraction and encapsulation.
[Hint: The differences are given in the tabular form below:-

Abstraction Encapsulation
1. It separates interface and 1. It groups together related concepts into
Implementation. one item.
2. It provides access to a specific part of 2. It hides data and the user cannot access
data. the same directly (data hiding).
3. It gives a coherent picture of what the 3. Coupling means dependency. Good
user wants. The degree of relatedness of an systems have low coupling. Encapsulation
encapsulated unit is defined as cohesion. results in lesser dependencies of one object
High cohesion is achieved by means of on other objects in a system that has low
good abstraction. coupling. Low coupling may be achieved
by designing a good encapsulation.
4. Abstraction is defined as a data type 4. Encapsulation packages data and
called as a class which separates interface functionality and hides the implementation
from implementation. details (information hiding).
5. The ability to encapsulate and isolate 5. Encapsulation is a concept embedded in
design from execution information is abstraction.
known as abstraction.

Q8. Distinguish between function call and message passing.


[Hint: The differences are given in the tabular form below:-

Function Call Message Passing


1. Function call may use zero or more 1. Message passing uses at least one
arguments. argument that identifies the receiving
agent.
2. It always identifies a single piece of 2. the function name is called as message
executable code. selector. The same name may be associated
with different receiving agents.
3. It is applied to data to carry out a task. 3. It is a way to access the data. Message
may invoke a function defined for a
specific purpose.
4. Consumer is responsible for choosing 4. Supplier is responsible for choosing the
functions that operate properly on the data. appropriate message.
5. There is no designated receiver in the 5. There is a designated receiving agent in
function call. message passing.

Q9. Distinguish between interface and implementation.


[Hint: The differences are given in the tabular form below:-

Interface Implementation
1. It is a user’s view point (what part). 1. It is the supplier’s view point (How
part).
2. It is used to interact with the outside 2. It describes how the delegated
world. responsibility is carried out.
3. User is permitted to access the interfaces 3. Functions or methods are permitted to
only. access the data. So, supplier is capable of
accessing data and interfaces.
4. It encapsulates the knowledge about the 4. It provides the restriction of access to
object. data by the user.

Q10. What are the main concepts involved in Object-oriented programming?


Write one line about each of these concepts.
[Delhi university, MCA-1st sem., 2008]

Q11. What are the main features of Java programming language? Give the
advantages of Java over C++. [GGSIPU, B. Tech. (CSE/IT)-5th sem., Dec.
2009]
[Hint: Refer to section 1.5 for Java features. Advantages of Java over C++ are as
follows:-
C++ JAVA2
1. it is compatible with C source code, 1. No backward compatibility with any
except for a few corner cases. previous language. But the syntax is highly
influenced by C/C++.
2. Write-once, compile anywhere 2. Write-once, run anywhere/ everywhere
(WOCA). (WORA/WORE).
3. It allows procedural programming, 3. It strongly encourages an object-oriented
functional programming, object-oriented programming paradigm.
programming and template meta-
programming.
4. It allows direct calls to native system 4. Call through the Java Native Interface
libraries. and recently Java Native Access.
5. Exposes low-level system facilities. 5. Runs on a virtual machine. Does not
always provide full access to the features
and performance of the platform on which
the software runs.
6. It only provides object types and type 6. It is reflective, allowing meta-
names. programming and dynamic code generation
at runtime.
7. Optional automated bounds checking. 7. Normally performs bound checking.
HotSpot can remove bounds checking.
8. It supports native unsigned arithmetic. 8. No native support for unsigned
arithmetic.
9. Pointers, references and pass-by-value 9. primitive and reference data types
are supported. always pass by value.
10. Explicit memory management. 10. Automatic garbage collection, no
concept of destructor and usage of
finalize() is not recommended.
11. It supports classes, structs and unions 11. It supports classes only and allocates
and can allocate them on heap or stack. them on heap.
12. It allows explicit overriding types. 12. Rigid type safety except for widening
conversions.

Q12. Write short notes on email, internet and intranet services.


[GGSIPU, B. Tech. (CSE/IT)-5th sem., Dec. 2009]

Q13. What is spaghetti code and how it is avoided in Java?


[Hint: It is a term used for the source code that has a complex and tangled control
structure like the code that uses many GOTOs, exceptions, threads or other
“unstructured” branching constructs. It is so called because the program flow tends to
look like a bowl of spaghetti i.e twisted and tangled. This type of code may result because
of less experienced programmers and complex software that underwent changes again
and again. Thus, structured programming decreased the incidence of spaghetti code.]

Q14. How can you force garbage collector in Java? [GGSIPU, B. Tech.
(CSE/IT)-5th sem., Sept. 2010]
[Hint: Garbage collection cannot be forced but only can be requested. Since JVM will
not start the garbage collection immediately, JVM will invoke “system.gc” to request the
garbage collection.]

Q15. a) Describe the distributed and dynamic property of Java?


b) What is the difference between JDK and JRE? How Java is
platform independent in case of JRE?
[GGSIPU, B. Tech. (CSE/IT)-5th sem., Sept. 2010]

Q16. Briefly explain the compilation process of java program, by stating the
role of class loader, byte code verifier and JSTL? [GGSIPU, B. Tech.
(CSE/IT)-5th sem., Dec. 2010]
[Hint: class loader has already been discussed. Let us see a Java Bytecode Verifier now.
It is a mini theorem prover that verifies that the language ground rules are respected.]

Q17. Write short notes on: a) JVM


b) Byte code and Unicode.
[Hint: We have already seen what JVM is and what is a bytecode. Let us now see what
is Unicode? Characters set in java are indices into 16-bit value that can be converted into
integers and manipulated with the integer operators like +, -. ]
[GGSIPU, B. Tech. (CSE/IT)-5th sem., Dec. 2011]
Q18. Briefly explain JVM, JDK and JRE. [GGSIPU, B. Tech. (CSE/IT)-5th
sem., Dec. 2011]

Q19. a) What do you mean by bytecode? Explain its working.


b) Why is Java more suitable as compared to other languages?
[MDU, B.E. (CSE/IT)-8th sem., Dec. 2008]

Q20. What are class loaders? [MDU, B.E. (CSE/IT)-8th sem., May 2009]
Q21. How does Java achieve portability? [GGSIPU, B. Tech. (CSE/IT)-5th
sem. , Dec. 2013]
Q22. Why is Java considered as the best language for internet applications?
[GGSIPU, B. Tech. (CSE/IT)-5th sem. , Dec. 2013]

1.12 Native Codes

The environment, in which you are using a subroutine written in other


programming language such as C/C++, is called as a native code. Java
provides the native keyword which is used to declare native code methods.
Once declared, these methods can be called from inside your Java programs
just as you call any other Java method. To declare a native method, precede
the method with the native modifier as follows:-

Public native int sqr( );

Please note here that you do not need to define any body for the method.
Also note that the native methods are linked to Java program
dynamically at run -time by following a rather complex series of steps.
A native method is written in some other in some other language like C or
C++ or assembly and compiled to the native machine code of a particular
processor. Native methods are stored in dynamically linked libraries
(DLL) or shared libraries. They are platform specific whereas Java
methods are platform independent. During execution of a Java program,
a call to native methods loads the DLL containing the native method.

Limitations/ drawbacks of Native codes

1. Security Loss: If you import a native method then there are chances
of a virus invitation because native code is not confined to the Java
execution environment.
2. Portability Loss: Since the native code is contained in a DLL,
therefore a Java program that uses native methods will be able to run
only on a machine for which a compatible DLL has been installed.

1.13 JAVA Application Types

Java applications are basically of four types:-

1. Applications: An application is a program that you execute


from the MS DOS prompt or UNIX prompt. Java provides both
text-based and GUI-based applications. These are stand-alone
programs. These do not require any web browser to execute. These
are general-purpose programs (programs written in other languages
like C/C++, Basic etc.) that run on any machine where the Java
runtime environment is installed.
2. Applets: The programs that reside on World Wide Web are
known as applets. The applets are downloaded by a browser to a
client’s system (that’s your system) and are run by that browser.
These applets are usually small in size to minimize download time.
These applets are invoked by a HTML web page. Thus, applets are
smaller Java programs that execute inside a web page. Applets
need Java enabled web browser like Microsoft Internet explorer or
hot java, to run. Please note that an applet is loaded and
executed when it is embedded into a web page through a web
server. When users view the web page in which the applet is
embedded, they interact with the applet. Also note that applets
have Graphical User Interface (GUIs). An applet cannot access
the resources of the local machine. Let us tabulate the differences
between the two in a tabular form now.

Applications Applets
1. Application programs use main ( ) 1. Applets do not use the main ( )
method for initiating the execution of method for initiating the execution of
the code. the code. Applets, when loaded,
automatically call certain methods of
Applet class to start and execute the
applet code.
2. These programs can run 2. Applets cannot run independently.
independently. They run embedded into a web page
on a web browser using HTML tag.
3. These can read from or write to 3. These cannot read from or write to
the files on a local computer. the files on a local computer.
4. These can run some other program 4. These cannot run any program
from the local computer. from the local computer.
5. Java language can use these 5. Applets are restricted from using
libraries of other languages like C libraries from other languages.
and C++ using native method.

3. Servlets: These programs extend the functionality of web services.


Servlets do not have graphical interfaces. Java servlets are server-
side components that can extend the functionality of a Java-
enabled web server.
4. Packages: They are collections of classes that can be shared by
other Java programs. Packages in Java are just like libraries in
C/C++. Java provides of packages like java.lang, java.util,
java.io etc.

1.14 Java Comparisons with C and C++

Let us compare the three—Java, C and C++ in a tabular form based on


certain features.

Features JAVA C C++


1. Goto, sizeof, No, not included Yes, included. Yes, included.
typedef
statement
2. Struct, union, No, not included Yes, included. Yes, included.
enum datatype
3. Pointers No, not included Yes, included. Yes, included.
4. Preprocessor No, not included Yes, included. Yes, included.
directives like
#include,
#define)
5. Break and With label Without label Without label
continue
6. Operator No, not included No, not included Yes, included.
overloading
7. Template No, not included No, not included Yes, included.
classes
8. Multiple Implemented No, not included Yes, included.
Inheritance using Interfaces
9. Global No, not included Yes, included. Yes, included.
variables
10. Header files No, not included Yes, included. Yes, included.

We are in a position to answer the following questions now.

Q1. What is the difference between applet and servlet?

Q2. Give the advantages of Java over C++.

Q3. Is chaining there in Servlet?


[Hint: Yes, chaining exists in Servlet]

Q4. Define what is a native code?

Q5. Write main drawbacks of Applet?

Q6. Write the differences between Servlet and JSP.

Q7. What are applets? Explain their usage. How are they different from Java
program.

Q8. Why is Java more suitable as compared to other languages?

Q9 Discuss about the three major java programming technologies as given


by Sun.
[Hint: J2ME, J2SE and J2EE; J2SE (Java 2 Platform, Micro Edition) is the core java
language. It provides an environment for developing many different types of Java
applications; it includes support for GUI programming, threads, input/output, networking,
XML, CORBA, Applets, JavaBeans, RMI, security and database access.
J2ME is not a slimmed –down version of J2SE rather it establishes a procedure for
defining what a particular JVM designed for an electronic device will provide. J2ME
technology has 2 components: -

a) Configurations: That defines the type of JVM that is being targeted.


b) Profiles: That describes specification details about the device that is
being targeted. Each device has a profile listing standard Java APIs
available for that device.

Please understand that configurations are composed of Java API and virtual
machines designed to run on two different types of devices and are as follows: -

a) The 1st type of device s those with 128-512KB of memory. This configuration is
called as the Connected Limited device Configuration (CLDC) and the
corresponding JVM is called as the K Virtual Machine or KVM.

b) The 2nd configuration is for devices with more than 512KB of memory. This
configuration is called as the Connected Device Configuration and uses the
standard JVM, with all capabilities of a regular desktop computer.

Profiles are defined by the Java Community Process (JCP), which allows for input
from any industry interested in a profile for a particular type of electronic device.
For example, a profile would be created for cellular phones, with the profile defining the
configuration to use for wireless phones and the Java APIs that will be available. Any
company that had interest in wireless phones could join the JCP to help determine which
configuration to choose and what Java API would look like for developing Java
applications for cellular, wireless phones.
J2EE is a collection of Java technologies that create a platform for distributed
applications. Both J2SE and J2EE allows for the most complex multi-tier software
applications to be portable across multiple platforms. It consists of different
technologies like EJB, JSP, XML etc.
Also understand that just as J2SE programs run in a JVM, J2EE applications run
in a J2EE-complaint application server. the application server implements the J2EE
specification, allowing developers to create applications that use any or all of the J2EE
technologies but that are still platform independent. For example, some popular
application servers are IBMs Web Sphere, BEA System’s Web Logic and
Macromedia’s JRun.]

Q10. Name some web browsers.


[Hint: Netscape, Firefox, Internet Explorer, Google Chrome etc.]

Q11. Name some popular Java IDEs.


[Hint: Eclipse, Netbeans, JBuilder, MS Visual J#, AnyJ (free for Linux), BlueJ,
JasmineIDE, TextPad, Ready, C_Forge, CodeGuide, CodeWarrior etc.]

Q12. Is it possible to have more than one JDK version on a system?


[Hint: Yes]

Q13. What is an IDE?


[Hint: Editor, compiler, debugger, trace facility etc. all are available in an IDE].
Q14. What is a project?
[Hint: A collection of source and resources files]

Q15. What is a compilation unit?


[Hint: Java source code file]

Q16. Give the roles of bin and lib in JDK.


[Hint: bin directory contains all tools like javac, applet viewer, awt tool etc. so,
executable files of the commands like javac, java, AppletViewer are available in bin
directory of JAVAHOME. While lib directory contains all packages and variables.]

Exercise Questions
Q1. What do you mean by object-oriented programming languages? What
are their features. Give some examples and explain.

Q2. “Java is architecturally neutral.” Explain.

Q3. What is the role of bytecodes in java? Explain with a neat sketch.

Q4. Define the following terms: -

a) Abstraction.
b) Data hiding.
c) Encapsulation.
d) Polymorphism.
e) Class
f) Objects
g) Interfaces.
h) ADTs.

Q5. Write an ADT for a stack showing its basic operations.

Q6. What are lists in Java? What is JCF? Explain.

Q7. Differentiate between a concrete class and an empty class.

Q8. Define what is a stub?

You might also like