Object Oriented Programming Using Java
What is Java?
• A high-level programming language developed by Sun Microsystems. Java was originally called
OAK, and was designed for handheld devices and set-top boxes. Oak was unsuccessful so in 1995
Sun changed the name to Java and modified the language to take advantage of the burgeoning
World Wide Web.
• Java is an object-oriented language similar to C++, but simplified to eliminate language features
that cause common programming errors. Java source code files (files with a .java extension) are
compiled into a format called bytecode (files with a .class extension), which can then be executed
by a Java interpreter. Compiled Java code can run on most computers because Java interpreters and
runtime environments, known as Java Virtual Machines (VMs), exist for most operating systems,
including UNIX, the Macintosh OS, and Windows. Bytecode can also be converted directly into
machine language instructions by a just-in-time compiler (JIT).
• Java is a general purpose programming language with a number of features that make the language
well suited for use on the World Wide Web. Small Java applications are called Java applets and can
be downloaded from a Web server and run on your computer by a Java-compatible Web browser,
such as Netscape Navigator or Microsoft Internet Explorer.
Features of Java
1. Java is a Platform
Java (with a capital J) is a platform for application development. A platform is a loosely defined computer
industry buzzword that typically means some combination of hardware and system software that will
mostly run all the same software. For instance PowerMacs running Mac OS 9.2 would be one platform.
DEC Alphas running Windows NT would be another.
Java solves the problem of platform-independence by using byte code. The Java compiler does not produce
native executable code for a particular machine like a C compiler would. Instead it produces a special
format called byte code. Java byte code written in hexadecimal, byte by byte, looks like this:
CA FE BA BE 00 03 00 2D 00 3E 08 00 3B 08 00 01 08 00 20 08
21 |
This looks a lot like machine language, but unlike machine language Java byte code is exactly the same on
every platform. This byte code fragment means the same thing on a Solaris workstation as it does on a
Macintosh PowerBook. Java programs that have been compiled into byte code still need an interpreter to
execute them on any given platform. The interpreter reads the byte code and translates it into the native
language of the host machine on the fly. The most common such interpreter is Sun's program java (with a
little j). Since the byte code is completely platform independent, only the interpreter and a few native
libraries need to be ported to get Java to run on a new computer or operating system. The rest of the
runtime environment including the compiler and most of the class libraries are written in Java.
2. Java is Simple
Java was designed to make it much easier to write bug free code. Java has the functionality needed to
implement its rich feature set. It does not add lots of syntactic sugar or unnecessary features. Despite its
simplicity Java has considerably more functionality than C, primarily because of the large class library.
Because Java is simple, it is easy to read and write.
About half of the bugs in C and C++ programs are related to memory allocation and deallocation.
Therefore the second important addition Java makes to providing bug-free code is automatic memory
allocation and deallocation. The C library memory allocation functions malloc() and free() are gone as
are C++'s destructors.
Java is an excellent teaching language, and an excellent choice with which to learn programming. The
language is small so it's easy to become fluent. The language is interpreted so the compile-run-link cycle is
much shorter. The runtime environment provides automatic memory allocation and garbage collection so
there's less for the programmer to think about. Java is object-oriented unlike Basic so the beginning
programmer doesn't have to unlearn bad programming habits when moving into real world projects.
Finally, it's very difficult (if not quite impossible) to write a Java program that will crash your system,
something that you can't say about any other language.
3. Java is Object-Oriented
Object oriented programming is the catch phrase of computer programming in the 1990's. In object-
oriented programs data is represented by objects. Objects have two sections, fields (instance variables) and
methods. Fields tell you what an object is. Methods tell you what an object does. These fields and methods
are closely tied to the object's real world characteristics and behavior. When a program is run messages are
22 |
passed back and forth between objects. When an object receives a message it responds accordingly as
defined by its methods.
Object oriented programming is alleged to have a number of advantages including:
• Simpler, easier to read programs
• More efficient reuse of code
• Faster time to market
• More robust, error-free code
4. Java is Platform Independent
Java was designed to not only be cross-platform in source form like C, but also in compiled binary form.
Since this is frankly impossible across processor architectures Java is compiled to an intermediate form
called byte-code. A Java program never really executes natively on the host machine. Rather a special
native program called the Java interpreter reads the byte code and executes the corresponding native
machine instructions. Thus to port Java programs to a new platform all that is needed is to port the
interpreter and some of the library routines. Even the compiler is written in Java. The byte codes are
precisely defined, and remain the same on all platforms.
The second important part of making Java cross-platform is the elimination of undefined or architecture
dependent constructs. Integers are always four bytes long, and floating point variables follow the IEEE 754
standard for computer arithmetic exactly. You don't have to worry that the meaning of an integer is going to
change if you move from a Pentium to a PowerPC. In Java everything is guaranteed.
However the virtual machine itself and some parts of the class library must be written in native code. These
are not always as easy or as quick to port as pure Java programs.
5. Java is Safe
Java was designed from the ground up to allow for secure execution of code across a network, even when
the source of that code was untrusted and possibly malicious.
This required the elimination of many features of C and C++. Most notably there are no pointers in Java.
Java programs cannot access arbitrary addresses in memory. All memory access is handled behind the
scenes by the (presumably) trusted runtime environment. Furthermore Java has strong typing. Variables
23 |
must be declared, and variables do not change types when you aren't looking. Casts are strictly limited to
casts between types that make sense. Thus you can cast an int to a long or a byte to a short but not a long to
a boolean or an int to a String.
Java implements a robust exception handling mechanism to deal with both expected and unexpected errors.
The worst that an applet can do to a host system is bring down the runtime environment. It cannot bring
down the entire system.
Most importantly Java applets can be executed in an environment that prohibits them from introducing
viruses, deleting or modifying files, or otherwise destroying data and crashing the host computer. A Java
enabled web browser checks the byte codes of an applet to verify that it doesn't do anything nasty before it
will run the applet.
6. Java is High Performance
Java byte codes can be compiled on the fly to code that rivals C++ in speed using a "just-in-time compiler."
Several companies are also working on native-machine-architecture compilers for Java.
It is certainly possible to write large programs in Java. The HotJava browser, the Eclipse integrated
development environment, the LimeWire file sharing application, the jEdit text editor, the JBoss
application server, the Tomcat servlet container, the Xerces XML parser, the Xalan XSLT processor, and
the javac compiler are large programs that are written entirely in Java.
7. Java is Multi-Threaded
Java is inherently multi-threaded. A single Java program can have many different threads executing
independently and continuously. Three Java applets on the same page can run together with each getting
equal time from the CPU with very little extra effort on the part of the programmer.
This makes Java very responsive to user input. It also helps to contribute to Java's robustness and provides
a mechanism whereby the Java environment can ensure that a malicious applet doesn't steal all of the host's
CPU cycles.
Unfortunately multithreading is so tightly integrated with Java, that it makes Java rather difficult to port to
architectures like Windows 3.1 or the PowerMac that don't natively support preemptive multi-threading.
There is a cost associated with multi-threading. Multi-threading is to Java what pointer arithmetic is to C,
that is, a source of devilishly hard to find bugs. Nonetheless, in simple programs it's possible to leave multi-
threading alone and normally be OK.
24 |
7. Java is dynamically linked
Java does not have an explicit link phase. Java source code is divided into .java files, roughly one per each
class in your program. The compiler compiles these into .class files containing byte code. Each .java file
generally produces exactly one .class file.
(There are a few exceptions non-public classes and inner classes).
The compiler searches the current directory and directories specified in the CLASSPATH environment
variable to find other classes explicitly referenced by name in each source code file. If the file you're
compiling depends on other, non-compiled files the compiler will try to find them and compile them as
well. The compiler is quite smart, and can handle circular dependencies as well as methods that are used
before they're declared. It also can determine whether a source code file has changed since the last time it
was compiled.
More importantly, classes that were unknown to a program when it was compiled can still be loaded into it
at runtime. For example, a web browser can load applets of differing classes that it's never seen before
without recompilation.
Furthermore, Java .class files tend to be quite small, a few kilobytes at most. It is not necessary to link in
large runtime libraries to produce a (non-native) executable. Instead the necessary classes are loaded from
the user's CLASSPATH.
8. Java is Garbage Collected
You do not need to explicitly allocate or deallocate memory in Java. Memory is allocated as needed, both
on the stack and the heap, and reclaimed by the garbage collector when it is no longer needed. There's no
malloc(), free(), or destructor methods.
There are constructors and these do allocate memory on the heap, but this is transparent to the programmer.
The exact algorithm used for garbage collection varies from one virtual machine to the next. The most
common approach in modern VMs is generational garbage collection for short-lived objects, followed by
mark and sweep for longer lived objects. I have never encountered a Java VM that used reference counting.
Applications and Applets
There are two types of programs implemented in java- applets and applications. The difference lies on how
they are executed.
25 |
Applications : Application is a Java class that has a main() method. Generally, application is a stand-alone
program, normally launched from the command line, and which has unrestricted access to the host system.
Applications can execute independently.
Applet is a program which is run in the context of an applet viewer or web browser, and which has strictly
limited access to the host system. Applets are used to provide interactive features to web applications that
cannot be provided by HTML alone. They can capture mouse input and also have controls like buttons or
check boxes. In response to the user action an applet can change the provided graphic content.
Requirements for Creating Java programs
• Text Editor: Notepad, Jcreater, emacs or vi. Personally I use BBEdit on the Mac and TextPad on
Windows.
• Java Development Kit (JDK) : is a program development environment for writing Java applets and
applications. It consists of a runtime environment that "sits on top" of the operating system layer as well as
the tools and programming that developers need to compile, debug, and run applets and applications written
in the Java language.
• Command line OS – for compiling and Execution environment.
Understanding structure of Java Application
Example 1
class Test {
public static void main (String args[]) {
System.out.println("Hello Java Programmer!");
}
class Test
• class – Keyword class indicates the start of a class program
• Test – Class name ; Valid named to identify the class. Follow the rules for naming variables to
name classes
26 |
• public static void main (String args[]) – main method. It contains the following elements. Main ()
is the point where the execution of the program begin.
• public – indicate that main method can be accessed by any object.
• static – indicate that main method is a class method and that only one main can exist.
• void – indicate main method does not return a value.
• String args[] – argument to main method. It is array of type string. This array is mechanism
through which runtime system passes information to your application.
Creating Your First Application
Your first application, HelloWorldApp, will simply display the greeting "Hello world!". To create this
program, you will:
• Create a source file
A source file contains code, written in the Java programming language, that you and other
programmers can understand. You can use any text editor to create and edit source files.
• Compile the source file into a .class file
The Java programming language compiler (javac) takes your source file and translates its text into
instructions that the Java virtual machine can understand. The instructions contained within this file
are known as bytecodes.
• Run the program
The Java application launcher tool (java) uses the Java virtual machine to run your application.
Create a Source File
To create a source file, you have two options:
First, start your editor. You can launch the Notepad editor from the Start menu by selecting Programs >
Accessories > Notepad. In a new document, type in the following code:
27 |
/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
*/
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
Note: Type all code, commands, and file names exactly as shown. Both the compiler (javac) and launcher (java) are
case-sensitive, so you must capitalize consistently.
HelloWorldApp is not the same as helloworldapp.
Save the code in a file with the name HelloWorldApp.java. To do this in Notepad, first choose the File > Save
As menu item. Then, in the Save As dialog box:
1. Using the Save in combo box, specify the folder (directory) where you'll save your file. In this example, the
directory is java on the C drive.
2. In the File name text field, type "HelloWorldApp.java", including the quotation marks.
3. From the Save as type combo box, choose Text Documents (*.txt).
4. In the Encoding combo box, leave the encoding as ANSI.
When you're finished, the dialog box should look like this.
28 |
The Save As dialog just before you click Save.
Now click Save, and exit Notepad.
Compile the Source File into a .class File
Bring up a shell, or "command," window. You can do this from the Start menu by choosing Command
Prompt (Windows XP), or by choosing Run... and then entering cmd. The shell window should look
similar to the following figure.
A shell window.
29 |
The prompt shows your current directory. When you bring up the prompt, your current directory is usually
your home directory for Windows XP (as shown in the preceding figure.
To compile your source file, change your current directory to the directory where your file is located. For
example, if your source directory is java on the C drive, type the following command at the prompt and
press Enter:
cd C:\java
Now the prompt should change to C:\java>.
Note: To change to a directory on a different drive, you must type an extra command: the name of the drive. For
example, to change to the java directory on the D drive, you must enter D:, as shown in the following figure.
Changing directory on an alternate drive.
If you enter dir at the prompt, you should see your source file, as the following figure shows.
30 |
Directory listing showing the .java source file.
Now you are ready to compile. At the prompt, type the following command and press Enter.
javac HelloWorldApp.java
The compiler has generated a bytecode file, HelloWorldApp.class. At the prompt, type dir to see the new file
that was generated, as shown in the following figure.
Directory listing, showing the generated .class file
Now that you have a .class file, you can run your program.
Run the Program
In the same directory, enter the following command at the prompt:
31 |
java HelloWorldApp
The next figure shows what you should now see:
The program prints "Hello World!" to the screen.
Congratulations! Your program works!
Compiling and Executing the Application in Windows Environment
It is possible to compile and run Java program on the Editor environment without using command
environment. This is achieved by use of the editors such as Textpad, Jcreater which are integrated with
JDK components.
Steps
1. Write the source code
2. Save the source code e.g Test.java. (NB: Class name is always the file name).
3. To compile go to Tools > Compile Java.
32 |
4. To execute (run) the class file go to Tools > Run Java Application.
Output
33 |