Chapter-1: Introduction To Java
Chapter-1: Introduction To Java
1.0 Introduction
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: -
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: -
………………
………………
…………………….
…………………….
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.
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
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.
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.
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.
.java file
//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
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.
Figure-3: JVM
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.
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.
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
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: -
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
Note: JAVA made the web more interactive and dynamic as it can be easily used in
web page.
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.
[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.]
[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).]
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:-
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.
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.
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.
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.]
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.]
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]
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.
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.
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.
Q7. What are applets? Explain their usage. How are they different from Java
program.
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.]
Exercise Questions
Q1. What do you mean by object-oriented programming languages? What
are their features. Give some examples and explain.
Q3. What is the role of bytecodes in java? Explain with a neat sketch.
a) Abstraction.
b) Data hiding.
c) Encapsulation.
d) Polymorphism.
e) Class
f) Objects
g) Interfaces.
h) ADTs.