Sams Teach Yourself Java 2 Platform in 21 Days with Cdrom


Sams Teach Yourself Java in 21 Days continues to be the most popular, best-selling Java tutorial on the market. It has been acclaimed for its clear and personable writing, for its extensive use of examples, and for its logical and complete organization. The Professional Reference Edition of the book includes an extra seven chapters covering advanced topics like object serialization, remote method invocation, accessibility, security, JavaBeans, JDBC and advanced data structures - as well as a 200-page reference ...
See more details below
Available through our Marketplace sellers.
Other sellers (Hardcover)
  • All (19) from $1.99   
  • New (3) from $27.99   
  • Used (16) from $1.99   
Sort by
Page 1 of 1
Showing All
Note: Marketplace items are not eligible for any coupons and promotions
Seller since 2008

Feedback rating:



New — never opened or used in original packaging.

Like New — packaging may have been opened. A "Like New" item is suitable to give as a gift.

Very Good — may have minor signs of wear on packaging but item works perfectly and has no damage.

Good — item is in good condition but packaging may have signs of shelf wear/aging or torn packaging. All specific defects should be noted in the Comments section associated with each item.

Acceptable — item is in working order but may show signs of wear such as scratches or torn packaging. All specific defects should be noted in the Comments section associated with each item.

Used — An item that has been opened and may show signs of wear. All specific defects should be noted in the Comments section associated with each item.

Refurbished — A used item that has been renewed or updated and verified to be in proper working condition. Not necessarily completed by the original manufacturer.


Ships from: fallbrook, CA

Usually ships in 1-2 business days

  • Standard, 48 States
  • Standard (AK, HI)
Seller since 2014

Feedback rating:


Condition: New
Brand New Item.

Ships from: Chatham, NJ

Usually ships in 1-2 business days

  • Canadian
  • International
  • Standard, 48 States
  • Standard (AK, HI)
  • Express, 48 States
  • Express (AK, HI)
Seller since 2014

Feedback rating:


Condition: New
Brand new.

Ships from: acton, MA

Usually ships in 1-2 business days

  • Standard, 48 States
  • Standard (AK, HI)
Page 1 of 1
Showing All
Sort by
Sending request ...


Sams Teach Yourself Java in 21 Days continues to be the most popular, best-selling Java tutorial on the market. It has been acclaimed for its clear and personable writing, for its extensive use of examples, and for its logical and complete organization. The Professional Reference Edition of the book includes an extra seven chapters covering advanced topics like object serialization, remote method invocation, accessibility, security, JavaBeans, JDBC and advanced data structures - as well as a 200-page reference section detailing the most commonly used aspects of the Java language.
Read More Show Less

Product Details

  • ISBN-13: 9780672314384
  • Publisher: Sams
  • Publication date: 1/21/1999
  • Series: Sams Teach Yourself Series
  • Edition description: BK&CD ROM
  • Edition number: 1
  • Pages: 1200
  • Product dimensions: 7.73 (w) x 9.44 (h) x 2.48 (d)

Table of Contents

Sams Teach Yourself Java 2 in 21 Days, Professional Reference Edition

- 3 -

The ABCs of Java

  • Introduction


    • What Java Is
    • Why Are You Here?
    • Diving into Java Programming
    • Summary
    • Q&A

    • Thinking in Terms of Objects
    • Objects and Classes
    • Attributes and Behavior
    • Organizing Classes and Class Behavior
    • Summary
    • Q&A

    • Statements and Expressions
    • Variables and Data Types
    • Comments
    • Literals
    • Expressions and Operators
    • String Arithmetic
    • Summary
    • Q&A

    • Creating New Objects
    • Accessing and Setting Class and Instance Variables
    • Calling Methods
    • References to Object s
    • Casting and Converting Objects and Primitive Types
    • Comparing Object Values and Classes
    • Inspecting Classes and Methods with Reflection
    • Summary
    • Q&A

    • Arrays
    • Block Statements
    • if Conditionals
    • switch Conditionals
    • for Loops
    • while and do Loops
    • Breaking Out of Loops
    • Labeled Loops
    • Summary
    • Q&A

    • Defining Classes
    • Creating Instance and Class Variables
    • Creating Methods
    • Creating Java Applications
    • Java Applications and Command-Line Arguments
    • Summary
    • Q&A

    • Creating Methods with the Same Name, Different Arguments
    • Constructor Methods
    • Overriding Methods
    • Overriding Constructors
    • Finalizer Methods
    • Summary
    • Q&A


    • How Applets and Applications Are Different
    • Applet Security Restrictions
    • Creating Applets
    • Including an Applet on a Web Page
    • More About the <APPLET> ; Tag
    • Java Archives
    • Passing Parameters to Applets
    • Applet Effects
    • Summary
    • Q&A

    • The Graphics Class
    • Drawing and Filling
    • Text and Fonts
    • Color
    • Advanced Graphics Operations Using Java2D
    • Summary
    • Q&A

    • Creating Animation in Java
    • Reducing Animation Flickering
    • Retrieving and Using Images
    • Creating Animation Using Images
    • An Example: Neko
    • Double-Buffering
    • Retrieving and Using Sounds
    • Summary
    • Q&A

    • The Abstract Windowing Toolkit
    • User-Interface Components
    • Summary
    • Q&A

    • Basic Interface Layout
    • Mixing Layout Managers
    • Advanced Interface Layout
    • Summary
    • Q&A

    • Event Handling
    • Handling Mouse Clicks
    • Handling Mouse Movements
    • Handling Key board Events
    • The Generic Event Handler
    • Handling Component Events
    • An Example: Background Color Switcher
    • Summary
    • Q&A

    • Windows, Frames, and Dialog Boxes
    • Menus
    • Creating Standalone AWT Applications
    • A Complete Example: RGB-to-HSB Converter
    • Summary
    • Q&A


    • Modifiers
    • Static Variables and Methods
    • Final Classes, Methods, and Variables
    • Abstract Classes and Methods
    • Packages
    • Using Packages
    • Creating Your Own Packages
    • Interfaces
    • The Problem of Single Inheritance
    • Creating and Extending Interfaces
    • Inner Classes
    • Summary
    • Q&A

    • Exceptions, the Old and Confusing Way
    • Java Exceptions
    • Managing Exceptions
    • Declaring Methods That Might Throw Exceptions
    • Creating and Throwing Your Own Exceptions
    • When and When Not to Use Exceptions
    • Summary
    • Q&A

    • Introduction to Streams
    • Byte Streams
    • Filtering a Stream
    • Character Streams
    • Files and Filename Filters
    • Summary
    • Q&A

    • Networking in Java
    • Trivia: A Simple Socket Client and Server
    • Applets and URL Objects
    • Summary
    • Q&A

    • The Benefits of Swing
    • Working with Swing
    • New Features of Swing
    • Summary
    • Q&A

    • The Main Event
    • Working with Methods
    • Summary
    • Q&A

    • Working with Swing
    • Swing User-Interface Improvements
    • A Swing Image Viewer Applet
    • Summary
    • Q&A


    • An Overview of the JDK
    • The java Interpreter
    • The javac Compiler
    • The appletviewer Browser
    • The javadoc Documentation Tool
    • The jdb Debugger
    • Using System Properties
    • Summary
    • Q&am p;A

    • Making Programs More Accessible
    • Using Accessibility Features
    • An Accessible Application: PageData
    • Summary
    • Q&A

    • Using Digital Signatures to Identify Applets
    • JDK Security Tools
    • Summary
    • Q&A

    • Object Serialization
    • Remote Method Invocation
    • Summary
    • Q&A

    • Data Structure Fundamentals
    • The Standard Java Data Structures
    • Building Your Own Data Structures
    • Summary
    • Q&A

    • Reusable Software Components
    • Development Tools
    • Working with JavaBeans
    • Summary
    • Q&A

    • Java Database Connectivity
    • Summary
    • Q&A


    • This Book's Web Site
    • Other Books to Consider
    • Sun's Java Site
    • Other Java Web Sites
    • Java Applet Rating Service
    • Java Newsgroups
    • Job Opportunities

    • Windows 95 and Windows NT Configuration

    • Choosing a Text Editor
    • Creating a File Association in Windows 95

    • Package java.applet
    • Package java.awt
    • Package java.awt.color
    • Package java.awt.datatransfer
    • Package java.awt.dnd
    • Package java.awt.event
    • Package java.awt.font
    • Package java.awt.geom
    • Package
    • Package java.awt.image
    • Package java.awt.image.renderable
    • Package java.awt.print
    • Package java.beans
    • Package java.beans.beancontext
    • Package
    • Package java.lang
    • Package java.lang.ref
    • Package java.lang.reflect
    • Package java.math
    • Package
    • Package java.rmi
    • Package java.rmi.activation
    • Package java.rmi.dgc
    • Package java.rmi.registry
    • Package java.rmi.server
    • Package
    • Package
    • Package
    • Package
    • Pack age
    • Package java.sql
    • Package java.text
    • Package java.util
    • Package java.util.jar
    • Package
    • Package javax.accessibility
    • Package javax.swing
    • Package javax.swing.border
    • Package javax.swing.colorchooser
    • Package javax.swing.event
    • Package javax.swing.filechooser
    • Package javax.swing.plaf
    • Package javax.swing.plaf.basic
    • Package javax.swing.plaf.metal
    • Package javax.swing.plaf.multi
    • Package javax.swing.table
    • Package javax.swing.text
    • Package javax.swing.text.html
    • Package javax.swing.tree
    • Package javax.swing.undo
    • Package org.omg.CORBA
    • Package org.omg.CORBA.DynAnyPackage
    • Package org.omg.CORBA.ORBPackage
    • Package org.omg.CORBA.TypeCodePackage
    • Package org.omg.CORBA.portable
    • Package org.omg.CosNaming
    • Package org.omg.CosNaming.NamingContextPackage

Read More Show Less

First Chapter

Sams Teach Yourself Java 2 in 21 Days, Professional Reference Edition - CH 3 - The ABCs of Java

[Figures are not included in this sample chapter]

Sams Teach Yourself Java 2 in 21 Days, Professional Reference Edition

- 3 -

The ABCs of Java

As you have learned, a Java program is made up of classes and objects, which inturn are made up of methods and variables. Methods are made up of statements andexpressions, which are made up of operators.

At this point, you might be afraid that Java is like the Russian nesting dollscalled Matryoshka. Every one of those dolls seems to have a smaller doll inside it,which is as intricate and detailed as its larger companion.

Relax, babushka--this chapter clears away the big dolls to reveal the smallestelements of Java programming. You'll leave classes, objects, and methods alone fora day and examine the basic things you can do in a single line of Java code.

The following subjects are covered:

  • Java statements and expressions

  • Variables and data types

  • Comments

  • Literals

  • Arithmetic

  • Comparisons

  • Logical operators

    NOTE: Because of Java's ties to C and C++, much of the material in this chapter will look familiar to programmers who are well-versed in those single-letter languages. When nec essary, technical notes such as this one describe specific differences between Java and other languages.

Statements and Expressions

All tasks that you want to accomplish in a Java program can be broken down intoa series of statements.

NEW TERM: A statement is a simple command written in a programminglanguage that causes something to happen.

Statements represent a single action that is taken in a Java program. All of thefollowing are simple Java statements:

int age = 31;import java.awt.dnd;System.out.println("You're not the boss of me!");player.score = 41367;

Some statements produce a value, such as when you add two numbers together ina program. These statements are called expressions.

NEW TERM: An expression is a statement that results in a value beingproduced. The value can be stored for later use in the program, used immediatelyin another statement, or disregarded. The value produced by a statement is calledits return value.

Some expressions produce a numerical return value, as in the example of addingtwo numbers together. Others produce a Boolean value--true or false--or can evenproduce a Java object. They are discussed later today.

Although many Java programs list one statement per line, this is a formattingdecision that does not determine where one statement ends and another one begins.Each statement in Java is terminated with a semicolon character (;). A programmercan put more than one statement on a line and it will compile successfully:

j.color = "lemon yellow"; j.hungry = false;

Statements in Java are groupe d using the opening curly brace ({) and closing curlybrace (}). A group of statements organized between these characters is called a blockor block statement, and you learn more about them during Day 5, "Lists,Logic, and Loops."

Variables and Data Types

In the Jabberwock application you created during Day 2, "A Taste of Object-OrientedProgramming," you used variables to keep track of information.

NEW TERM: Variables are a place where information can be storedwhile a program is running. The value can be changed at any point in the program--hencethe name.

In order to create a variable, you must give it a name and identify what typeof information it will store. You also can give a variable an initial value at thesame time you create it.

There are three kinds of variables in Java: instance variables, class variables,and local variables.

Instance variables, as you learned yesterday, are used to define an object'sattributes. Class variables define the attributes of an entire class of objects,and apply to all instances of it.

Local variables are used inside method definitions, or even smaller blocksof statements within a method. They only can be used while the method or block isbeing executed by the Java interpreter, and they cease to exist afterward.

Although all three kinds of variables are created in much the same way, classand instance variables are used in a different manner than local variables. You learnabout local variables today and cover instance and class variables during Day 4,"Object Lessons."

NOTE: Unlike other languages, Java does no t have global variables (variables that can be used in all parts of a program). Instance and class variables are used to communicate information from one object to another, and these replace the need for global variables.

Creating Variables

Before you can use a variable in a Java program, you must create the variableby declaring its name and the type of information it will store. The type of informationis listed first, followed by the name of the variable. The following are all examplesof variable declarations:

int highScore;String username;boolean gameOver;

NOTE: You learn about variable types later today, but you might be familiar with the types used in this example. The int type represents integers, boolean is used for true/false values, and String is a special variable type used to store text.

Local variables can be declared at any place inside a method, just like any otherJava statement, but they must be declared before they can be used. The normal placefor variable declarations is immediately after the statement that names and identifiesthe method.

In the following example, three variables are declared at the top of a program'smain() method:

public static void main (String arguments[] ) {    int total;    String reportTitle;    boolean active;}
If you are creating several variables of the same type, you can declare all of them in the same statement by separating the variable names with commas. The following statement creates three String variables named street, city, and s tate: 
String street, city, state;

Variables can be assigned a value when they are created by using an equal sign(=) followed by the value. The following statements create new variables and givethem initial values:

int zipcode = 90210;String name = "Brandon";boolean cheatedOnKelly = true;int age = 28, height = 70, weight = 140;

As the last statement indicates, you can assign values to multiple variables ofthe same type by using commas to separate them.

Local variables must be given values before they are used in a program, or theprogram won't compile successfully. For this reason, it is good practice to giveinitial values to all local variables.

Instance and class variable definitions are given an initial value depending onthe type of information they hold:

  • Numeric variables  0

  • Characters  '\0'

  • Booleans  false

  • Objects  null

Naming Variables

Variable names in Java must start with a letter, an underscore character (_),or a dollar sign ($). They cannot start with a number. After the first character,variable names can include any combination of letters or numbers.

NOTE: In addition, the Java language uses the Unicode character set, which includes the standard character set plus thousands of others to represent international alphabets. Accented characters and other symbols can be used in variable names as long as they have a Unicode character number.

When naming a variable and using it in a program, it's important to remember thatJ ava is case-sensitive--the capitalization of letters must be consistent. Becauseof this, a program can have a variable named X and another named x--and a rose isnot a Rose is not a ROSE.

In programs in this book and elsewhere, Java variables are given meaningful namesthat include several words joined together. To make it easier to spot the words,the following rule of thumb is used:

  • The first letter of the variable name is lowercase.

  • Each successive word in the variable name begins with a capital letter.

  • All other letters are lowercase.

The following variable declarations follow this rule of naming:

Button loadFile;int areaCode;boolean playerSetNewHighScore;

Variable Types

In addition to a name, a variable declaration must include the type of informationbeing stored. The type can be any of the following:

  • One of the basic data types

  • The name of a class or interface

  • An array

You learn how to declare and use array variables on Day 5. This lesson focuseson the other variable types.

Data Types

There are eight basic variable types for the storage of integers, floating-pointnumbers, characters, and Boolean values. These often are called primitive typesbecause they are built-in parts of the Java language rather than being objects, whichmakes them more efficient to use. These data types have the same size and characteristicsno matter what operating system and platform you're on, unlike some data types inother programming languages.

There are four data types that can be used to store integers. The one to use dependson the size of th e integer, as indicated in Table 3.1.


Type Size Values That Can Be Stored
byte 8 bits -128 to 127
short 16 bits -32,768 to 32,767
int 32 bits -2,147,483,648 to 2,147,483,647
long 64 bits -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

All of these types are signed, which means that they can hold either positiveor negative numbers. The type used for a variable depends on the range of valuesit might need to hold. None of these integer variables can reliably store a valuethat is too large or too small for its designated variable type, so you should takecare when designating the type.

NEW TERM: Another type of number that can be stored is a floating-pointnumber, which has the type float or double. Floating-point numbers representnumbers with a decimal part. The float type should be suffic ient for most uses, sinceit can handle any number from 1.4E-45 to 3.4E+38. If not, the double type can beused for more precise numbers ranging from 4.9E-324 to 1.7E+308.

The char type is used for individual characters such as letters, numbers, punctuation,and other symbols.

The last of the eight basic data types is boolean. As you have learned, Booleanvalues hold either true or false in Java.

All these variable types are listed in lowercase, and you must use them as suchin programs. There are classes with the same name as some of these data types butdifferent capitalization--for example, Boolean and Char. These have different functionalityin a Java program, so you can't use them interchangeably. You see how these specialclasses are used tomorrow.

Class Types

In addition to the eight basic data types, a variable can have a class as itstype, as in the following examples:

String lastName = "Walsh";Color hair;Jabberwock firstMonster;

When a variable has a class as its type, the variable refers to an object of thatclass or one of its subclasses.

The last of the examples in the preceding list, Jabberwock firstMonster; createsa variable named firstMonster that refers to a Jabberwock object.

Referring to a superclass as a variable type is useful when the variable mightbe one of several different subclasses. For example, consider a class hierarchy witha Fruit superclass and three subclasses: Apple, Pear, and Strawberry. If you createa Fruit variable called favoriteFruit, it could be used to refer to an Apple, Pear,or Strawberry object.

Declaring a variable of type Object means that it can hold any object.

NOTE: Java does not have anything comparable to the typedef statement from C and C++. To declare new types in Java, a new class is declared and variables can use that class as their type.

Assigning Values to Variables

Once a variable has been declared, a value can be assigned to it with the assignmentoperator--an equal sign (=). The following are examples of assignment statements:

idCode = 8675309;
snappyDresser = false;


One of the most important ways to improve the readability of your program is touse comments.

NEW TERM: Comments are information included in a program strictlyfor the benefit of humans trying to figure out what's going on in the program. TheJava compiler ignores comments entirely when preparing a runnable version of a Javasource file.

There are three different kinds of comments you can use in Java programs, andyou can use each of them at your discretion.

The first way to add a comment to a program is to precede it with two slash characters(//). Everything from the slashes to the end of the line is considered a comment,as in the following statement:

int creditHours = 3; // set up credit hours for course

In this example, everything from the // to the end of the line is a comment andis disregarded by a Java compiler.

If you need to make a comment that takes up more than one line, you can beginit with the text /* and end it with the text */. Everything between these two delimitersis considered a comment, as in the following:

/* This program was written late at night under theinfluence of expired antihistamine medicine andgeneric supermarket soda. I offer no warrantiesexpress nor implied that it works for any usefulpurpose whatsoever. */

The final type of comment is meant to be computer-readable as well as human-readable.If you begin a comment with the text /** (instead of /*) and end it with */, thecomment is interpreted to be official documentation on how the class and its publicmethods work.

This kind of comment then can be read by utilities such as the javadoc tool includedwith the JDK. The javadoc program uses official comments to create a set of Web pagesthat document the program, its class hierarchy and methods.

All of the official documentation on Java's class library comes from javadoc-stylecomments. You can view Java 2 documentation on the Web at the following page:


In addition to variables, you will also use a literal in a Java statement.

NEW TERM: Literals are any numbers, text, or other information thatdirectly represent a value.

Literal is a programming term that essentially means that what you type is whatyou get. The following assignment statement uses a literal:

int year = 1998;

The literal is 1998, because it directly represents the integer value 1998. Numbers,characters, and strings all are examples of literals.

Although the meaning and usage of literals will seem intuitive most of the time,Java has some special types of literals that represent different kinds of numbers,characters, strings, and Boolean values.

Number Literals

Java has several integer literals. The number 4, for example, is an integer literalof the int variable type. It also can be assigned to byte and short variables becausethe number is small enough to fit into those integer types. An integer literal largerthan an int can hold is automatically considered to be of the type long. You alsocan indicate that a literal should be a long integer by adding the letter L (L orl) to the number. For example, the following statement stores the value 4 to a longinteger:

long pennyTotal = 4L;

To represent a negative number as a literal, prepend a minus sign (-) to the literal,as in -45.

NOTE: Octal and hexadecimal numbering systems are convenient for many advanced programming uses, but unlikely to be needed by beginners. Octal numbers are a base-8 numbering system, which means they can only represent the values 0 through 7 as a single digit. The eighth number in octal is 10 (or 010 as a Java literal).
Hexadecimal is a base-16 numbering system, and it can represent 16 numbers as a single digit. The letters A through F represent the last six digits, so the first 16 numbers are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
The octal and hexadecimal systems are better suited for certain tasks in programming than the normal decimal system is. If you have ever used HTML to set a Web page's background color, you have used hexadecimal numbers.

If you need to use a literal integer with octal numbering, prepend a 0 to thenumber. For example, the octal number 777 would be the literal 0777. Hexadecimalintegers are used as literals by prepending the number with 0x, as in 0x12 or 0xFF.

Floating-point literals use a period character (.) for the decimal point, as youwould expect. The following statement uses a literal to set up a double variable:

double myGPA = 2.25;

All floating-point literals are considered the double variable type instead offloat. To specify a literal of float, add the letter F (F or f) to the literal, asin the following example:

float piValue = 3.1415927F;

You can use exponents in floating-point literals by using the letter e or E followedby the exponent, which can be a negative number. The following statements use exponentialnotation:

double x = 12e22;double y = 19E-95; 

Boolean Literals

The Boolean values true and false also are literals. These are the only two valuesyou can use when assigning a value to a boolean variable type or using a Booleanin a statement in other ways.

If you have used other languages such as C, you might expect that a value of 1is equivalent to true and 0 is equivalent to false. This isn't the case in Java--youmust use the values true or false to represent Boolean values. The following statementsets a boolean variable:

boolean toThineOwnSelf = true;

Note that the literal true does not have quotation marks around it. If it did,the Java compiler would assume that it was a string of characters.

Character Literals

Character literals are expressed by a single character surrounded by single quotationmarks, such as `a', `#', and `3'. You might be familiar with the ASCII characterset, which includes 128 characters including letters, numerals, punctuation, andother characters useful i n computing. Java supports thousands of additional charactersthrough the 16-bit Unicode standard.

Some character literals represent characters that are not readily printable oraccessible through a keyboard. Table 3.2 lists the special codes that can representthese special characters as well as characters from the Unicode character set. Theletter d in the octal, hex, and Unicode escape codes represents a number ora hexadecimal digit (a-f or A-F).


Escape Meaning
\n New line
\t Tab
\b Backspace
\r Carriage return
\f Formfeed
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\d Octal
\xd Hexadecimal
\ud Unicode character

NOTE: C and C++ programmers should note that Java does not include character codes for \a (bell) or \v (vertical tab).

String Literals

The final literal that you can use in a Java program represents strings of characters.A string in Java is an object rather than being a basic data type, and strings arenot stored in arrays as they are in languages such as C.

Because string objects are real objects in Java, methods are available to combinestrings, modify strings, and determine whether two strings have the same value.

String literals consist of a series of characters inside double quotation marks,as in the following statements:

String coAuthor = "Laura Lemay, killer of trees";String password = "swordfish";

Strings can include the character escape codes listed in Table 3.2 previously,as shown here:

String example = "Socrates asked, \"Hemlock is poison?\"";System.out.println("Bob Kemp\nOne on One Sports\n2 a.m. to 6 a.m.&q uot;);String title = "Sams Teach Yourself Java in a 3-Day Weekend\u2122"

In the last example here, the Unicode code sequence \u2122 produces a °/oosymbol on systems that have been configured to support Unicode.

CAUTION: Most users in English-speaking countries aren't likely to see Unicode characters when they run Java programs. Although Java supports the transmission of Unicode characters, the user's system also must support it for the characters to be displayed. Unicode support provides a way to encode its characters for systems that support the standard. Although Java 1.02 only supported the Latin subset of Unicode, Java 1.1 and 2 support the display of any Unicode character that can be represented by a host font.
For more information about Unicode, visit the Unicode Consortium Web site at

Although string literals are used in a manner similar to other literals in a program,they are handled differently behind the scenes.

When a string literal is used, Java stores that value as a String object. Youdon't have to explicitly create a new object, as you must do when working with otherobjects, so they are as easy to work with as basic data types. Strings are unusualin this respect--none of the basic types is stored as an object when used. You learnmore about strings and the String class today and tomorrow.

Expressions and Operators

An expression is a statement that produces a value. Some of the most commonexpressions are mathematical, such as in the following source code example:

int x = 3;int y = 4;int z = x * y;

The last statement in this example is an expression. The multiplication operator* is used to multiply the x and y integers, and the expression produces the resultof the multiplication. This result is stored in the z integer.

The value produced by an expression is called a return value, as you have learned.This value can be assigned to a variable and used in many other ways in your Javaprograms.

Most of the expressions in Java use operators like *.

NEW TERM: Operators are special symbols used for mathematical functions,some types of assignment statements, and logical comparisons.


There are five operators used to accomplish basic arithmetic in Java. These areshown in Table 3.3.


Operator Meaning Example
+ Addition 3 + 4
- Subtraction 5 - 7
* Multiplication 5 * 5
/ Division 14 / 7
% Modulus 20 % 7

Each operator takes two operands, one on either side of the operator. The subtractionoperator also can be used to negate a single operand--which is equivalent to multiplyingthat operand by -1.

One thing to be mindful of when using division is the kind of numbers you're dealingwith. If you store a division operation into an integer, the result will be roundedoff to a whole number because the int data type can't handle floating-point numbers.As an example, the expression 31 / 9 results in 3 if stored as an integer.

Modulus division, which uses the % operator, produces the remainder of a divisionoperation. Using 31 % 9 results in 4 because 31 divided by 9 leaves a remainder of4.

Note that most arithmetic operations involving integers produce an int regardlessof the original type of the operands. If you're working with other numbers, suchas floating-point numbers or long integers, you should make sure that the operandshave the same type you're trying to end up with.

Listing 3.1 is an example of simple arithmetic in Java.


 1: class AmoebaMath { 2:     public static void main (String arguments[]) { 3:         int x = 6; 4:         short y = 4; 5:         float a = .12f; 6: 7:         System.out.println("You start with " + x + " pet amoebas."); 8:         Sys tem.out.println("\tTwo get married and their spouses move              in."); 9:         x = x + 2;10:         System.out.println("You now have " + x);11:12:         System.out.println("\tMitosis occurs, doubling the number of             amoebas.");13:         x = x * 2;14:         System.out.println("You now have " + x);15:16:         System.out.println("\tThere's a fight. " + y + " amoebas move             out.");17:         x = x - y;18:         System.out.println("You now have " + x);19:20:         System.out.println("\tParamecia attack! You lose one-third of              the colony.");21:         x = x - (x / 3);22:         System.out.println("You end up with " + x + " pet amoebas.");23:         System.out.println("Daily upkeep cost per amoeba: $" + a);24:         System.out.println("Total daily cost: $" + (a * x));25:     }26: } 
If you run this Java application, it produces the following output:
You start with 6 pet amoebas.    Two get married and their spouses move in.You now have 8    Mitosis occurs, doubling the number of amoebas.You now have 16    There's a fight. 4 amoebas move out.You now have 12    Paramecia attack! You lose one-third of the colony.You end up with 8 pet amoebas.Daily upkeep cost per amoeba: $0.12Total daily cost: $0.96

In this simple Java application, three variables are created with initial valuesin lines 3-5: the integer x, the short integer y, and the floating-point number a.Because the default type for floating-point numbers is double, an f is appended tothe literal .12 to indicate tha t it is of type float.

The rest of the program uses arithmetic operators to track the population of anamoeba colony. (No amoebas were harmed during the making of this chapter.)

This program also makes use of System.out.println() in several statements. TheSystem.out.println() method is used in an application to display strings and otherinformation to the standard output device, which usually is the screen.

System.out.println() takes a single argument within its parentheses: a string.In order to present more than one variable or literal as the argument to println(),you can use the + operator to combine these elements into a single string.

You learn more about this use of the + operator later today.

More About Assignment

Assigning a value to a variable is an expression, because it produces a value.Because of this feature, you can string assignment statements together the followingway:

x = y = z = 7;

In this statement, all three variables end up with the value of 7.

The right side of an assignment expression always is calculated before the assignmenttakes place. This makes it possible to use an expression statement as in the followingcode example:

int x = 5;x = x + 2;

In the expression x = x + 2, the first thing that happens is that x + 2 is calculated.The result of this calculation, 7, is then assigned to x.

Using an expression to change a variable's value is an extremely common task inprogramming. There are several operators used strictly in these cases.

Table 3.4 shows these assignment operators and the expressions they are functionallyequivalent to.


Expression Meaning
x += y x = x + y
x -= y x = x - y
x *= y x = x * y
x /= y x = x / y

CAUTION: These shorthand assignment operators are functionally equivalent to the longer assignment statements for which they substitute. However, if either side of your assignment statement is part of a complex expression, there are cases where the operators are not equivalent. For example, if x equals 20 and y equals 5, the following two statements do not produce the same value:

x = x / y + 5;x /= y + 5;

When in doubt, simplify an expression using multiple assignment statements and don't use the shorthand operators.

Incrementing and Decrementing

Another common task is to add or subtract 1 from an integer variable. There arespecial operators for these expressions, which are called increment and decrementoperations.

NEW TERM: Incrementi ng a variable means to add 1 to its value, anddecrementing a variable means to subtract 1 from its value.

The increment operator is ++ and the decrement operator is --. These operatorsare placed immediately after or immediately before a variable name, as in the followingcode example:

int x = 7;x = x++;

In this example, the statement x = x++ increments the x variable from 7 to 8.

These increment and decrement operators can be placed before or after a variablename, and this affects the value of expressions that involve these operators.

NEW TERM: Increment and decrement operators are called prefix operatorsif listed before a variable name, and postfix operators if listed after aname.

In a simple expression such as standards--;, using a prefix or postfix operator doesn't change the result. When increment and decrement operations are part of a larger expression, however, the choice between prefix and postfix operators is important.

Consider the following two expressions:

int x, y, z;x = 42;y = x++;z = ++x;

These two expressions yield very different results because of the difference betweenprefix and postfix operations. When you use postfix operators as in y = x++, y receivesthe value of x before it is incremented by 1. When using prefix operators as in z= ++x, x is incremented by 1 before the value is assigned to z. The end result ofthis example is that y equals 42, z equals 44, and x equals 44.

If you're still having some trouble figuring this out, here's the example againwith comments describing each step:

int x, y, z; // x, y, and z are all declaredx = 42;      // x is given the value of 42y = x++;     // y is given x's value (42) before it is incremented             // and x is then incremented to 43z = ++x;     // x is incremented to 44, and z is given x's value

CAUTION: As with shorthand operators, increment and decrement operators can produce results you might not have expected when used in extremely complex expressions. The concept of "assigning x to y before x is incremented" isn't precisely right, because Java evaluates everything on the right side of an expression before assigning its value to the left side. Java stores some values before handling an expression in order to make postfix work the way it has been described in this section. When you're not getting the results you expect from a complex expression that includes prefix and postfix operators, try to break the expression into multiple statements to simplify it.


Java has several operators that are used when making comparisons between variables,variables and literals, or other types of information in a program.

These operators are used in expressions that return Boolean values of true orfalse, depending on whether the comparison being made is true or not. Table 3.5 showsthe comparison operators.


Operator Meaning Example
== Equal x == 3
!= Not equal x != 3
< Less than x < 3
> Greater than x > 3
<= Less than or equal to x <= 3
>= Greater than or equal to x >= 3

The following example shows a comparison operator in use:

boolean hip;int age = 31;hip = age < 25;

The expression age < 25 produces a result of either true or false, dependingon the value of the integer age. Because age is 31 in this example (which is notless than 25), hip is given the boolean value false.

Logical Operators

Expressions that result in Boolean values such as comparison operations can becombined to form more complex expressions. This is handled through logical opera tors.These operators are used for the logical combinations AND, OR, XOR, and logical NOT.

For AND combinations, the & or && logical operators are used. Whentwo Boolean expressions are linked by the & or && operators, the combinedexpression returns a true value only if both Boolean expressions are true.

Consider this example, taken directly from the film Harold & Maude:

boolean unusual = (age < 21) & (girlfriendAge > 78);

This expression combines two comparison expressions: age < 21 and girlfriendAge> 78. If both of these expressions are true, the value true is assigned to thevariable unusual. In any other circumstance, the value false is assigned to unusual.

The difference between & and && lies in how much work Java does onthe combined expression. If & is used, the expressions on either side of the& are evaluated no matter what. If && is used and the left side of the&& is false, the expression on the right side of the && never isevaluated.

For OR combinations, the | or || logical operators are used. These combined expressionsreturn a true value if either Boolean expression is true.

Consider this Harold & Maude-inspired example:

boolean unusual = (grimThoughts > 10) || (girlfriendAge > 78);

This expression combines two comparison expressions: grimThoughts > 10 andgirlfriendAge > 78. If either of these expressions is true, the value true isassigned to the variable unusual. Only if both of these expressions is false willthe value false be assigned to unusual.

Note the use of || instead of |. Because of this usage, if grimThoughts > 10is true, unusual is set to true and the second expression never is evaluated.

The XOR combination has one logical operator, ^. This results in a true valueonly if both Boolean expressions it combines have opposite values. If both are trueor both are false, the ^ operator produces a false value.

The NOT combination uses the ! logical operator followed by a single expression.It reverses the value of a Boolean expression the same way that a minus symbol reversesthe positive or negative sign on a number.

For example, if age < 30 returns a true value, !(age < 30) returns a falsevalue.

These logical operators can seem completely illogical when encountered for thefirst time. You get plenty of chances to work with them in subsequent chapters, especiallyon Day 5.

Operator Precedence

When more than one operator is used in an expression, Java has an establishedprecedence to determine the order in which operators are evaluated. In many cases,this precedence determines the overall value of the expression.

For example, consider the following expression:

y = 6 + 4 / 2;

The y variable receives the value 5 or the value 8, depending on which arithmeticoperation is handled first. If the 6 + 4 expression comes first, y has the valueof 5. Otherwise, y equals 8.

In general, the order from first to last is the following:

  • Increment and decrement operations

  • Arithmetic operations

  • Comparisons

  • Logical operations

  • Assignment expressions

If two operations have the same precedence, the one on the left in the actuale xpression is handled before the one on the right. Table 3.7 shows the specific precedenceof the various operators in Java. Operators farther up the table are evaluated first.


Operator Notes
. [] () Parentheses (()) are used to group expressions; period (.) is used for access to methods and variables within objects and classes (discussed tomorrow); square brackets ([]) are used for arrays. (This operator is discussed later in the week.)
++ -- ! ~ instanceof The instanceof operator returns true or false based on whether the object is an instance of the named class or any of that class's subclasses (discussed tomorrow).
new (type)expression The new operator is used for creating new instances of classes; () in this case is for casting a value to another type. (You learn about both of these tomorrow.)
* / % Multiplication, division, modulus.
+ - Addition, subtraction.
<< >> >>> Bitwise left and right shift.
< > <= >= Relational comparison tests.
== != Equality.
| OR
&& Logical AND
|| Logical OR
? : Shorthand for if...then...else (discussed on Day 5).
= += -= *= /= %= ^= Various assignments.
&= |= <<= >>= >>>= More assignments.

Returning to the expression y = 6 + 4 / 2, Table 3.7 shows that division is evaluatedbefore addition, so the value of y will be 8.

To change the order in which expressions are evaluated, place parentheses aroundthe expressions that should be evaluated first. You can nest one set of parenthesesinside another to make sure that expressions evaluate in the desired order--the innermostparenthetic expression is evaluated first.

The following expression results in a value of 5:

y = (6 + 4) / 2

The value of 5 is the result because 6 + 4 is calculated before the result, 10,is divided by 2.

Parentheses also can be useful to improve the readability of an expression. Ifthe precedence of an expression isn't immediately clear to you, adding parenthesesto impose the desired precedence can make the statement easier to understand.

String Arithmetic

As stated earlier today, the + operator has a double life outside the world ofmathematics. It can be used to concatenate two or more strings.

NEW TERM: Concatenate means to link two things together. For reasonsunknown, it is the verb of choice when describing the act of combining two strings--winningout over paste, glue, affix, combine, link, and conjoin.

In several examples, you have seen statements that look something like this:

String firstName = "Raymond";System.out.println("Everybody loves " + firstName);

These two lines result in the following text being displayed:

Everybody loves Raymond

The + operator combines strings, other objects, and variables to form a singlestring. In the preceding example, the literal Everybody loves is concatenated tothe value of the String object firstName.

Working with the concatenation operator is easier in Java because of the way itcan handle any variable type and obje ct value as if it were a string. If any partof a concatenation operation is a String or String literal, all elements of the operationwill be treated as if they were strings:

System.out.println(4 + " score and " + 7 + " years ago.");

This produces the output text 4 score and 7 years ago., as if the integer literals4 and 7 were strings.

There also is a shorthand += operator to add something to the end of a string.For example, consider the following expression:

myName += " Jr.";

This expression is equivalent to the following:

myName = myName + " Jr.";

In this example, it changes the value of myName (which might be something likeEfrem Zimbalist) by adding Jr. at the end (Efrem Zimbalist Jr.).


Anyone who pops open a set of Matryoska dolls has to be a bit disappointed toreach the smallest doll in the group. Ideally, advances in microengineering shouldenable Russian artisans to create ever-smaller and smaller dolls, until someone reachesthe subatomic threshold and is declared the winner.

You have reached Java's smallest nesting doll today, but it shouldn't be a letdown.Using statements and expressions enables you to begin building effective methods,which make effective objects and classes possible.

Today you learned about creating variables and assigning values to them; usingliterals to represent numeric, character, and string values; and working with operators.Tomorrow you put these skills to use as you develop objects for Java programs.

To summarize today's material, Table 3.8 lists the operators you learned about.Be a doll and look them over carefully.


Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal
!= Not equal
&& Logical AND
|| Logical OR
! Logical NOT
| OR
= Assignment
++ Increment
-- Decrement
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
%= Modulus and assign


Q What happens if you assign an integer value to a variable that is too large for that variable to hold?
Logically, you might think that the variable is converted to the next larger type, but this isn't what happens. Instead, an overflow occurs--a situation in which the number wraps around from one size extreme to the other. An example overflow would be a byte variable that goes from 127 (acceptable value) to 128 (unacceptable). It would wrap around to the lowest acceptable value, which is -128, and start counting upward from there. Overflow isn't something you can readily deal with in a program, so you should be sure to give your variables plenty of living space in their chosen data type.

Q Why does Java have all these shorthand operators for arithmetic and assignment? It's really hard to read that way.
Java's syntax is based on C++, which is based on C (more Russian nesting doll behavior). C is an expert language that values programming power over readability, and the shorthand operators are one of the legacies of that design priority. Using them in a program isn't required because effective substitutes a re available, so you can avoid them in your own programming if you prefer.

Read More Show Less

Customer Reviews

Be the first to write a review
( 0 )
Rating Distribution

5 Star


4 Star


3 Star


2 Star


1 Star


Your Rating:

Your Name: Create a Pen Name or

Barnes & Review Rules

Our reader reviews allow you to share your comments on titles you liked, or didn't, with others. By submitting an online review, you are representing to Barnes & that all information contained in your review is original and accurate in all respects, and that the submission of such content by you and the posting of such content by Barnes & does not and will not violate the rights of any third party. Please follow the rules below to help ensure that your review can be posted.

Reviews by Our Customers Under the Age of 13

We highly value and respect everyone's opinion concerning the titles we offer. However, we cannot allow persons under the age of 13 to have accounts at or to post customer reviews. Please see our Terms of Use for more details.

What to exclude from your review:

Please do not write about reviews, commentary, or information posted on the product page. If you see any errors in the information on the product page, please send us an email.

Reviews should not contain any of the following:

  • - HTML tags, profanity, obscenities, vulgarities, or comments that defame anyone
  • - Time-sensitive information such as tour dates, signings, lectures, etc.
  • - Single-word reviews. Other people will read your review to discover why you liked or didn't like the title. Be descriptive.
  • - Comments focusing on the author or that may ruin the ending for others
  • - Phone numbers, addresses, URLs
  • - Pricing and availability information or alternative ordering information
  • - Advertisements or commercial solicitation


  • - By submitting a review, you grant to Barnes & and its sublicensees the royalty-free, perpetual, irrevocable right and license to use the review in accordance with the Barnes & Terms of Use.
  • - Barnes & reserves the right not to post any review -- particularly those that do not follow the terms and conditions of these Rules. Barnes & also reserves the right to remove any review at any time without notice.
  • - See Terms of Use for other conditions and disclaimers.
Search for Products You'd Like to Recommend

Recommend other products that relate to your review. Just search for them below and share!

Create a Pen Name

Your Pen Name is your unique identity on It will appear on the reviews you write and other website activities. Your Pen Name cannot be edited, changed or deleted once submitted.

Your Pen Name can be any combination of alphanumeric characters (plus - and _), and must be at least two characters long.

Continue Anonymously

    If you find inappropriate content, please report it to Barnes & Noble
    Why is this product inappropriate?
    Comments (optional)