Gsjava
Gsjava
JBuilder 2005
Borland Software Corporation 100 Enterprise Way Scotts Valley, California 95066-3249 www.borland.com Refer to the file deploy.html located in the redist directory of your JBuilder product for a complete list of files that you can distribute in accordance with the JBuilder License Statement and Limited Warranty. Borland Software Corporation may have patents and/or pending patent applications covering subject matter in this document. Please refer to the product CD or the About dialog box for the list of applicable patents. The furnishing of this document does not give you any license to these patents. COPYRIGHT 19972004 Borland Software Corporation. All rights reserved. All Borland brand and product names are trademarks or registered trademarks of Borland Software Corporation in the United States and other countries. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. All other marks are the property of their respective owners. For third-party conditions and disclaimers, see the Release Notes on your JBuilder product CD. Printed in the U.S.A. JB2005gsjava 6E6R0804 0405060708-9 8 7 6 5 4 3 2 1 PDF
Contents
Chapter 1
Introduction
Documentation conventions . . . . . . . Developer support and resources. . . . . Contacting Borland Developer Support Online resources. . . . . . . . . . . . World Wide Web . . . . . . . . . . . . Borland newsgroups . . . . . . . . . . Usenet newsgroups . . . . . . . . . . Reporting bugs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1
2 4 4 4 4 4 5 5
Chapter 2
7
. 7 . 7 . 8 . 8 . 8 . 9 . 9 . 9 . 9 . 10 . 10 . 10
Applying concepts . . . . . . . Escape sequences . . . . . Strings . . . . . . . . . . Determining access . . . . Handling methods . . . . . Using type conversions . . . Implicit casting. . . . . . Explicit conversion . . . . . Flow control. . . . . . . . . Loops . . . . . . . . . . Loop control statements. Conditional statements . . . Handling exceptions . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
27 27 28 28 30 30 30 31 31 31 33 33 35
Chapter 5
37
37 37 38 38 38 39 40 40 40 40 41 41 41 42 42 42 43 43 43 44 44
Chapter 3
13
. 13 . 13 . 14 . 15 . 16 . 16 . 16 . 17 . 17 . 18 . 18 . 19 . 20 . 21 . 22 . 22 . 22 . 23 . 24 . 24
Chapter 6
59
59 60 60 60 61 61 64 66 67 67 67 68 70 71 71 75 76
Chapter 4
25
. 25 . 25 . 26 . 26 . 27
Chapter 10
97
Chapter 7
Threading techniques
The lifecycle of a thread . . . . . . . . . . Customizing the run() method. . . . . . Subclassing the Thread class . . . . Implementing the Runnable interface Defining a thread . . . . . . . . . . . . Starting a thread. . . . . . . . . . . . . Making a thread not runnable . . . . . . Stopping a thread . . . . . . . . . . . . Thread priority . . . . . . . . . . . . . . . Time slicing . . . . . . . . . . . . . . . Synchronizing threads . . . . . . . . . . . Thread groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
79
79 79 79 80 82 82 82 83 83 83 84 84
How JNI works . . . . . . . . . . . . . . . . . . . .97 Using the native keyword . . . . . . . . . . . . . . .98 Using the javah tool . . . . . . . . . . . . . . . . . .98
Appendix A
101
. 101 . 101 . 102 . 102 . 103 . 103 . 103 . 104 . 104 . 104 . 104 . 105 . 106 . 108 . 109 . 111 . 114 . 115 . 115 . 116 . 116 . 116 . 117 . 117 . 117
Chapter 8
Serialization
Why serialize? . . . . . . . . . . . Java serialization . . . . . . . . . . Using the Serializable interface . Using output streams . . . . . . . . ObjectOutputStream methods. . Using input streams . . . . . . . . ObjectInputStream methods . . Writing and reading object streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
85
85 85 86 87 88 88 90 90
Chapter 9
91
. . . . . . . 92 . . . . . . . 92 . . . . . . . 92 . . . . . . . 93 . . . . . . . 94 . . . . . . . 95
Appendix B
119 121
ii
Chapter
1
Chapter 1
Introduction
Java is an object-oriented programming language. Switching to object-oriented programming (OOP) from other programming paradigms can be difficult. Java focuses on creating objects (data structures or behaviors) that can be assessed and manipulated by the program. Like other programming languages, Java provides support for reading and writing data to and from different input and output devices. Java uses processes that increase the efficiency of input/output, facilitate internationalization, and provide better support for non-UNIX platforms. Java looks over your program as it runs and automatically deallocates memory that is no longer required. This means you dont have to keep track of memory pointers or manually deallocate memory. This feature means a program is less likely to crash and that memory cant be intentionally misused. This book is intended to serve programmers who use other languages as a general introduction to the Java programming language. The Borland Community site provides an annotated list of books on Java programming and related subjects at http://community.borland.com/books/java/0,1427,c|3,00.html. Examples of applications, APIs, and code snippets are at http://codecentral.borland.com/ codecentral/ccweb.exe/home. This book includes the following chapters:
I
Java syntax: Chapter 2, Java language elements, Chapter 3, Java language structure, and Chapter 4, Java language control. These three chapters define basic Java syntax and introduce you to object-oriented programming concepts. Each section is divided into two main parts: Terms and Applying concepts. Terms builds vocabulary, adding to concepts you already understand. Applying concepts demonstrates the use of concepts presented up to that point. Some concepts are revisited several times, at increasing levels of complexity.
Chapter 5, The Java class libraries This chapter presents an overview of the Java 2 class libraries and the Java 2 Platform editions.
Chapter 6, Object-oriented programming in Java This chapter introduces the object-oriented features of Java. You will create Java classes, instantiate objects, and access member variables in a short tutorial. You will learn to use inheritance to create new classes, use interfaces to add new
C h a pt e r 1 : I nt r o d uc t io n
D o c um en t a t i on c o n v en t i on s
capabilities to your classes, use polymorphism to make related classes respond in different ways to the same message, and use packages to group related classes together.
I
Chapter 7, Threading techniques A thread is a single sequential flow of control within a program. One of the powerful aspects of the Java language is you can easily program multiple threads of execution to run concurrently within the same program. This chapter explains how to create multithreaded programs, and provides links to other resources with more indepth information.
Chapter 8, Serialization Serialization saves and restores a Java objects state. This chapter describes how to serialize objects using Java. It describes the Serializable interface, how to write an object to disk, and how to read the object back into memory again.
Chapter 9, An introduction to the Java Virtual Machine The JVM is the native software that allows a Java program to run on a particular machine. This chapter explains the JVMs general structure and purpose. It discusses the major roles of the JVM, particularly in Java security. It goes into more detail about three specific security features: the Java verifier, the Security Manager, and the Class Loader.
Chapter 10, Working with the Java Native Interface (JNI) This chapter explains how to invoke native methods in Java applications using the Java Native Method Interface (JNI). It begins by explaining how the JNI works, then discusses the native keyword and how any Java method can become a native method. Finally, it examines the JDKs javah tool, which is used to generate C header files for Java classes.
Appendix A, Java language quick reference This appendix contains a partial list of class libraries and their main functions, a list of the Java2 platform editions, a complete list of Java keywords as of JDK 1.3, extensive tables of data type conversions between primitive and reference types, Java escape sequences, and extensive tables of operators and their actions.
Appendix B, Learning more about Java Resources on the Java language abound. This chapter has links to, and ideas for finding, good sources of information about the Java language.
Documentation conventions
The Borland documentation for JBuilder uses the typefaces and symbols described in the following table to indicate special text.
Table 1.1
Typeface
Bold
Italics Keycaps
2 G et t in g S t a r t e d wi t h J a v a
Do c u m e nt at i o n c o nv e n t io n s
Table 1.1
Typeface
Monospaced type
I I I
Java identifiers, such as names of variables, classes, package names, interfaces, components, properties, methods, and events argument names field names Java keywords, such as void and static
[] <>
Square brackets in text or syntax listings enclose optional items. Do not type the brackets. Angle brackets are used to indicate variables in directory paths, command options, and code samples. For example, <filename> may be used to indicate where you need to supply a file name (including file extension), and <username> typically indicates that you must provide your user name. When replacing variables in directory paths, command options, and code samples, replace the entire variable, including the angle brackets (< >). For example, you would replace <filename> with the name of a file, such as employee.jds, and omit the angle brackets. Note: Angle brackets are used in HTML, XML, JSP, and other tag-based files to demarcate document elements, such as <font color=red> and <ejb-jar>. The following convention describes how variable strings are specified within code samples that are already using angle brackets for delimiters. This formatting is used to indicate variable strings within code samples that are already using angle brackets as delimiters. For example,
Italics, serif
<url="jdbc:borland:jbuilder\\samples\\guestbook.jds">
... In code examples, an ellipsis () indicates code that has been omitted from the example to save space and improve clarity. On a button, an ellipsis indicates that the button links to a selection dialog box.
JBuilder is available on multiple platforms. See the following table for a description of platform conventions used in the documentation.
Table 1.2
Item
Paths Home directory
<username>
I
For Windows 2000 and XP, the home directory is C:\Documents and
Settings\<username>
Screen shots Screen shots reflect the Borland Look & Feel on various platforms.
C h a pt e r 1 : I nt r o d uc t io n
D e v el o pe r s u p po r t a n d re s o ur c e s
Online resources
You can get information from any of these online sources: World Wide Web Electronic newsletters
http://www.borland.com/ http://info.borland.com/techpubs/jbuilder/
To subscribe to electronic newsletters, use the online form at:
http://www.borland.com/products/newsletters/index.html
http://www.borland.com/jbuilder/ (updated software and other files) http://info.borland.com/techpubs/jbuilder/ (updated documentation and other files) http://bdn.borland.com/ (contains our web-based news magazine for developers)
Borland newsgroups
When you register JBuilder you can participate in many threaded discussion groups devoted to JBuilder. The Borland newsgroups provide a means for the global community of Borland customers to exchange tips and techniques about Borland products and related tools and technologies. You can find user-supported newsgroups for JBuilder and other Borland products at http://www.borland.com/newsgroups/.
4 G et t in g S t a r t e d wi t h J a v a
De v e lo p er s u p po r t a n d r e s o ur c e s
Usenet newsgroups
The following Usenet groups are devoted to Java and related programming issues:
I I I I I I I I I I
news:comp.lang.java.advocacy news:comp.lang.java.announce news:comp.lang.java.beans news:comp.lang.java.databases news:comp.lang.java.gui news:comp.lang.java.help news:comp.lang.java.machine news:comp.lang.java.programmer news:comp.lang.java.security news:comp.lang.java.softwaretools
Note
These newsgroups are maintained by users and are not official Borland sites.
Reporting bugs
If you find what you think may be a bug in the software, please report it to Borland at one of the following sites:
I
Support Programs page at http://www.borland.com/devsupport/namerica/. Click the Information link under Reporting Defects to open the Welcome page of Quality Central, Borlands bug-tracking tool. Quality Central at http://qc.borland.com. Follow the instructions on the Quality Central page in the Bugs Report section. Quality Central menu command on the main Tools menu of JBuilder (Tools|Quality Central). Follow the instructions to create your QC user account and report the bug. See the Borland Quality Central documentation for more information.
When you report a bug, please include all the steps needed to reproduce the bug, including any special environmental settings you used and other programs you were using with JBuilder. Please be specific about the expected behavior versus what actually happened. If you have comments (compliments, suggestions, or issues) for the JBuilder documentation team, you may email jpgpubs@borland.com. This is for documentation issues only. Please note that you must address support issues to developer support. JBuilder is made by developers for developers. We really value your input.
C h a pt e r 1 : I nt r o d uc t io n
6 G et t in g S t a r t e d wi t h J a v a
Chapter
2
Chapter 2
This section provides you with foundational concepts about the elements of the Java programming language that will be used throughout this chapter. It assumes you understand general programming concepts, but have little or no experience with Java.
Terms
The following terms and concepts are discussed in this chapter:
I I I I I I
Identifier
The identifier is the name you choose to call an element (such as a variable or a method). Java will accept any valid identifier, but for reasons of usability, its best to use a plain-language term thats modified to meet the following requirements:
I
It should start with a letter. Strictly speaking, it can begin with a Unicode currency symbol or an underscore (_), but some of these symbols may be used in imported files or internal processing. They are best avoided. After that, it may contain any alphanumeric characters (letters or numbers), underscores, or Unicode currency symbols (such as or $), but no other special characters. It must be all one word (no spaces or hyphens).
Capitalization of an identifier depends on the kind of identifier it is. Java is casesensitive, so be careful of capitalization. Correct capitalization styles are mentioned in context.
Ch a p t er 2: J av a l an g u ag e e le m e nt s
T er m s
Data type
Data types classify the kind of information that certain Java programming elements can contain. Data types fall into two main categories:
I I
Naturally, different kinds of data types can hold different kinds and amounts of information. You can convert the data type of a variable to a different type, within limits: you cannot cast to or from the boolean type, and you cannot cast an object to an object of an unrelated class. Java will prevent you from risking your data. This means it will easily let you convert a variable or object to a larger type, but will try to prevent you from converting it to a smaller type. When you change a data type with a larger capacity to one with a smaller capacity, you must use a type of statement called a type cast.
Range
+/ 9.00x1018 +/ 2x109 +/ 9x1018 +/ 2.0x109 +/ 32768 +/ 128
8 G et t in g S t a r t e d wi t h J a v a
T erms
upper case letter and the first letter of each natural word within the name is capitalized also, for instance, NameOfClass. A class is a complete and coherent piece of code that defines a logically unified set of objects and their behavior. For more information on classes, see Chapter 6, Objectoriented programming in Java. Any class can be used as a data type once it has been created and imported into the program. Because the String class is the class most often used as a data type, we will focus on it in this chapter.
Strings
The String data type is actually the String class. The String class stores any sequence of alphanumeric characters, spaces, and normal punctuation (termed strings), enclosed in double quotes. Strings can contain any of the Unicode escape sequences and require \" to put double quotes inside of a string, but, generally, the String class itself tells the program how to interpret the characters correctly.
Arrays
An array is a data structure containing a group of values of the same data type. For instance, an array can accept a group of String values, a group of int values, or a group of boolean values. As long as all of the values are of the same data type, they can go into the same array. Arrays are characterized by a pair of square brackets. When you declare an array in Java, you can put the brackets either after the identifier or after the data type:
Variable
A variable is a value that a programmer names and defines. Variables need an identifier and a value.
Literal
A literal is the actual representation of a number, a character, a state, or a string. A literal represents the value of an identifier. Alphanumeric literals include strings in double quotes, single char characters in single quotes, and boolean true/false values. Integer literals may be stored as decimals, octals, or hexadecimals, but think about your syntax: any integer with a leading 0 (as in a date) will be interpreted as an octal. Floating point literals can only be expressed as decimals. They will be treated as double unless you specify the type. For a more detailed explanation of literals and their capacities, see The Java Handbook by Patrick Naughton.
Ch a p t er 2: J av a l an g u ag e e le m e nt s
A p p ly i ng c o n c ep t s
Applying concepts
The following sections demonstrate how to apply the terms and concepts introduced earlier in this chapter.
Declaring variables
The act of declaring a variable sets aside memory for the variable you declare. Declaring a variable requires only two things: a data type and an identifier, in that order. The data type tells the program how much memory to allocate. The identifier labels the allocated memory. Declare the variable only once. Once you have declared the variable appropriately, just refer to its identifier in order to access that block of memory. Variable declarations look like this:
boolean isOn;
The data type boolean can be set to true or false. The identifier isOn is the name that the programmer has given to the memory allocated for this variable. The name isOn has meaning for the human reader as something that would logically accept true/false values. The data type int tells you that you will be dealing with a whole number of less than ten digits. The identifier studentsEnrolled suggests what the number will signify. Since students are whole people, the appropriate data type calls for whole numbers. The data type float is appropriate because money is generally represented in decimals. You know that money is involved because the programmer has usefully named this variable creditCardSales.
int studentsEnrolled;
float creditCardSales;
Methods
Methods in Java are equivalent to functions or subroutines in other languages. The method defines an action to be performed on an object. Methods consist of a name and a pair of parentheses:
getData()
Here, getData is the name and the parentheses tell the program that it is a method. If the method needs particular information in order to get its job done, what it needs goes inside the parentheses. Whats inside the parentheses is called the argument, or arg for short. In a method declaration, the arg must include a data type and an identifier:
drawString(String remark)
Here, drawString is the name of the method, and String remark is the data type and variable name for the string that the method must draw. You must tell the program what type of data the method will return, or if it will return anything at all. This is called the return type. You can make a method return data of any primitive type. If the method doesnt need to return anything (as in most actionperforming methods), the return type must be void. Return type, name, and parentheses with any needed args give a very basic method declaration:
10 G e t t i n g S t a rt ed w it h J av a
A p p ly i n g c on c e p t s
Your method is probably more complex than that. Once you have typed and named it and told it what args it will need (if any), you must define it completely. You do this below the method name, nesting the body of the definition in a pair of curly braces. This gives a more complex method declaration:
String drawString(String remark) { //Declares the method. remark = "My, what big teeth you have!"; //Defines what's in the method. } //Closes the method body.
Once you have defined the method, you only need to refer to it by its name and pass it any args it needs to do its job right then:
drawString(remark);.
C ha p t e r 2 : J a v a la ng u a ge e le m e n t s
11
12 G e t t i n g S t a rt ed w it h J av a
Chapter
3
Chapter 3
This section provides you with foundational concepts about the structure of the Java programming language that will be used throughout this chapter. It assumes you understand general programming concepts, but have little or no experience with Java.
Terms
The following terms and concepts are discussed in this chapter:
I I I I I I
Keywords
Keywords are reserved Java terms that modify other syntax elements. Keywords can define an objects accessibility, a methods flow, or a variables data type. Keywords can never be used as identifiers. Many of Javas keywords are borrowed from C/C++. Also, as in C/C++, keywords are always written in lowercase. Generally speaking, Javas keywords can be categorized according to their functions (examples are in parentheses):
I I I I I I
Data and return types and terms (int, void, return) Package, class, member, and interface (package, class, static) Access modifiers (public, private, protected) Loops and loop controls (if, switch, break) Exception handling (throw, try, finally) Reserved wordsnot used yet, but unavailable (goto, const)
Some keywords are discussed in context in these chapters. For a complete list of keywords and what they mean, see Java keywords on page 102.
C h a pt er 3 : J a v a la n g ua g e s t r uc t ur e
13
T er m s
Operators
Operators allow you to access, manipulate, relate, or refer to Java language elements, from variables to classes. Operators have properties of precedence and associativity. When several operators act on the same element (or operand), the operators precedence determines which operator will act first. When more than one operator has the same precedence, the rules of associativity apply. These rules are generally mathematical; for instance, operators will usually be used from left to right, and operator expressions inside parentheses will be evaluated before operator expressions outside parentheses. The calculations for determining precedence are fairly complex, and are documented on Suns web site. Operators generally fall into six categories: assignment, arithmetic, logical, comparison, bitwise, and ternary. Assignment means storing the value to the right of the = inside the variable to the left of it. You can either assign a value to a variable when you declare it or after you have declared it. The machine doesnt care; you decide which way makes sense in your program and your practice:
double bankBalance; //Declaration bankBalance = 100.35; //Assignment double bankBalance = 100.35; //Declaration with assignment
In both cases, the value of 100.35 is stored inside the memory reserved by the declaration of the bankBalance variable. Assignment operators allow you to assign values to variables. They also allow you to perform an operation on an expression and then assign the new value to the right-hand operand, using a single combined expression. Arithmetic operators perform mathematical calculations on both integer and floatingpoint values. The usual mathematical signs apply: + adds, - subtracts, * multiplies, and / divides two numbers. Logical, or Boolean, operators allow the programmer to group boolean expressions in a useful way, telling the program exactly how to determine a specific condition. Comparison operators evaluate single expressions against other parts of the code. More complex comparisons (like string comparisons) are done programmatically. Bitwise operators act on the individual 0s and 1s of binary digits. Javas bitwise operators can preserve the sign of the original number; not all languages do. The ternary operator, ?:, provides a shorthand way of writing a very simple if-thenelse statement. It consists of a Boolean condition statement followed by two expressions:
Operand
object member data type String number number number boolean
Behavior
Accesses a member of the object. Casts a data type.1 Joins up strings (concatenator). Adds. This is the unary2 minus (reverses number sign). Subtracts. This is the boolean NOT operator.
(<type>) + !
14 G e t t i n g S t a rt ed w it h J av a
T erms
Operator
Operand
integer, boolean most elements with variables
Behavior
This is both the bitwise (integer) and boolean AND operator. When doubled (&&), it is the boolean conditional AND. Assigns an element to another element (for instance, a value to a variable, or a class to an instance). This can be combined with other operators to perform the other operation and assign the resulting value. For instance, += adds the lefthand value to the right, then assigns the new value to the right-hand side of the expression.
& =
1. Its important to distinguish between operation and punctuation. Parentheses are used around args as punctuation. They are used around a data type in an operation that changes a variables data type to the one inside the parentheses. 2. A unary operator takes a single operand, a binary operator takes two operands, and a ternary operator takes three operands.
Comments
Commenting code is excellent programming practice. Good comments can help you scan your code more quickly, keep track of what youve done as you build a complex program, and remind you of things you want to add or tune. You can use comments to hide parts of code that you want to save for special situations or keep out of the way while you work on something that might conflict. Comments can help you remember what you were doing when you return to one project after working on another, or when you come back from vacation. In a team development environment or whenever code is passed between programmers, comments can help others understand the purpose and associations of everything you comment on, without having to parse out every bit of it to be sure they understand. Java uses three kinds of comments: single-line comments, multi-line comments, and Javadoc comments. Comment
Single-line
Tag
Purpose
Suitable for brief remarks on the function or structure of a statement or expression. They require only an opening tag: as soon as you start a new line, youre back into code. Good for any comment that will cover more than one line, as when you want to go into some detail about whats happening in the code or when you need to embed legal notices in the code. It requires both opening and closing tags. This is a multi-line comment that the JDKs Javadoc utility can read and turn into HTML documentation. Javadoc has tags you can use to extend its functionality. Its used to provide help for APIs, generate to do lists, and embed flags in code. It requires both opening and closing tags. To learn more about the Javadoc tool, go to Suns Javadoc page at http://java.sun.com/j2se/
// ... /* ... */
Multi-line
Javadoc
/** ... */
1.3/docs/tooldocs/javadoc/.
Here are some examples:
/* You can put as many lines of discussion or as many pages of boilerplate as you like between these two tags. */ /* Note that, if you really get carried away, you can nest single-line comments //inside of the multi-line comments and the compiler will have no trouble with it at all. */
C h a pt er 3 : J a v a la n g ua g e s t r uc t ur e
15
T er m s
/* Just don't try nesting /* multi-line types of comments */ /** of any sort */ because that will generate a compiler error. */ /**Useful information about what the code does goes in Javadoc tags. Special tags such as @todo can be used here to take advantage of Javadoc's helpful features. */
Statements
A statement is a single command. One command can cover many lines of code, but the compiler reads the whole thing as one command. Individual (usually single-line) statements end in a semicolon (;), and group (multi-line) statements end in a closing curly brace (}). Multi-line statements are generally called code blocks. By default, Java runs statements in the order in which theyre written, but Java allows forward references to terms that havent been defined yet.
Code blocks
A code block is everything between the curly braces, and includes the expression that introduces the curly brace part:
Understanding scope
Scope rules determine where in a program a variable is recognized. Variables fall into two main scope categorizes:
I I
Global variables: Variables that are recognized across an entire class. Local variables: Variables that are recognized only in the code block where they were declared.
Scope rules are tightly related to code blocks. The one general scope rule is: a variable declared in a code block is visible only in that block and any blocks nested inside it. The following code illustrates this:
class Scoping { int x = 0; void method1() { int y; y = x; // This works. method1 can access y. } void method2() { int z = 1; z = y; // This does not work: // y is defined outside method2's scope. } }
16 G e t t i n g S t a rt ed w it h J av a
A p p ly i n g c on c e p t s
This code declares a class called scoping, which has two methods: method1() and method2(). The class itself is considered the main code block, and the two methods are its nested blocks. The x variable is declared in the main block, so it is visible (recognized by the compiler) in both method1() and method2(). Variables y and z, on the other hand, were declared in two independent, nested blocks; therefore, attempting to use y in method2() is illegal since y is not visible in that block.
Note
A program that relies on global variables can be error-prone for two reasons:
1 Global variables are difficult to keep track of. 2 A change to a global variable in one part of the program can have an unexpected
side effect in another part of the program. Local variables are safer to use since they have a limited life span. For example, a variable declared inside a method can be accessed only from that method, so there is no danger of it being misused somewhere else in the program. End every simple statement with a semicolon. Be sure every curly brace has a mate. Organize your curly braces in some consistent way (as in the examples above) so you can keep track of the pairs. Many Java IDEs (such as JBuilder) automatically nest the curly braces according to your settings.
Applying concepts
The following sections demonstrate how to apply the terms and concepts introduced earlier in this chapter.
Using operators
Review
There are six basic kinds of operators (arithmetic, logical, assignment, comparison, bitwise, and ternary), and operators affect one, two, or three operands, making them unary, binary, or ternary operators. They have properties of precedence and associativity, which determine the order theyre processed in. Operators are assigned numbers that establish their precedence. These numbers vary by circumstances and are determined by a complex set of rules. The higher the number, the higher the order of precedence (that is, the more likely it is to be evaluated sooner than others). An operator of precedence 1 (the lowest) will be evaluated last, and an operator with a precedence of 15 (the highest) will be evaluated first. Operators with the same precedence are normally evaluated from left to right. Precedence is evaluated before associativity. For instance, the expression a + b - c * d will not be evaluated from left to right; multiplication has precedence over addition, so c * d is evaluated first. Addition and subtraction have the same order of precedence, so associativity applies: a and b are added next, then the product of c * d is subtracted from that sum. Its good practice to use parentheses around mathematical expressions you want evaluated first, regardless of their precedence, for instance: (a + b) - (c * d). The program will evaluate this operation the same way, but for the human reader, this format is clearer.
See also
I
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/expressions.html
C h a pt er 3 : J a v a la n g ua g e s t r uc t ur e
17
A p p ly i ng c o n c ep t s
Arithmetic operators
Java provides a full set of operators for mathematical calculations. Java, unlike some languages, can perform mathematical functions on both integer and floating-point values. You will probably find these operators familiar. Here are the arithmetic operators: Operator Definition
Auto-increment/decrement: Adds one to, or subtracts one from, its single operand. If the value of i is 4, ++i is 5. See below for more information. Unary plus/minus: sets or changes the positive/negative value of a single number. Multiplication. Division. Modulus: Divides the first operand by the second operand and returns the remainder. See below for a brief mathematical review. Addition/subtraction
Assoc.
Right
Whether you use pre-increment/decrement or post-increment/decrement matters only when you return the initial value of the incremented/decremented variable. Use pre- or post-increment/decrement depending on when you want the new value to be assigned:
y = 3; b = 9; x; a; ++y; b--;
//1. variable declaration //2. //3. //4. //5. pre-increment: y and x return 4. //6. post-decrement: b returns 9, a returns 8.
In statement 4, pre-increment, the y variables value is incremented by 1, and then its new value (4) is assigned to x. Both x and y originally had a value of 3; now they both have the value of 4. In statement 5, post-decrement, bs current value (9) is assigned to a and then the value of b is decremented (to 8). b originally had a value of 9 and a had no value assigned; now a is 9 and b is 8. The modulus operator requires an explanation to those who last studied math a long time ago. Remember that when you divide two numbers, they rarely divide evenly. What is left over after you have divided the numbers (without adding any new decimal places) is the remainder. For instance, 3 goes into 5 once, with 2 left over. The remainder (in this case, 2) is what the modulus operator evaluates for. Since remainders recur in a division cycle on a predictable basis (for instance, an hour is modulus 60), the modulus operator is particularly useful when you want to tell a program to repeat a process at specific intervals.
Logical operators
Logical (or Boolean) operators allow the programmer to group boolean expressions to determine certain conditions. These operators perform the standard Boolean operations AND, OR, NOT, and XOR.
18 G e t t i n g S t a rt ed w it h J av a
A p p ly i n g c on c e p t s
Assoc.
Right
&
Left
^ |
Left Left
&&
Left
||
Left
The evaluation operators always evaluate both operands. The conditional operators, on the other hand, always evaluate the first operand, and if that determines the value of the whole expression, they dont evaluate the second operand. For example:
if ( !isHighPressure && (temperature1 > temperature2)) { ... } //Statement 1: conditional boolean1 = (x < y) || ( a > b); boolean2 = (10 > 5) & (5 > 1); //Statement 2: conditional //Statement 3: evaluation
The first statement evaluates !isHighPressure first. If !isHighPressure is false (that is, if the pressure is high; note the logical double-negative of ! and false), the second operand, temperature1 > temperature2, doesnt need to be evaluated. && only needs one false value in order to know what value to return. In the second statement, the value of boolean1 will be true if x is less than y. If x is more than y, the second expression will be evaluated; if a is less than b, the value of boolean1 will still be true. In the third statement, however, the compiler will compute the values of both operands before assigning true or false to boolean2, because & is an evaluation operator, not a conditional one.
Assignment operators
You know that the basic assignment operator (=) lets you assign a value to a variable. With Javas set of assignment operators, you can perform an operation on either operand and assign the new value to a variable in one step.
C h a pt er 3 : J a v a la n g ua g e s t r uc t ur e
19
A p p ly i ng c o n c ep t s
Assoc.
Right Right Right Right Right
= += -= *= /=
The first operator is familiar by now. The rest of the assignment operators perform an operation first, and then store the result of the operation in the operand on the left side of the expression. Here are some examples:
int y = 2; y *= 2; //same as (y = y * 2) boolean b1 = true, b2 = false; b1 &= b2; //same as (b1 = b1 & b2)
Comparison operators
Comparison operators allow you to compare one value to another. The following table lists the comparison operators: Operator Definition
Less than Greater than Less than or equal to Greater than or equal to Equal to Not equal to
Assoc.
Left Left Left Left Left Left
The equality operator can be used to compare two object variables of the same type. In this case, the result of the comparison is true only if both variables refer to the same object. Here is a demonstration:
m1 = new Mammal(); m2 = new Mammal(); boolean b1 = m1 == m2; //b1 is false m1 = m2; boolean b2 = m1 == m2; //b2 is true
The result of the first equality test is false because m1 and m2 refer to different objects (even though they are of the same type). The second comparison is true because both variables now represent the same object.
Note
Most of the time, however, the equals() method in the Object class is used instead of the comparison operator. The comparing class must be subclassed from Object before objects of the comparing class can be compared using equals().
20 G e t t i n g S t a rt ed w it h J av a
A p p ly i n g c on c e p t s
Bitwise operators
Bitwise operators are of two types: shift operators and Boolean operators. The shift operators are used to shift the binary digits of an integer to the right or the left. Consider the following example (the short integer type is used instead of int for conciseness):
1111111111110011
Note
The shifting operation is different in Java than in C/C++ in how it is used with signed integers. A signed integer is one whose left-most bit is used to indicate the integers positive or negative sign: the bit is 1 if the integer is negative, 0 if positive. In Java, integers are always signed, whereas in C/C++ they are signed only by default. In most implementations of C/C++, a bitwise shift operation does not preserve the integers sign; the sign bit would be shifted out. In Java, however, the shift operators preserve the sign bit (unless you use the >>> to perform an unsigned shift). This means that the sign bit is duplicated, then shifted. The following table lists Javas bitwise operators: Operator Definition
Bitwise NOT Inverts each bit of the operand, so each 0 becomes 1 and vice versa. Signed left shift Shifts the bits of the left operand to the left, by the number of digits specified in the right operand, with 0s shifted in from the right. Highorder bits are lost. Signed right shift Shifts the bits of the left operand to the right, by the number of digits specified on the right. If the left operand is negative, 0s are shifted in from the left; if it is positive, 1s are shifted in. This preserves the original sign. Zero-fill right shift Shifts right, but always fills in with 0s. Bitwise AND Can be used with = to assign the value. Bitwise OR Can be used with = to assign the value. Bitwise XOR Can be used with = to assign the value. Left-shift with assignment Right-shift with assignment Zero-fill right shift with assignment
Assoc.
Right Left
~ <<
>>
Left
C h a pt er 3 : J a v a la n g ua g e s t r uc t ur e
21
A p p ly i ng c o n c ep t s
Using methods
You know that methods are what get things done. Methods cannot contain other methods, but they can contain variables and class references. Here is a brief example to review. This method helps a music store with its inventory:
//Declare the method: return type, name, args: public int getTotalCDs(int numRockCDs, int numJazzCDs, int numPopCDs) { //Declare the variable totalCDs. The other three variables are declared elsewhere: int totalCDs = numRockCDs + numJazzCDs + numPopCDs; //Make it do something useful. In this case, print this line on the screen: System.out.println("Total CDs in stock = " + totalCDs); }
In Java, you can define more than one method with the same name, as long as the different methods require different arguments. For instance, both public int getTotalCDs(int numRockCDs, int numJazzCDs, in numPopCDs) and public int getTotalCDs(int salesRetailCD, int salesWholesaleCD) are legal in the same class. Java will recognize the different patterns of arguments (the method signatures) and apply the correct method when you make a call. Assigning the same name to different methods is called method overloading. To access a method from other parts of a program, you must first create an instance of the class the method resides in, and then use that object to call the method:
//Create an instance totalCD of the class Inventory: Inventory totalCD = new Inventory(); //Access the getTotalCDs() method inside of Inventory, storing the value in total: int total = totalCD.getTotalCDs(myNumRockCDs, myNumJazzCDs, myNumPopCDs);
Using arrays
Note that the size of an array is not part of its declaration. The memory an array requires is not actually allocated until you initialize the array.
22 G e t t i n g S t a rt ed w it h J av a
A p p ly i n g c on c e p t s
To initialize the array (and allocate the needed memory), you must use the new operator as follows:
int studentID[] = new int[20]; //Creates array of 20 int elements. char[] grades = new char[20]; //Creates array of 20 char elements. float[][] coordinates = new float[10][5]; //2-dimensional, 10x5 array of float elements.
Note
In creating two-dimensional arrays, the first array number defines number of rows and the second array number defines number of columns. Java counts positions starting with 0. This means the elements of a 20-element array will be numbered from 0 to 19: the first element will be 0, the second will be 1, and so on. Be careful how you count when youre working with arrays. When an array is created, the value of all its elements is null or 0; values are assigned later.
Note
The use of the new operator in Java is similar to that of the malloc command in C and the new operator in C++. To initialize an array, specify the values of the array elements inside a set of curly braces. For multi-dimensional arrays, use nested curly braces. For example:
char[] grades = {'A', 'B', 'C', 'D', 'F'}; float[][] coordinates = {{0.0, 0.1}, {0.2, 0.3}};
The first statement creates a char array called grades. It initializes the arrays elements with the values A through F. Notice that we did not have to use the new operator to create this array; by initializing the array, enough memory is automatically allocated for the array to hold all the initialized values. Therefore, the first statement creates a char array of 5 elements. The second statement creates a two-dimensional float array called coordinates, whose size is 2 by 2. Basically, coordinates is an array consisting of two array elements: the arrays first row is initialized to 0.0 and 0.1, and the second row to 0.2 and 0.3.
Using constructors
A class is a full piece of code, enclosed in a pair of curly braces, that defines a logically coherent set of variables, attributes, and actions. A package is a logically associated set of classes. Note that a class is just a set of instructions. It doesnt do anything itself. Its analogous to a recipe: you can make a cake from the right recipe, but the recipe is not the cake, its only the instructions for it. The cake is an object you have created from the instructions in the recipe. In Java, we would say that we have created an instance of cake from the recipe Cake. The act of creating an instance of a class is called instantiating that object. You instantiate an object of a class. To instantiate an object, use the assignment operator (=), the keyword new, and a special kind of method called a constructor. A call to a constructor is the name of the class being instantiated followed by a pair of parentheses. Although it looks like a method, it takes a classs name; thats why its capitalized:
C h a pt er 3 : J a v a la n g ua g e s t r uc t ur e
23
A p p ly i ng c o n c ep t s
A constructor sets up a new instance of a class: it initializes all the variables in that class, making them immediately available. It can also perform any start-up routines required by the object. For example, when you need to drive your car, the first thing you do is open the door, climb in, put the clutch in, and start the engine. (After that, you can do all the things normally involved in driving, like getting into gear and using the accelerator.) The constructor handles the programmatic equivalents of the actions and objects involved in getting in and starting the car. Once you have created an instance, you can use the instance name to access members of that class. For more information on constructors, see Case study: A simple OOP example on page 61.
Member access
The access operator (.) is used to access members inside of an instantiated object. The basic syntax is:
<instanceName>.<memberName>
Precise syntax of the member name depends on the kind of member. These can include variables (<memberName>), methods (<memberName>()), or subclasses (<MemberName>). You can use this operation inside of other syntax elements wherever you need to access a member. For example:
setColor(Color.pink);
This method needs a color to do its job. The programmer used an access operation as an arg to access the variable pink within the class Color.
Arrays
Array elements are accessed by subscripting, or indexing, the array variable. To index an array variable, follow the array variables name with the elements number (index) surrounded by square brackets. Arrays are always indexed starting from 0. If you have an array with 9 elements, the first element is the 0 index and the last element is the 8 index. (Coding as if elements were numbered from 1 is a common mistake.) In the case of multi-dimensional arrays, you must use an index for each dimension to access an element. The first index is the row and the second index is the column. For example:
firstElement = grades[0]; //firstElement = 'A' fifthElement = grades[4]; //fifthElement = 'F' row2Col1 = coordinates[1][0]; //row2Col1 = 0.2
The following snippet of code demonstrates one use of arrays. It creates an array of 5 int elements called intArray, then uses a for loop to store the integers 0 through 4 in the elements of the array:
int[] intArray = new int [5]; int index; for (index = 0; index < 5; index++) intArray [index] = index;
This code increments the index variable from 0 to 4, and at every pass, it stores its value in the element of intArray indexed by the variable index.
24 G e t t i n g S t a rt ed w it h J av a
Chapter
4
Chapter 4
This section provides you with foundational concepts about control of the Java programming language that will be used throughout this chapter. It assumes you understand general programming concepts, but have little or no experience with Java.
Terms
The following terms and concepts are discussed in this chapter:
I I I I
String handling Type casting and conversion Return types and statements Flow control statements
String handling
The String class provides methods that allow you to get substrings or to index characters within a string. However, the value of a declared String cant be changed. If you need to change the String value associated with that variable, you must point the variable to a new value:
String text1 = new String("Good evening."); // Declares text1 and assigns a value. text1 = "Hi, honey, I'm home!" // Assigns a new value to text1.
Indexing allows you to point to a particular character in a string. Java counts each position in a string starting from 0, so that the first position is 0, the second position is 1, and so on. This gives the eighth position in a string an index of 7. The StringBuffer class provides a workaround. It also offers several other ways to manipulate a strings contents. The StringBuffer class stores your string in a buffer (a special area of memory) whose size you can explicitly control; this allows you to change the string as much as necessary before you have to declare a String and make the string permanent. Generally, the String class is for string storage and the StringBuffer class is for string manipulation.
C h ap t e r 4 : J a v a la ng u a ge c o n t r ol
25
T er m s
short, char, int, long, float, double int, long, float, double int, long, float, double long, float, double float, double double
To cast a data type, put the type you want to cast to in parentheses immediately before the variable you want to cast: (int)x. This is what it looks like in context, where x is the variable being cast, float is the original data type, int is the target data type, and y is the variable storing the new value:
This assumes that the value of x would fit inside of int. Note that xs decimal values are lost in the conversion. Java rounds decimals down to the nearest whole number.
void is a special return type. It signifies that the method doesnt need to give anything back when its finished. It is most commonly used in action methods that are only required to do something, not to pass any information on.
All other return types require a return statement at the end of the method. You can use the return statement in a void method to leave the method at a certain point, but otherwise its needless. A return statement consists of the word return and the string, data, variable name, or concatenation required:
return numCD;
Its common to use parentheses for concatenations:
26 G e t t i n g S t a rt ed w it h J av a
A p p ly i n g c on c e p t s
Applying concepts
The following sections demonstrate how to apply the terms and concepts introduced earlier in this chapter.
Escape sequences
A special type of character literal is called an escape sequence. Like C/C++, Java uses escape sequences to represent special control characters and characters that cannot be printed. An escape sequence is represented by a backslash (\) followed by a character code. The following table summarizes these escape sequences: Character
Backslash Backspace Carriage return Double quote Form feed Horizontal tab New line Octal character Single quote Unicode character
Escape Sequence
Non-decimal numeric characters are escape sequences. An octal character is represented by three octal digits, and a Unicode character is represented by lowercase u followed by four hexadecimal digits. For example, the decimal number 57 is represented by the octal code \071 and the Unicode sequence \u0039. The sample string in the following statement prints out the words Name and "Hildegaard von Bingen" separated by two tabs on one line, and prints out ID and "1098", also separated by two tabs, on the second line:
C h ap t e r 4 : J a v a la ng u a ge c o n t r ol
27
A p p ly i ng c o n c ep t s
Strings
The string of characters you specify in a String is a literal; the program will use exactly what you specify, without changing it in any way. However, the String class provides the means to chain strings together (called string concatenation), see and use whats inside of strings (compare strings, search strings, or extract a substring from a string), and convert other kinds of data to strings. Some examples follow:
I
String firstNames = "Joseph, Elvira and Hans"; String modifier = " really "; String tastes = "like chocolate.";
I
Get a substring from a string, selecting from the ninth column to the end of the string:
Compare part of the substring to another string, convert a string to capital letters, then concatenate it with other strings to get a return value:
boolean bFirst = firstNames.startsWith("Emine"); // Returns false in this case. String caps = modifier.toUpperCase(); // Yields " REALLY " return firstNames + caps + tastes; // Returns the line: // Elvira and Hans REALLY like chocolate.
For more information on how to use the String class, see Suns API documentation at http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html.
StringBuffer
If you want more control over your strings, use the StringBuffer class. This class is part of the java.lang package.
StringBuffer stores your strings in a buffer so that you dont have to declare a permanent String until you need it. Some of the advantages to this are that you dont have to redeclare a String if its content changes. You can reserve a size for the buffer larger than what is already in there. StringBuffer provides methods in addition to those in String that allow you to modify the contents of strings in new ways. For instance, StringBuffers setCharAt() method changes the character at the index specified in the first parameter, to the new value specified in the second parameter: StringBuffer word = new StringBuffer ("yellow"); word.setCharAt (0, 'b'); //word is now "bellow"
Determining access
By default, classes are available to all of the members inside them, and the members within the class are available to each other. However, this access can be widely modified. Access modifiers determine how visible a classs or members information is to other members and classes. Access modifiers include:
I
public: A public member is visible to members outside the public members scope, as long as the parent class is visible. A public class is visible to all other classes in all other packages. private: A private members access is limited to the members own class.
28 G e t t i n g S t a rt ed w it h J av a
A p p ly i n g c on c e p t s
protected: A protected member can be accessed by other members of its class and by members of classes in the same package (as long as the members parent class is accessible), but not from other packages. A protected class is available to other classes in the same package, but not to other packages.
If no access modifier is declared, the member is available to all classes inside the parent package, but not outside the package.
class Waistline { private boolean invitationGiven = false; // This is private. private int weight = 170; // So is this. public void acceptInvitation() { invitationGiven = true; } // This is public.
//Class JunkFood is declared and object junkFood is instantiated elsewhere: public void eat(JunkFood junkFood) { /*This object only accepts more junkFood if it has an invitation * and if it is able to accept. Notice that isAcceptingFood() * checks to see if the object is too big to accept more food: */ if (invitationGiven && isAcceptingFood()) { /*This object's new weight will be whatever its current weight * is, plus the weight added by junkFood. Weight increments * as more junkFood is added: */ weight += junkFood.getWeight(); } } //Only the object knows if it's accepting food: private boolean isAcceptingFood() { // This object will only accept food if there's room: return (isTooBig() ? false : true); } //Objects in the same package can see if this object is too big: protected boolean isTooBig() { //It can accept food if its weight is less than 185: return (weight > 185) ? true : false; } }
Notice that isAcceptingFood() and invitationGiven are private. Only members inside this class know if this object is capable of accepting food or if it has an invitation.
isTooBig() is protected. Only classes inside this package can see if this objects weight exceeds its limit or not.
The only methods that are exposed to the outside are acceptInvitation() and eat(). Any class can perceive these methods.
C h ap t e r 4 : J a v a la ng u a ge c o n t r ol
29
A p p ly i ng c o n c ep t s
Handling methods
The main() method deserves special attention. It is the point of entry into a program (except an applet). Its written like this:
statics class-wide association affects how you call a static method and how you call other methods from within a static method. static members can be called from other types of members by simply using the name of the method, and static members can call each other the same way. You dont need to create an instance of the class in order to access a static method within it.
To access nonstatic members of a nonstatic class from within a static method, you must instantiate the class of the member you want to reach and use that instance with the access operator, just as you would for any other method call. Notice that the arg for the main() method is a String array, with other args allowed. Remember that this method is where the compiler starts working. When you pass an arg from the command line, its passed as a string to the String array in the declaration of the main() method, and uses that arg to start running the program. When you pass a data type other than a String, it will still be received as a string. You must code into the body of the main() method the required conversion from String to the data type needed.
Type conversion is the process of converting the data type of a variable for the duration of a specific operation. The standard form for a narrowing conversion is called a cast; it may risk your data.
Implicit casting
There are times when a cast is performed implicitly by the compiler. The following is an example:
30 G e t t i n g S t a rt ed w it h J av a
A p p ly i n g c on c e p t s
Explicit conversion
Syntax for a widening cast is simple:
floatValue = (float)doubValue; // To float "floatValue" // from double "doubValue". longValue = (long)floatValue; // To long "longValue" // from float "floatValue". // This is one of four possible constructions.
(Note that decimals are rounded down by default.) Be sure you thoroughly understand the syntax for the types you want to cast; this process can get messy. For more information, see Converting and casting data types on page 104.
Flow control
Review
There are three types of loop statements: iteration statements (for, while, and dowhile) create loops, selection statements (switch and all the if statements) tell the program under what circumstances the program will use statements, and jump statements (break, continue, and return) shift control out to another part of the program.
Loops
Each statement in a program is executed once. However, it is sometimes necessary to execute statements several times until a condition is met. Java provides three ways to loop statements: while, do and for loops.
I
The while loop The while loop is used to create a block of code that will execute as long as a particular condition is met. This is the general syntax of the while loop:
while ( <boolean condition statement> ) { <code to execute as long as that condition is true> }
The loop first checks the condition. If the conditions value is true, it executes the entire block. It then reevaluates the condition, and repeats this process until the condition becomes false. At that point, the loop stops executing. For instance, to print Looping 10 times:
//Initiates x at 0. //Boolean condition statement. //Prints "Looping" once. //Increments x for the next iteration.
When the loop first starts executing, it checks whether the value of x is less than 10. Since it is, the body of the loop is executed. In this case, the word Looping is printed on the screen, and then the value of x is incremented. This loop continues until the value of x equals 10, when the loop stops executing. Unless you intend to write an infinite loop, make sure there is some point in the loop where the conditions value becomes false and the loop terminates. You can also terminate a loop by using the return, continue, or break statements.
C h ap t e r 4 : J a v a la ng u a ge c o n t r ol
31
A p p ly i ng c o n c ep t s
The do-while loop The do-while loop is similar to the while loop, except that it evaluates the condition after the statements instead of before. The following code shows the previous while loop converted to a do loop:
The for loop The for loop is the most powerful loop construct. Here is the general syntax of a for loop:
for (int x=1,y=20, z=0; x<=10 && y>10; x++, y--) { z+= x+y; }
Lets break this loop up into its four main sections:
a b c d
The initialization expression: int x =1, y=20, z=0 The Boolean condition: x<=10 && y>10 The iteration expression: x++, y-The main body of executable code: z+= x + y
32 G e t t i n g S t a rt ed w it h J av a
A p p ly i n g c on c e p t s
The break statement The break statement will allow you to exit a loop structure before the test condition is met. Once a break statement is encountered, the loop immediately terminates, skipping any remaining code. For instance:
int x = 0; while (x < 10){ System.out.println("Looping"); x++; if (x == 5) break; else ... //do something else }
In this example, the loop will stop executing when x equals 5.
I
The continue statement The continue statement is used to skip the rest of the loop and resume execution at the next loop iteration.
for ( int x = 0 ; x < 10 ; x++){ if(x == 5) continue; //go back to beginning of loop with x=6 System.out.println("Looping"); }
This example will not print Looping if x is 5, but will continue to print for 6, 7, 8, and 9.
Conditional statements
Conditional statements are used to provide your code with decision-making capabilities. There are two conditional structures in Java: the if-else statement, and the switch statement.
I
if (<condition1>) { ... //code block 1 } else if (<condition2>) { ... //code block 2 } else { ... //code block 3 }
The if-else statement is typically made up of multiple blocks. Only one of the blocks will execute when the if-else statement executes, based on which of the conditions is true. The else-if and else blocks are optional. Also, the if-else statement is not restricted to three blocks: it can contain as many else-if blocks as needed.
C h ap t e r 4 : J a v a la ng u a ge c o n t r ol
33
A p p ly i ng c o n c ep t s
is even"); is odd"); equals y"); is less than y"); is greater than y");
The switch statement The switch statement is similar to the if-else statement. Here is the general syntax of the switch statement:
switch (<expression>){ case <value1>: <codeBlock1>; break; case <value2>: <codeBlock2>; break; default : <codeBlock3>; }
Note the following:
I
If there is only one statement in a code block, the block does not need to be enclosed in braces. The default code block corresponds to the else block in an if-else statement. The code blocks are executed based on the value of a variable or expression, not on a condition. The value of <expression> must be of an integer type, or a type that can be safely converted to int, such as char. The case values must be constant expressions that are of the same data type as the original expression. The break keyword is optional. It is used to end the execution of the switch statement once a code block executes. If its not used after codeBlock1, then codeBlock2 executes right after codeBlock1 finishes executing. If a code block should execute when expression is one of a number of values, each of the values must be specified like this: case <value>:.
I I
switch (c){ case '1': case '3': case '5': case '7': case '9': System.out.println("c is an odd number"); break; case '0': case '2': case '4': case '6': case '8': System.out.println("c is an even number"); break; case ' ': System.out.println("c is a space"); break; default : System.out.println("c is not a number or a space"); }
The switch will evaluate c and jump to the case statement whose value is equal to c. If none of the case values equal c, the default section will be executed. Notice how multiple values can be used for each block.
34 G e t t i n g S t a rt ed w it h J av a
A p p ly i n g c on c e p t s
Handling exceptions
Exception handling provides a structured means of catching run-time errors in your program and making them return meaningful information about themselves. You can also set the exception handler to perform certain actions before allowing the program to terminate. Exception handling uses the keywords try, catch, and finally. A method can declare an exception by using the throws and throw keywords. In Java, an exception can be a subclass of the class java.lang.Exception or java.lang.Error. When a method declares that an exception has occurred, we say that it throws an exception. To catch an exception means to handle an exception. Exceptions that are explicitly declared in the method declaration must be caught, or the code will not compile. Exceptions that are not explicitly declared in the method declaration could still halt your program when it runs, but it will compile. Note that good exception handling makes your code more robust. To catch an exception, you enclose the code which might cause the exception in a try block, then enclose the code you want to use to handle the exception in a catch block. If there is important code (such as clean-up code) that you want to make sure will run even if an exception is thrown and the program gets shut down, enclose that code in a finally block at the end. Here is an example of how this works:
try { ... // Some code that might throw an exception goes here. } catch( Exception e ) { ... // Exception handling code goes here. // This next line outputs a stack trace of the exception: e.printStackTrace(); } finally { ... // Code in here is guaranteed to be executed, // whether or not an exception is thrown in the try block. }
The try block should be used to enclose any code that might throw an exception that needs to be handled. If no exception is thrown, all of the code in the try block will execute. If, however, an exception is thrown, then the code in the try block stops executing at the point where the exception is thrown and the control flows to the catch block, where the exception is handled. You can do whatever you need to do to handle the exception in one or more catch blocks. The simplest way to handle exceptions is to handle all of them in one catch block. To do this, the argument in parentheses after catch should indicate the class Exception, followed by a variable name to assign to this exception. This indicates that any exception which is an instance of java.lang.Exception or any of its subclasses will be caught; in other words, any exception. If you need to write different exception handling code depending on the type of exception, you can use more than one catch block. In that case, instead of passing Exception as the type of exception in the catch argument, you indicate the class name of the specific type of exception you want to catch. This may be any subclass of Exception. Keep in mind that the catch block will always catch the indicated type of exception and any of its subclasses. Code in the finally block is guaranteed to be executed, even if the try block code does not complete for some reason. For instance, the code in the try block might not complete if it throws an exception, but the code in the finally block will still execute. This makes the finally block a good place to put clean-up code. If you know that a method youre writing is going to be called by other code, you might leave it up to the calling code to handle the exception that your method might throw. In that case, you would simply declare that the method can throw an exception. Code that
C h ap t e r 4 : J a v a la ng u a ge c o n t r ol
35
A p p ly i ng c o n c ep t s
might throw an exception can use the throws keyword to declare an exception. This can be an alternative to catching the exception, since if a method declares that it throws an exception, it does not have to handle that exception. Here is an example of using throws:
public void myMethod() throws SomeException { ... // Code here might throw SomeException, or one of its subclasses. // SomeException is assumed to be a subclass of Exception. }
You can also use the throw keyword to indicate that something has gone wrong. For instance, you might use this to throw an exception of your own when a user has entered invalid information and you want to show them an error message. To do this, you would use a statement like:
36 G e t t i n g S t a rt ed w it h J av a
Chapter
5
Chapter 5
Most programming languages rely on pre-built libraries of classes to support certain functionality. In the Java language, these groups of related classes called packages vary by Java edition. Each edition is used for specific purposes, such as applications, enterprise applications, and consumer products.
Java 2 Platform
Standard Edition Enterprise Edition Micro Edition
Description
Contains classes that are the core of the Java language. Contains J2SE classes and additional classes for developing enterprise applications. Contains a subset of J2SE classes and is used in consumer electronic products.
Standard Edition
The Java 2 Platform, Standard Edition (J2SE) provides developers with a feature-rich, stable, secure, cross-platform development environment. This Java edition supports such core features as database connectivity, user interface design, input/output, and network programming and includes the fundamental packages of the Java language.
C ha p t e r 5: T h e J av a c l as s li br a r ie s
37
J a v a 2 S t a nd a r d E di t i on p a c k ag e s
See also
I I
Java 2 Platform Standard Edition Overview at http://java.sun.com/j2se/ Introducing the Java Platform at http://developer.java.sun.com/developer/
onlineTraining/new2java/programming/intro/
I
Enterprise Edition
The Java 2, Enterprise Edition (J2EE) provides the developer with tools to build and deploy multitier enterprise applications. J2EE includes the J2SE packages as well as additional packages which support Enterprise JavaBeans development, Java servlets, JavaServer Pages, XML, and flexible transaction control.
See also
I
overview.html
I
developer/technicalArticles/J2EE/index.html
Micro Edition
The Java 2, Micro Edition (J2ME) is used in a variety of consumer electronic products, such as pagers, smart cards, cell phones, hand-held PDAs, and set-top boxes. While J2ME provides the same Java language advantages of code portability across platforms, the ability to run anywhere, and safe network delivery as J2SE and J2EE, it uses a smaller set of packages. J2ME includes a subset of the J2SE packages with an additional package specific to the Micro Edition, javax.microedition.io. In addition, J2ME applications are upwardly scalable to work with J2SE and J2EE.
See also
I I
Java 2 Platform Micro Edition Overview at http://java.sun.com/j2me/ Consumer & Embedded Products technical articles at
http://developer.java.sun.com/developer/technicalArticles/ConsumerProducts/ index.html
Package
Language Utilities
java.lang java.util
38 G e t t i n g S t a rt ed w it h J av a
J a v a 2 S t a n d ar d E d i t io n p a c k ag e s
Table 5.2
Package
I/O Text Math AWT Swing Javax Applet Beans Reflection XML processing
java.io java.text java.math java.awt javax.swing javax java.applet java.beans java.lang.reflect org.w3c.dom org.xml.sax javax.xml.transform javax.xml.parsers java.sql javax.sql java.rmi java.net java.security
Note
Java packages vary by Java 2 Platform edition. The Java 2 Software Development Kit (SDK) is available in several editions used for various purposes: Standard Edition (J2SE), Enterprise Edition (J2EE), and Micro Edition (J2ME).
See also
I I
Java 2 Platform editions on page 37 Java 2 Platform, Standard Edition, API Specification in the JDK API Documentation Suns tutorial, Creating and using packages at http://www.java.sun.com/docs/ books/tutorial/java/interpack/packages.html Packages in Managing paths in Building Applications with JBuilder
See also
I I
C ha p t e r 5: T h e J av a c l as s li br a r ie s
39
J a v a 2 S t a nd a r d E di t i on p a c k ag e s
See also
I I
See also
I I
See also
I I
java.text in the JDK API Documentation Internationalizing programs with JBuilder in Building Applications with JBuilder
See also
I I I
java.math in the JDK API Documentation java.lang.Math class in the JDK API Documentation Arbitrary-Precision Math in the JDK Guide to Features
40 G e t t i n g S t a rt ed w it h J av a
J a v a 2 S t a n d ar d E d i t io n p a c k ag e s
See also
I I I
awt/
I I
Tutorial: Building an applet in Getting Started with JBuilder Visual Design with JBuilder in Designing Applications with JBuilder
See also
I I
http://www.java.sun.com/docs/books/tutorial/uiswing/index.html
I
Introduction Managing the component palette Using layout managers Using nested panels and layouts Tutorial: Building a Java text editor
See also
I I I I I I I
javax.accessibility in the JDK API Documentation javax.naming in the JDK API Documentation javax.rmi in the JDK API Documentation javax.sound.midi in the JDK API Documentation javax.sound.sampled in the JDK API Documentation javax.swing in the JDK API Documentation javax.transaction in the JDK API Documentation
C ha p t e r 5: T h e J av a c l as s li br a r ie s
41
J a v a 2 S t a nd a r d E di t i on p a c k ag e s
See also
I I
tutorial/applet/index.html
I I I
Chapter 9, An introduction to the Java Virtual Machine Working with applets in the Developing Web Applications Tutorial: Building an applet in Getting Started with JBuilder
See also
I I
http://developer.java.sun.com/developer/technicalArticles/jbeans/index.html
I
See also
I I
java.lang.reflect in the JDK API Documentation Reflection in the JDK Guide to Features
42 G e t t i n g S t a rt ed w it h J av a
J a v a 2 S t a n d ar d E d i t io n p a c k ag e s
XML processing
Java, in conjunction with XML (Extensible Markup Language), provides a portable, flexible framework for creating, exchanging, and manipulating information between applications and over the Internet, as well as transforming XML documents into other document types. The Java API for XML processing (JAXP) includes the basic facilities for working with XML documents: Document Object Model (DOM), Simple API for XML Parsing (SAX), XSL Transformations (XSLT), and a pluggability layer for parsers.
See also
I I I I I I I
org.w3c.dom in the JDK API Documentation org.xml.sax in the JDK API Documentation javax.xml.transform in the JDK API Documentation javax.xml.parsers in the JDK API Documentation Java Technology & XML Home Page at http://java.sun.com/xml/ XML in the Java 2 Platform in the JDK Guide to Features Suns XML Tutorial at http://java.sun.com/xml/tutorial_intro.html
See also
I I
tutorial/jdbc/index.html
I
C ha p t e r 5: T h e J av a c l as s li br a r ie s
43
J a v a 2 S t a nd a r d E di t i on p a c k ag e s
An example of writing a distributed database application using RMI and DataSetData is located in the samples/DataExpress/StreamableDataSets directory of your JBuilder installation. This example includes a server application that will take data from the employee sample table and send the data via RMI in the form of DataSetData. A client application communicates with the server through a custom Provider and a custom Resolver, and displays the data in a grid. (This sample is a feature of JBuilder Enterprise.)
See also
I I I
See also
I I
java.net in the JDK API Documentation Networking Features in the JDK Guide to Features
Classes that implement access control and prevent untrusted code from performing sensitive operations. Authentication classes that implement message digests and digital signatures and authenticate classes and other objects.
Using these classes, developers can protect access to applets and Java code, including applications, beans, and servlets, by creating permissions and security policies. When code is loaded, it is assigned permissions based on the security policy. Permissions specify which resources can be accessed, such as read/write or connection access. The policy, which controls which permissions are available, is usually initialized from an external configurable policy file which defines the codes security policy. The use of permissions and policy allow for flexible, configurable, and extensible access control to the code.
See also
I I
java.security in the JDK API Documentation Security in the JDK Guide to Features
44 G e t t i n g S t a rt ed w it h J av a
J a v a 2 S t a n d ar d E d i t io n p a c k ag e s
that all Java classes are derived from it. The Object class itself contains a constructor and several methods of importance, including clone(), equals(), and toString(). Method Argument Description
Creates and returns a copy of an object. Indicates whether another object is equal to the specified object. Returns a string representation of an object
() (Object obj) ()
An object that uses the clone() method simply makes a copy of itself. When a copy is made, the new memory is allocated for the clone first, then contents of the original object is copied into the clone object. In the following example where the Document class implements the Cloneable interface, a copy of the Document class containing a text and author property is created using the clone() method. An object is not seen as cloneable unless it implements the Cloneable interface.
See also
I
Wrapper
C ha p t e r 5: T h e J av a c l as s li br a r ie s
45
J a v a 2 S t a nd a r d E di t i on p a c k ag e s
The constructor for the wrapper classes, such as Character(char value), simply takes an argument of the class type it is wrapping. For example, the following code demonstrates how a Character wrapper class is constructed.
d1 d2 d3 d4 d5
= = = = =
Some of these methods are overloaded to accept and return different data types. The Math class also declares the constants PI and E.
Note
The java.math package, unlike java.lang.Math, provides support classes for working with arbitrarily large numbers.
See also
I I
java.lang.Math in the JDK API Documentation java.math in the JDK API Documentation
46 G e t t i n g S t a rt ed w it h J av a
J a v a 2 S t a n d ar d E d i t io n p a c k ag e s
Constructor
Argument
Description
Creates a new String that contains a subarray of the argument. Initializes a new String object with the contents of the StringBuffer argument.
String String
The String class contains several important methods that are essential when dealing with strings. These methods are used to edit, compare, and analyze strings. Because strings are immutable and cannot be changed, none of these methods can change the character sequence. The StringBuffer class, discussed in the next section, provides methods for changing strings. The following table lists some of the more crucial methods and declares what they accept and return. Method Argument Returns Description
Returns the number of characters in the string. Returns the character at the specified index of the string. Compares a string to the argument string. Returns the index location of the first occurrence of the specified character. Returns a new string that is a substring of the string. Concatenates the specified String to the end of this string. Returns the string in lowercase. Returns the string in uppercase. Returns the string representation of the Object argument.
() (int index) (String value) (int ch) (int beginIndex, int endIndex) (String str)
A very efficient feature associated with many of these methods is that they are overloaded for more flexibility. The following demonstrates how the String class and some of its methods can be used.
Important
String s1 = new String("Hello World."); char cArray[] = {'J', 'B', 'u', 'i', 'l', 'd', 'e', 'r'}; String s2 = new String(cArray); //s2 = "JBuilder" int i = s1.length(); char c = s1.charAt(6); i = s1.indexOf('e'); //i = 12 //c = 'W' //i = 1 (index of 'e' in "Hello World.")
String s3 = "abcdef".substring(2, 5); //s3 = "cde" String s4 = s3.concat("f"); //s4 = "cdef" String s5 = String.valueOf(i); //s5 = "1" (valueOf() is static)
See also
I
C ha p t e r 5: T h e J av a c l as s li br a r ie s
47
J a v a 2 S t a nd a r d E di t i on p a c k ag e s
String str.
There are several important methods that separate the StringBuffer class from the String class: capacity(), setLength(), setCharAt(), append(), insert() and toString(). The append() and insert() methods are overloaded to accept various data types. Method Argument Description
Sets the length of the Stringbuffer. Returns the amount of memory allocated to the
setLength (int newLength) capacity () setCharAt (int index, char ch) append insert toString (char c) (int offset, char c) ()
StringBuffer.
Sets the character at the specified index of the StringBuffer to ch. Adds the string representation of the data type in the argument to the StringBuffer. This method is overloaded to accept various data types. Inserts the string representation of the data type in the argument into this StringBuffer. This method is overloaded to accept various data types. Converts the StringBuffer to a String.
The capacity() method, which returns the amount of memory allocated for the StringBuffer, can return a larger value than the length() method. Memory allocated for a StringBuffer can be set with the StringBuffer(int length) constructor. The following code demonstrates some of the methods associated with the StringBuffer class.
StringBuffer s1 = new StringBuffer(10); int c = s1.capacity(); int len = s1.length(); s1.append("Bor"); s1.append("land"); c = s1.capacity(); len = s1.length(); s1.setLength(2); //c = 10 //len = 0 //s1 = "Bor" //s1 = "Borland" //c = 10 //len = 7 //s1 = "Bo"
48 G e t t i n g S t a rt ed w it h J av a
J a v a 2 S t a n d ar d E d i t io n p a c k ag e s
See also
I
arrayCopy
arraycopy(Object src, int src_position, Object dst, int dst_position, int length) () (String libname) (String key) () (String filename) (int status) (String key, String value)
See also
I
C ha p t e r 5: T h e J av a c l as s li br a r ie s
49
J a v a 2 S t a nd a r d E di t i on p a c k ag e s
The methods defined in the Enumeration interface allow the Enumeration object to continuously retrieve all the elements from a set of values, one by one. There are only two methods declared in the Enumeration interface, hasMoreElements() and nextElement(). The hasMoreElements() method returns true if more elements remain in the data structure. The nextElement() method is used to return the next value in the structure being enumerated. The following example creates a class called CanEnumerate, which implements the Enumeration interface. An instance of that class is used to print all the elements of the Vector object, v.
See also
I
The following table lists some of the more important methods of the Vector class and the arguments they accept. Method Argument Description
Sets the size of a vector. Returns the capacity of a vector. Returns the number of elements stored in a vector. Returns an enumeration of elements of a vector. Returns the element at the specified index. Returns the first element of a vector (at index 0).
50 G e t t i n g S t a rt ed w it h J av a
J a v a 2 S t a n d ar d E d i t io n p a c k ag e s
Method
Argument
Description
Returns the last element of a vector. Removes the element at the specified index. Adds the specified object to the end of a vector, increasing its size by one. Returns a string representation of each element in a vector.
The following code demonstrates the use of the Vector class. A Vector object called vector1 is created and enumerates its elements in three ways: using Enumerations nextElement() method, using Vectors elementAt() method, and using Vectors toString() method. An AWT component, textArea, is created to display the output. The text property is set using the setText() method.
Vector vector1 = new Vector(); for (int i = 0; i < 10;i++) { vector1.addElement(new Integer(i)); //addElement accepts object or //composite types } //but not primitive types //enumerate vector1 using nextElement() Enumeration e = vector1.elements(); textArea1.setText("The elements using Enumeration's nextElement():\n"); while (e.hasMoreElements()) { textArea1.append(e.nextElement()+ " | "); } textArea1.append("\n\n"); //enumerate using the elementAt() method textArea1.append("The elements using Vector's elementAt():\n"); for (int i = 0; i < vector1.size();i++) { textArea1.append(vector1.elementAt(i) + " | "); } textArea1.append("\n\n"); //enumerate using the toString() method textArea1.append("Here's the vector as a String:\n"); textArea1.append(vector1.toString());
The following figure demonstrates what this code would accomplish if it was used within an application.
Figure 5.1
See also
I
C ha p t e r 5: T h e J av a c l as s li br a r ie s
51
J a v a 2 S t a nd a r d E di t i on p a c k ag e s
Input stream classes read data as a continuous stream of bytes. If no data is currently available, the input stream class blocks or waits until data becomes available. In addition to the input stream classes, the java.io package provides reader classes (except for DataInputStream). Examples of reader classes include Reader, BufferedReader, FileReader, and StringReader. Reader classes are identical to input stream classes, except that they read Unicode characters instead of bytes.
See also
I
52 G e t t i n g S t a rt ed w it h J av a
J a v a 2 S t a n d ar d E d i t io n p a c k ag e s
an argument, while the second simply takes a file object. The third constructor takes a file descriptor object. File classes are discussed later. Constructor Argument Description
Creates a FileInputStream by opening a connection to the file named by the path name filename in the file system. Creates a FileInputStream by opening a connection to the file named by the fileobject file in the file system. Creates a FileInputStream by using the file descriptor fdObj, which represents an existing connection to an actual file in the file system.
import java.io.*; class FileReader { public static void main(String args[]) { byte buff[] = new byte[80]; try { InputStream fileIn = new FileInputStream("Readme.txt"); int i = fileIn.read(buff); String s = new String(buff); System.out.println(s); } catch(FileNotFoundException e) { } catch(IOException e) { } } }
In this example, a character array that stores the input data is created. Then, a FileInputStream object is instantiated and the input files name is passed to its constructor. Next, the FileInputStream read() method is used to read a stream of characters and store them in the buff array. The first 80 bytes are read from the Readme.txt file and stored in the buff array.
Note
The FileReader class could also be used in place of the FileInputStream() method. The only changes needed would be a char array used in place of the byte array, and the reader object would be instantiated as follows:
See also
I
C ha p t e r 5: T h e J av a c l as s li br a r ie s
53
J a v a 2 S t a nd a r d E di t i on p a c k ag e s
See also
I
PrintStream PrintStream
Several of the methods defined in the PrintStream class are shown in the following table. Method Argument Description
Flushes the stream and returns a false value if an error is detected. Prints an object. Prints a string. Prints and terminates the line using the line separator string which is defined by the system property line.separator and is not necessarily a single newline character ('\n'). Prints an object and terminates the line. This method behaves as though it invokes print(Object) and then println().
println
(Object obj)
The print() and println() methods are overloaded to receive different data types.
See also
I
54 G e t t i n g S t a rt ed w it h J av a
J a v a 2 S t a n d ar d E d i t io n p a c k ag e s
BufferedOutputStream BufferedOutputStream
(OutputStream out) Creates a new 512-byte buffered output (OutputStream out, int size)
Creates a new buffered output stream to write data to the output stream with the specified buffer size.
BufferedOutputStream has three methods to flush and write to the output stream.
Method Argument Description
Flushes the buffered output stream. Writes len bytes from the byte array starting at offset off to the buffered output stream. Writes the byte to the buffered output stream.
See also
I
() () (int b) (type v)
See also
I
C ha p t e r 5: T h e J av a c l as s li br a r ie s
55
J a v a 2 S t a nd a r d E di t i on p a c k ag e s
involved is already open. FileOutputStream in the java.io package, a subclass of OutputStream, has several constructors. Constructor Argument Description
Creates a file output stream to write to the file specified. Creates an output file stream to write to the file descriptor, which represents an existing connection to an actual file in the file system. Creates an output file stream to write to the file with the specified name. Creates an output file stream to write to the file with the specified name.
FileOutputStream FileOutputStream
FileOutputStream FileOutputStream
FileOutputStream has several methods, including close(), finalize(), and several write() methods.
Method Argument Description
Closes the file output stream and releases any associated system resources. Cleans up the connection to the file and calls the close() method when there are no more references to the stream. Returns the file descriptor associated with the stream. Writes len bytes from the byte array starting at offset off to the file output stream.
See also
I
File classes
The FileInputStream and FileOutputStream classes in the java.io package only provide basic functions for handling file input and output. The java.io package provides the File class and RandomAccessFile class for more advanced file support. The File class provides easy access to file attributes and functions, while the RandomAccessFile class provides various methods for reading and writing to and from a file.
(String path) (String parent, String child) (File parent, String child)
The File class also implements many important methods which check for the existence, readability, writeability, type, size, and modification time of files and
56 G e t t i n g S t a rt ed w it h J av a
J a v a 2 S t a n d ar d E d i t io n p a c k ag e s
directories, as well as making new directories and renaming and deleting files and directories. Method Argument Returns Description
Deletes the file or directories. Tests whether the application can read the file denoted by the abstract pathname. Tests whether the application can write to the file. Renames the file. Returns the name string of the file or directory. Returns the pathname string of the parent directory of the file or directory. Converts the abstract pathname into a pathname string.
() () () (File dest) () () ()
See also
I
RandomAccessFile RandomAccessFile
There are many powerful methods implemented by the RandomAccessFile class. Some of these methods include: Method Argument Description
Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occur. Reads the next byte of data from the input stream. Reads up to len bytes of data starting from offset off from the input stream into an array. Reads the specified data type from a file, such as readChar, readByte, readLong. Writes the specified byte to the file. Writes len bytes from the byte array starting at offset off to the output stream. Returns the length of the file. Closes the file and releases any associated system resources.
(long pos) () (byte b[], int off, int len) () (int b) (byte b[], int off, int len) () ()
C ha p t e r 5: T h e J av a c l as s li br a r ie s
57
J a v a 2 S t a nd a r d E di t i on p a c k ag e s
See also
I
The StreamTokenizer class uses instance variables nval, sval, and ttype to hold the number value, string value, and type of the token respectively. The StreamTokenizer class implements several methods used to define the lexical syntax of tokens. Method Argument Description
Parses the next token from the input stream. Returns TT_NUMBER if the next token is a number, TT_WORD if the next token is a word or a character. Parses the numbers. Returns the current line number. Returns the current value in the ttype field on the next call of the nextToken() method. Returns the string equivalent of the current token.
() () () () ()
See also
I
58 G e t t i n g S t a rt ed w it h J av a
Chapter
6
Chapter 6
Object-oriented programming has been around since the introduction of the language Simula 67 in 1967. It really came to the forefront of programming paradigms in the mid-1980s, however. Unlike traditional structured programming, object-oriented programming places the data and the operations that pertain to the data within a single data structure. In structured programming, the data and the operations on the data are separate and data structures are sent to procedures and functions to be operated on. Objectoriented programming solves many of the problems inherent in this design because the attributes and operations are part of the same entity. This more closely models the real world, in which all objects have both attributes and activities associated with them. Java is a pure object-oriented language, meaning that the outermost level of data structure in Java is the object. There are no stand-alone constants, variables, or functions in Java. Everything is accessed through classes and objects. This is one of the nicest features of Java. Other hybrid object-oriented languages have aspects of structured languages in addition to object extensions. For example, C++ and Object Pascal are object-oriented languages, but you can still write structured programming constructs, which dilutes the effectiveness of the object-oriented extensions. You just cant do that in Java! This chapter assumes you have some knowledge about programming in other objectoriented languages. If you dont, you should refer to other sources to find a more indepth explanation of object-oriented programming. This chapter attempts to highlight and summarize the object-oriented features of Java.
Classes
Classes and objects are not the same thing. A class is a type definition, whereas an object is a declaration of an instance of a class type. Once you create a class, you can create as many objects based on that class as you want. The same relationship exists between classes and objects as between cherry pie recipes and cherry pies; you can make as many cherry pies as you want from a single recipe. The process of creating an object from a class is referred to as instantiating an object or creating an instance of a class.
C h a pt er 6 : O b je c t - o ri e nt e d p r og r a m m in g i n J a v a
59
C l as s e s
class MyClass { }
While this class is not yet useful, it is legal in Java. A more useful class would contain some data members and methods, which youll add soon. First, examine the syntax for instantiating a class. To create an instance of this class, use the new operator in conjunction with the class name. You must declare an instance variable for the object:
MyClass myObject;
Just declaring an instance variable doesnt allocate memory and other resources for the object, however. Doing so creates a reference called myObject, but it doesnt instantiate the object. The new operator performs this task.
Data members
As stated above, a class in Java can contain both data members and methods. A data member or member variable is a variable declared within the class. A method is a function or routine that performs some task. Here is a class that contains just data members:
public class DogClass { String name, eyeColor; int age; boolean hasTail; }
This example creates a class called DogClass that contains data members: name, eyeColor, age, and a flag called hasTail. You can include any data type as a member variable of a class. To access a data member, you must first create an instance of the class, then access the data using the . operator.
Class methods
You can also include methods in classes. In fact, there are no standalone functions or procedures in Java. All subroutines are defined as methods of classes. Here is an example of DogClass with a speak() method added:
public class DogClass { String name,eyeColor; int age; boolean hasTail; public void speak() { JOptionPane.showMessageDialog(null, "Woof! Woof!"); } }
60 G e t t i n g S t a rt ed w it h J av a
Class es
Notice that when you define methods, the implementation for the method appears directly below the declaration. This is unlike some other object-oriented languages where the class is defined in one location and the implementation code appears somewhere else. A method must specify a return type and any parameters received by the method. The speak() method takes no parameters. It also doesnt return a value, so its return type is void. To call the method, you would access it just like you would access the member variables; that is, using the . operator. For example,
Beginning an application using JBuilders Application wizard. Selecting components from the component palette and placing them on the UI designer. Setting component properties using the Inspector. Switching between the editor and the UI designer in JBuilders content pane. Using the editor.
I I I
C h a pt er 6 : O b je c t - o ri e nt e d p r og r a m m in g i n J a v a
61
C l as s e s
This is what the running sample application you will build looks like:
Figure 6.1
Follow these steps listed in this section to create a simple UI for this sample application.
1 Start creating the application and designing its UI: a Start a new project. Choose File|New Project to start the Project wizard. b Enter oop1 in the Project Name field and click Finish. A new project opens. c Choose File|New, click the General tab, and click the Application icon to start the
Application wizard.
d Accept the default class name. The package name will be oop1. e Click Next and then Finish to create a Frame1.java and an Application1.java file. f
Click the Design tab in the content pane to display the UI designer for Frame1.java. of contentPane to XYLayout (if you are a Foundation user, set layout to null). XYLayout and null are seldom ideal for an application, but until you learn about using layouts, you can use them to create a quick-and-dirty UI.
g Select contentPane in the structure pane. In the Inspector set the layout property
2 Place the needed components on the UI designer, using the above screen shot as a
reference:
a Click the Swing tab on the component palette and click the JTextField
component. (When you position your cursor over a component, a tooltip appears labeling the component. Click the component labeled javax.swing.JTextField.) Click in the UI designer and hold down the mouse button as you draw the component onscreen. Repeat this step five more times until you have two groups of three JTextField components on your form.
b Hold down the Shift key as you click each JTextField on the UI designer so that all
of them are selected. Select the text property in the Inspector and delete the text that appears there. This will delete all the text in each JTextField component.
c Change the name property value of each JTextField. Name the first one
txtfldDogName, the second txtfldDogEyeColor, the third txtfldDogAge, the fourth txtfldManName, the fifth txtfldManEyeColor, and the sixth txtfldManAge.
d Draw six JLabel components on the form, each one adjacent to a JTextField
component.
e Change the text property values for these components to label each JTextField
component appropriately. For example, the text property of the JLabel at the top of the form should be Name, the second Eye Color, and so on.
f
Place two JCheckBox components on the form. Place the first one below the first group of three JTextField components, and the second check box beneath the second group of JTextField components.
62 G e t t i n g S t a rt ed w it h J av a
Class es
g Select each JCheckBox component on the form in turn and change the first ones
text property to Has Tail, and second ones text property to Is Married.
h Change the value of the name property for the first check box to chkboxDog, and
Place two JButton components on the form, one to the right of the top group of components, and the second to the right of the bottom group of components. Change the text property of the first button to Create Dog, and change the text property of the second button to Create Man.
The final step is to save the project by choosing File|Save All. Youre now ready to begin programming. First create a new class:
1 Choose File|New Class to start the Class wizard. 2 Keep the name of the package as oop1, specify the Class Name as DogClass, and
other options.
4 Click OK.
The Class wizard creates the DogClass.java file for you. Modify the code it created so that your code looks like this:
package oop1; public class DogClass { String name, eyeColor; int age; boolean hasTail; public DogClass() { name = "Snoopy"; eyeColor = "Brown"; age = 2; hasTail = true; } }
You defined DogClass with some member variables. There is also a constructor to instantiate DogClass objects. Using the Class wizard, create a ManClass.java file by following the same steps except specifying the Class Name as ManClass. Modify the resulting code so that it looks like this:
package oop1; public class ManClass { String name, eyeColor; int age; boolean isMarried; public ManClass() { name = "Steven"; eyeColor = "Blue"; age = 35; isMarried = true; } }
C h a pt er 6 : O b je c t - o ri e nt e d p r og r a m m in g i n J a v a
63
C l as s e s
The two classes are very similar. Youll take advantage of this similarity in an upcoming section. Click the Frame1 tab at the top of content pane to return to the Frame1 class. Click the Source tab at the bottom to return to open the editor. Declare two instance variables as references to the objects. Here is the source listing of the Frame1 variable declarations shown in bold; add the lines in bold to your class:
public class Frame1 extends JFrame { // Create a reference for the dog and man objects DogClass dog; ManClass man; JPanel contentPane; JPanel jPanel1 = new JPanel(); . . .
Click the Design tab at the bottom of content pane to return to the UI you designed. Double-click the Create Dog button. JBuilder creates the beginning of an event handler for that button and places your cursor within the event handler code. Fill in the event handler code so that you instantiate a dog object and fill in the dog text fields. Your code should look like this:
Class inheritance
The dog and man objects you created have many similarities. One of the benefits of object-oriented programming is the ability to handle similarities like this within a hierarchy. This ability is referred to as inheritance. When a class inherits from another class, the child class automatically inherits all the characteristics (member variables) and behavior (methods) from the parent class. Inheritance is always additive; there is no way to inherit from a class and get less than what the parent class has.
64 G e t t i n g S t a rt ed w it h J av a
Class es
Inheritance in Java is handled through the keyword extends. When one class inherits from another class, the child class extends the parent class. For example,
package oop1; public class MammalClass { String name, eyeColor; int age; public MammalClass() { name = "The Name"; eyeColor = "Brown"; age = 0; } }
Notice that the MammalClass has common characteristics from both the DogClass and the ManClass. Now, rewrite DogClass and ManClass to take advantage of inheritance. Modify the code of DogClass so that it look like this:
package oop1; public class DogClass extends MammalClass { boolean hasTail; public DogClass() { // implied super() name = "Snoopy"; age = 2; hasTail = true; } }
Modify the code of ManClass so that it looks like this:
package oop1; public class ManClass extends MammalClass{ boolean isMarried; public ManClass() { name = "Steven"; eyeColor = "Blue"; age = 35; isMarried = true; } }
C h a pt er 6 : O b je c t - o ri e nt e d p r og r a m m in g i n J a v a
65
C l as s e s
Notice that DogClass doesnt specifically assign an eyeColor value, but ManClass does. DogClass doesnt need to assign a value to eyeColor because the dog Snoopy has brown eyes and DogClass inherits brown eyes from the MammalClass, which declares an eyeColor variable and assigns it the value of Brown. The man Steven, however, has blue eyes, so its necessary to assign the value Blue to the eyeColor variable inherited from MammalClass. Try compiling and running your project again. (Choosing Run|Run Project will compile and then run your application.) Youll see that the UI of your program looks just as it did before, but now the dog and man objects inherit all common member variables from MammalClass. As soon as DogClass extends MammalClass, DogClass has all the member variables and methods that the MammalClass has. In fact, even MammalClass is inherited from another class. All classes in Java ultimately extend the Object class; so if a class is declared that doesnt extend another class, it implicitly extends the Object class. Classes in Java can inherit from only one class at a time (single inheritance). Unlike Java, some languages (such as C++) allow a class to inherit from several classes at once (multiple inheritance). A class can extend just one class at a time. Although there is no restriction on how many times you can use inheritance to extend the hierarchy, you must do so one extension at a time. Multiple inheritance is a nice feature, but it leads to very complex object hierarchies. Java has a mechanism that provides many of the same benefits without so much complexity, as youll see later. The MammalClass has a constructor that sets very practical and convenient default values. It would be nice if the subclasses could access this constructor. In fact, they can. You can do this in Java two different ways. If you dont call the parents constructor explicitly, Java automatically calls the parents default constructor for you as the first line of the child constructor. The only way to prevent this behavior is to call one of the parents constructors yourself as the first line of the child class constructor. Constructor calls are always chained like this, and you cant defeat this mechanism. This is a very nice feature of the Java language, because in other object-oriented languages, failing to call the parents constructor is a common bug. Java will always do this for you if you dont. That is the meaning of the comment in the first line of the DogClass constructor, // implied super(). The MammalClass constructor is called at that point automatically. This mechanism relies on the existence of a superclass (parent class) constructor that takes no parameters. If the constructor doesnt exist and you dont call one of the other constructors as the first line of the child constructor, the class wont compile.
66 G e t t i n g S t a rt ed w it h J av a
Class es
Access modifiers
Its important to understand when members (both variables and methods) in the class are accessible. There are several options in Java to allow you to closely tailor how accessible you want these members to be. Usually you want to limit the scope of program elements, including class members, as much as possible. The fewer places something is accessible, the fewer places it can be accessed incorrectly. There are four different access modifiers for class members in Java: private, protected, public, and default (or the absence of any modifier). This is slightly complicated by the fact that classes within the same package have different access than classes outside the package. Therefore, here are two tables that show both the accessibility and inheritability of classes and member variables from within the same package and from outside the package (packages are discussed in a later section).
Inherited
Yes Yes Yes No
Accessible
Yes Yes Yes No
This table shows how class members are accessed and inherited from with respect to other members in the same package. For example, a member that is declared to be private cannot be accessed by, or inherited from, other members of the same package. On the other hand, members declared using the other modifiers could be accessed by and inherited from all other members of that package. All parts of the sample application are part of the oop1 package, so you dont have to worry about accessing classes in another package.
Inherited
No Yes Yes No
Accessible
No Yes No No
For example, this table shows that a protected member could be inherited from, but not accessed, by classes outside its package. Note that in both access tables public members are available to anyone who wants to access them (notice that constructors are always public), whereas private members are never accessible nor inheritable outside the class. So, you should declare any member variable or method you want to keep internal to the class private. A recommended practice in object-oriented programming is to hide information within the class by making all of the member variables of the class private and accessing them through methods that are in a specific format called accessor methods.
C h a pt er 6 : O b je c t - o ri e nt e d p r og r a m m in g i n J a v a
67
C l as s e s
Accessor methods
Accessor methods (sometimes called getters and setters) are methods that provide the outward public interface to the class while keeping the actual data storage private to the class. This is a good idea because you can, at any time in the future, change the internal representation of the data in the class without touching the methods that actually set those internal values. As long as you dont change the public interface to the class, you dont break any code that relies on that class and its public methods. Accessor methods in Java usually come in pairs: one to get the internal value, and another to set the internal value. By convention, the Get method uses the internal private variable name with get as a prefix. The Set method does the same with set. A read-only property would only have a Get method. Usually, Boolean Get methods use is or has as the prefix instead of get. Accessor methods also make it easy to validate the data that is assigned to a particular member variable. Here is an example. In your DogClass, make all of the internal member variables private and add accessor methods to access the internal values. DogClass creates just one new member variable, tail.
package oop1; public class DogClass extends MammalClass{ // accessor methods for properties // Tail public boolean hasTail() { return tail; } public void setTail( boolean value ) { tail = value; } public DogClass() { setName("Snoopy"); setAge(2); setTail(true); } private boolean tail; }
The variable tail has been moved to the bottom of the class and now is declared as private. The location of the definition is not important, but its common in Java to place the private members of the class at the bottom of the class definition (after all, you cant get to them outside the class; therefore, if you are reading the code, you are interested in the public aspects first). DogClass now has public methods to retrieve and set the value of tail. The getter is hasTail() and setter is setTail(). Follow the same patterns and revise ManClass so that it looks like this:
package oop1; public class ManClass extends MammalClass { public boolean isMarried() { return married; } public void setMarried(boolean value) { married = value; }
68 G e t t i n g S t a rt ed w it h J av a
Class es
public class MammalClass { // accessor methods for properties // name public String getName() { return name; } public void setName(String value) { name = value; } // eyecolor public String getEyeColor() { return eyeColor; } public void setEyeColor(String value) { eyeColor = value; } // sound public String getSound() { return sound; } public void setSound(String value) { sound = value; } // age public int getAge() { return age; } public void setAge(int value) { if (value > 0) { age = value; } else age = 0; }
C h a pt er 6 : O b je c t - o ri e nt e d p r og r a m m in g i n J a v a
69
C l as s e s
public MammalClass() { setName("The Name"); setEyeColor("Brown"); setAge(0); } private String name, eyeColor, sound; private int age; }
Also note that a new sound member variable has been added to MammalClass. It too has accessor methods. Because DogClass and ManClass extend MammalClass, they also have a sound property. The event handlers in Frame1.java should also use the accessors. Modify the event handlers so they look like this:
void jButton1_actionPerformed(ActionEvent e) { dog = new DogClass(); txtfldDogName.setText(dog.getName()); txtfldDogEyeColor.setText(dog.getEyeColor()); txtfldDogAge.setText(Integer.toString(dog.getAge())); chkboxDog.setSelected(true); } void jButton2_actionPerformed(ActionEvent e) { man = new ManClass(); txtfldManName.setText(man.getName()); txtfldManEyeColor.setText(man.getEyeColor()); txtfldManAge.setText(Integer.toString(man.getAge())); chkboxMan.setSelected(true); }
Abstract classes
Its possible to declare a method in a class as abstract, meaning that there will be no implementation for the method within this class, but all classes that extend this class must provide an implementation. For example, suppose you want all mammals to have the ability to report their top running speed, but you want each mammal to report a different speed. In the mammal class you should create an abstract method called speed(). Add a speed() method to MammalClass just above the private member variable declarations at the bottom of the source code:
70 G e t t i n g S t a rt ed w it h J av a
import javax.swing.*;
This statement makes the entire Swing library available to these classes. Youll read more about import statements soon.
Polymorphism
Polymorphism is the ability for two separate yet related classes to receive the same message but to act on it in their own way. In other words, two different (but related) classes can have the same method name, but they implement the method in different ways. Therefore, you can have a class method that is also implemented in a child class, and you can access the code from the parents class (similar to the automatic constructor chaining discussed earlier). Just as in the constructor example, you can use the keyword super to access any methods or member variables of the superclass. Here is a simple example. We have two classes, Parent and Child.
class Parent { int aValue = 1; int someMethod(){ return aValue; } } class Child extends Parent { int aValue; // this aValue is part of this class int someMethod() { // this overrides Parent's method aValue = super.aValue + 1; // access Parent's aValue with super return super.someMethod() + aValue; } }
The someMethod() of Child overrides the someMethod() of Parent. A method of a child class with the same name as a method in the parent class, but that is implemented differently and therefore has different behavior is an overridden method. Can you see how the someMethod() of the Child class would return the value of 3? The method accesses the aValue variable of Parent using the super keyword, adds the value of 1 to it, and assigns the resulting value of 2 to its own aValue variable. The last line of the method calls the someMethod() of Parent, which simply returns Parent.aValue with a value of 1. To that, it adds the value of Child.aValue, which was assigned the value of 2 in the previous line. So 1 + 2 = 3.
Using interfaces
An interface is much like an abstract class but with one important difference: an interface cannot include any code. The interface mechanism in Java is meant to replace multiple inheritance.
C h a pt er 6 : O b je c t - o ri e nt e d p r og r a m m in g i n J a v a
71
P o l y m or p h is m
An interface is a specialized class declaration that can declare constants and method declarations, but not method implementations. You can never put code in an interface. Here is an interface declaration for our sample application: You can use the JBuilder Interface wizard to start an interface:
1 Choose File|New to open the object gallery and click the General tab. Double-click
unchanged. (You can uncheck the Generate Header Comments to omit headers.)
3 Choose OK to generate the new interface.
Within the new SoundInterface, add a speak() method declaration so that the interface looks like this:
package oop1; import javax.swing.*; abstract public class MammalClass implements SoundInterface { // accessor methods for properties // name public String getName() { return name; } public void setName( String value ) { name = value; } // eyecolor public String getEyeColor() { return eyeColor; }
72 G e t t i n g S t a rt ed w it h J av a
public void setEyeColor( String value ) { eyeColor = value; } // sound public String getSound() { return sound; } public void setSound( String value ) { sound = value; } // age public int getAge() { return age; } public void setAge( int value ) { if ( value > 0 ) { age = value; } else age = 0; } public MammalClass() { setName("The Name"); setEyeColor("Brown"); setAge(0); } public void speak() { JOptionPane.showMessageDialog(null, this.getSound(), this.getName() + " Says", 1); } abstract public void speed(); private String name, eyeColor, sound; private int age; }
The MammalClass definition now implements the SoundInterface fully. Because the speak() method implementation uses the JOptionPane component, which is part of the Swing library, you must add an import statement near the top of the file:
import javax.swing.*;
This import statement makes the entire Swing library available to MammalClass. Youll read more about import statements in The import statement on page 77. Because DogClass and ManClass extend MammalClass, they now automatically have access to the speak() method defined in MammalClass. They dont have to specifically implement speak() themselves. The value of the sound variable passed to the speak()
C h a pt er 6 : O b je c t - o ri e nt e d p r og r a m m in g i n J a v a
73
P o l y m or p h is m
method is set in the constructors of DogClass and ManClass. Here is how the DogClass class should look:
package oop1; import javax.swing.*; public class DogClass extends MammalClass{ public boolean hasTail() { return tail; } public void setTail(boolean value) { tail = value; } public DogClass() { setName("Snoopy"); setSound("Woof, Woof!"); setAge(2); setTail(true); } public void speed() { JOptionPane.showMessageDialog(null, "30 mph", "Dog Speed", 1); } private boolean tail; }
This is how ManClass should look:
package oop1; import javax.swing.*; public class ManClass extends MammalClass { public boolean isMarried() { return married; } public void setMarried(boolean value) { married = value; } public ManClass() { setName("Steven"); setEyeColor("Blue"); setSound("Hello there! I'm " + this.getName() + "."); setAge(35); setMarried(true); } public void speed() { JOptionPane.showMessageDialog(null, "17 mph", "Man Speed", 1); } private boolean married; }
74 G e t t i n g S t a rt ed w it h J av a
change the value of the text property of the second button to Speak.
Figure 6.2
New version of the sample application with Speed and Speak buttons added
Click the Source tab to return to the Frame1.java code and add code shown here in bold to the class definition:
// Create a reference for the objects DogClass dog; ManClass man; //Create an Array of SoundInterface SoundInterface soundList[] = new SoundInterface[2]; //Create an Array of Mammal MammalClass mammalList[] = new MammalClass[2];
You have added code that creates two arrays: one for Mammals and one for SoundInterfaces. Also add code to the Create Dog and Create Man event handlers that add references to the dog and man objects to the arrays:
void button1_actionPerformed(ActionEvent e) { dog = new DogClass(); txtfldDogName.setText(dog.getName()); txtfldDogEyeColor.setText(dog.getEyeColor()); txtfldDogAge.setText(Integer.toString(dog.getAge())); chkboxDog.setSelected(true); mammalList[0] = dog; soundList[0] = dog; } void button2_actionPerformed(ActionEvent e) { man = new ManClass(); txtfldManName.setText(man.getName()); txtfldManEyeColor.setText(man.getEyeColor());
C h a pt er 6 : O b je c t - o ri e nt e d p r og r a m m in g i n J a v a
75
J a v a p ac k a g es
Java packages
To facilitate code reuse, Java allows you to group several class definitions together in a logical grouping called a package. If, for instance, you create a group of business rules that model the work processes of your organization, you might want to place them together in a package. This makes it easier to reuse code that you have previously created.
76 G e t t i n g S t a rt ed w it h J av a
J a v a p a c k ag e s
import java.applet.*;
This tells the compiler if you see a class name you do not recognize, look in the java.applet package for it. Now, when you declare a new class, you can say,
Declaring packages
Creating your own packages is almost as easy as using them. For instance, if you want to create a package called mypackage, you would simply use a package statement at the beginning of your file:
package mypackage; public class Hello extends java.applet.Applet { public void init() { add(new java.awt.Label("Hello World Wide Web!")); } } // end class
Now, any other program can access the classes declared in mypackage with the statement:
import mypackage.*;
Remember, this file should be in a subdirectory called mypackage. This allows your Java compiler to easily locate your package. JBuilders Project wizard will automatically set the directory to match the project name. Also, keep in mind that the base directory of any package you import must be listed in the Source Path of the JBuilder IDE or the Source Path of your project. This is good to remember if you decide to relocate a package to a different base directory. For more information about working with packages in JBuilder, see Packages in Building Applications with JBuilder.
C h a pt er 6 : O b je c t - o ri e nt e d p r og r a m m in g i n J a v a
77
78 G e t t i n g S t a rt ed w it h J av a
Chapter
7
Chapter 7
Threading techniques
Threads are a part of every Java program. A thread is a single sequential flow of control within a program. It has a beginning, a sequence, and an end. A thread cannot run on its own; it runs within a program. If your program is a single sequence of execution, you dont need to set up a thread explicitly, the Java Virtual Machine (VM) will take care of this for you. One of the powerful aspects of the Java language is that you can easily program multiple threads of execution to run concurrently within the same program. For example, a web browser can download a file from one site, and access another site at the same time. If the browser cant do two simultaneous tasks, youd need to wait until the file had finished downloading before you could browse to another site. The Java VM always has multiple threads, called daemon threads, running. For example, a continually running daemon thread performs garbage collection tasks. Another daemon thread handles mouse and keyboard events. It is possible for your program to lock up one of the Java VM threads. If your program appears to be dead, with no events being sent to your program, try using threads.
C ha p t e r 7: T h r ea d in g t e c h ni qu e s
79
T he l if e c y c le o f a t hr e a d
As an example, the following class, CountThread, subclasses Thread and overrides its run() method. In this example, the run() method identifies a thread and prints its name to the screen. The for loop counts integers from the start value to the finish value and prints each count to the screen. Then, before the loop finishes execution, the method prints a string that indicates the thread has finished executing.
public class CountThread extends Thread { private int start; private int finish; public CountThread(int from, int to) { this.start = from; this.finish = to; } public void run() { System.out.println(this.getName()+ " started executing..."); for (int i = start; i <= finish; i++) { System.out.print (i + " "); } System.out.println(this.getName() + " finished executing."); } }
To test the CountThread class, you can create a test class:
public class ThreadTester { static public void main(String[] args) { CountThread thread1 = new CountThread(1, 10); CountThread thread2 = new CountThread(20, 30); thread1.start(); thread2.start(); } }
The main() method in the test application creates two CountThread objects: thread1 that counts from 1 to 10, and thread2 that counts from 20 to 30. Both threads are then started by calling their start() methods. The output from this test application could look like this:
Thread-0 started executing... 1 2 3 4 5 6 7 8 9 10 Thread-0 finished executing. Thread-1 started executing... 20 21 22 23 24 25 26 27 28 29 30 Thread-1 finished executing.
Notice that the output does not show the thread names as thread1 and thread2. Unless you specifically assign a name to a thread, Java will automatically give it a name of the form Thread-n, where n is a unique number, starting with 0. You can assign a name to a thread in the class constructor or with the setName(String) method. In this example, Thread-0 started executing first and finished first. However, it could have started first and finished last, or partially started and been interrupted by Thread-1. This is because threads in Java are not guaranteed to execute in any particular sequence. In fact, each time you execute ThreadTester, you might get a different output. Basically, the process of scheduling threads is controlled by the Java thread scheduler, and not the programmer. For more information, see the topic called Thread priority on page 83.
80 G e t t i n g S t a rt ed w it h J av a
T he li f e c y c le o f a t h r ea d
Note
If your class subclasses a class other than Thread, for example, Applet, you should use the Runnable interface to create threads. To create a new CountThread class that implements the Runnable interface, you need to change the class definition of the CountThread class. The class definition code, with the changes highlighted in bold-faced type, would look like this:
public class CountThread implements Runnable { private int start; private int finish; public CountThread(int from, int to) { this.start = from; this.finish = to; } public void run() { System.out.println(Thread.currentThread() + " started executing..."); for (int i=start; i <= finish; i++) { System.out.print (i + " "); } System.out.println(Thread.currentThread() + " finished executing."); } }
The test application would need to change the way its objects are created. Instead of instantiating CountThread, the application needs to create a Runnable object from the new class and pass it to one of the threads constructors. The code, with the changes highlighted in bold-faced type, would look like this:
public class ThreadTester { static public void main(String[] args) { CountThreadRun thread1 = new CountThreadRun(1, 10); new Thread(thread1).start(); CountThreadRun thread2 = new CountThreadRun(20, 30); new Thread(thread2).start(); } }
The output from this program would look like this:
Thread[Thread-0,5,main] started executing... 1 2 3 4 5 6 7 8 9 10 Thread[Thread-0,5,main] finished executing. Thread[Thread-1,5,main] started executing... 20 21 22 23 24 25 26 27 28 29 30 Thread[Thread-1,5,main] finished executing. Thread-0 is the name of the thread, 5 is the priority the thread was given when it was created, and main is the default ThreadGroup to which the thread was assigned. (The priority and the group are assigned by the Java VM if none are specified.)
See also
I I
C ha p t e r 7: T h r ea d in g t e c h ni qu e s
81
T he l if e c y c le o f a t hr e a d
Defining a thread
The Thread class provides seven constructors. These constructors combine the following three parameters in various ways:
I I I
A Runnable object whose run() method will execute inside the thread. A String object to identify the thread. A ThreadGroup object to assign the thread to. The ThreadGroup class organizes groups of related threads. Description
Allocates a new Thread object. Allocates a new Thread object so that it has target as its run object. Allocates a new Thread object so that it has target as its run object and the specified name as its name. Allocates a new Thread object so that it has the specified name as its name. Allocates a new Thread object so that it belongs to the thread group referred to by group and has target as its run object. Allocates a new Thread object so that it has target as its run object, the specified name as its name, and belongs to the thread group referred to by group. Allocates a new Thread object so that it belongs to the thread group referred to by group and has the specified name as its name.
Constructor
Thread() Thread(Runnable target) Thread(Runnable target, String name) Thread(String name) Thread(ThreadGroup group, Runnable target) Thread(ThreadGroup group, Runnable target, String name) Thread(ThreadGroup group, String name)
If you want to associate state with a thread, use a ThreadLocal object when you create the thread. This class allows each thread to have its own independently initialized copy of a private static variable, for example, a user or transaction ID.
Starting a thread
To start a thread call the start() method. This method creates the system resources necessary to run the thread, schedules the thread, and calls the threads run() method. After the start() method returns, the thread is running and is in a runnable state. Because most computers have only a single CPU, the Java VM must schedule threads. For more information see the topic called Thread priority on page 83.
A sleep() method: these methods allow you to specify a specific number of seconds and nanoseconds to not run. The wait() method: this method causes the current thread to wait for a specified condition to be met. Block the thread on input or output.
When the thread is not runnable, the thread will not run, even if the processor becomes available. To exit the not runnable state, the condition for the entrance to the not runnable state must be met. For example, if you used the sleep() method, the specified number of seconds must have passed. If you used the wait() method, another object
82 G e t t i n g S t a rt ed w it h J av a
T h r e ad pr i or i t y
must tell the waiting thread (with notify() or notifyAll()) of a change in condition. If a thread is blocked by input or output, the input or output must finish. You can also use the join() method to have a thread wait for an executing thread to finish. You call this method for the thread being waited on. You can specify a timeout for a thread by passing a parameter to the method in milliseconds. The join() method waits on the thread until either the timeout has expired or the thread has terminated. This method works in conjunction with the isAlive() methodisAlive() returns true if the thread has been started and not stopped. Note that the suspend() and resume() methods have been deprecated. The suspend() method is deadlock-prone. If the target thread is locking a monitor that protects a critical system resource when it is suspended, no thread can access this resource until the target thread is resumed. A monitor is a Java object used to verify that only one thread at a time is executing the synchronized methods for the object. For more information, see the topic called Synchronizing threads on page 84.
Stopping a thread
You can no longer stop a thread with the stop() method. This method has been deprecated, as it is unsafe. Stopping a thread will cause it to unlock all of the monitors it has locked. If an object previously protected by one of these monitors is in an inconsistent state, other threads will see that object as inconsistent. This can cause your program to be corrupted. To stop a thread, terminate the run() method with a finite loop. For more information, see the topic in the Java 2 SDK, Standard Edition Documentation called Why are Thread.stop, Thread.suspend, Thread.resume and runtime.runFinalizersOnExit Deprecated?.
Thread priority
When a Java thread is created, it inherits its priority from the thread that created it. You can set a threads priority using the setPriority() method. Thread priorities are represented as integer values ranging from MIN_PRIORITY to MAX_PRIORITY (constants in the Thread class). The thread with the highest priority is executed. When that thread stops, yields, or becomes not runnable, a lower priority thread will be executed. If two threads of the same priority are waiting, the Java scheduler will choose one of them to run in a round-robin fashion. The thread will run until:
I I I
A higher priority thread becomes runnable. The thread yields, by use of the yield() method, or its run() method exits. Its time allotment has expired. This only applies to systems that support time slicing.
This type of scheduling is based on a scheduling algorithm called fixed priority scheduling. Threads are run based on their priority when compared to other threads. The thread with the highest priority will always be running.
Time slicing
Some operating systems use a scheduling mechanism knows as time-slicing. Time-slicing divides the CPU into time slots. The system gives the highest priority threads that are of equal priority time to run, until one or more of them finishes, or until a higher priority thread is in a runnable state. Because time-slicing is not supported on all operating systems, your program should not depend on a time-slicing scheduling mechanism.
C ha p t e r 7: T h r ea d in g t e c h ni qu e s
83
S y n c h r on i zi n g t hr e a ds
Synchronizing threads
One of the central problems of multithreaded computing is handling situations where more than one thread has access to the same data structure. For example, if one thread was trying to update the elements in a list, while another thread was simultaneously trying to sort them, your program could deadlock or produce incorrect results. To prevent this problem, you need to use thread synchronization. The simplest way to prevent two objects from accessing the same method at the same time is to require a thread to obtain a lock. While a thread holds the lock, another thread that needs a lock has to wait until the first thread releases the lock. To keep a method thread-safe, use the synchronized keyword when declaring methods that can only be executed by one thread at a time. Note than you can also synchronize on an object. For example, if you create a swap() method that swaps values using a local variable and you create two different threads to execute the method, your program could produce incorrect results. The first thread, due to the Java scheduler, might only be able to execute the first half of the method. Then, the second thread might be able to execute the entire method, but using incorrect values (since the first thread did not complete the operation). The first thread would then return to finish the method. In this case, it would appear as if the swapping of values never took place. To prevent this from happening, use the synchronized keyword in your method declaration. As a basic rule, any method that modifies an objects property should be declared synchronized.
Thread groups
Every Java thread is a member of a thread group. A thread group collects multiple threads into a single object and manipulates all those threads at once. Thread groups are implemented by the java.lang.ThreadGroup class. The runtime system puts a thread into a thread group during thread construction. The thread is either put into a default group or into a thread group you specify when the thread is created. You cannot move a thread into a new group once the thread has been created. If you create a thread without specifying a group name in its constructor, the runtime system places the new thread in the same group as the thread that created it. Usually, unspecified threads are put into the main thread group. However, if you create a thread in an applet, the new thread might be put into a thread group other than main, depending on the browser or viewer the applet is running in. If you construct a thread with a ThreadGroup, the group can be:
I I I
A name of your own creation A group created by the Java runtime A group created by the application in which your applet is running
To obtain the name of the group your thread is part of, use the getThreadGroup() method. Once you know a threads group, you can determine what other threads are in the group and manipulate them all at once.
84 G e t t i n g S t a rt ed w it h J av a
Chapter
8
Chapter 8
Serialization
Object serialization is the process of storing a complete object to disk or other storage system, ready to be restored at any time. The process of restoring the object is known as deserialization. In this section, youll learn why serialization is useful and how Java implements serialization and deserialization. An object that has been serialized is said to be persistent. Most objects in memory are transient, meaning that they go away when their references drop out of scope or the computer loses power. Persistent objects exist as long as there is a copy of them stored somewhere on a disk, tape, or in ROM.
Why serialize?
Traditionally, saving data to a disk or other storage device required that you define a special data format, write a set of functions to write and read that format, and create a mapping between the file format and the format of your data. The functions to read and write data were either simple and lacked extensibility, or they were complex and difficult to create and maintain. Java is completely based around objects and object-oriented programming and provides a storage mechanism for objects in the form of serialization. Using the Java way of doing things, you no longer have to worry about details of file formats and input/ output (I/O). Instead, you can concentrate on solving your real-world tasks by designing and implementing objects. If, for instance, you make a class persistent and later add new fields to it, you dont have to worry about modifying routines that read and write the data for you. All fields in a serialized object will automatically be written and restored.
Java serialization
Serialization first appeared as a feature of JDK 1.1. Javas support for serialization consists of the Serializable interface, the ObjectOutputStream class and the ObjectInputStream class, as well as a few supporting classes and interfaces. Well examine all three of these items as we demonstrate an application that can save user information to a disk and read it back.
C h a pt e r 8 : S e r ia l iz a t io n
85
J a v a s e ri a liz a t i o n
Suppose, for instance, you wanted to save information about a particular user as shown here.
Figure 8.1
After the user types in his or her name and password into the appropriate fields, the application should save information about this user to disk. Of course, this is a very simple example, but you can easily imagine saving data about user application preferences, the last document opened, and so on. Using JBuilder, you can design a user interface like the one shown above. See the Designing Applications with JBuilder book if you need help with this task. Name the Name text field textFieldName, and the password field passwordFieldName. Besides the two labels you can see, add a third one near the bottom of the frame and name it labelOutput.
The Class wizard creates the new class file for you and adds it to the project. Modify the generated code so that it looks like this:
package serialize; public class UserInfo implements java.io.Serializable { private String userName = ""; private String userPassword = ""; public UserInfo() { } public String getUserName() { return userName; } public void setUserName(String s) { userName = s; }
86 G e t t i n g S t a rt ed w it h J av a
Us i ng o ut pu t s t r e a m s
import java.io.*
void jButton1_actionPerformed(ActionEvent e) { UserInfo user = new UserInfo(); // instantiate a user object user.setUserName(textFieldName.getText()); user.setUserPassword(textFieldPassword.getText()); }
If you are using JBuilders UI designer, double-click the Serialize button and JBuilder starts the jButton1_actionPerformed() event code for you. Instantiate a user object, then add the user.setUserName() and user.setUserPassword() method calls to the event handler. Next, open a FileOutputStream to the file that will contain the serialized data. In this example, the file will be called C:\userInfo.ser. Add this code to the Serialize button event handler:
out.writeObject(u); out.flush();
C h a pt e r 8 : S e r ia l iz a t io n
87
U s in g i np u t s t r e a m s
Close the output stream to free up any resources, such as file descriptors, used by the stream.
out.close(); }
Add code to the handler that catches an IOException if there were any problems writing to the file or if the object does not support the Serializable interface.
void jButton1_actionPerformed(ActionEvent e) { UserInfo user = new UserInfo(); user.setUserName(textFieldName.getText()); user.setUserPassword(textFieldPassword.getText()); try { FileOutputStream file = new FileOutputStream("c:\userInfo.ser"); ObjectOutputStream out = new ObjectOutputStream(file); out.writeObject(user); out.flush(); } catch (java.io.IOException IOE) { labelOutput.setText("IOException"); } finally { out.close(); } }
Now compile your project and run it. Enter values in the Name and Password fields and click the Serialize button. You can verify that the object has been written by opening it in a text editor. (Dont try to edit it, or the file will probably be corrupted!) Notice that a serialized object contains a mixture of ASCII text and binary data:
Figure 8.2
ObjectOutputStream methods
The ObjectOutputStream class contains several useful methods for writing data to a stream. You arent restricted to writing objects. Calling writeInt(), writeFloat(), writeDouble(), and so on, will write any of the fundamental types to a stream. If you want to write more than one object or fundamental type to the same stream, you can do so by repeatedly calling these methods against the same ObjectOutputStream object. When you do this, however, you must read the objects back in the same order.
88 G e t t i n g S t a rt ed w it h J av a
U s in g in pu t s t r e a m s
You can begin the process by creating a new FileInputStream object to read from the file you just wrote. If you are using JBuilder, double-click the Deserialize button in the UI Designer, and in the event handler that JBuilder creates for you, add the highlighted code:
input.close();
Finally, you can use the user object as you would any other object of the UserInfo class. In this case, you display the name and password in the third label field you added to the dialog box:
void jButton2_actionPerformed(ActionEvent e) { try { FileInputStream file = new FileInputStream("c:\userInfo.ser"); ObjectInputStream input = new ObjectInputStream(file); UserInfo user = (UserInfo)input.readObject(); input.close(); labelOutput.setText("Name is " + user.getUserName() + ", password is: " + user.getUserPassword()); }
C h a pt e r 8 : S e r ia l iz a t io n
89
W r it i n g a n d r ea d in g o bj ec t s t r e am s
ObjectInputStream methods
ObjectInputStream also has methods such as readDouble(), readFloat(), and so on, which are the counterparts to the writeDouble(), writeFloat(), and such methods. You must call each method in sequence, the same way the objects were written to the stream.
90 G e t t i n g S t a rt ed w it h J av a
Chapter
9
Chapter 9
This chapter provides an introduction to the Java Virtual Machine (JVM). While it is important for you to be familiar with basic information concerning the JVM, unless you get into very advanced Java programming, the JVM is typically something you dont need to worry about. This chapter is for your information only. Before exploring the Java Virtual Machine, we will explain some of the terminology used in this chapter. First, the Java Virtual Machine (JVM) is the environment in which Java programs execute. The Java Virtual Machine specification essentially defines an abstract computer, and specifies the instructions that this computer can execute. These instructions are called bytecodes. Generally speaking, Java bytecodes are to the JVM what an instruction set is to a CPU. A bytecode is a byte-long instruction that the Java compiler generates, and the Java interpreter executes. When the compiler compiles a .java file, it produces a series of bytecodes and stores them in a .class file. The Java interpreter can then execute the bytecodes stored in the .class file. Other terminology used in this chapter involves Java applications and applets. It is sometimes appropriate to distinguish between a Java application and a Java applet. In some sections of this chapter, however, that distinction is inappropriate. In such cases, we will use the word app to refer to both Java applications and Java applets. It is important here to clarify what Java really is. Java is more than just a computer language; it is a computer environment. This is because Java is composed of two separate main elements, each of which is an essential part of Java: the design-time Java (the Java language itself) and the runtime Java (the JVM). This interpretation of the word Java is a more technical one. Interestingly enough, the practical interpretation of the word Java is that it stands for the runtime environment not the language. When you say something like this machine can run Java, what you really mean is that the machine supports the Java Runtime Environment (JRE); more precisely, it implements a Java Virtual Machine. A distinction should be made between the Java Virtual Machine Specification and an implementation of the Java Virtual Machine. The JVM specification is a document (available from Suns website) which defines how to implement a JVM. When an implementation of the JVM correctly follows this specification, it essentially ensures that Java apps can run on this implementation of the JVM with the same results those
Ch a p t er 9 : A n in t r o du c t i on t o t h e J a v a V ir t u a l M ac h in e
91
J a v a V M s e c u r it y
same Java apps produce when running on any other implementation of the JVM. The JVM specification ensures that Java programs will be able to run on any platform. The JVM specification is platform independent, because it can be implemented on any platform. Note that a specific implementation of the JVM is platform dependent. This is because the JVM implementation is the only portion of Java that directly interacts with the operating system (OS) of your computer. Because each OS is different, any specific JVM implementation must know how to interact with the specific OS for which it is intended. Having Java programs run under an implementation of the JVM guarantees a predictable runtime environment, because all implementations of the JVM conform to the JVM specification. Even though there are different implementations of the JVM, they all must meet certain requirements to guarantee portability. In other words, whatever differs among the various implementations does not affect portability. The JVM is responsible for performing the following functions:
I I I I I
Allocating memory for created objects Performing garbage collection Handling register and stack operations Calling on the host system for certain functions, such as device access Monitoring the security of Java apps
Throughout the remaining chapter, we will focus on the last function: security.
Java VM security
One of the JVMs most important roles is monitoring the security of Java apps. The JVM uses a specific mechanism to force certain security restrictions on Java apps. This mechanism (or security model) has the following roles:
I
Determines to what extent the code being run is trusted and assigns it the appropriate level of access Assures that bytecodes do not perform illegal operations Verifies that every bytecode is generated correctly
I I
In the following sections, we will see how these security roles are taken care of in Java.
92 G e t t i n g S t a rt ed w it h J av a
Ja v a V M s e c ur i t y
The first stage of the verifier is concerned with verifying the structure of the class file. All class files share a common structure; for example, they must always begin with what is called the magic number, whose value is 0xCAFEBABE. At this stage, the verifier also checks that the constant pool is not corrupted (the constant pool is where the class files strings and numbers are stored). In addition, the verifier makes sure that there are no added bytes at the end of the class file. The second stage performs system-level verifications. This involves verifying the validity of all references to the constant pool, and ensuring that classes are subclassed properly. The third stage involves validating the bytecodes. This is the most significant and complex stage in the entire verification process. Validating a bytecode means checking that its type is valid and that its arguments have the appropriate number and type. The verifier also checks that method calls are passed the correct type and number of arguments, and that each external function returns the proper type. The final stage is where runtime checks take place. At this stage, externally referenced classes are loaded, and their methods are checked. The method check involves checking that the method calls match the signature of the methods in the external classes. The verifier also monitors access attempts by the currently loaded class to make sure that the class does not violate access restrictions. Another access check is done on variables to ensure that private and protected variables are not accessed illegally. From this exhaustive verification process, we can see how important the Java verifier is to the security model. It is also important to note that the verification process must be done at the verifier level, and not at the compilers, since any compiler can be programmed to generate Java bytecodes. Clearly then, relying on the compiler to perform the verification process is dangerous, since the compiler can be programmed to bypass it. This point illustrates why the JVM is necessary. If you need more information on the Java verifier, please see the Java Virtual Machine Specification at http://java.sun.com/docs/books/vmspec/index.html.
Ch a p t er 9 : A n in t r o du c t i on t o t h e J a v a V ir t u a l M ac h in e
93
J a v a V M s e c u r it y
dangerous operation, it can consult with the SecurityManager object that is loaded into the environment. The way Java apps use the SecurityManager class is generally the same. An instance of SecurityManager is first created, either by using a special command line argument when the app is started (-Djava.security.manager), or in code similar to the following:
Determines whether the class it is attempting to load has already been loaded Loads class files into the Virtual Machine Determines the permissions assigned to the loaded class in accordance with the security policy Provides certain information about loaded classes to the security manager Determines the path from which the class should be loaded (System classes are always loaded from the BOOTCLASSPATH)
I I
Each instance of a class is associated with a class loader object, which is an instance of a subclass of the abstract class java.lang.ClassLoader. Class loading happens automatically when a class is instantiated. It is possible to create a custom class loader by subclassing ClassLoader or one of its existing subclasses, but in most cases this is not necessary. If you need more information about the class loader mechanism, see the documentation for java.lang.ClassLoader and the Security Architecture document in the JDK documentation.
94 G e t t i n g S t a rt ed w it h J av a
Ja v a V M s e c ur i t y
So far, weve seen how the Java verifier, the SecurityManager, and the class loader work to ensure the security of Java apps. In addition to these, there are other mechanisms not described in this chapter, such as those in the java.security package, which add to the security of Java apps. There is also a measure of security built into the Java language itself, but that is outside the scope of this chapter.
Ch a p t er 9 : A n in t r o du c t i on t o t h e J a v a V ir t u a l M ac h in e
95
96 G e t t i n g S t a rt ed w it h J av a
Chapter
10
Chapter 10
This chapter explains how to invoke native methods in Java applications using the Java Native Method Interface (JNI). It begins by explaining how the JNI works, then discusses the native keyword and how any Java method can become a native method. Finally, it examines the JDKs javah tool, which is used to generate C header files for Java classes. Even though Java code is designed to run on multiple platforms, there are certain situations where it may not be enough by itself. For example,
I
The standard Java class library doesnt support platform-dependent features needed by your application. You want to access an existing library from another language and make it accessible to your Java code. You have code you want to implement in a lower-level program like assembly, then have your Java application call it.
The Java Native Interface is a standard cross-platform programming interface included in the JDK. It enables you to write Java programs that can operate with applications and libraries written in other programming languages, such as C, C++, and assembly. Using JNI, you can write Java native methods to create, inspect, and update Java objects (including arrays and strings), call Java methods, catch and throw exceptions, load classes and obtain class information, and perform runtime type checking. In addition, you can use the Invocation API to embed the Java Virtual Machine into your native applications, then use the JNI interface pointer to access VM features. This allows you to make existing applications Java-enabled without having to link with the VM source code.
C h ap t e r 1 0: W o r k i n g w it h t he J a v a N a t i v e I n t e rf ac e ( J N I )
97
U s in g t h e n at iv e k e y wo r d
platform-independent, because every JVM implementation must still comply with certain standards needed to achieve platform independence (such as the standard structure of a .class file). The only problem with this scenario is that accessing native libraries from Java apps becomes difficult, since the runtime system differs across the various JVM implementations. For that reason, Sun came up with the JNI as a standard way for accessing native libraries from Java applications. The way native methods are accessed from Java applications changed in the JDK 1.1. The old way allowed a Java class to directly access methods in a native library. The new implementation uses the JNI as an intermediate layer between a Java class and a native library. Instead of having the JVM make direct calls to native methods, the JVM uses a pointer to the JNI to make the actual calls. This way, even if the JVM implementations are different, the layer they use to access the native methods (the JNI) is always the same.
98 G e t t i n g S t a rt ed w it h J av a
U s in g t he j av a h t o ol
className represents the name of the class (without the .class extension) for which you want to generate a C header file. You can specify more than one class at the command line. For each class, javah adds a .h file to the classs directory by default. To put the .h files in a different directory, use the -o option. If a class is in a package, you must specify the package along with the class name.
For example, to generate a header file for the class myClass in the package myPackage, do the following:
javah myPackage.myClass
The generated header file will include the package name, (myPackage_myClass.h). Below is a list of some of the javah options: Option Description
Creates a JNI header file Displays progress information Displays the version of javah Outputs the .h file in specified directory Overrides the default class path
The contents of the .h file generated by javah include all the function prototypes for the native methods in the class. The prototypes are modified to allow the Java runtime system to find and invoke the native methods. This modification basically involves changing the name of the method according to a naming convention established for native method invocation. The modified name includes the prefix Java_ to the class and method names. So, if you have a native method called nativeMethod in a class called myClass, the name that appears in the myClass.h file is Java_myClass_nativeMethod. For more information on JNI, see the following:
I I
Java Native Interface at http://java.sun.com/j2se/1.3/docs/guide/jni/ Java Native Interface Specification at http://java.sun.com/j2se/1.3/docs/guide/jni/ spec/jniTOC.doc.html The Java Tutorial, Trail: Java Native Interface at http://java.sun.com/docs/books/ tutorial/native1.1/index.html
The Java Native Interface: Programmers Guide and Specification (Java Series) by Sheng Liang amazon.com fatbrain.com
Essential Jni: Java Native Interface (Essential Java), by Rob Gordon amazon.com fatbrain.com
C h ap t e r 1 0: W o r k i n g w it h t he J a v a N a t i v e I n t e rf ac e ( J N I )
99
100 G e t t i ng S t a r t e d w it h J a v a
Appendix
A
Appendix A
Java 2 Platform
Standard Edition Enterprise Edition Micro Edition
Description
Contains classes that are the core of the Java language. Contains J2SE classes and additional classes for developing enterprise applications. Contains a subset of J2SE classes and is used in consumer electronic products.
A p pe n di x A : J a v a l an g ua g e qu i c k r ef er e n ce
101
J a v a k e y wo r d s
network programming and includes the fundamental packages of the Java language. Some of these J2SE packages are listed in the following table.
Table A.2
Package
Language Utilities I/O Text Math AWT Swing Javax Applet Beans Reflection SQL RMI Networking Security
java.lang java.util java.io java.text java.math java.awt javax.swing javax java.applet java.beans java.lang.reflect java.sql java.rmi java.net java.security
Java keywords
These tables cover the following types of keywords:
I I I I I I
Data and return types and terms Packages, classes, members, and interfaces Access modifiers Loops and flow controls Exception handling Reserved
Keyword
Use
16 bits, one character. 4 bytes, single-precision. 8 bytes, double-precision. 4 bytes, integer.
void
return
102 G e t t i ng S t a r t e d w it h J a v a
J a v a k e y w or d s
Keyword
Use
Makes all classes in the imported class or package visible to the current program. Instantiates a class. Checks an objects inheritance. This method or class must be extended to be used. In a class definition, implements a defined interface.
package
import
Access modifiers
Keyword Use
Class: accessible from anywhere. Subclass: accessible as long as its class is accessible. Access limited to members own class.
Keyword
Use
Access limited to members classs package.
public
protected
private
package
Default access level; dont use it explicitly. Cannot be subclassed by another package.
Keyword
Use
Selection statement. Selection statement. Fallback statement. Iteration statement. Iteration statement.
A p pe n di x A : J a v a l an g ua g e qu i c k r ef er e n ce
103
C o nv e r t i ng a n d c as t i n g da t a t y p e s
Exception handling
Keyword Use
Lists the exceptions a method could throw. Opening exception-handling statement. Runs its code before terminating the program.
Keyword
Use
Transfers control of the method to the exception handler. Captures the exception.
throw catch
Reserved
Keyword Use
Reserved for future use.
Keyword
Use
Reserved for future use.
goto
const
http://www.unicode.org/
This section contains tables of the following conversions:
I I I I I I
Primitive to primitive Primitive to String Primitive to reference String to primitive Reference to primitive Reference to reference
Primitive to primitive
Java doesnt support casting to or from boolean values. In order to work around Javas strict logical typing, you must assign an appropriate equivalent value to the variable and then convert that. 0 and 1 are often used to represent false and true values.
104 G e t t i ng S t a r t e d w it h J a v a
C o nv e r t in g a n d c a s t in g d a t a t y p e s
Syntax
From other primitive type p To boolean t:
Comments
Other primitive types include byte, short, char, int, long, double, float.
b = (byte) (t?1:0);
From boolean t To char c:
c = (char) (t?'1':'0');
From short, char, int, long, double, or float
n
To byte b:
b = (byte)n;
From byte b To short, int, long, double, or float n:
n = b;
From byte b To char c:
c = (char)b;
Primitive to String
Primitive data types are mutable; reference types are immutable objects. Casting to or from a reference type is risky. Java doesnt support casting to or from boolean values. In order to work around Javas strict logical typing, you must assign an appropriate equivalent value to the variable and then convert that. 0 and 1 are often used to represent false and true values. Syntax
From boolean t To String gg:
Comments
gg = t ? "true" : "false";
From byte b To String gg: The following may be substituted for toString, where appropriate:
gg = Integer.toString(b);
or
gg = String.valueOf(b);
gg = Integer.toString(b, 7);
A p pe n di x A : J a v a l an g ua g e qu i c k r ef er e n ce
105
C o nv e r t i ng a n d c as t i n g da t a t y p e s
Syntax
From short or int n To String gg:
Comments
The following may be substituted for toString, where appropriate:
gg = Integer.toString(n);
or
gg = String.valueOf(n);
gg = Integer.toString(n, 7);
From char c To String gg:
gg = String.valueOf(n);
gg = Integer.toString(n, 7);
From float f To String gg: These casts protect more data. Double precision: java.text.DecimalFormat df2 = new java.text.DecimalFormat("###,##0.00"); gg = df2.format(f); Scientific notation (protects exponents) (JDK 1.2.x and up): java.text.DecimalFormat de = new java.text.DecimalFormat("0.000000E00"); gg = de.format(f); These casts protect more data. Double precision:
gg = Float.toString(f);
or
gg = String.valueOf(f);
For decimal protection or scientific notation, see next column.
gg = Double.toString(d);
or
gg = String.valueOf(d);
For decimal protection or scientific notation, see next column.
Primitive to reference
Java provides classes that correspond to primitive data types and provide methods that facilitate conversions. Note that primitive data types are mutable; reference types are immutable objects. Casting to or from a reference type is risky. Java doesnt support casting to or from boolean values. In order to work around Javas strict logical typing, you must assign an appropriate equivalent value to the variable and then convert that. 0 and 1 are often used to represent false and true values.
106 G e t t i ng S t a r t e d w it h J a v a
C o nv e r t in g a n d c a s t in g d a t a t y p e s
Syntax
From boolean t To Boolean tt:
Comments
tt = new Boolean(t); From Primitive type p (other than boolean) To Boolean tt tt = new Boolean(p != 0);
For char, see next column.
From boolean t To Character cc: cc = new Character(t ? '1' : '0'); From byte b To Character cc:
double n
To Character cc:
cc = new Character((char)n);
From boolean t To Integer ii:
ii = new Integer(b);
Fromshort, char, or int n To Integer ii:
ii = new Integer(n);
From long, float, or double f To Integer ii:
ii = new Integer((int) f); From boolean t To Long nn: nn = new Long(t ? 1 : 0);
From byte b To Long nn:
nn = new Long(b); From short, char, int, or long s To Long nn: nn = new Long(s);
From float, double f To Long nn:
nn = new Long((long)f);
From boolean t To Float ff:
A p pe n di x A : J a v a l an g ua g e qu i c k r ef er e n ce
107
C o nv e r t i ng a n d c as t i n g da t a t y p e s
Syntax
From byte b To Float ff:
Comments
ff = new Float(b); From short, char, int, long, float, or double n To Float ff: ff = new Float(n);
From boolean t To Double dd:
dd = new Double(b); From short, char, int, long, float, or double n To Double dd: dd = new Double(n);
String to primitive
Note that primitive data types are mutable; reference types are immutable objects. Casting to or from a reference type is risky. Java doesnt support casting to or from boolean values. In order to work around Javas strict logical typing, you must assign an appropriate equivalent value to the variable and then convert that. The numbers 0 and 1, the strings true and false, or equally intuitive values are used here to represent true and false values. Syntax
From String gg To boolean t: t = new Boolean(gg.trim()).booleanValue(); From String gg To byte b: try { b = (byte)Integer.parseInt(gg.trim()); } catch (NumberFormatException e) { ... }
Comments
Caution: t will only be true when the value of gg is true (case insensitive); if the string is 1, yes, or any other affirmative, this conversion will return a false value. Note: If the value of gg is null, trim() will throw a NullPointerException. If you dont use trim(), make sure theres no trailing white space. For bases other than 10, such as 8: try { b = (byte)Integer.parseInt(gg.trim(), 7); } catch (NumberFormatException e) { ... } Note: If the value of gg is null, trim() will throw a NullPointerException. If you dont use trim(), make sure theres no trailing white space. For bases other than 10, such as 8: try { s = (short)Integer.parseInt(gg.trim(), 7); } catch (NumberFormatException e) { ... }
108 G e t t i ng S t a r t e d w it h J a v a
C o nv e r t in g a n d c a s t in g d a t a t y p e s
Syntax
From String gg To char c: try { c = (char)Integer.parseInt(gg.trim()); } catch (NumberFormatException e) { ... }
Comments
Note: If the value of gg is null, trim() will throw a NullPointerException. If you dont use trim(), make sure theres no trailing white space. For bases other than 10, such as 8: try { c = (char)Integer.parseInt(gg.trim(), 7); } catch (NumberFormatException e) { ... } Note: If the value of gg is null, trim() will throw a NullPointerException. If you dont use trim(), make sure theres no trailing white space. For bases other than 10, such as 8: try { i = Integer.parseInt(gg.trim(), 7); } catch (NumberFormatException e) { ... } Note: If the value of gg is null, trim() will throw a NullPointerException. If you dont use trim(), make sure theres no trailing white space.
From String gg To long n: try { n = Long.parseLong(gg.trim()); } catch (NumberFormatException e) { ... } From String gg To float f: try { f = Float.valueOf(gg.trim()).floatValue; } catch (NumberFormatException e) { ... }
Note: If the value of gg is null, trim() will throw a NullPointerException. If you dont use trim(), make sure theres no trailing white space. For JDK 1.2.x or better: try { f = Float.parseFloat(gg.trim()); } catch (NumberFormatException e) { ... } Note: If the value of gg is null, trim() will throw a NullPointerException. If you dont use trim(), make sure theres no trailing white space. For JDK 1.2.x or better: try { d = Double.parseDouble(gg.trim()); } catch (NumberFormatException e) { ... }
Reference to primitive
Java provides classes that correspond to the primitive data types. This table shows how to convert a variable from one of these classes to a primitive data type for a single operation. To convert from a reference type to a primitive, you must first get the value of the reference as a primitive, then cast the primitive. Primitive data types are mutable; reference types are immutable objects. Converting to or from a reference type is risky.
A p pe n di x A : J a v a l an g ua g e qu i c k r ef er e n ce
109
C o nv e r t i ng a n d c as t i n g da t a t y p e s
Java doesnt support casting to or from boolean values. In order to work around Javas strict logical typing, you must assign an appropriate equivalent value to the variable and then convert that. 0 and 1 are often used to represent false and true values. Syntax
From Boolean tt To boolean t:
Comments
t = tt.booleanValue();
From Boolean tt To byte b:
n = tt.booleanValue() ? 1 : 0);
From Character cc To boolean t:
t = cc.charValue() != 0;
From Character cc To byte b:
b = ii.byteValue();
From Integer, Long, Float, or Double nn To short s:
s = nn.shortValue();
From Integer, Long, Float, or Double nn To char c:
c = (char)nn.intValue();
From Integer, Long, Float, or Double nn To int i:
110 G e t t i ng S t a r t e d w it h J a v a
C o nv e r t in g a n d c a s t in g d a t a t y p e s
Syntax
From Long, Float, or Double dd To long n:
Comments
d = nn.doubleValue();
Reference to reference
Java provides classes that correspond to the primitive data types. This table shows how to convert a variable from one of these classes to another for a single operation.
Note
For legal class to class conversions apart from whats shown here, widening conversions are implicit. Narrowing casts use this syntax:
castToObjectName = (CastToObjectClass)castFromObjectName;
You must cast between classes that are in the same inheritance hierarchy. If you cast an object to an incompatible class, it will throw a ClassCastException. Reference types are immutable objects. Converting between reference types is risky. Syntax
From String gg To Boolean tt:
Comments
Note: If the value of gg is null, trim() will throw a NullPointerException. If you dont use trim(), make sure theres no trailing white space. Alternative:
tt = new Boolean(gg.trim());
tt = Boolean.valueOf(gg.trim());
From String gg To Character cc: cc = new Character(gg.charAt(<index>)); From String gg To Integer ii: Note: If the value of gg is null, trim() will throw a NullPointerException. If you dont use trim(), make sure theres no trailing white space. Alternative:
try { ii = Integer.valueOf(gg.trim()); } catch (NumberFormatException e) { ... } Note: If the value of gg is null, trim() will throw a NullPointerException. If you dont use trim(),
make sure theres no trailing white space. Alternative:
A p pe n di x A : J a v a l an g ua g e qu i c k r ef er e n ce
111
C o nv e r t i ng a n d c as t i n g da t a t y p e s
Syntax
From String gg To Float ff:
Comments
Note: If the value of gg is null, trim() will throw a NullPointerException. If you dont use trim(), make sure theres no trailing white space. Alternative:
try { ff = Float.valueOf(gg.trim()); } catch ... } Note: If the value of gg is null, trim() will throw a NullPointerException. If you dont use trim(),
make sure theres no trailing white space. Alternative:
From Boolean tt To Character cc: cc = new Character(tt.booleanValue() ?'1':'0'); From Boolean tt To Integer ii: ii = new Integer(tt.booleanValue() ? 1 : 0); From Boolean tt To Long nn: nn = new Long(tt.booleanValue() ? 1 : 0); From Boolean tt To Float ff: ff = new Float(tt.booleanValue() ? 1 : 0); From Boolean tt To Double dd:
dd = new Double(tt.booleanValue() ? 1 : 0);
From Character cc To Boolean tt: tt = new Boolean(cc.charValue() != '0'); From Character cc To Integer ii: ii = new Integer(cc.charValue()); From Character cc To Long nn: nn = new Long(cc.charValue()); From any class rr To String gg: gg = rr.toString();
112 G e t t i ng S t a r t e d w it h J a v a
C o nv e r t in g a n d c a s t in g d a t a t y p e s
Syntax
From Float ff To String gg: gg = ff.toString();
Comments
These variations protect more data. Double precision: java.text.DecimalFormat df2 = new java.text.DecimalFormat("###,##0.00"); gg = df2.format(ff.floatValue()); Scientific notation (JDK 1.2.x on up): java.text.DecimalFormat de = new java.text.DecimalFormat("0.000000E00"); gg = de.format(ff.floatValue());
These variations protect more data. Double precision: java.text.DecimalFormat df2 = new java.text.DecimalFormat("###,##0.00"); gg = df2.format(dd.doubleValue()); Scientific notation (JDK 1.2.x on up):
java.text.DecimalFormat de = new java.text.DecimalFormat("0.0000000000E00"); gg = de.format(dd.doubleValue());
From Integer ii To Boolean tt: tt = new Boolean(ii.intValue() != 0); From Integer ii To Character cc: cc = new Character((char)ii.intValue()); From Integer ii To Long nn: nn = new Long(ii.intValue()); From Integer ii To Float ff: ff = new Float(ii.intValue()); From Integer ii To Double dd: dd = new Double(ii.intValue()); From Long nn To Boolean tt: tt = new Boolean(nn.longValue() != 0); From Long nn To Character cc: cc = new Character((char)nn.intValue()); From Long nn To Integer ii: ii = new Integer(nn.intValue()); From Long nn To Float ff: ff = new Float(nn.longValue()); From Long nn To Double dd: dd = new Double(nn.longValue()); Note: Some Unicode values may be rendered as nonprintable characters. Consult
http://www.unicode.org/
A p pe n di x A : J a v a l an g ua g e qu i c k r ef er e n ce
113
E s c a p e s eq u e nc e s
Syntax
From Float ff To Boolean tt: tt = new Boolean(ff.floatValue() != 0); From Float ff To Character cc: cc = new Character((char)ff.intValue()); From Float ff To Integer ii: ii = new Integer(ff.intValue()); From Float ff To Long nn: nn = new Long(ff.longValue()); From Float ff To Double dd: dd = new Double(ff.floatValue()); From Double dd To Boolean tt: tt = new Boolean(dd.doubleValue() != 0); From Double dd To Character cc: cc = new Character((char)dd.intValue()); From Double dd To Integer ii: ii = new Integer(dd.intValue()); From Double dd To Long nn: nn = new Long(dd.longValue()); From Double dd To Float ff: ff = new Float(dd.floatValue());
Comments
http://www.unicode.org/
http://www.unicode.org/
Escape sequences
An octal character is represented by a sequence of three octal digits, and a Unicode character is represented by a sequence of four hexadecimal digits. Octal characters are preceded by the standard escape mark, \, and Unicode characters are preceded by \u. For example, the decimal number 57 is represented by the octal code \071 and the Unicode sequence \u0039. Octal code accepts 0, 1, 2, or 3 in the left-most position, and any number from 07 in the other two positions. Unicode sequences can represent numbers, letters, symbols, or nonprinting characters such as line breaks or tabs. For more information on Unicode, see http://www.unicode.org/ Character
Backslash Backspace Carriage return Double quote Form feed
Escape Sequence
\\ \b \r \" \f
114 G e t t i ng S t a r t e d w it h J a v a
O perat ors
Character
Horizontal tab New line Octal character Single quote Unicode character
Escape Sequence
Operators
This section lists the following:
I I I I I I I
Basic operators Arithmetic operators Logical operators Assignment operators Comparison operators Bitwise operators Ternary operator
The order in which operations in a compound statement are evaluated depends on associativity (left/right, parentheses) and precedence (hierarchy.) The rules of precedence are complicated. For a quick summary, see http://java.sun.com/docs/ books/tutorial/java/nutsandbolts/expressions.html.
Basic operators
Operator
.
Operand
object member data type String number number number boolean integer, boolean
Behavior
Accesses a member of the object. Casts a variable to a different data type.1 Joins up strings (concatenator). Adds. This is the unary2 minus (reverses number sign). Subtracts. This is the boolean NOT operator. This is both the bitwise (integer) and boolean AND operator. When doubled (&&), it is the boolean conditional AND. Assigns an element to another element (for instance, a value to a variable, or a class to an instance). This can be combined with other operators to perform the other operation and assign the resulting value. For instance, += adds the left-hand value to the right, then assigns the new value to the right-hand side of the expression.
(<type>) + ! & =
1. Its important to distinguish between an operator and a delimiter. Parentheses are used around args (for instance) as delimiters that mark the args in the statement. They are used around a data type as operators that change a variables data type to the one inside the parentheses. 2. A unary operator affects a single operand, a binary operator affects two operands, and a ternary operator affects three operands.
A p pe n di x A : J a v a l an g ua g e qu i c k r ef er e n ce
115
O pe r a t o r s
Arithmetic operators
Operator Assoc.
Right
Definition
Auto-increment/decrement: Adds one to, or subtracts one from, its single operand. Can be used before or after operand, depending on when you want the original value changed. Unary plus/minus: sets or changes the positive/negative value of a single number. Multiplication. Division. Modulus: Divides the first operand by the second operand and returns the remainder (not the result). Addition/subtraction
++/-+/* / % +/-
Logical operators
Operator Assoc.
Right
Definition
Boolean NOT (unary) Changes true to false or false to true. Because of its low precedence, you may need to use parentheses around this statement. Evaluation AND (binary) Yields true only if both operands are true. Always evaluates both operands. Evaluation XOR (binary) Yields true if only one operand is true. Evaluates both operands. Evaluation OR (binary) Yields true if one or both of the operands is true. Evaluates both operands. Conditional AND (binary) Yields true only if both operands are true. Called conditional because it only evaluates the second operand if the first operand is true. Conditional OR (binary) Yields true if either one or both operands is true; returns false if both are false. Doesnt evaluate second operand if first operand is true.
&
Left
Left
Left
&&
Left
||
Left
Assignment operators
Operator Assoc.
Right Right Right Right Right
Definition
Assign the value on the right to the variable on the left. Add the value on the right to the value of the variable on the left; assign the new value to the original variable. Subtract the value on the right from the value of the variable on the left; assign the new value to the original variable. Multiply the value on the right with the value of the variable on the left; assign the new value to the original variable. Divide the value on the right from the value of the variable on the left; assign the new value to the original variable.
= += -= *= /=
116 G e t t i ng S t a r t e d w it h J a v a
O perat ors
Comparison operators
Operator Assoc.
Left Left Left Left Left Left
Definition
Less than Greater than Less than or equal to Greater than or equal to Equal to Not equal to
Bitwise operators
Note
A signed integer is one whose left-most bit is used to indicate the integers positive or negative sign: the bit is 1 if the integer is negative, 0 if positive. In Java, integers are always signed, whereas in C/C++ they are signed only by default. In Java, the shift operators preserve the sign bit, so that the sign bit is duplicated, then shifted. For example, right shifting 10010011 by 1 is 11001001. Operator Assoc.
Right Left
Definition
Bitwise NOT Inverts each bit of the operand, so each 0 becomes 1 and vice versa. Signed left shift Shifts the bits of the left operand to the left, by the number of digits specified in the right operand, with 0s shifted in from the right. Highorder bits are lost. Signed right shift Shifts the bits of the left operand to the right, by the number of digits specified in the right operand. If the left operand is negative, 0s are shifted in from the left; if it is positive, 1s are shifted in. This preserves the original sign. Zero-fill right shift Shifts right, but always fills in with 0s. Bitwise AND Can be used with = to assign the value. Bitwise OR Can be used with = to assign the value. Bitwise XOR Can be used with = to assign the value. Left-shift with assignment Right-shift with assignment Zero-fill right shift with assignment
~ <<
>>
Left
Ternary operator
The ternary operator ?: performs a very simple if-then-else operation inside of a single statement. For example:
A p pe n di x A : J a v a l an g ua g e qu i c k r ef er e n ce
117
O pe r a t o r s
The Boolean condition, expression 1, is evaluated first. If it resolves true or if its resolution depends on the rest of the ternary statement, then expression 2 is evaluated. If expression 2 is false, expression 3 is used. For example:
118 G e t t i ng S t a r t e d w it h J a v a
Appendix
B
Appendix B
Resources on the Java language abound. The http://java.sun.com web site of Sun Microsystems is a good place to search for more information; youll find many interesting links. If youre new to Java, youll especially want to see Suns online Java tutorial at http://java.sun.com/docs/books/tutorial/.
Online glossaries
To quickly find definitions of Java terms, see one of Suns online glossaries:
I
Sun Microsystems Java Glossary in HTML: http://java.sun.com/docs/ glossary.nonjava.html#top Sun Microsystems Java Glossary in Java: http://java.sun.com/docs/glossary.html
Books
There are many excellent books about programming with Java. To see a list of Java titles on the Borland Developer Network, go to http://bdn.borland.com/books/java/ 0,1427,c|3,00.html. Sun also publishes a set of books called the Java Series. See the list of titles at http://java.sun.com/docs/books/. Youll find books for all levels of Java programming. Besides browsing through Java books at your favorite book store, you might also simply type Java books into your favorite web search engine to find lists of books that Java programmers recommend or that favorite publishers are offering.
A p p e nd ix B : L e ar n in g m o r e ab o ut J a va
119
120 G e t t i ng S t a r t e d w it h J a v a
Index
Symbols
. (dot) operator 60 ?: ternary operator 14 technical support 4 World Wide Web 4 break keyword 103 break statements 33 BufferedOutputStream class 55 bugs, reporting 5 byte keyword 102 bytecodes 91 translating into native instructions 95 violations 92
A
abstract classes 70 abstract keyword 103 access modifiers 28, 67 default 67 not specified 67 outside of a package 67 table of 103 within a package 67 AccessController class 93 accessing members 24 accessor methods 68 applet package 42 applications example for developing 61 arithmetic operators defined 14 table of 18, 116 using 18 arrays accessing 24 defined 9 indexing 24 representing strings 50 using 22 assert keyword 103 assignment operators defined 14 table of 19, 116 AWT package 41
C
C header files 98 calling methods 60 case keyword 103 casting 26 See also type conversions catch keyword 104 char keyword 102 character arrays 50 character literals 27 See also escape sequences checkPermission() 93 checkRead() 93 checkWrite() 93 child classes 64 class definitions 60 grouping 76 class files compilation 91 structure of 92 class inheritance 64 class keyword 103 class libraries 37 class loader 94 classes accessing members 67 defined 59 implementing interfaces 71 objects vs. 59 type wrapper 45 ClassLoader class 94 ClassNotFoundException exception 89 code comments 15 reusing 76 code blocks defined 16 static 98 comments 15 comparison operators defined 14 table of 20, 117 compilers just-in-time (JIT) 95 composite data types 8 arrays 9 Strings 9 conditional statements 33 if-else 33 switch 34
B
basic data types 8 basic operators table of 115 beans package 42 binary numbers reversing sign 21 bits shifting, signed and unsigned 21 bitwise operators 21 defined 14 table of 21, 117 bitwise shifts 21 boolean keyword 102 boolean operators defined 14 table of 19 Borland contacting 4 developer support 4 e-mail 5 newsgroups 4 online resources 4 reporting bugs 5
I n d ex
121
constructors 61 calling parent 66 multiple 66 superclasses 66 syntax 23 using 23 continue keyword 103 continue statements 33 control characters 27 See also escape sequences control statements 33 conversions primitive to primitive 104 primitive to String 105 primitives to reference types 106 reference to primitive 109 reference to reference 111 String to primitive 108 tables of 104 creating a thread 82 creating an object 23
escape sequences 27 table of 114 exception handling 35 defined 27 keywords, table of 104 exceptions 35 catch blocks 35 finally blocks 35 statements 35 throw keyword 36 throws keyword 35 try blocks 35 extends keyword 64, 103 external packages importing 77 Externalizable interface 90
F
File class 56 file classes 56 RandomAccessFile class 57 file input/output 56 FileInputStream class 52, 88 FileOutputStream class 55, 87 final keyword 103 finalizers 61 finally keyword 104 float keyword 102 flow control defined 27 using 31 flush() 87 fonts 2 JBuilder documentation conventions 2 for keyword 103 for loops using 32 freeing stream resources 88 functions 10 See also methods
D
daemon threads 79 data and return types table of 102 data members 60 accessing 67 data types arrays 9 composite 8 converting and casting 26 defined 8 numeric, table of 8 primitive 8, 45 reading 90 Strings 9 writing to streams 88 DataOutputStream class 55 declaring a variable 10 declaring classes 60 declaring packages 77 decrement/increment 18 default keyword 67, 103 defining classes 60 deserialization defined 85 example 88 deserializing objects 85 Developer Support 4 developing applications 61 do keyword 103 do loops using 32 documentation conventions 2 platform conventions 3 dot operator 60 double keyword 102
G
garbage collection 60, 61 role of JVM 92 getter methods 68 grouping threads 84
H
handling exceptions 35 See also exceptions header files 98
I
identifiers defined 7 if keyword 103 if-else statements using 33 implements keyword 71, 103 implicit type casting defined 30 import keyword 103
E
else keyword 103 Enterprise Edition (J2EE) 38 Enumeration interface 49
122 G e t t i ng S t a r t e d w it h J a v a
import statements 77 increment/decrement 18 inheritance 64 multiple 66 single 66 input stream classes 52 FileInputStream 52 InputStream 52 input streams 88 input/output (io) package 40 InputStream class 52 instance of keyword 103 instance variables 60 instantiating abstract classes 70 classes 60 defined 23, 59 int keyword 102 interface keyword 71, 103 Interface wizard 71 interfaces defined 71 Java Native Interface 97 replacing multiple inheritance 71
J
J2EE (Java 2 Enterprise Edition) 38 J2ME (Java 2 Micro Edition) 38 J2SE (Java 2 Standard Edition) 37, 101 Java defined 91 object-oriented language 59 Java 2 Enterprise Edition 38 Java 2 Micro Edition 38 Java 2 Standard Edition 37, 38, 101 Java bytecodes 91 Java class libraries 37 Java class loader 94 Java editions 37, 101 table of 37, 101 Java language glossaries 119 resources 119 Java Native Interface 97 See also JNI Java Runtime Environment 91 See also JRE Java security package 93 Java verifier 92 Java Virtual Machine 91 See also JVM java.applet package 42 java.awt package 41 java.beans package 42 java.io package 40 java.lang package 39 java.lang.reflect package 42 java.math package 40 java.net package 44 java.rmi package 43 java.security package 44 java.sql package 43 java.text package 40 java.util package 40
javah 98 options 99 javax packages 41 javax.swing package 41 JBuilder newsgroups 4 reporting bugs 5 JIT compilers (just-in-time) 95 JNI (Java Native Interface) JRE (Java Runtime Environment) relation to JVM 91 just-in-time compilers (JIT) 95 JVM (Java Virtual Machine) advantages 92 and JNI 97 class loader 94 definition 91 instructions 91 introduction 91 main roles 92 memory management 92 portability 92 relation to JRE 91 security 92 specification vs. implementation 92 verifier 92
K
keywords access modifiers 28, 103 data and return types 102 defined 13 exception handling 104 loops 103 packages, classes, members, interfaces 103 reserved 104 tables of 102
L
language package 39 Math class 46 Object class 44 String class 46 StringBuffer class 48 System class 49 type wrapper classes 45 libraries accessing native 97 Java class 37 static code blocks 98 literals defined 9 logical operators defined 14 table of 19, 116 long keyword 102 loop controls break statements 33 continue statements 33 loop statements defined 27 loops conditional statements 33 controlling execution 33
I n d ex
123
keywords, table of 103 terminating 31 loops, using 31 do 32 for 32 if-else 33 switch 34 while 31
M
Math class 46 math functions 46 math operators table of 18 using 18 math package 40 member access 24 member variables 60 memory allocation getting StringBuffer 48 memory management role of JVM 92 method calls 60, 98 methods 10 accessing 97 declaration 60 defined 60 implementation 60 main 30 overloading 66 overriding 71 static 30 using 22 Micro Edition (J2ME) 38 multiple inheritance 66 replaced by interfaces 71 multiple threads 79
ObjectInputStream class 85, 88 methods 90 object-oriented programming 59 example 61 ObjectOutputStream class 85, 87 methods 88 objects allocating memory for 60 classes vs. 59 deallocating memory for 60 defined 59 deserialization 85 referencing 90 serializing 85 operators access 24 arithmetic 18 arithmetic, table of 116 assignment, table of 19, 116 basic 115 bitwise 21 bitwise, table of 117 comparison, table of 20, 117 defined 14 logical or boolean 18 logical, table of 116 tables of 115 ternary 22, 117 using 17 output stream classes 54 BufferedOutputStream 55 DataOutputStream 55 FileOutputStream 55, 87 OutputStream 54 PrintStream 54 OutputStream class 54 overloading methods 66 overriding methods 71
N
narrowing type conversions 31 native code interface 97 See also JNI native keyword 98, 103 native machine instructions 95 negative binary numbers 21 networking package 44 new keyword 103 new operator 60 newsgroups 4 Borland and JBuilder 4 public 5 Usenet 5 nonprinting characters 27 See also escape sequences NotSerializableException exception 87 numeric data types, table of 8
P
package keyword 103 package statements 77 packages accessing class members 67 accessing members outside 67 declaring 77 defined 76 importing 77 Java, table of 38 parent classes 64 persistent objects 85 platform independence 97 pointers 97 polymorphism 71 example 72 portability of Java 92 pre- and post-increment/decrement 18 primitive data types 8 converting to other primitive types 104 converting to reference 106 converting to Strings 105 defined 45 PrintStream class 54
O
Object class 44 object references 60 object streams read/writes 90
124 G e t t i ng S t a r t e d w it h J a v a
private keyword 67, 103 protected keyword 67, 103 prototypes 99 public keyword 28, 67, 103
R
RandomAccessFile class 57 reading data types 90 reading object streams 90 readObject() 88, 90 reference data types converting to other reference 111 converting to primitive 109 referencing objects 60, 90 reflections package 42 reporting bugs 5 reserved keywords table of 104 resources freeing stream 88 restoring objects 85 return keyword 102 return statements 26 return types 26 RMI package 43 run() 79 Runnable interface implementing 80 runtime environment, Java 91 See also JRE
stopping a thread 83 storing objects to disk 85 stream resources freeing 88 streams 87, 88 input streams 52 output streams 54 partitioning as tokens 58 read/writes 90 StreamTokenizer class 58 strictfp keyword 102 String class 46 String data type converting to primitive 108 defined 9 StringBuffer class 48 strings 25 constructing 46 handling 25, 28 manipulating 25 subroutines 10 See also methods super keyword 66, 103 superclasses 66 Swing package 41 switch keyword 103 switch statements 34 synchronized keyword 103 synchronizing threads 84 System class 49
S
saving objects 85 scope defined 16 security applet vs. application 94 class loader 94 in the JVM 92 serialization and 90 security manager 93 security package 44, 93 security policy 93 SecurityManager class 93 Serializable interface 85, 86 serialization defined 85 reasons for 85 security and 90 serializing objects 85 setSecurityManager() 94 setter methods 68 setting thread priority 83 short keyword 102 single inheritance 66 source code reusing 76 SQL package 43 Standard Edition (J2SE) 37, 101 starting a thread 82 statements defined 16 static code blocks 98 static keyword 28, 103
T
ternary operator 22, 117 defined 14 test conditions, aborting 33 text package 40 this keyword 103 Thread class subclassing 79 Thread constructors 82 ThreadGroup class 84 threads 79 creating 82 customizing run() method 79 daemon threads 79 groups 84 implementing Runnable interface 80 lifecycle 79 making not runnable 82 multiple threads 79 priority 83 starting 82 stopping 83 synchronizing 84 time-slicing 83 throw keyword 104 throws keyword 104 time-slicing 83 tokens 58 transient keyword 103 transient objects 85 try keyword 104 type casting 26 See also type conversions
I n d ex
125
type conversions 26 implicit casting 30 narrowing explicit 31 tables of 104 widening conversions, table of 26 type wrapper classes 45 types reading 90 writing to streams 88
Vector class 50 verification of Java bytecodes 92 Virtual Machine, Java 91 See also JVM void keyword 28, 102 void return type defined 26
U
UnsatisfiedLineError exceptions 98 Usenet newsgroups 5 utility classes 40 utility package 40 Enumeration interface 49 Vector class 50
W
while keyword 103 while loops using 31 widening conversions table of 26 wrapper classes 45 writeObject() 87, 90 writing object streams 90 writing to file streams 87
V
values comparing 20 variable declarations 10 variables defined 9 instance 60 member 60 objects as 59
X
XML processing 43
126 G e t t i ng S t a r t e d w it h J a v a