74
Chapter 1 Getting Started Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Chapter 1 Getting Started Copyright © 2008 Pearson Addison-Wesley. All rights reserved

  • View
    221

  • Download
    2

Embed Size (px)

Citation preview

Chapter 1

Getting Started

Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Introduction To JavaIntroduction To Java

Most are familiar with Java as a language Most are familiar with Java as a language for Internet applicationsfor Internet applications

We will study Java as a general purpose We will study Java as a general purpose programming languageprogramming language The syntax of expressions and assignments The syntax of expressions and assignments

will be similar to that of other high-level will be similar to that of other high-level languageslanguages

Details concerning the handling of strings and Details concerning the handling of strings and console output will probably be newconsole output will probably be new

1-2Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Origins of the Java LanguageOrigins of the Java Language

Created by Sun Microsystems team led by Created by Sun Microsystems team led by James Gosling (1991)James Gosling (1991)

Originally designed for programming home Originally designed for programming home appliancesappliances Difficult task because appliances are controlled by a Difficult task because appliances are controlled by a

wide variety of computer processorswide variety of computer processors Team developed a two-step translation process to Team developed a two-step translation process to

simplify the task of compiler writing for each class of simplify the task of compiler writing for each class of appliancesappliances

1-3Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Origins of the Java LanguageOrigins of the Java Language

Significance of Java translation processSignificance of Java translation process Writing a compiler (translation program) for each type Writing a compiler (translation program) for each type

of appliance processor would have been very costlyof appliance processor would have been very costly

Instead, developed intermediate language that is the Instead, developed intermediate language that is the same for all types of processors : Java same for all types of processors : Java byte-codebyte-code

Therefore, only a small, easy to write program was Therefore, only a small, easy to write program was needed to translate byte-code into the machine code needed to translate byte-code into the machine code for each processorfor each processor

1-4Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Origins of the Java LanguageOrigins of the Java Language Patrick Naughton & Jonathan Payne at Sun Patrick Naughton & Jonathan Payne at Sun

Microsystems developed a Web browser that Microsystems developed a Web browser that could run programs over the Internet (1994)could run programs over the Internet (1994) Beginning of Java's connection to the InternetBeginning of Java's connection to the Internet Original browser evolves into Original browser evolves into HotJavaHotJava

Netscape Inc. made its Web browser capable of Netscape Inc. made its Web browser capable of running Java programs in 1995running Java programs in 1995 Other companies follow suitOther companies follow suit

1-5Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Objects and MethodsObjects and Methods

Java is an Java is an object-oriented programming object-oriented programming (OOP)(OOP) language language A Programming methodology that views a A Programming methodology that views a

program as consisting of program as consisting of objectsobjects that interact that interact with one another by means of actions with one another by means of actions • (called (called methodsmethods))

Objects of the same kind are said to have the Objects of the same kind are said to have the same same typetype or be in the same or be in the same classclass

Hmmm…Where have you heard this before?Hmmm…Where have you heard this before?

1-6Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Terminology ComparisonsTerminology Comparisons

Other high-level languages have Other high-level languages have constructs called procedures, methods, constructs called procedures, methods, functions, and/or subprogramsfunctions, and/or subprograms These are called These are called methodsmethods in Java in Java

All programming constructs in Java, including All programming constructs in Java, including methodsmethods, are part of a , are part of a classclass

1-7Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Java Application ProgramsJava Application Programs

There are two types of Java programs: There are two types of Java programs: applicationsapplications and and appletsapplets

A Java A Java application program application program or "regular" Java or "regular" Java program is a class with a method named program is a class with a method named main

When a Java program is run, the When a Java program is run, the run-time systemrun-time system automatically invokes the method named automatically invokes the method named mainmain

All Java application programs start with the All Java application programs start with the mainmain methodmethod

1-8Copyright © 2008 Pearson Addison-Wesley. All rights reserved

AppletsApplets

A Java A Java appletapplet ( (little Java applicationlittle Java application) is a Java ) is a Java program that is meant to be run from a Web program that is meant to be run from a Web browserbrowser Can be run from a location on the InternetCan be run from a location on the Internet Can also be run with an applet viewer program for Can also be run with an applet viewer program for

debuggingdebugging Applets always use a windowing interfaceApplets always use a windowing interface

In contrast, application programs may use a In contrast, application programs may use a windowing interface or console (i.e., text) I/Owindowing interface or console (i.e., text) I/O

1-9Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Sample Java Application ProgramSample Java Application Program

1-10Copyright © 2008 Pearson Addison-Wesley. All rights reserved

System.out.printlnSystem.out.println

Java programs work by having things Java programs work by having things called called objectsobjects perform actions perform actions System.outSystem.out: an object used for sending : an object used for sending

output to the screenoutput to the screen The actions performed by an object are The actions performed by an object are

called called methodsmethods printlnprintln: the method or action that the : the method or action that the System.outSystem.out object performs object performs

1-11Copyright © 2008 Pearson Addison-Wesley. All rights reserved

System.out.printlnSystem.out.println

InvokingInvoking or or callingcalling a method: When an object a method: When an object performs an action using a methodperforms an action using a method Also called Also called sending a messagesending a message to the object to the object Method invocation syntax (in order): an objectMethod invocation syntax (in order): an object,, a dot a dot

(period), the method name, and a pair of parentheses(period), the method name, and a pair of parentheses ArgumentsArguments: : Zero or more pieces of information Zero or more pieces of information

needed by the method that are placed inside the needed by the method that are placed inside the parenthesesparentheses

System.out.println("This is an argument");

1-12Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Variable declarations Variable declarations

Variable declarations in Java are similar to Variable declarations in Java are similar to those in other programming languagesthose in other programming languages Simply give the type of the variable followed Simply give the type of the variable followed

by its name and a semicolonby its name and a semicolon

int answer;int answer;

1-13Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Using Using == and and ++

In Java, the equal sign (In Java, the equal sign (==) is used as the ) is used as the assignment operatorassignment operator The variable on the left side of the assignment The variable on the left side of the assignment

operator is operator is assigned the valueassigned the value of the expression on of the expression on the right side of the assignment operatorthe right side of the assignment operator

answer = 2 + 2;answer = 2 + 2; In Java, the plus sign (In Java, the plus sign (++) can be used to denote ) can be used to denote

addition or addition or concatenationconcatenation Using Using ++,, two strings can be concatenated, or two strings can be concatenated, or

connected, togetherconnected, togetherSystem.out.println("2 plus 2 is " + answer);

1-14Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Computer Language LevelsComputer Language Levels High-level languageHigh-level language: A language that people can read, : A language that people can read,

write, and understandwrite, and understand A program written in a high-level language must be translated into a A program written in a high-level language must be translated into a

language that can be understood by a computer before it can be runlanguage that can be understood by a computer before it can be run

Machine languageMachine language: A language that computers understand: A language that computers understand

Low-level languageLow-level language: Machine language or any language : Machine language or any language similar to machine language similar to machine language

CompilerCompiler: A program that translates a high-level language : A program that translates a high-level language program into an equivalent low-level language programprogram into an equivalent low-level language program

This translation process is called This translation process is called compilingcompiling

1-15Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Byte-Code and the Java Virtual MachineByte-Code and the Java Virtual Machine

The compilers for most programming languages The compilers for most programming languages translate high-level programs directly into the machine translate high-level programs directly into the machine language for a particular computerlanguage for a particular computer

Since different computers have different machine languages, a Since different computers have different machine languages, a different compiler is needed for each onedifferent compiler is needed for each one

In contrast, the Java compiler translates Java programs In contrast, the Java compiler translates Java programs into into byte-codebyte-code, a machine language for a fictitious , a machine language for a fictitious computer called the computer called the Java Virtual Machine (JVM)Java Virtual Machine (JVM)

Once compiled to Once compiled to byte-codebyte-code, a Java program can be used on , a Java program can be used on any computer, making it very portableany computer, making it very portable

1-16Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Byte-Code and the Java Virtual MachineByte-Code and the Java Virtual Machine

Interpreter:Interpreter: The program that translates a The program that translates a program written in Java byte-code into the program written in Java byte-code into the machine language for a particular computer machine language for a particular computer when a Java program is executedwhen a Java program is executed

The interpreter translates and immediately executes The interpreter translates and immediately executes each byte-code instruction, one after anothereach byte-code instruction, one after another

Translating byte-code into machine code is relatively Translating byte-code into machine code is relatively easy compared to the initial compilation step easy compared to the initial compilation step

1-17Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Program terminologyProgram terminology CodeCode:: A program or a part of a program A program or a part of a program

Source codeSource code (or (or source programsource program): A program ): A program written in a high-level language such as Javawritten in a high-level language such as Java The input to the compiler programThe input to the compiler program

Object codeObject code: The translated low-level program: The translated low-level program The output from the compiler program, e.g., Java The output from the compiler program, e.g., Java

byte-codebyte-code In the case of Java byte-code, the input to the Java In the case of Java byte-code, the input to the Java

byte-code interpreter byte-code interpreter

1-18Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Class LoaderClass Loader

Java programs are divided into smaller parts Java programs are divided into smaller parts called called classesclasses Each class definition is normally in a separate file and Each class definition is normally in a separate file and

compiled separatelycompiled separately

Class LoaderClass Loader: A program that connects the : A program that connects the byte-code of the classes needed to run a Java byte-code of the classes needed to run a Java programprogram In other programming languages, the corresponding In other programming languages, the corresponding

program is called a program is called a linkerlinker

1-19Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Compiling a Java Program or Compiling a Java Program or ClassClass

Each class definition must be in a file whose name is the Each class definition must be in a file whose name is the same as the class name followed by same as the class name followed by ..javajava

The class The class FirstProgramFirstProgram must be in a file named must be in a file named FirstProgram.javaFirstProgram.java

Are you confused? Let’s Look at the code….Are you confused? Let’s Look at the code…. Each class is compiled with the command Each class is compiled with the command javacjavac

followed by the name of the file in which the class followed by the name of the file in which the class residesresides

javac FirstProgram.javajavac FirstProgram.java The result is a byte-code program whose filename is the same The result is a byte-code program whose filename is the same

as the class name followed by as the class name followed by ..classclass FirstProgram.classFirstProgram.class

1-20Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Running a Java ProgramRunning a Java Program A Java program can be given the A Java program can be given the runrun command command

((javajava) after all its classes have been compiled) after all its classes have been compiled Only run the class that contains the Only run the class that contains the mainmain method (the method (the

system will automatically load and run the other system will automatically load and run the other classes, if any)classes, if any)

The The mainmain method begins with the line: method begins with the line:public static void main(String[ ] args)public static void main(String[ ] args) Follow the run command by the name of the class Follow the run command by the name of the class

only (only (no no .java.java or or ..classclass extension extension))

For example:For example:java FirstProgramjava FirstProgram

1-21Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Syntax and SemanticsSyntax and Semantics

SyntaxSyntax: The arrangement of words and : The arrangement of words and punctuations that are legal in a language, punctuations that are legal in a language, the the grammar rulesgrammar rules of a language of a language

SemanticsSemantics: The meaning of things written : The meaning of things written while following the syntax rules of a while following the syntax rules of a languagelanguage

1-22Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Tip: Error MessagesTip: Error Messages

BugBug: A mistake in a program: A mistake in a program The process of eliminating bugs is called The process of eliminating bugs is called

debuggingdebugging Syntax errorSyntax error: : A grammatical mistake in a A grammatical mistake in a

programprogram The compiler can detect these errors, and will The compiler can detect these errors, and will

output an error message saying what it thinks output an error message saying what it thinks the error is, and where it thinks the error isthe error is, and where it thinks the error is

Note: This may not be where the actual error Note: This may not be where the actual error is!is!

1-23Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Tip: Error MessagesTip: Error Messages Run-time errorRun-time error: : An error that is not detected An error that is not detected

until a program is rununtil a program is run The compiler cannot detect these errors: an error The compiler cannot detect these errors: an error

message is not generated after compilation, but after message is not generated after compilation, but after executionexecution

Logic error:Logic error: A mistake in the underlying A mistake in the underlying algorithm for a programalgorithm for a program The compiler cannot detect these errors, and no error The compiler cannot detect these errors, and no error

message is generated after compilation or execution, message is generated after compilation or execution, but the program does not do what it is supposed to dobut the program does not do what it is supposed to do

These are the most difficult to debug!These are the most difficult to debug!

1-24Copyright © 2008 Pearson Addison-Wesley. All rights reserved

IdentifiersIdentifiers

IdentifierIdentifier:: The name of a variable or other item The name of a variable or other item (class, method, object, etc.) defined in a (class, method, object, etc.) defined in a programprogram A Java identifier must start with an alpha character, A Java identifier must start with an alpha character,

and all the characters must be letters, digits, or the and all the characters must be letters, digits, or the underscore symbolunderscore symbol

Java identifiers can theoretically be of any lengthJava identifiers can theoretically be of any length But the longer you make the name, the better the But the longer you make the name, the better the

chances of you having a typing error…..So keep the chances of you having a typing error…..So keep the names of reasonable lengthnames of reasonable length

Java is a case-sensitive language: Java is a case-sensitive language: RateRate, , raterate, and , and RATERATE are the names of 3 different variables are the names of 3 different variables

1-25Copyright © 2008 Pearson Addison-Wesley. All rights reserved

IdentifiersIdentifiers Keywords and Reserved words: Identifiers that Keywords and Reserved words: Identifiers that

have a predefined meaning in Javahave a predefined meaning in Java Do not use them to name anything elseDo not use them to name anything else

public class void staticpublic class void static Predefined identifiers: Identifiers that are Predefined identifiers: Identifiers that are

defined in libraries required by the Java defined in libraries required by the Java language standardlanguage standard

Although they can be redefined, this could be Although they can be redefined, this could be confusing and dangerous if doing so would change confusing and dangerous if doing so would change their standard meaningtheir standard meaning

System String printlnSystem String println

1-26Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Naming ConventionsNaming Conventions Start the names of variables, classes, methods, Start the names of variables, classes, methods,

and objects with a and objects with a lowercaselowercase letter. Use letter. Use uppercase to indicate "word" boundaries, and uppercase to indicate "word" boundaries, and restrict the remaining characters to digits and restrict the remaining characters to digits and lowercase letters.lowercase letters.

What do I mean? For example:What do I mean? For example:topSpeedtopSpeed bankRate1bankRate1 timeOfArrivaltimeOfArrival

Start the Start the names of classesnames of classes with an with an uppercase uppercase letter and, otherwise, adhere to the rules aboveletter and, otherwise, adhere to the rules above

FirstProgramFirstProgram MyClass StringMyClass String

1-27Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Variable DeclarationsVariable Declarations Every variable in a Java program must be Every variable in a Java program must be declareddeclared

before it is usedbefore it is used

A variable declaration tells the compiler what kind of data type A variable declaration tells the compiler what kind of data type will be storedwill be stored

The type of the variable is followed by 1 or more variable names The type of the variable is followed by 1 or more variable names separated by commas, and terminated with a semicolon (;)separated by commas, and terminated with a semicolon (;)

Variables are typically declared at the start of a block (indicated Variables are typically declared at the start of a block (indicated by an opening brace by an opening brace {{ ) )

Basic types in Java are called Basic types in Java are called primitiveprimitive types typesint numberOfBeans;int numberOfBeans;double oneWeight, totalWeight;double oneWeight, totalWeight;

1-28Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Primitive TypesPrimitive Types

1-29Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Assignment Statements With Primitive Assignment Statements With Primitive TypesTypes

In Java, the assignment statement is used In Java, the assignment statement is used to change the value of a variableto change the value of a variable The equal sign (The equal sign (==) is used as the assignment ) is used as the assignment

operatoroperator An assignment statement consists of a variable An assignment statement consists of a variable

on the left side of the operator, and an on the left side of the operator, and an expressionexpression on the right side of the operator on the right side of the operator

Variable = Expression;Variable = Expression; An An expressionexpression consists of a variable, number, or consists of a variable, number, or

mix of variables, numbers, operators, and/or mix of variables, numbers, operators, and/or method invocationsmethod invocations

temperature = 98.6;temperature = 98.6; count = numberOfBeans;count = numberOfBeans;

1-30Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Assignment Statements With Primitive Assignment Statements With Primitive TypesTypes

When an assignment statement is executed, the When an assignment statement is executed, the expression is first evaluated, and then the variable on expression is first evaluated, and then the variable on the left-hand side of the equal sign is set equal to the the left-hand side of the equal sign is set equal to the value of the expressionvalue of the expression

distance = rate * time;distance = rate * time; Note: a variable can occur on both sides of the Note: a variable can occur on both sides of the

assignment operatorassignment operatorcount = count + 2;count = count + 2;

What happens with this statement?What happens with this statement?

The assignment operator is automatically executed The assignment operator is automatically executed from right-to-left, so assignment statements can be from right-to-left, so assignment statements can be chainedchained

number2 = number1 = 3;number2 = number1 = 3;1-31Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Tip: Initialize VariablesTip: Initialize Variables

A variable that has been declared but that has A variable that has been declared but that has not yet been given a value by some means is not yet been given a value by some means is said to be said to be uninitializeduninitialized

In certain cases an uninitialized variable is given In certain cases an uninitialized variable is given a default valuea default value It is best It is best NOT NOT to rely on thisto rely on this Your program can produce unpredictable resultsYour program can produce unpredictable results Explicitly initialized variables have the added benefit Explicitly initialized variables have the added benefit

of improving program clarity AND behaving properly of improving program clarity AND behaving properly with correct values.with correct values.

1-32Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Tip: Initialize VariablesTip: Initialize Variables

The declaration of a variable can be combined The declaration of a variable can be combined with its initialization via an assignment statementwith its initialization via an assignment statement

int count = 0;int count = 0;double distance = 55 * .5;double distance = 55 * .5;char grade = 'A';char grade = 'A';

Note: some variables can be initialized and others can Note: some variables can be initialized and others can remain uninitialized in the same declarationremain uninitialized in the same declaration

int initialCount = 50, finalCount;int initialCount = 50, finalCount;

1-33Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Shorthand Assignment Shorthand Assignment StatementsStatements

Shorthand assignment notation combines the Shorthand assignment notation combines the assignment operatorassignment operator ( (==) and an ) and an arithmeticarithmetic operator operator

It is used to change the value of a variable by adding, It is used to change the value of a variable by adding, subtracting, multiplying, or dividing by a specified valuesubtracting, multiplying, or dividing by a specified value

The general form isThe general form isVariable Op Variable Op == Expression Expression

which is equivalent to which is equivalent to Variable Variable == Variable Op (Expression) Variable Op (Expression)

The The ExpressionExpression can be another variable, a constant, or a can be another variable, a constant, or a more complicated expressionmore complicated expression

Some examples of what Some examples of what OpOp can be are can be are ++, , --, , **, , //,, or or %%

1-34Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Shorthand Assignment Statements

Example: Equivalent To:

count += 2; count = count + 2;

sum -= discount; sum = sum – discount;

bonus *= 2; bonus = bonus * 2;

time /=

rushFactor;

time =

time / rushFactor;

change %= 100; change = change % 100;

amount *=

count1 + count2;

amount = amount * (count1 + count2);

1-35Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Assignment CompatibilityAssignment Compatibility

In general, the value of one type cannot be In general, the value of one type cannot be stored in a variable of another typestored in a variable of another type

int intVariable = 2.99; //Illegalint intVariable = 2.99; //Illegal The above example results in a type mismatch The above example results in a type mismatch

because a because a doubledouble value cannot be stored in an value cannot be stored in an intint variablevariable

However, there are exceptions to thisHowever, there are exceptions to thisdouble doubleVariable = 2;double doubleVariable = 2;

For example, an For example, an intint value can be stored in a value can be stored in a doubledouble type type

1-36Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Assignment CompatibilityAssignment Compatibility More generally, a value of any type in the following list More generally, a value of any type in the following list

can be assigned to a variable of any type that appears to can be assigned to a variable of any type that appears to the right of itthe right of itbytebyteshortshortintintlonglongfloatfloatdoubledoublecharchar Note that as your move down the list from left to right, the range Note that as your move down the list from left to right, the range

of allowed values for the types becomes largerof allowed values for the types becomes larger An explicit An explicit type cast type cast is required to assign a value of one is required to assign a value of one

type to a variable whose type appears to the left of it on type to a variable whose type appears to the left of it on the above list (e.g., the above list (e.g., doubledouble to to intint))

Note that in Java an Note that in Java an intint cannot be assigned to a cannot be assigned to a variable of type variable of type booleanboolean, nor can a , nor can a booleanboolean be be assigned to a variable of type assigned to a variable of type intint

1-37Copyright © 2008 Pearson Addison-Wesley. All rights reserved

ConstantsConstants ConstantConstant (or (or literalliteral): An item in Java which has ): An item in Java which has

one specific value that cannot changeone specific value that cannot change Constants of an integer type may not be written with a Constants of an integer type may not be written with a

decimal point (e.g., decimal point (e.g., 1010)) Constants of a floating-point type can be written in Constants of a floating-point type can be written in

ordinary decimal fraction form (e.g., ordinary decimal fraction form (e.g., 367000.0367000.0 or or 0.0005890.000589) )

Constant of a floating-point type can also be written in Constant of a floating-point type can also be written in scientific scientific (or (or floating-pointfloating-point) ) notation notation (e.g., (e.g., 3.67e53.67e5 or or 5.89e-45.89e-4))

• Note that the number before the Note that the number before the ee may contain a decimal may contain a decimal point, but the number after the point, but the number after the ee may not may not

1-38Copyright © 2008 Pearson Addison-Wesley. All rights reserved

ConstantsConstants Constants of type Constants of type charchar are expressed by are expressed by

placing a single character in single quotes (e.g., placing a single character in single quotes (e.g., ''ZZ''))

Constants for strings of characters are enclosed Constants for strings of characters are enclosed by double quotes (e.g., by double quotes (e.g., ""WelcomeWelcome to Java"to Java"))

There are only two There are only two booleanboolean type constants, type constants, truetrue and and falsefalse Note that they must be spelled with all Note that they must be spelled with all lowercase

lettersletters

1-39Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Arithmetic Operators and ExpressionsArithmetic Operators and Expressions

As in most languages, As in most languages, expressionsexpressions can be can be formed in Java using variables, constants, formed in Java using variables, constants, and arithmetic operatorsand arithmetic operators These operators are These operators are ++ (addition), (addition), --

(subtraction), (subtraction), ** (multiplication), (multiplication), // (division), (division), and and %% (modulo, remainder) (modulo, remainder)

An expression can be used anyplace it is An expression can be used anyplace it is legal to use a value of the type produced by legal to use a value of the type produced by the expressionthe expression

1-40Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Arithmetic Operators and ExpressionsArithmetic Operators and Expressions

If an arithmetic operator is combined with If an arithmetic operator is combined with intint operands, then the resulting type is operands, then the resulting type is intint

If an arithmetic operator is combined with one or two If an arithmetic operator is combined with one or two doubledouble operands, then the resulting type is operands, then the resulting type is doubledouble

If different types are combined in an expression, then the If different types are combined in an expression, then the resulting type is the right-most type on the following list resulting type is the right-most type on the following list that is found within the expressionthat is found within the expressionbytebyteshortshortintintlonglongfloatfloatdoubledoublecharchar Exception: If the type produced should be Exception: If the type produced should be bytebyte or or shortshort

(according to the rules above), then the type produced will (according to the rules above), then the type produced will actually be an actually be an intint

1-41Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Parentheses and Precedence Parentheses and Precedence RulesRules

An expression can be An expression can be fully parenthesizedfully parenthesized in in order to specify exactly what subexpressions are order to specify exactly what subexpressions are combined with each operatorcombined with each operator

If some or all of the parentheses in an If some or all of the parentheses in an expression are omitted, Java will follow expression are omitted, Java will follow precedenceprecedence rules to determine, in effect, where rules to determine, in effect, where to place themto place them However, it's best (and sometimes necessary) to However, it's best (and sometimes necessary) to

include theminclude them

1-42Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Precedence RulesPrecedence Rules

1-43Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Precedence and Associativity Precedence and Associativity RulesRules

When the order of two adjacent operations must When the order of two adjacent operations must be determined, the operation of higher be determined, the operation of higher precedence (and its apparent arguments) is precedence (and its apparent arguments) is grouped before the operation of lower grouped before the operation of lower precedenceprecedence

base + rate * hoursbase + rate * hours is evaluated as is evaluated asbase + (rate * hours)base + (rate * hours)

When two operations have equal precedence, When two operations have equal precedence, the order of operations is determined by the order of operations is determined by associativityassociativity rules rules

1-44Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Precedence and Associativity Precedence and Associativity RulesRules

Unary operators of equal precedence are grouped Unary operators of equal precedence are grouped right-to-leftright-to-left+-+rate+-+rate is evaluated as is evaluated as +(-(+rate))+(-(+rate))

Binary operators of equal precedence are grouped Binary operators of equal precedence are grouped left-to-rightleft-to-rightbase + rate + hoursbase + rate + hours is evaluated asis evaluated as

(base + rate) + hours(base + rate) + hours Exception: A string of assignment operators is Exception: A string of assignment operators is

grouped right-to-leftgrouped right-to-leftn1 = n2 = n3;n1 = n2 = n3; is evaluated asis evaluated as n1 = (n2 = n3);n1 = (n2 = n3);

1-45Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Pitfall: Round-Off Errors in Floating-Point Pitfall: Round-Off Errors in Floating-Point NumbersNumbers

Floating point numbers are only approximate Floating point numbers are only approximate quantitiesquantities Mathematically, the floating-point number 1.0/3.0 is Mathematically, the floating-point number 1.0/3.0 is

equal to 0.3333333 . . .equal to 0.3333333 . . . A computer has a finite amount of storage spaceA computer has a finite amount of storage space

• It may store 1.0/3.0 as something like 0.3333333333, which It may store 1.0/3.0 as something like 0.3333333333, which is slightly smaller than one-thirdis slightly smaller than one-third

Computers actually store numbers in binary notation, Computers actually store numbers in binary notation, but the consequences are the same: floating-point but the consequences are the same: floating-point numbers may lose accuracynumbers may lose accuracy

1-46Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Integer and Floating-Point Integer and Floating-Point DivisionDivision

When one or both operands are a floating-point type, When one or both operands are a floating-point type, division results in a floating-point typedivision results in a floating-point type15.0/215.0/2 evaluates toevaluates to 7.57.5

When both operands are integer types, division results in When both operands are integer types, division results in an integer typean integer type

Any fractional part is discarded Any fractional part is discarded The number is not roundedThe number is not rounded

15/215/2 evaluates toevaluates to 77 Be careful to make at least one of the operands a Be careful to make at least one of the operands a

floating-point type if the fractional portion is neededfloating-point type if the fractional portion is needed

1-47Copyright © 2008 Pearson Addison-Wesley. All rights reserved

The The %% Operator Operator

The The %% operator is used with operands of type operator is used with operands of type intint to recover the information lost after to recover the information lost after performing integer divisionperforming integer division15/215/2 evaluates to the quotientevaluates to the quotient 77

15%215%2 evaluates to the remainderevaluates to the remainder 11 The The %% operator can be used to count by 2's, 3's, operator can be used to count by 2's, 3's,

or any other numberor any other number To count by twos, perform the operation To count by twos, perform the operation numbernumber % 2% 2, ,

and when the result is and when the result is 00, , numbernumber is even is even

1-48Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Type CastingType Casting A A type casttype cast takes a value of one type and produces a takes a value of one type and produces a

value of another type with an "equivalent" valuevalue of another type with an "equivalent" value If If nn and and mm are integers to be divided, and the fractional portion of are integers to be divided, and the fractional portion of

the result must be preserved, at least one of the two must be the result must be preserved, at least one of the two must be type cast to a floating-point type type cast to a floating-point type beforebefore the division operation is the division operation is performedperformeddouble ans = n / (double)m;double ans = n / (double)m;

Note that the desired type is placed inside parentheses Note that the desired type is placed inside parentheses immediately in front of the variable to be castimmediately in front of the variable to be cast

Note also that the type and value of the variable to be cast does Note also that the type and value of the variable to be cast does not changenot change

1-49Copyright © 2008 Pearson Addison-Wesley. All rights reserved

More Details About Type More Details About Type CastingCasting

When type casting from a floating-point to an integer When type casting from a floating-point to an integer type, the number is truncated, not roundedtype, the number is truncated, not rounded

(int)2.9(int)2.9 evaluates to evaluates to 22, not , not 33 When the value of an integer type is assigned to a When the value of an integer type is assigned to a

variable of a floating-point type, Java performs an variable of a floating-point type, Java performs an automatic type cast called a automatic type cast called a type coerciontype coercion

double d = 5;double d = 5; In contrast, it is illegal to place a In contrast, it is illegal to place a doubledouble value into an value into an intint variable without an explicit type cast variable without an explicit type cast

int i = 5.5; // Illegalint i = 5.5; // Illegalint i = (int)5.5 // Correctint i = (int)5.5 // Correct

1-50Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Increment and Decrement OperatorsIncrement and Decrement Operators

The The increment operatorincrement operator ( (++++) adds one to ) adds one to the value of a variablethe value of a variable If If nn is equal to is equal to 22, then , then n++n++ or or ++n++n will change will change

the value of the value of nn to to 33 The The decrement operatordecrement operator ( (----) subtracts ) subtracts

one from the value of a variableone from the value of a variable If If nn is equal to is equal to 44, then , then n--n-- or or --n--n will change will change

the value of the value of nn to to 33

1-51Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Increment and Decrement OperatorsIncrement and Decrement Operators

When either operator precedes its variable, and When either operator precedes its variable, and is part of an expression, then the expression is is part of an expression, then the expression is evaluated using the changed value of the evaluated using the changed value of the variablevariable If If nn is equal to is equal to 22, then , then 2*(++n)2*(++n) evaluates to evaluates to 66

When either operator follows its variable, and is When either operator follows its variable, and is part of an expression, then the expression is part of an expression, then the expression is evaluated using the original value of the evaluated using the original value of the variable, and only then is the variable value variable, and only then is the variable value changedchanged If If nn is equal to is equal to 22, then , then 2*(n++)2*(n++) evaluates to evaluates to 44

1-52Copyright © 2008 Pearson Addison-Wesley. All rights reserved

The Class The Class StringString There is no primitive type for strings in JavaThere is no primitive type for strings in Java The class The class StringString is a predefined class in Java that is is a predefined class in Java that is

used to store and process stringsused to store and process strings Objects of type Objects of type StringString are made up of strings of are made up of strings of

characters that are written within double quotescharacters that are written within double quotes Any quoted string is a constant of type Any quoted string is a constant of type StringString

"Live long and prosper.""Live long and prosper." A variable of type A variable of type StringString can be given the value of a can be given the value of a StringString object objectString blessing = "Live long and prosper.";String blessing = "Live long and prosper.";

1-53Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Concatenation of StringsConcatenation of Strings ConcatenationConcatenation: Using the : Using the ++ operator on two strings in operator on two strings in

order to connect them to form one longer stringorder to connect them to form one longer string If If greetinggreeting is equal to is equal to "Hello"Hello "", and , and javaClassjavaClass is equal to is equal to "class""class", then , then greeting + javaClassgreeting + javaClass is equal to is equal to "Hello "Hello class"class"

Any number of strings can be concatenated togetherAny number of strings can be concatenated together When a string is combined with almost any other type of When a string is combined with almost any other type of

item, the result is a stringitem, the result is a string "The answer is " + 42"The answer is " + 42 evaluates to evaluates to "The answer is 42""The answer is 42"

1-54Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Classes, Objects, and MethodsClasses, Objects, and Methods A A classclass is the name for a type whose values are objects is the name for a type whose values are objects ObjectsObjects are entities that store data and take actions are entities that store data and take actions

Objects of the Objects of the StringString class store data consisting of strings of class store data consisting of strings of characterscharacters

The actions that an object can take are called The actions that an object can take are called methodsmethods Methods can return a value of a single type and/or perform an Methods can return a value of a single type and/or perform an

actionaction All objects within a class have the same methods, but each can All objects within a class have the same methods, but each can

have different data valueshave different data values

1-55Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Classes, Objects, and MethodsClasses, Objects, and Methods

InvokingInvoking or or calling a methodcalling a method: a method is called : a method is called into action by writing the name of the calling into action by writing the name of the calling object, followed by a dot, followed by the method object, followed by a dot, followed by the method name, followed by parenthesesname, followed by parentheses This is sometimes referred to as This is sometimes referred to as sending a message sending a message

to the objectto the object The parentheses contain the information (if any) The parentheses contain the information (if any)

needed by the methodneeded by the method This information is called an This information is called an argumentargument (or (or argumentsarguments))

1-56Copyright © 2008 Pearson Addison-Wesley. All rights reserved

String MethodsString Methods The The StringString class contains many useful methods for class contains many useful methods for

string-processing applicationsstring-processing applications A A StringString method is called by writing a method is called by writing a StringString object, a dot, object, a dot,

the name of the method, and a pair of parentheses to enclose the name of the method, and a pair of parentheses to enclose any argumentsany arguments

If a If a StringString method returns a value, then it can be placed method returns a value, then it can be placed anywhere that a value of its type can be usedanywhere that a value of its type can be usedString greeting = "Hello";String greeting = "Hello";int count = greeting.length();int count = greeting.length();System.out.println("Length is " + System.out.println("Length is " + greeting.length());greeting.length());

Always count from zero when referring to the Always count from zero when referring to the positionposition or or index index of of a character in a stringa character in a string

1-57Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class Some Methods in the Class StringString (Part 1 (Part 1 of 8)of 8)

1-58Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class Some Methods in the Class StringString (Part 2 (Part 2 of 8)of 8)

1-59Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class Some Methods in the Class StringString (Part 3 (Part 3 of 8)of 8)

1-60Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class Some Methods in the Class StringString (Part 4 of (Part 4 of 8)8)

1-61Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class Some Methods in the Class StringString (Part 5 of (Part 5 of 8)8)

1-62Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class Some Methods in the Class StringString (Part 6 (Part 6 of 8)of 8)

1-63Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class Some Methods in the Class StringString (Part 7 (Part 7 of 8)of 8)

1-64Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class Some Methods in the Class StringString (Part 8 (Part 8 of 8)of 8)

1-65Copyright © 2008 Pearson Addison-Wesley. All rights reserved

String IndexesString Indexes

1-66Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Escape SequencesEscape Sequences

A backslash (A backslash (\\) immediately preceding a ) immediately preceding a character (i.e., without any space) denotes character (i.e., without any space) denotes an an escape sequenceescape sequence or an or an escape escape charactercharacter The character following the backslash does The character following the backslash does

not have its usual meaningnot have its usual meaning Although it is formed using two symbols, it is Although it is formed using two symbols, it is

regarded as a single characterregarded as a single character

1-67Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Escape SequencesEscape Sequences

1-68Copyright © 2008 Pearson Addison-Wesley. All rights reserved

String ProcessingString Processing A A StringString object in Java is considered to be immutable, object in Java is considered to be immutable,

i.e., the characters it contains cannot be changedi.e., the characters it contains cannot be changed There is another class in Java called There is another class in Java called StringBufferStringBuffer

that has methods for editing its string objectsthat has methods for editing its string objects However, it is possible to change the value of a However, it is possible to change the value of a StringString

variable by using an assignment statementvariable by using an assignment statementString name = "Soprano";String name = "Soprano";name = "Anthony " + name;name = "Anthony " + name;

1-69Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Character SetsCharacter Sets ASCIIASCII: A character set used by many programming : A character set used by many programming

languages that contains all the characters normally used languages that contains all the characters normally used on an English-language keyboard, plus a few special on an English-language keyboard, plus a few special characterscharacters

Each character is represented by a particular numberEach character is represented by a particular number UnicodeUnicode: A character set used by the Java language : A character set used by the Java language

that includes all the ASCII characters plus many of the that includes all the ASCII characters plus many of the characters used in languages with a different alphabet characters used in languages with a different alphabet from Englishfrom English

1-70Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Naming ConstantsNaming Constants Instead of using "anonymous" numbers in a program, Instead of using "anonymous" numbers in a program,

always declare them as named constants, and use their always declare them as named constants, and use their name insteadname insteadpublic static final int INCHES_PER_FOOT = 12;public static final int INCHES_PER_FOOT = 12;public static final double RATE = 0.14;public static final double RATE = 0.14; This prevents a value from being changed inadvertentlyThis prevents a value from being changed inadvertently It has the added advantage that when a value must be modified, It has the added advantage that when a value must be modified,

it need only be changed in one placeit need only be changed in one place Note the naming convention for constants: Use all uppercase Note the naming convention for constants: Use all uppercase

letters, and designate word boundaries with an underscore letters, and designate word boundaries with an underscore charactercharacter

1-71Copyright © 2008 Pearson Addison-Wesley. All rights reserved

CommentsComments A A line commentline comment begins with the symbols begins with the symbols ////, and , and

causes the compiler to ignore the remainder of causes the compiler to ignore the remainder of the linethe line This type of comment is used for the code writer or for This type of comment is used for the code writer or for

a programmer who modifies the codea programmer who modifies the code A A block commentblock comment begins with the symbol pair begins with the symbol pair /*/*, and ends with the symbol pair , and ends with the symbol pair */*/ The compiler ignores anything in betweenThe compiler ignores anything in between This type of comment can span several linesThis type of comment can span several lines This type of comment provides documentation for the This type of comment provides documentation for the

users of the programusers of the program

1-72Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Program DocumentationProgram Documentation Java comes with a program called Java comes with a program called javadocjavadoc

that will automatically extract documentation that will automatically extract documentation from block comments in the classes you from block comments in the classes you definedefine As long as their opening has an extra asterisk As long as their opening has an extra asterisk

((/**/**)) Ultimately, a well written program is self-Ultimately, a well written program is self-

documentingdocumenting Its structure is made clear by the choice of Its structure is made clear by the choice of

identifier names and the indenting patternidentifier names and the indenting pattern When one structure is nested inside another, the When one structure is nested inside another, the

inside structure is indented one more levelinside structure is indented one more level

1-73Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Comments and a Named Comments and a Named ConstantConstant

1-74Copyright © 2008 Pearson Addison-Wesley. All rights reserved