Download Introduction to Java - New Age International

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Falcon (programming language) wikipedia , lookup

Structured programming wikipedia , lookup

C Sharp syntax wikipedia , lookup

Go (programming language) wikipedia , lookup

Library (computing) wikipedia , lookup

Object-oriented programming wikipedia , lookup

Java syntax wikipedia , lookup

One-pass compiler wikipedia , lookup

Compiler wikipedia , lookup

Name mangling wikipedia , lookup

Interpreter (computing) wikipedia , lookup

Scala (programming language) wikipedia , lookup

Java (programming language) wikipedia , lookup

C Sharp (programming language) wikipedia , lookup

Java performance wikipedia , lookup

Transcript
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 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 subsolutions 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
Simula, SmallTalk etc.
1.1
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
2
JAVA Programming
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.
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.
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.
3
Introduction to Java
1.2
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 Fig. 1.1.
Fig. 1.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.
4
JAVA Programming
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 1.2.
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.
5
Introduction to Java
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 Fig. 1.2.
Fig. 1.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.3
JAVA VIRTUAL MACHINE (JVM)
Java platform consists of a JAVA VIRTUAL MACHINE and a package of ready made software
components. It is shown in Fig. 1.3. This package is known as Java Application Programming Interface
(API).
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,
Fig. 1.3: JVM
we can say that JVM is an interpreter for a bytecode. Java
6
JAVA Programming
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 Fig. 1.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 1.4 shows a program
running on the Java platform.
Fig. 1.4: Snapshot of Java running program
From Fig. 1.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:
Q.1. What is a compiler?
Q.2. Define a bytecode.
Q.3. What is JVM?
Q.4. Name some runtime data areas of JVM.
[Hint: Heap, Stack, Registers, Method area, Runtime constant Pool]
Q.5. What was the earlier name of Java? [GGSIPU, B. Tech(CSE/IT)-5th sem, August 2009]
Ans. Oak.
7
Introduction to Java
Q.6. What actually JVM is—Interpreter or Compiler?
[GGSIPU, B. Tech(CSE/IT)-5th sem, Sept. 2010]
Q.7. What is the difference between JDK and JRE? How Java is platform independent in
case of JRE?
[GGSIPU, B. Tech(CSE/IT)-5th sem, Oct. 2010]
Q.8. Briefly explain JVM, JDK and JRE?
[GGSIPU, B. Tech(CSE/IT)-5th sem, Dec. 2011]
[Hint: JRE is important set of tools that are required in order to display Java applications on
server. Such application can include software and games. JRE works as the communicator
between OS in question and Java based programs.]
1.4
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 realtime, 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. 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.5
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” [1]. 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.
8
JAVA Programming
(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 objectoriented carpenter would think primarily of the tools. The object-oriented facilities of Java
are essentially those of C++” [1]. 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 typed 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
9
Introduction to Java
that end a lot of emphasis has been placed on security. Java enables that construction of virusfree, 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 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.6
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.
10
JAVA Programming
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.7
USING JAVA WITH OTHER STOOLS
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.