|
James Bac Dang |
|
Introduction to Java By now, you've almost certainly heard of Java. Java is the programming language of the
Internet, and there are good reasons for this claim. Programming the Internet means
bringing Web pages to life, making them responsive and intelligent. Java helps you do
this, but it can do more. Because Java is a universal language for creating applications,
its future may lie with devices not yet invented. Java may well represent a major step
forward in the history of computers. The Internet has forced a change in this way of doing things. By definition, everything on the Internet is shared. You and I can access the Internet with different kinds of computers, but the data can live anywhere. I can place a picture of my cat on a Windows site, for example, and you can view it on a PC. Interactive Web pages must also be platform neutral. Commands to be performed inside a Web page must be executable everywhere. So for the Web to become interactive, it needs a truly universal command language.
Java isn't C++. You can't just sit down, write C++ code, and get a successful Java program
after making a couple of small adjustments.
No support for pointers. "C without pointers" would be virtually a
contradiction in terms! But it just shows you that Java isn't C or C++.
Lack of support for pointers (address variables) has important implications. It means that
Java is not the powerful systems programming language that C++ is. But, generally speaking
specifically, Java is used specifically for writing applications: programs that entertain,
inform, or do actual work.
WHAT JAVA IS SUMMARY Software controls computers (often referred to as hardware). Java is one of today's most popular software development languages. Java was developed by Sun Microsystems. Sun provides an implementation of the Java 2 Platform called the Java 2 Software Development Kit (J2SDK), version 1.2 that includes the minimum set of tools you need to write software in Java. Java is a fully object-oriented language with strong support for proper software engineering techniques. A computer is a device capable of performing computations and making logical decisions at speeds millions, and even billions, of times faster than human beings can. Computers process data under the control of sets of instructions called computer programs. These computer programs guide the computer through orderly sets of actions specified by people called computer programmers. The various devices (such as the keyboard, screen, disks, memory and processing units) that comprise a computer system are referred to as hardware. The computer programs that run on a computer are referred to as software. The input unit is the "receiving" section of the computer. It obtains information (data and computer programs) from various input devices and places this information at the disposal of the other units so that the information may be processed. The output unit is the "shipping" section of the computer. It takes information processed by the computer and places it on output devices to make it available for use outside the computer. The memory unit is the rapid access, relatively low-capacity "warehouse" section of the computer. It retains information that has been entered through the input unit so that the information may be made immediately available for processing when it is needed and retains information that has already been processed until that information can be placed on output devices by the output unit. The arithmetic and logic unit (ALU) is the "manufacturing" section of the computer. It is responsible for performing calculations such as addition, subtraction, multiplication and division, and making decisions. The central processing unit (CPU) is the "administrative" section of the computer. It is the computer's coordinator and is responsible for supervising the operation of the other sections. The secondary storage unit is the long-term, high-capacity "warehousing" section of the computer. Programs or data not being used by the other units are normally placed on secondary storage devices (such as disks) until they are needed, possibly hours, days, months or even years later. Early computers were capable of performing only one job or task at a time. This form of computer operation is often called single-user batch processing. Software systems called operating systems were developed to help make it more convenient to use computers. Early operating systems managed the smooth transition between jobs and minimized the time it took for computer operators to switch between jobs. Multiprogramming involves the "simultaneous" operation of many jobs on the computer-the computer shares its resources among the jobs competing for its attention. Timesharing is a special case of multiprogramming in which dozens or even hundreds of users share the computer through terminals. The computer runs a small portion of one user's job and then moves on to service the next user. The computer does this so quickly that it may provide service to each user several times per second, so users' programs appear to run simultaneously. An advantage of timesharing is that the user receives almost immediate responses to requests rather than having to wait long periods for results as with previous modes of computing. In 1977, Apple Computer popularized the phenomenon of personal computing. In 1981, IBM introduced the IBM Personal Computer. Almost overnight, personal computing became legitimate in business, industry and government organizations. Although early personal computers were not powerful enough to timeshare several users, these machines could be linked together in computer networks, sometimes over telephone lines and sometimes in local area networks (LANs) within an organization. This led to the phenomenon of distributed computing, in which an organization's computing is distributed over networks to the sites at which the real work of the organization is performed. Today, information is easily shared across computer networks where some computers called file servers offer a common store of programs and data that may be used by client computers distributed throughout the network, hence the term client/server computing. C and C++ have become the programming languages of choice for writing software for operating systems, for computer networking and for distributed client/server applications. Java is rapidly becoming the language of choice for developing Internet-based applications. Computer languages may be divided into three general types: machine languages, assembly languages and high-level languages. Any computer can directly understand only its own machine language. Machine languages generally consist of strings of numbers (ultimately reduced to 1s and 0s) that instruct computers to perform their most elementary operations one at a time. Machine languages are machine dependent. English-like abbreviations formed the basis of assembly languages. Translator programs called assemblers convert assembly-language programs to machine language at computer speeds. Compilers translate high-level language programs into machine language programs. High-level languages (like Java) contain English words and conventional mathematical notations. Interpreter programs directly execute high-level language programs without the need for compiling those programs into machine language. Although compiled programs execute much faster than interpreted programs, interpreters are popular in program development environments in which programs are recompiled frequently as new features are added and errors are corrected. Objects are essentially reusable software components that model items in the real world. Modular, object-oriented design and implementation approaches make software development groups more productive than is possible with previous popular programming techniques such as structured programming. Object-oriented programs are often easier to understand, correct and modify. Java originated at Sun Microsystems as a project for intelligent consumer electronic devices. When the World Wide Web exploded in popularity in 1993, Sun people saw the immediate potential of using Java to create Web pages with so-called dynamic content. Java is now used to create Web pages with dynamic and interactive content, to develop large-scale enterprise applications, to enhance the functionality of World Wide Web servers, to provide applications for consumer devices, and so on. Java programs consist of pieces called classes. Classes consist of pieces called methods that perform tasks and return information when they complete their tasks. Most Java programmers use rich collections of existing classes in Java class libraries. FORTRAN (FORmula TRANslator) was developed by IBM Corporation between 1954 and 1957 for scientific and engineering applications that require complex mathematical computations. COBOL (COmmon Business Oriented Language) was developed in 1959 by a group of computer manufacturers and government and industrial computer users. COBOL is used primarily for commercial applications that require precise and efficient manipulation of large amounts of data. Pascal was designed at about the same time as C. It was created by Professor Nicklaus Wirth and was intended for academic use. Basic was developed in 1965 at Dartmouth University as a simple language to help novices become comfortable with programming. Structured programming is a disciplined approach to writing programs that are clearer than unstructured programs, easier to test and debug, and easier to modify. The Ada language was developed under the sponsorship of the United States Department of Defense (DOD) during the 1970s and early 1980s. One important capability of Ada is called multitasking; this allows programmers to specify that many activities are to occur in parallel. Most high-level languages-including C and C++-generally allow the programmer to write programs that perform only one activity at a time. Java, through a technique called multithreading, enables programmers to write programs with parallel activities. The Internet was developed more than three decades ago with funding supplied by the Department of Defense. Originally designed to connect the main computer systems of about a dozen universities and research organizations, the Internet today is accessible by hundreds of millions of computers worldwide. The World Wide Web allows computer users to locate and view documents over the Internet. Java systems generally consist of several parts: an environment, the language, the Java Applications Programming Interface (API), and various class libraries. Java programs normally go through five phases to be executed-edit, compile, load, verify and execute. Java program file names end with the . java extension. The Java compiler (javac) translates a Java program into bytecodes-the language understood by the Java interpreter. If a program compiles correctly, a file with the .class extension is produced. This is the file containing the bytecodes that are interpreted during the execution phase. A Java program must first be placed in memory before it can be executed. This is done by the class loader, which takes the . class file (or files) containing the bytecodes and transfers it to memory. The . class file can be loaded from a disk on your system or over a network. An application is a program that is normally stored and executed from the user's local computer. An applet is a small program that is normally stored on a remote computer that users connect to via a World Wide Web browser. Applets are loaded from a remote computer into the browser, executed in the browser and discarded when execution completes. Applications are loaded into memory and executed using the java interpreter. Browsers are used to view documents on the World Wide Web called HTML (Hypertext Markup Language) documents. When the browser sees an applet in an HTML document, the browser launches the Java class loader to load the applet. The browsers that support Java each have a built-in Java interpreter. Once the applet is loaded, the Java interpreter in the browser begins executing the applet. Applets can also be executed from the command line using the appletviewer command provided with the Java 2 Software Development Kit (J2SDK). The appletviewer is commonly referred to as the minimum browser-it only knows how to interpret applets. Before the bytecodes in an applet are executed by the Java interpreter built into a browser or the appletviewer, they are verified by the bytecode verifier to ensure that the bytecodes for downloaded classes are valid and that they do not violate Java's security restrictions. An intermediate step between interpreters and compilers is a just-in-time (JIT) compiler that, as the interpreter runs, produces compiled code for the programs and executes the programs in machine language rather than reinterpreting them. JIT compilers do not produce machine language that is as efficient as a full compiler. For organizations wanting to do heavy-duty information systems development, Integrated Development Environments (IDEs) are available from the major software suppliers. The IDEs provide many tools for supporting the software development process. An application is a program that executes using the Java interpreter. A comment that begins with / / is called a single-line comment. Programmers insert comments to document programs and improve program readability. A string of characters contained between double quotation marks is called a string, a character string, a message or a string literal. Blank lines, space characters, newline characters and tab characters are known as white-space characters. White-space characters outside strings are ignored by the compiler. Keyword class introduces a class definition and is immediately followed by the class name. Keywords (or reserved words) are reserved for use by Java. By convention, all class names in Java begin with a capital first letter. If a class name has more than one word, each word should be capitalized. An identifier is a series of characters consisting of letters, digits, underscores and dollar signs ($) that does not begin with a digit, does not contain any spaces and is not a keyword. Java is case sensitive-uppercase and lowercase letters are different. A left brace, {, begins the body of every class definition. A corresponding right brace, }, ends each class definition. Java applications begin executing at method main. Methods are able to perform tasks and return information when they complete their tasks. The first line of method main must be defined as public static void main( String args[]) A left brace, {, begins the body of a method definition. A corresponding right brace, }, ends the method definition's body. System. out is known as the standard output object. System. out allows Java applications to display strings and other types of information in the command window from which the Java application is executed. The escape sequence \n means newline. Other escape sequences include \t (tab), \r (carriage return), \ \ (backslash) and \ " (double quote). Method print ln of the System. out object displays (or prints) a line of information in the command window. When println completes its task, it automatically positions to the beginning of the next line in the command window. Every statement must end with a semicolon (also known as the statement terminator). The difference between System.out.print and System.out.println is that System.out.print does not position to the beginning of the next line in the command window when it finishes displaying its argument. The next character that is displayed in the command window will appear immediately after the last character displayed with System.out.print. Java contains many predefined classes that are grouped by directories on disk into categories of related classes called packages. The packages are referred to collectively as the Java class library or the Java applications programming interface (Java API). Class JOptionPane is defined for us in a package called Javax.swing. Class JOptionPane contains methods that display a dialog box containing information. The compiler uses import statements to locate classes required to compile a Java program. The Javax.swing package contains many classes that help define a graphical user interface (GUI) for an application. GUI components facilitate data entry by the user of a program and data outputs by a program. Method showmessageDialog of class JOptionPane requires two arguments. Until we JOptionPane in detail in Chapter 12, the first argument will always be the keyword null. The second argument is the string to display. A static method is called by following its class name by a dot (.) and the method name. Method exit of class system terminates an application. Class system is part of the package Java.lang. Package Java.lang is automatically imported in every Java program. A variable is a location in the computer's memory where a value can be stored for use by a program. A variable name is any valid identifier. All variables must be declared with a name and a data type before they can be used in a program. Declarations end with a semicolon (;) and can be split over several lines with each variable in the declaration separated by a comma (i.e., a comma-separated list of variable names). Variables of type int hold integer values (i.e., whole numbers such as 7, -11, 0, 31914). Types such as int, float, double and char are often called primitive data types. Primitive type names are keywords of the Java programming language. A prompt directs the user to take a specific action. A variable is assigned a value with an assignment statement using the assignment operator=. The = operator is called a binary operator because it has two operands. Method Integer.parseInt (a static method of class integer) converts its String argument to an integer. Java has a version of the + operator for string concatenation that enables a string and a value of another data type (including another string) to be concatenated. Variable names correspond to locations in the computer's memory. Every variable has a name, a type, a size and a value. When a value is placed in a memory location, this value replaces the previous value in that location. When a value is read out of a memory location, the process is nondestructive. The arithmetic operators are binary operators because they each operate on two operands. Integer division yields an integer quotient. Arithmetic expressions in Java must be written in straight-line form to facilitate entering programs into the computer. Operators in arithmetic expressions are applied in a precise sequence determined by the rules of operator precedence. Parentheses may be used to force the order of evaluation of operators to occur in any sequence desired by the programmer. When we say operators are applied from left to right, we are referring to the associate of the operators. Some operators associate from right to left. Java's if structure allows a program to make a decision based on the truth or falsity of a condition. If the condition is met (the condition is true), the statement in the body of the if structure is executed. If the condition is not met (the condition is false), the body statement is not executed. Conditions in if structures can be formed by using the equality operators and relational operators. The empty string is a string containing no characters. Every variable declared in a method must be initialized before it can be used in an expression.
|