Module 1: An Introduction to Java
Language Overview
- What is Java?
- An object-oriented programming language with which programs are first
compiled and then interpreted:
- Unlike most programming languages, Java programs are compiled to
an intermediate code called bytecode
- The bytecode is interpreted by the Java interpreter
or JVM (Java Virtual Machine)
- A run-time environment that provides
operating-system type features (GUI's, threads, networking).
- A large library for application developement.
- A few development-supporting tools.
- A "community process" by which Java programmers and software
developers can contribute to future evolution of the language.
When you "download" Java, you really download a development
kit (usually called JDK) that contains:
- The compiler javac
and interpreter java.
- Support tools (like javadoc, jar, for example).
- Native OS support (whatever's needed to produce the
run-time environment: I/O, windows, threads etc).
- History:
- Java started off in 1991 as the language "Oak",
designed for working with devices.
- In 1994, Java designers realized the potential
of the web and the lack of a browser-controlling language.
- The browser HotJava was released in 1995, showing
off the power of Java.
- In 1996, Netscape decided to build a Java interpreter
(Java 1.02) into its browser.
- Java has since grown in popularity and capability:
- Java 1.0 and 1.1 are no longer in use.
- Java 1.2 is not recommended for most application development,
but parts of it are still used in PDA-type applications.
- Java 1.4 continues to be supported.
- Java 1.6 is the current (as of 2008) stable version.
- You can download either the standard edition or the
Enterprise edition (with more packages).
- Versions of Java are available for PDA's and embedded
applications.
- Additional libraries/packages are also available for special
applications (e.g., JavaMail, Java Media Framework etc).
- What can you do with Java?
- Nothing that you can't already do with C++ and
associated packages.
- With C++, you need a package (e.g, Tk/Tcl or
Xlib) for GUI's, a package for threads, a package for this, a package for
that...
- Java has features and a huge integrated library
that make it easier to:
- develop GUI-based, multithreaded, networked applications;
- develop web-based applications with security,
programmer-control, and database access;
- develop portable ("write-once, execute anywhere")
applications;
- allow remote-method invocation, object persistence,
dynamic loading;
- develop international applications, using local
languages and conventions.
- Showing off Java's features:
Java's designers describe Java as:
Java: A simple, object-oriented, distributed,
interpreted, robust, secure, architecture-neutral, portable, high-performance,
multithreaded, dynamic language.
Let's examine the hype:
- Is Java simple?
- Depends on your point of view:
C/Ada/Pascal programmer: |
"No way" |
Visual Basic programmer: |
"Not as simple as VB" |
C++ programmer: |
"Simpler language, but has a huge library"
|
- Size: interpreter and core-library is less than 300K (quite
small)
- Is Java object-oriented?
- Yes - support is provided for creating and using
objects.
- Not as pure as Smalltalk.
- Library is more object-oriented than C++'s library.
- Is Java distributed?
- Basic networking (using sockets) is much easier
in Java than in C/C++.
- A program can download code across the net and
execute it.
- Remote invocation (using RMI) is available, but
not trivial to use.
- Oriented towards client/server systems rather
than true distributed systems.
- Is Java interpreted?
- In one sense, yes - the compiler creates an intermediate
code (bytecode) that is interpreted.
- The interpreter is called the Java Virtual Machine
(JVM).
- It is not interpreted at the high-level, as a
script language is.
- Is Java robust?
- Designers' meaning of "robust": Java
has no pointers, so you can't corrupt memory.
- This is largely true if you avoid native
methods.
- Is Java secure?
- Java is probably the most secure general-purpose
language:
- No direct access (via pointers) to memory is
allowed.
- Bytecodes are checked by the interpreter before
execution.
- Sandbox model.
- Code can be digitally signed.
- Java provides some degree of control over security,
but is generally conservative.
- Security leaks are occasionally found, but SUN
moves quickly to fix them.
- Is Java architecture-neutral? Portable?
- Mostly, yes.
- As long as a machine implements the JVM and runtime
system, any Java program can run on it.
- Any browser that implements JVM can run Java.
- Data types have standardized definitions (e.g,
an int is
exactly 4 bytes anywhere).
- But...
- GUI windows can look different on Unix and Win-95.
- Graphics is pixel-based, so screen resolution
affects size.
- Language bugs have different effects on different
systems.
- Is Java high-performance?
- No! An interpreted, garbage-collecting language
can never be as fast as C/C++.
- C++ is about 2-10 times faster than interpreted
Java.
- Although native compilers are now available for Java,
C++ is 1-3 times faster (because of Java's garbage collection and extensive
checking)
- Note: with native compilation, you lose portability.
- Consider design cycle (and debugging with C++'s
pointers).
- Is Java multithreaded?
- Yes, although user-control over threads is limited.
- Thread implementation depends on underlying OS
or thread package.
- Is Java dynamic?
- What does "dynamic" mean? The ability
to load and execute code into an already-running program.
- Java is dynamic, but it's not easy to perform
dynamic loading.
Java's other nice features, for example:
- Applets
- Java let's you build web applications. Applets
have (almost) the full power of Java.
- Java's applets are secure (Sandbox model), unlike
CGI.
- The real reason for Java's popularity?
- Serialization and JAR
- Write and read objects to and from disk (persistence).
- Write into and read from compressed, structure-preserving
zip-like files.
- Java Beans
- Design components for use in a VB-like drag-and-drop
environment.
- Internationalization
- Write code that takes local custom into account
(e.g, dates, decimal points).
- Unicode is used instead of Ascii so that any
language can be handled.
- JDBC
- JDBC allows database access directly in Java.
- Many Dbase vendors have now implemented their
end of JDBC.
- Native methods
- You can write Java code that communicates with
C/C++ code.
- C/C++ code can be directly incorporated into
Java.
(The result is not portable, of course).
- Problems with Java (today):
- Java does not have a standard component-based
development environment, although Java Beans comes close.
- Java takes the "lowest common denominator"
approach to supporting OS features.
- Font and document management are difficult
in Java.
- Java's current applet technology makes server
communication non-trivial.
- For efficient, high-performance scientific code,
it's better to use C/C++.
- For low-level system stuff, you have to use C/C++.
- Single biggest advantage of using
Java:
(IMHO) Shorter development time.
Our first Java program: Helloworld
The file is
a plain text file:
public class HelloWorld {
public static void main (String[] argv)
{
System.out.println ("Hello World!");
}
}
To compile, use the compiler javac
(This is for Unix, don't type the percentage symbol):
% javac HelloWorld.java
This should produce a file called
HelloWorld.class
(the executable bytecode to be interpreted)
in the same directory.
To execute (java
is the Java interpreter):
% java HelloWorld
In-class exercise: Try it out!
Helloworld - a closer look
We will now look at HelloWorld2.java,
which similar to HelloWorld.java but has
more explanation:
// File: HelloWorld2.java
// Author: Rahul Simha
// Date created: August 14, 1998.
//
// Note how in-line comments start with //
// I will follow the above convention of filename, author etc.
public // Accessible outside this file. "public" is a reserved word.
class // "class" is a reserved word.
HelloWorld2 // The name of the class - same name as filename.
{ // Braces instead of begin/end.
public // This function must be accessible. "public" is reserved.
static // "static" is reserved.
void // The return value - nothing. "void" is reserved.
main // To start execution, a class must have a "main" function.
// "main" is sort-of reserved.
(String[] argv)
// Command line parameters are placed by the run-time system
// in argv[0], argv[1], etc.
{
System.out.println ("Hello World!");
// System.out is an object that contains a useful function
// called println, which takes in a string and prints it out on
// a new line.
System.out.println ("Here's the list of arguments you gave me:");
for (int i=0; i < argv.length; i++)
System.out.println ("Argument#" + i + ": " + argv[i]);
// Notice how strings can be concatenated with the `+' operator.
// Is `i' a string or a variable?
System.out.println ("Bye!");
}
}
Try executing this as either (Unix):
% java HelloWorld2
or
% java HelloWorld2 I dont know whats going on
A more complex example
Just to get a feel for a real Java program, let's
look at a more complex example:
(source file)
import java.awt.*;
import java.awt.event.*;
public class MoreComplexExample
extends Frame
implements ActionListener {
// Store current location of mouse
int currentX=0, currentY=0;
// Peculiarities of the Java GUI model -- listener objects
public void createListeners ()
{
this.addMouseListener (
new MouseAdapter ()
{
public void mousePressed (MouseEvent m)
{
System.out.println ("mousePressed event: " + m.paramString());
int x = m.getX();
int y = m.getY();
Graphics g = MoreComplexExample.this.getGraphics();
g.drawLine (currentX, currentY, x, y);
currentX = x;
currentY = y;
}
}
);
this.addMouseMotionListener (
new MouseMotionAdapter ()
{
public void mouseDragged (MouseEvent m)
{
System.out.println ("mouseDragged event: " + m.paramString());
int x = m.getX();
int y = m.getY();
Graphics g = MoreComplexExample.this.getGraphics();
g.drawLine (currentX, currentY, x, y);
currentX = x;
currentY = y;
}
}
);
}
// Button-pressed events
public void actionPerformed (ActionEvent a)
{
String eventDesc = a.getActionCommand();
System.out.println ("Button event: " + eventDesc);
Color c = Color.gray;
if (eventDesc.equalsIgnoreCase ("quit"))
System.exit(0);
else if (eventDesc.equalsIgnoreCase ("red"))
c = Color.red;
else if (eventDesc.equalsIgnoreCase ("blue"))
c = Color.blue;
else if (eventDesc.equalsIgnoreCase ("green"))
c = Color.green;
this.setBackground (c);
this.repaint();
}
// Test the code via a static function
public static void test ()
{
MoreComplexExample f = new MoreComplexExample ();
FlowLayout fl = new FlowLayout();
f.setLayout (fl);
Button qb = new Button ("Quit");
qb.addActionListener (f);
f.add (qb);
Button rb = new Button ("Red");
rb.addActionListener (f);
f.add (rb);
Button bb = new Button ("Blue");
bb.addActionListener (f);
f.add (bb);
Button gb = new Button ("Green");
gb.addActionListener (f);
f.add (gb);
f.createListeners ();
f.setResizable (true);
f.setSize (500,600);
f.setVisible (true);
}
// To start execution, "main" is needed
public static void main (String[] argv)
{
test ();
}
}
To compile:
% javac MoreComplexExample.java
To execute:
% java MoreComplexExample
In-class exercise 2: Try executing the
program.