📄 http:^^www.cs.wisc.edu^~cs537-1^java-tutorial.html
字号:
Date: Tue, 05 Nov 1996 00:27:28 GMTServer: NCSA/1.5Content-type: text/htmlLast-modified: Thu, 31 Oct 1996 21:38:52 GMTContent-length: 64410<html><head><title>Java for C++ Programmers</title></head><body bgcolor="#ffffff"><h1>Java for C++ Programmers</h1><hr><h2> Contents </h2><ul><li><!WA0><!WA0><!WA0><!WA0><!WA0><!WA0><a href="#intro"> Introduction </a><li><!WA1><!WA1><!WA1><!WA1><!WA1><!WA1><a href="#sort"> A First Example </a><li><!WA2><!WA2><!WA2><!WA2><!WA2><!WA2><a href="#objects"> Values, Objects, and Pointers </a><li><!WA3><!WA3><!WA3><!WA3><!WA3><!WA3><a href="#garbage"> Garbage Collection </a><li><!WA4><!WA4><!WA4><!WA4><!WA4><!WA4><a href="#access"> Static, Final, Public, and Private </a><li><!WA5><!WA5><!WA5><!WA5><!WA5><!WA5><a href="#arrays"> Arrays </a><li><!WA6><!WA6><!WA6><!WA6><!WA6><!WA6><a href="#strings"> Strings </a><li><!WA7><!WA7><!WA7><!WA7><!WA7><!WA7><a href="#constructors"> Constructors and Overloading </a><li><!WA8><!WA8><!WA8><!WA8><!WA8><!WA8><a href="#inheritance"> Inheritance, Interfaces, and Casts </a><li><!WA9><!WA9><!WA9><!WA9><!WA9><!WA9><a href="#exceptions"> Exceptions </a><li><!WA10><!WA10><!WA10><!WA10><!WA10><!WA10><a href="#threads"> Threads </a><li><!WA11><!WA11><!WA11><!WA11><!WA11><!WA11><a href="#io"> Input and Output </a><li><!WA12><!WA12><!WA12><!WA12><!WA12><!WA12><a href="#util"> Other Goodies </a></ul><a name="intro"><h2> Introduction </h2></a><p>The purpose of these notes is to help 537 students learn enough aboutJava to do the course projects.All of the students have experience programming in C++,but practically none of whom have used Java.<h3> What is Java? </h3><p>Before we turn to the details, it is worth considering why Javahas created such a stir.Much of it has nothing to do with the language <em> per se </em>but with the way it is intended to be used.<p>To understand this point, you have to know a little bit aboutthe World-Wide Web.The Web consists of a set of<em> servers </em>scattered around the Internet,each of which maintains a set of<em> pages. </em>Each page has a ``name'' called a<em> Universal Resource Locator </em> (URL)that uniquely distinguishes it from any other page in the world.The URL starts with the name of the server.For example, the URL of this document,<code>http://www.cs.wisc.edu/~cs537-1/java-tutorial.html</code>,says that it can be retrieved by using the HyperText Transfer Protocol(http) to connect to server <code>www.cs.wisc.edu</code> and ask it forthe page it calls <code>/~cs537-1/java-tutorial.html</code>.<p>Each page is written in a combination of text and formatting directives calledthe<em> HyperText Markup Language </em> (HTML).A<em> browser </em>is a program that runs on a personal computer or workstationthat knows how to display HTML documents(<em> Netscape Navigator </em> is currentlythe most popular browser by far, but Microsoft and others are tryingto change that).HTML is fairly simple.For example, the directive <code><p></code> is used to starta paragraph, and text is set in <i>Italics</i> by surrounding itwith <code><i></code>and <code></i></code>.The most important directive precedes some text with<code><a name="</code><em>URL</em><code>></code>and follows it with <code></a></code>.The browser underlines the text, and when the user clicks on it withthe mouse, the browser goes and gets the page named by the URL anddisplays it.To see more examples of HTML, take a look at this document.If you are using Netscape Navigator, select ``Document Source''from the ``View'' pull-down menu at the top of the window.<p>No sooner had HTML caught on that people wanted to extend it.Directives were added to show text in different<font color="#00ff00">colors</font>and<font size="+3">sizes</font>,or make it<blink>blink</blink>.A set of directives was added to display<!WA13><!WA13><!WA13><!WA13><!WA13><!WA13><a href="http://www.cs.wisc.edu/~cs537-1/cs537.html#schedule">tables</a> and images<!WA14><!WA14><!WA14><!WA14><!WA14><!WA14><IMG ALIGN=TOP SRC="http://www.cs.wisc.edu/pics/getstats.gif">.<p>Next came sound and movies.The possibilities seemed endless.<p>There was one big problem, however:If you created a document using a new feature, it couldn't be displayedby a browser that didn't ``understand'' that feature.Thus for a feature to be useful, it had to be implemented by all (or at least a substantial fraction of) the millionsof browsers ``out there''.<p>Then someone got a bright idea:How about including with each document a program capable of displaying it?The browser wouldn't have to ``understand'' the document.It could just run the executable code that came with it, and that codewould know how to display the document.Unfortunately, this idea has two very serious problems.<p>The first problem is that browsers run on all sorts of computers,running all sorts of operating systems.If I include with my document a program designed to run on a SparcStationunder Solaris, it will be useless on a Pentium running Windows 95.The second program concerns security.Running programs from random untrusted sources on your own computer isasking for trouble.That's what viruses are all about.Instead of displaying the document, the program may clear your disk orlook for private information and send it back overthe network to a bad guy.<p>Fortunately, there is another idea that solves both of these problems.Instead of including a machine-language program with a document,send a program written for a<em>virtual machine</em>that is simulated by a software interpreter.Arrange to have each browser include an interpreter for the virtual machine.In a sense, this just re-introduces the previous problem of requiringa new feature to be implemented by everyone's browser, but only onelast time.Once you've convinced all the browser vendors to implement an interpreterfor the virtual machine,they won't have to implement any more extensions.<p>The interpreter can also include security safeguards.For example, if it doesn't implement any operation to open files,you don't have to worry about a mischievous program stealing your data.It is very difficult, if not impossible, to build such safeguards aroundmachine-language programs, because such programs can contain ``bugs''that are actually devious tricks to circumvent security restrictions.A subscript out of bounds may actually be an attemptto read some data stored outside the memory space allocated tothe program.<p>The Java language was specially designed as a ``cleaned up'' versionof C++ with these loopholes removed.If you assign random garbage to a C++ pointer variable and then dereferenceit, you will get whatever is stored in memory at that address.For example, the following fetches whatever happens to be store atlocation 1000 in memory:<pre><font color="0f0fff"> int *p = (int *)1000; int x = *p;</font></pre>Java prevents you from doing this sort of thing, whether accidentallyor on purpose, by a combination of strong type checking and runtimechecks.A pointer variable is always initialized to <samp><font color="0f0fff">null</font></samp>,and you can only assign other pointer values (not integers or otherdata) to it.If you attempt to dereference a null pointer, you get a runtime exception.<p>Because Java was designed primarily to build active, multimedia, interactivedocuments, its standard runtime library has lots of features to aid increating user interfaces.There are standard classes to create scrollbars, pop-up menus, etc.There are special facilities for manipulating URL's and networkconnections.We will not be using any of these features.On the other hand, there is one thing operating systems and userinterfaces have in common:They both require multiple, cooperating threads of control.We will be using these features in this course.<h3> Applications <em>vs</em> Applets </h3><p>The first thing you have to decide when writing a Java program iswhether you are writing an<em>application</em> or an <em>applet</em>.An applet is piece of code designed to display a part of a document.It is run by a browser in response to an HTML directive in the document.We will not be writing any applets in this course.<p>An application is a stand-alone program.All of our programs will be applications.<a name="sort"><h2> A First Example </h2></a><p>Large parts of Java are identical to C++.For example, the following procedure, which sorts an array of integersusing insertion sort, is exactly the same in C++ or Java.<pre><font color="0f0fff">/** Sort the array a[] in ascending order using an insertion sort. */void sort(int a[], int size) { for (int i = 1; i < size; i++) { // a[0..i-1] is sorted; insert a[i] in the proper place int x = a[i]; int j; for (j = i-1; j >=0; --j) { if (a[j] <= x) break; a[j+1] = a[j]; } // now a[0..j] are all <= x and a[j+2..i] are > x a[j+1] = x; }}</font></pre><p>Note that the syntax of control structures (such as <samp><font color="0f0fff">for</font></samp>and <samp><font color="0f0fff">if</font></samp>), assignment statements, variable declarations,and comments are all the same in Java as in C++.<p>To test this procedure in a C++ program, we might use a ``main program''like this:<pre><font color="0f0fff">#include <iostream.h>#include <stdlib.h>extern "C" int random();/** Test program to test sort */int main(int argc, char *argv[]) { if (argc != 2) { cerr << "usage: sort array-size" << endl; exit(1); } int size = atoi(argv[1]); int *test = new int[size]; for (int i = 0; i < size; i++) test[i] = random() % 100; cout << "before" << endl; for (int i = 0; i < size; i++) cout << test[i] << endl; sort(test, size); cout << "after" << endl; for (int i = 0; i < size; i++) cout << test[i] << endl; return 0;}</font></pre><p>A Java program to test the sort procedure is different in a few ways.Here is a complete Java program using the <samp><font color="0f0fff">sort</font></samp> procedure.<pre><font color="0f0fff">import java.io.*;import java.util.Random;class SortTest { /** Sort the array a[] in ascending order using an insertion sort. */ static void sort(int a[], int size) { for (int i = 1; i < size; i++) { // a[0..i-1] is sorted; insert a[i] in the proper place int x = a[i]; int j; for (j = i-1; j >=0; --j) { if (a[j] <= x)
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -