Java Tutorial
About Java
-
Java is designed to be portable
-
Compiles into bytecode using javac
-
Must use interpreter to run a java program (java)
-
Interpreters available on many platforms
-
Java is a Web language
-
Can be run in most Web browsers
-
Java treats URLs
just as easily as most languages treat files
-
Java is similar to C++, but:
-
No multiple inhertance in classes
(but there is multiple inheritance in interfaces
-
No pointers (but there are references)
-
You don't have to worry about deleting objects -- Java has a build-in garbage
collector!
-
No preprocessor
-
No structs or unions
-
No enums
-
No typedef
-
Java has packages
"Hello World" Application
(This program is from (Campione & Walrath 1996).)
1 /**
2 * The HelloWorldApp class impliments an application that
3 * simply displays "Hello World!" to the standard output.
4 */
5 class HelloWorldApp {
6 public static void main(String[] args) {
7 System.out.println("Hello World!"); //Display the string
8 }
9 }
-
1-4: Doc comment -- "/** .. */" is used as comment,
and also used by automatic document generator.
-
Other comments are like C++'s:
"/* .. */" and
"//" (from here to end-of-line).
-
5: Class declaration; similar to C++
-
6: main method is required in application classes; similar to C's
main()
-
Parameters are similar to C's argv and argc, but argc
(arg count) isn't required because args is a a Java array, which is a real
OO-type container that can tell us the length and will not let us address
memory beyond its end.
-
7: Call method of println of class variable object out
in class System.
Compiling
$ javac HelloWorldApp.java
Produces the file HelloWorldApp.class containing bytecode
Running
The class in run in the Java interpreter:
$ java HelloWorldApp
Hello World!
$
Use the name of the class, not the the name of the file.
"Hello World" Applet
(This program is from (Campione & Walrath 1996).)
1 import java.applet.Applet;
2 import java.awt.Graphics;
3
4 class HelloWorld extends Applet {
5 public void paint(Graphics g) {
6 g.drawString("Hello World!", 50, 25);
7 }
8 }
-
1-2: import allows you to use the classes Applet and Graphics
without any prefixes.
-
java.lang is automatically imported (That's why the application in the
previous section didn't have to have an import line.
-
Can also import whole packages:
import java.applet.*;
import java.awt.*;
4: Class declaration; a subclass of class Applet
5: Overrides class Applet's paint() method; argument is the drawing
context
6: Call g's drawString() method to write "Hello World!" at coordinate
(50,25) relative to the upper left corner of the applet's display area.
Compiling
$ javac HelloWorld.java
Produces the file HelloWorld.class containing bytecode.
But it's not an application, it's and applet, so we need to run it in
a browser.
The HTML File
<HTML>
<HEAD>
<TITLE>A simple program</TITLE>
</HEAD>
<BODY>
Here is the output:
<APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25>
</APPLET>
</BODY>
</HTML>
Name the .java (and .class) file with the same name as the class. Put the
.class file in the same directory as the HTML file.
When the above HTML file is viewed in netscape, the HelloWorld class's
paint method is called:
View HelloWorld.html.
Types
Java Primitive Types
Type |
Size/Format |
integers |
byte |
8-bit two's complement |
short |
16-bit two's complement |
int |
32-bit two's complement |
long |
64-bit two's complement |
reals |
float |
32-bit IEEE 754 |
double |
64-bit IEEE 754 |
others types |
char |
16-bit Unicode char |
boolean |
true or false |
-
Primitive
types (see table at right)
-
Types are fixed, platform independant (contrast C++)
-
References
(implicit only)
-
Arrays
-
Classes
-
Interfaces
-
Operators, expressions
are all similar to C++'s
1 int[] arrayOfInts = new int[10];
2
3 for (int i=0; i ≤ arrayOfInts.length; i++) {
4 arrayOfInts[j] = j;
5 System.out.println("[j] = " + arrayOfInts[i]);
6 }
-
1: declaration uses [] to specify array
-
no untyped ("void*") arrays
-
user new to instantiate array
-
3:length attribute retrieves the number of elements
-
4:assignment like C++
-
5:integer is coerced into a string before being concatonated to
"[j] = "
1 String file;
2 file = "Input";
3 file = file + ".txt";
-
1: declaration of a String object, file
-
2: assignment to String literal
-
3: concatonation operator +
Can throw
ArrayIndexOutOfBoundsException
or NullPointerException
(for uninitialized object or array in an array)
See also Objects,
Classes, and Interfaces in Sun's Java Tutorial.
Very similar to C++. Exceptions:
-
You don't have to worry about deleting objects! Theres a garbage
collector!
-
class declaration is slighly different
[ modifiers ] class className
[ extends superClassName ]
[ implements InterfaceNames ] {
...}
-
modifiers
are
-
public: visible outside package
-
abstract: can't instantiate obejcts from this class
-
final: can't subclass this class
-
extends: inherits from
-
implements: implements the interface, and will be used by the type system
Note: here multiple inheritance is allowed
[accessSpecifier] [static] [final] [transient]
[volitile] type variableName
-
static: class variable
-
final: const
-
transient: not part of the persistent state
-
volitile: may be modified asynchronously
[accessSpecifier] [static] [final] [native]
[synchronized] type methodName ([paramList])
[throws exceptionsList]
-
static: class method
-
final: method can't be overridden in a subclass
-
native: method is written in another language
-
synchronized: method is a concurrent method
[public] interface interfaceName
[ extends listOfSuperInterfaces ]
...}
-
extends: inherits from
-
interfaces many not have member variables
-
interface methods may not have bodies
Access specifiers
Specifier |
class |
subclass |
package |
world |
private |
*
|
|
|
|
protected |
*
|
*
|
*
|
|
public |
*
|
*
|
*
|
*
|
package |
*
|
|
*
|
|
Notes
-
Method arguments are always pass-by-value
-
primitive types cannot be changed
-
reference types (arrays and objects) can be changed
-
super keyword is used to reference the parent class
-
Class object is always the top type (classes with no explicit superclasses
are subclasses of class object.
Examples
Try the above examples. Then copy them to your own directory and modify
them in interesting ways. There is lots of on line documentation on Java,
so it shouldn't be hard to make trivial modifications like randomized colors
on Nervous Text, or changing the timing on the waving wizard. Use you imagination.
449 students now have permission to use fsi. You must use fsi, and set
your path to include /usr/java/bin to be able to use javac. You can copy
the source from my web directory, as well as the html.
Have fun!
References
Arnold, K. & Gosling, J. (1996). The Java Programming Language, Addison-Wesley.
Campione, M. & Walrath, K. (1996). The Java Tutorial: Object-Oriented
Programming for the Internet. Reading, Massachusetts, Addison-Wesley.
Flanagan, D. (1996). Java in a Netshell. Bonn, O'Reilly &
Associates.
Sun Microsystems Inc. (1997). Java API Documentation (version
1.0.2). http://www.javasoft.com:80/doc/api_documentation.html,
February 4, 1997.
Sun Microsystems Inc. (1997). The Java Tutorial. http://www.javasoft.com/nav/read/tutorial.html,
February 20, 1997.
Sun Microsystems Inc. (1997). The Java Language Specification.
http://www.javasoft.com/doc/language_specification.html,
February 11, 1997.
Software
Engineering Research Network, Department
of Computer Science
Rob
Kremer