Introduction to JAVA
Objective:
- The history of the JAVA Language and
its salient feature
- What are the JAVA Runtime Environment
(JRE) and the JAVA Virtual Machine (JVM)
- JAVA and OOP
- How to run your first JAVA Program
The Java programming language is a relatively
high-level language, in that details of
the machine representation are not available
through the language. It includes automatic
storage management, typically using a
garbage collector, to avoid the safety
problems of explicit deallocation (as
in C's free or C++'s delete). High-performance
garbage-collected implementations can
have bound----ed pauses to support systems
programming and real-time applications.
The language does not include any unsafe
constructs, such as array accesses without
index checking, since such unsafe constructs
would cause a program to behave in an
unspecified way.
Introduction to JAVA
The story of JAVA starts from 1990s. James
Gosling, Patrick Naughton, Chris Warth and
their other team members started working
on the Green project. The project was to
design firmware (software code programmed
onto chips e.g. Rom, BIOS0 for electronic
equipment. For this purpose they used C++
as the programming language. But because
of some limitations in C++, they decided
to create their own language. They started
working on this new language in 1991 at
Sun Microsystems. After 18 months of development
they developed a new language which they
named Oak, after the name of
the oak tree peeping through the window
of James Goslings office. Unluckily
the agreement between Sun and the electronic
company did not go on any longer and thereon
further development of the new language
also stopped.
In 1993 when the worldwide web was getting
importance SUN Microsystems decided to launch
their language for the World Wide Web. So
in 1995 a re-featured language was announced
for the public. The language was given the
name JAVA.
What is JAVA? Salient Features
JAVA supports the writing of standalone
applications and applets. The old adage
that practice makes perfect is certainly
true when learning a programming language.
to encourage programming on the computer,
the mechanics of compiling and running JAVA
programs are outlined.
JAVA programming language is usually mentioned
in the context of the World Wide Web and
browsers that are capable of running programs
called Applets. Applets are usually small
in size to minimize download time and are
invoked by a HML web page.
JAVA applications are stand-alone programs
that do not require any web browser to execute.
They are typically general purpose programs
that run on any machine where the JAVA Runtime
Environment (JRE) is installed.
Speed of Development elimination
of the compile-link-load-test cycle.
Code of Portability enable
the operating system to make system level
calls on behalf of the runtime environment.
Provide a way for programs to run more
than one thread of activity
Provide a means to change programs dynamically
during their runtime life by allowing them
to download code modules.
Provide a means of checking code modules
that are loaded to assure security.
The JAVA Runtime Environment (JRE) and
JAVA Virtual Machine (JVM)
You can run JAVA programs on a wide variety
of computers using a range of operating
system. Your JAVA program will run just
as well on a PC running Windows 9x /NT/2000
as it will on Linux or a Sun Solaris workstation.
This is possible because a JAVA program
does not execute directly on your computer.
It runs on a standardized hypothetical computer
that is called the JAVA Virtual Machine
or JVM. The JAVA Runtime Environment JRE
consists of all the JAVA Language Libraries
required to compile a JAVA source file and
the JAVA Virtual Machine (JVM) required
to execute the compiled JAVA byte code.
The following figure explains the whole
process of compiling and executing a JAVA
program on a computer:
A JAVA compiler converts the JAVA source
code that you write into a binary program
consisting of byte codes. Byte Codes are
machine instructions for the JAVA Virtual
Machine. When you execute a JAVA program,
a program called the JAVA Interpreter performs
the following:
Inspects and deciphers the byte codes for
the program
Checks it to ensure that it has not been
tampered with is safe to execute
And then executes the actions that the byte
codes specifies within the JAVA Virtual
Machine.
A Java Interpreter can run stand alone,
or it can be part of a web browser such
as Netscape Navigator or Microsoft Internet
Explorer where it can be invoked automatically
to run applets in a web page.
Because a JAVA program consists of byte
codes rather than native machine instructions,
it is completely insulated from the particular
hardware on which it is run. Any computer
that has the JAVA environment implemented
will handle your programs as well as any
other, and because the JAVA interpreter
sits between your program and the physical
machine, it can prevent unauthorized actions
in the program from being executed.
Introduction to OOP
Software Development and maintenance is
costly and chances of errors are also there.
Objected oriented techniques and languages
are designed to address these problems through
re-usable software and program designs that
more closely model the real world.
As the name implies, a fundamental concept
behind OOP is the use of objects. An object
is a programming structure that group related
methods and the data those methods use.
It is mechanism that lets a programmer easily
represent objects in the real world with
objects in software. Furthermore an object
is designed to be a reusable entity that
can be used in multiple programs.
An object-oriented approach promotes the
development of programs by constructing
them from software components. These development
can often be reused in more than one situation.
By having reusable code, the need to create
new software for each new programming project
is reduced; reusable code in turn reduces
software development time and costs
JAVA is an object-oriented language. It
represents an evolutionary step in software
development, even among existing object-oriented
languages, improving on previous techniques
and contributing new important characteristics,
such as relationship with the web.
Object-Oriented Programming Defined
Object-oriented programming is a method
of programming based on a hierarchy of classes,
and well-defined and cooperating objects.
Classes
A class is a structure that defines the
data and the methods to work on that data.
When you write programs in the Java language,
all program data is wrapped in a class,
whether it is a class you write or a class
you use from the Java platform API libraries.
The ExampleProgram class from the simple
program in the first lesson of Part 1 is
a programmer-written class that uses the
java.lang.System class from the Java platform
API libraries to print a character string
to the command line.
class ExampleProgram {
public static void main(String[] args){
System.out.println("I'm a simple Program");
}
}
Classes in the Java platform API libraries
define a set of objects that share a common
structure and behavior. The java.lang.System
class used in the example defines such things
as standard input, output, and error streams,
and access to system properties. In contrast,
the java.lang.String class defines character
strings.
In the example, you do not see an explicit
use of the String class, but in the Java
language, a character string can be used
anywhere a method expects to receive a String
object. During execution, the Java platform
creates a String object from the character
string passed to the System.out.println
call, but your program cannot call any of
the String class methods because it did
not instantiate the String object.
If you want access to the String methods,
you can rewrite the example program to create
a String object as follows. This way, you
can call a method such as the String.concat
method that adds text to the original string.
class ExampleProgram {
public static void main(String[] args){
String text = new String("I'm a simple
Program ");
System.out.println(text);
String text2 = text.concat(
"that uses classes and objects");
System.out.println(text2);
}
}
The output looks like this:
I'm a simple Program
I'm a simple Program that uses classes and
objects
Objects
An
instance is an executable copy of a class.
Another name for instance is object. There
can be any number of objects of a given
class in memory at any one time.
In the last example, four different String
objects are created for the concatenation
operation, text object, text2 object, and
a String object created behind the scenes
from the " that uses classes and objects"
character string passed to the String.concat
method.
Also, because String objects cannot be
edited, the java.lang.String.concat method
converts the String objects to StringBuffer
(editable) string objects to do the concatenation.
Besides the String object, there is an
instance of the ExampleProgram.java class
in memory as well.
The System class is never instantiated
by the ExampleProgram class because it contains
only static variables and methods, and therefore,
cannot be instantiated by a program, but
it is instantiated behind the scenes by
the JavaTM virtual machine (VM).
Well-Defined Boundaries and Cooperation
Class definitions must allow objects to
cooperate during execution. In the previous
section, you saw how the System, String,
and StringBuffer objects cooperated to print
a concatenated character string to the command
line.
This section changes the example program
to display the concatenated character string
in a JLabel component in a user interface
to further illustrate the concepts of well-defined
class boundaries and object cooperation.
The program code to place the text in a
label to display it in a user interface
uses a number of cooperating classes. Each
class has its own function and purpose as
summarized below, and where appropriate,
the classes are defined to work with objects
of another class.
- ExampleProgram defines the program data
and methods to work on that data.
- JFrame defines the top-level window
including the window title and frame menu.
- WindowEvent defines behavior for (works
with) the Close option on the frame menu.
- String defines a character string to
create the label.
- JLabel defines a user interface component
to display static text.
- JPanel defines the background color,
contains the label, and uses the default
layout manager (java.awt.FlowLayout) to
position the label on the display.
Inheritance
One
object-oriented concept that helps objects
work together is inheritance. Inheritance
defines relationships among classes in an
object-oriented language. In the Java programming
language, all classes descend from java.lang.Object
and implement its methods.
The following diagram shows the class hierarchy
as it descends from java.lang.Object for
the classes in the user interface example
above. The java.lang.Object methods are
also shown because they are inherited and
implemented by all of its subclasses, which
is every class in the Java API libraries.
java.lang.Object defines the core set of
behaviors that all classes have in common.
As you move down the hierarchy, each class
adds its own set of class-specific fields
and methods to what it inherits from its
superclass or superclasses. The java.awt.swing.JFrame
class inherits fields and methods from java.awt.Frame,
which inherits fields and methods from java.awt.Container,
which inherits fields and methods from java.awt.Component,
which finally inherits from java.lang.Object,
and each subclass adds its own fields and
methods as needed.
Polymorphism
Another way objects work together is to
define methods that take other objects as
parameters. You get even more cooperation
and efficiency when the objects are united
by a common superclass. All classes in the
Java programming language have an inheritance
relationship.
For example, if you define a method that
takes a java.lang.Object as a parameter,
it can accept any object in the entire Java
platform. If you define a method that takes
a java.awt.Component as a parameter, it
can accept any component object. This form
of cooperation is called polymorphism.
Interface
n English, an interface is a device or a
system that unrelated entities use to interact.
According to this definition, a remote control
is an interface between you and a television
set, the English language is an interface
between two people, and the protocol of
behavior enforced in the military is the
interface between people of different ranks.
Within the Java programming language, an
interface is a device that unrelated objects
use to interact with each other. An interface
is probably most analogous to a protocol
(an agreed on behavior). In fact, other
object-oriented languages have the functionality
of interfaces, but they call their interfaces
protocols. The bicycle class and its class
hierarchy defines what a bicycle can and
cannot do in terms of its "bicycleness."
But bicycles interact with the world on
other terms. For example, a bicycle in a
store could be managed by an inventory program.
An inventory program doesn't care what class
of items it manages as long as each item
provides certain information, such as price
and tracking number. Instead of forcing
class relationships on otherwise unrelated
items, the inventory program sets up a protocol
of communication. This protocol comes in
the form of a set of constant and method
definitions contained within an interface.
The inventory interface would define, but
not implement, methods that set and get
the retail price, assign a tracking number,
and so on. To work in the inventory program,
the bicycle class must agree to this protocol
by implementing the interface. When a class
implements an interface, the class agrees
to implement all the methods defined in
the interface. Thus, the bicycle class would
provide the implementations for the methods
that set and get retail price, assign a
tracking number, and so on. You use an interface
to define a protocol of behavior that can
be implemented by any class anywhere in
the class hierarchy. Interfaces are useful
for the following: Capturing similarities
among unrelated classes without artificially
forcing a class relationship. Declaring
methods that one or more classes are expected
to implement. Revealing an object's programming
interface without revealing its class.
JAVA Programs
Two types of programs can be developed in
JAVA:
Standalone applications
Applets
Standalone JAVA Applications
A standalone application is what is normally
meant by a program: source code that is
compiled and directly executed. In order
to create a standalone application in JAVA,
the program must define a class with a special
method main. The main() method in the class
is the starting point for the execution
of any standalone application.
Applets
Applets are JAVA programs that must be run
in other applications such as web browsers.
Most of the well-known web browsers are
capable of running JAVA applets. The applet
viewer provided with the JDK can be used
to test applets. This is often useful, since
the JAVA runtime environment found in web
browsers is often not up to date with the
latest JAVA version.
My First JAVA Program
Create your first JAVA program to display
Hello World at the console by
following the steps below:
Open a notepad file and save it as MyFirstProgram.java
Write the following code and save the file
Class MyFirstProgram{
public static void main(String args[]){
System.out.println(Hello World);
}
}
Compile the above file invoking the JAVA
Compiler to generate the byte code for the
above program. This will create another
file with the name MyFirstProgram.class.
c:\> javac MyFirstProgram.java
To execute the above program invoked the
JAVA Virtual Machine (JVM) with the java
command.
c:\> java MyFirstProgram
then the output will be as:
Hello World
|