A Programmer's Guide To Java SE 8 Oracle Certified Associate (OCA)
A%20Programmer's%20Guide%20to%20Java%20SE%208%20Oracle%20Certified%20Associate
User Manual: Pdf
Open the PDF directly: View PDF .
Page Count: 2629 [warning: Documents this large are best viewed by clicking the View PDF Link!]
- About This E-Book
- Title Page
- Copyright Page
- Dedication Page
- Contents Overview
- Contents
- Figures
- Tables
- Examples
- Foreword
- Preface
- 1. Basics of Java Programming
- 1.1 Introduction
- 1.2 Classes
- 1.3 Objects
- 1.4 Instance Members
- 1.5 Static Members
- 1.6 Inheritance
- 1.7 Associations: Aggregation and Composition
- 1.8 Tenets of Java
- Review Questions
- 1.9 Java Programs
- 1.10 Sample Java Application
- 1.11 Program Output
- 1.12 The Java Ecosystem
- Review Questions
- Chapter Summary
- Programming Exercise
- 2. Language Fundamentals
- 3. Declarations
- 4. Access Control
- 4.1 Java Source File Structure
- 4.2 Packages
- 4.3 Searching for Classes
- Review Questions
- 4.4 Scope Rules
- 4.5 Accessibility Modifiers for Top-Level Type Declarations
- 4.6 Non-Accessibility Modifiers for Classes
- Review Questions
- 4.7 Member Accessibility Modifiers
- Review Questions
- 4.8 Non-Accessibility Modifiers for Members
- Review Questions
- Chapter Summary
- Programming Exercise
- 5. Operators and Expressions
- 5.1 Conversions
- 5.2 Type Conversion Contexts
- 5.3 Precedence and Associativity Rules for Operators
- 5.4 Evaluation Order of Operands
- 5.5 Representing Integers
- 5.6 The Simple Assignment Operator =
- Review Questions
- 5.7 Arithmetic Operators: *, /, %, +, -
- Arithmetic Operator Precedence and Associativity
- Evaluation Order in Arithmetic Expressions
- Range of Numeric Values
- Unary Arithmetic Operators: -, +
- Multiplicative Binary Operators: *, /, %
- Additive Binary Operators: +, -
- Numeric Promotions in Arithmetic Expressions
- Arithmetic Compound Assignment Operators: *=, /=, %=, +=, -=
- Review Questions
- 5.8 The Binary String Concatenation Operator +
- 5.9 Variable Increment and Decrement Operators: ++, --
- Review Questions
- 5.10 Boolean Expressions
- 5.11 Relational Operators: <, <=, >, >=
- 5.12 Equality
- 5.13 Boolean Logical Operators: !, ^, &, |
- 5.14 Conditional Operators: &&, ||
- 5.15 Integer Bitwise Operators: ~, &, |, ^
- Review Questions
- 5.16 The Conditional Operator: ?:
- 5.17 Other Operators: new, [], instanceof, ->
- Review Questions
- Chapter Summary
- Programming Exercise
- 6. Control Flow
- 6.1 Overview of Control Flow Statements
- 6.2 Selection Statements
- Review Questions
- 6.3 Iteration Statements
- 6.4 Transfer Statements
- Review Questions
- 6.5 Stack-Based Execution and Exception Propagation
- 6.6 Exception Types
- 6.7 Exception Handling: try, catch, and finally
- 6.8 The throw Statement
- 6.9 The throws Clause
- 6.10 Advantages of Exception Handling
- Review Questions
- Chapter Summary
- Programming Exercises
- 7. Object-Oriented Programming
- 7.1 Single Implementation Inheritance
- 7.2 Overriding Methods
- 7.3 Hiding Members
- 7.4 The Object Reference super
- Review Questions
- 7.5 Chaining Constructors Using this() and super()
- Review Questions
- 7.6 Interfaces
- Review Questions
- 7.7 Arrays and Subtyping
- 7.8 Reference Values and Conversions
- 7.9 Reference Value Assignment Conversions
- 7.10 Method Invocation Conversions Involving References
- 7.11 Reference Casting and the instanceof Operator
- Review Questions
- 7.12 Polymorphism and Dynamic Method Lookup
- 7.13 Inheritance versus Aggregation
- 7.14 Basic Concepts in Object-Oriented Design
- Review Questions
- Chapter Summary
- Programming Exercises
- 8. Fundamental Classes
- 8.1 Overview of the java.lang Package
- 8.2 The Object Class
- Review Questions
- 8.3 The Wrapper Classes
- Review Questions
- 8.4 The String Class
- Immutability
- Creating and Initializing Strings
- The CharSequence Interface
- Reading Characters from a String
- Comparing Strings
- Character Case in a String
- Concatenation of Strings
- Joining of CharSequence Objects
- Searching for Characters and Substrings
- Extracting Substrings
- Converting Primitive Values and Objects to Strings
- Formatted Strings
- Review Questions
- 8.5 The StringBuilder and StringBuffer Classes
- Review Questions
- Chapter Summary
- Programming Exercises
- 9. Object Lifetime
- 9.1 Garbage Collection
- 9.2 Reachable Objects
- 9.3 Facilitating Garbage Collection
- 9.4 Object Finalization
- 9.5 Finalizer Chaining
- 9.6 Invoking Garbage Collection Programmatically
- Review Questions
- 9.7 Initializers
- 9.8 Field Initializer Expressions
- 9.9 Static Initializer Blocks
- 9.10 Instance Initializer Blocks
- 9.11 Constructing Initial Object State
- Review Questions
- Chapter Summary
- 10. The ArrayList<E> Class and Lambda Expressions
- 11. Date and Time
- Appendix A. Taking the Java SE 8 Programmer I Exam
- Appendix B. Exam Topics: Java SE 8 Programmer I
- Appendix C. Annotated Answers to Review Questions
- Appendix D. Solutions to Programming Exercises
- Appendix E. Mock Exam: Java SE 8 Programmer I
- Appendix F. Annotated Answers to Mock Exam I
- Index
- Code Snippets
WOW! eBook
www.wowebook.org
AboutThisE-Book
EPUBisanopen,industry-standardformatfore-books.However,supportforEPUB
anditsmanyfeaturesvariesacrossreadingdevicesandapplications.Useyourdeviceor
appsettingstocustomizethepresentationtoyourliking.Settingsthatyoucancustomize
oftenincludefont,fontsize,singleordoublecolumn,landscapeorportraitmode,and
figuresthatyoucanclickortaptoenlarge.Foradditionalinformationaboutthesettings
andfeaturesonyourreadingdeviceorapp,visitthedevicemanufacturer’sWebsite.
Manytitlesincludeprogrammingcodeorconfigurationexamples.Tooptimizethe
presentationoftheseelements,viewthee-bookinsingle-column,landscapemodeand
adjustthefontsizetothesmallestsetting.Inadditiontopresentingcodeand
configurationsinthereflowabletextformat,wehaveincludedimagesofthecodethat
mimicthepresentationfoundintheprintbook;therefore,wherethereflowableformat
maycompromisethepresentationofthecodelisting,youwillseea“Clickheretoview
codeimage”link.Clickthelinktoviewtheprint-fidelitycodeimage.Toreturntothe
previouspageviewed,clicktheBackbuttononyourdeviceorapp.
WOW! eBook
www.wowebook.org
AProgrammer’sGuidetoJava®SE8
OracleCertifiedAssociate(OCA)
AComprehensivePrimer
KhalidA.Mughal
RolfW.Rasmussen
Boston•Columbus•Indianapolis•NewYork•SanFrancisco•Amsterdam•CapeTown
Dubai•London•Madrid•Milan•Munich•Paris•Montreal•Toronto•Delhi•Mexico
City
SãoPaulo•Sydney•HongKong•Seoul•Singapore•Taipei•Tokyo
WOW! eBook
www.wowebook.org
Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproducts
areclaimedastrademarks.Wherethosedesignationsappearinthisbook,andthe
publisherwasawareofatrademarkclaim,thedesignationshavebeenprintedwithinitial
capitallettersorinallcapitals.
Theauthorsandpublisherhavetakencareinthepreparationofthisbook,butmakeno
expressedorimpliedwarrantyofanykindandassumenoresponsibilityforerrorsor
omissions.Noliabilityisassumedforincidentalorconsequentialdamagesinconnection
withorarisingoutoftheuseoftheinformationorprogramscontainedherein.
Forinformationaboutbuyingthistitleinbulkquantities,orforspecialsalesopportunities
(whichmayincludeelectronicversions;customcoverdesigns;andcontentparticularto
yourbusiness,traininggoals,marketingfocus,orbrandinginterests),pleasecontactour
corporatesalesdepartmentatcorpsales@pearsoned.comor(800)382-3419.
Forgovernmentsalesinquiries,pleasecontactgovernmentsales@pearsoned.com.
ForquestionsaboutsalesoutsidetheU.S.,pleasecontactintlcs@pearson.com.
VisitusontheWeb:informit.com/aw
LibraryofCongressControlNumber:2016937073
Copyright©2017PearsonEducation,Inc.
Allrightsreserved.PrintedintheUnitedStatesofAmerica.Thispublicationisprotected
bycopyright,andpermissionmustbeobtainedfromthepublisherpriortoanyprohibited
reproduction,storageinaretrievalsystem,ortransmissioninanyformorbyanymeans,
electronic,mechanical,photocopying,recording,orlikewise.Forinformationregarding
permissions,requestformsandtheappropriatecontactswithinthePearsonEducation
GlobalRights&PermissionsDepartment,pleasevisitwww.pearsoned.com/permissions/.
ISBN-13:978-0-13-293021-5
ISBN-10:0-13-293021-8
TextprintedintheUnitedStatesonrecycledpaperatRRDonnelleyinCrawfordsville,
Indiana.
Firstprinting,July2016
WOW! eBook
www.wowebook.org
Tothelovingmemoryofmymother,ZubaidaBegum,
andmyfather,MohammedAzim
—K.A.M.
ForOliviaE.Rasmussenand
LouiseJ.Dahlmo
—R.W.R.
WOW! eBook
www.wowebook.org
ContentsOverview
Figures
Tables
Examples
Foreword
Preface
1BasicsofJavaProgramming
2LanguageFundamentals
3Declarations
4AccessControl
5OperatorsandExpressions
6ControlFlow
7Object-OrientedProgramming
8FundamentalClasses
9ObjectLifetime
10TheArrayList<E>ClassandLambdaExpressions
11DateandTime
ATakingtheJavaSE8ProgrammerIExam
BExamTopics:JavaSE8ProgrammerI
CAnnotatedAnswerstoReviewQuestions
DSolutionstoProgrammingExercises
EMockExam:JavaSE8ProgrammerI
FAnnotatedAnswerstoMockExamI
Index
WOW! eBook
www.wowebook.org
Contents
Figures
Tables
Examples
Foreword
Preface
1BasicsofJavaProgramming
1.1Introduction
1.2Classes
DeclaringMembers:FieldsandMethods
1.3Objects
ClassInstantiation,ReferenceValues,andReferences
ObjectAliases
1.4InstanceMembers
InvokingMethods
1.5StaticMembers
1.6Inheritance
1.7Associations:AggregationandComposition
1.8TenetsofJava
ReviewQuestions
1.9JavaPrograms
1.10SampleJavaApplication
EssentialElementsofaJavaApplication
CompilingandRunninganApplication
1.11ProgramOutput
FormattedOutput
1.12TheJavaEcosystem
Object-OrientedParadigm
Interpreted:TheJVM
Architecture-NeutralandPortableBytecode
Simplicity
WOW! eBook
www.wowebook.org
DynamicandDistributed
RobustandSecure
HighPerformanceandMultithreaded
ReviewQuestions
ChapterSummary
ProgrammingExercise
2LanguageFundamentals
2.1BasicLanguageElements
LexicalTokens
Identifiers
Keywords
Separators
Literals
IntegerLiterals
Floating-PointLiterals
UnderscoresinNumericalLiterals
BooleanLiterals
CharacterLiterals
StringLiterals
Whitespace
Comments
ReviewQuestions
2.2PrimitiveDataTypes
TheIntegerTypes
ThecharType
TheFloating-PointTypes
ThebooleanType
ReviewQuestions
2.3VariableDeclarations
DeclaringandInitializingVariables
ReferenceVariables
2.4InitialValuesforVariables
WOW! eBook
www.wowebook.org
DefaultValuesforFields
InitializingLocalVariablesofPrimitiveDataTypes
InitializingLocalReferenceVariables
LifetimeofVariables
ReviewQuestions
ChapterSummary
ProgrammingExercise
3Declarations
3.1ClassDeclarations
3.2MethodDeclarations
Statements
InstanceMethodsandtheObjectReferencethis
MethodOverloading
3.3Constructors
TheDefaultConstructor
OverloadedConstructors
ReviewQuestions
3.4Arrays
DeclaringArrayVariables
ConstructinganArray
InitializinganArray
UsinganArray
AnonymousArrays
MultidimensionalArrays
SortingArrays
SearchingArrays
ReviewQuestions
3.5ParameterPassing
PassingPrimitiveDataValues
PassingReferenceValues
PassingArrays
ArrayElementsasActualParameters
WOW! eBook
www.wowebook.org
finalParameters
3.6VariableArityMethods
CallingaVariableArityMethod
VariableArityandFixedArityMethodCalls
3.7Themain()Method
ProgramArguments
3.8EnumeratedTypes
DeclaringType-safeEnums
UsingType-safeEnums
SelectedMethodsforEnumTypes
ReviewQuestions
ChapterSummary
ProgrammingExercise
4AccessControl
4.1JavaSourceFileStructure
4.2Packages
DefiningPackages
UsingPackages
CompilingCodeintoPackages
RunningCodefromPackages
4.3SearchingforClasses
ReviewQuestions
4.4ScopeRules
ClassScopeforMembers
BlockScopeforLocalVariables
4.5AccessibilityModifiersforTop-LevelTypeDeclarations
4.6Non-AccessibilityModifiersforClasses
abstractClasses
finalClasses
ReviewQuestions
4.7MemberAccessibilityModifiers
publicMembers
WOW! eBook
www.wowebook.org
protectedMembers
DefaultAccessibilityforMembers
privateMembers
ReviewQuestions
4.8Non-AccessibilityModifiersforMembers
staticMembers
finalMembers
abstractMethods
synchronizedMethods
nativeMethods
transientFields
volatileFields
ReviewQuestions
ChapterSummary
ProgrammingExercise
5OperatorsandExpressions
5.1Conversions
WideningandNarrowingPrimitiveConversions
WideningandNarrowingReferenceConversions
BoxingandUnboxingConversions
OtherConversions
5.2TypeConversionContexts
AssignmentContext
MethodInvocationContext
CastingContextoftheUnaryTypeCastOperator:(type)
NumericPromotionContext
5.3PrecedenceandAssociativityRulesforOperators
5.4EvaluationOrderofOperands
Left-HandOperandEvaluationFirst
OperandEvaluationbeforeOperationExecution
Left-to-RightEvaluationofArgumentLists
5.5RepresentingIntegers
WOW! eBook
www.wowebook.org
CalculatingTwo’sComplement
ConvertingBinaryNumberstoDecimals
ConvertingDecimalstoBinaryNumbers
RelationshipsamongBinary,Octal,andHexadecimalNumbers
5.6TheSimpleAssignmentOperator=
AssigningPrimitiveValues
AssigningReferences
MultipleAssignments
TypeConversionsinanAssignmentContext
ReviewQuestions
5.7ArithmeticOperators:*,/,%,+,-
ArithmeticOperatorPrecedenceandAssociativity
EvaluationOrderinArithmeticExpressions
RangeofNumericValues
UnaryArithmeticOperators:-,+
MultiplicativeBinaryOperators:*,/,%
AdditiveBinaryOperators:+,-
NumericPromotionsinArithmeticExpressions
ArithmeticCompoundAssignmentOperators:*=,/=,%=,+=,-=
ReviewQuestions
5.8TheBinaryStringConcatenationOperator+
5.9VariableIncrementandDecrementOperators:++,--
TheIncrementOperator++
TheDecrementOperator--
ReviewQuestions
5.10BooleanExpressions
5.11RelationalOperators:<,<=,>,>=
5.12Equality
PrimitiveDataValueEquality:==,!=
ObjectReferenceEquality:==,!=
ObjectValueEquality
WOW! eBook
www.wowebook.org
5.13BooleanLogicalOperators:!,^,&,|
OperandEvaluationforBooleanLogicalOperators
BooleanLogicalCompoundAssignmentOperators:&=,^=,|=
5.14ConditionalOperators:&&,||
Short-CircuitEvaluation
5.15IntegerBitwiseOperators:~,&,|,^
BitwiseCompoundAssignmentOperators:&=,^=,|=
ReviewQuestions
5.16TheConditionalOperator:?:
5.17OtherOperators:new,[],instanceof,->
ReviewQuestions
ChapterSummary
ProgrammingExercise
6ControlFlow
6.1OverviewofControlFlowStatements
6.2SelectionStatements
TheSimpleifStatement
Theif-elseStatement
TheswitchStatement
ReviewQuestions
6.3IterationStatements
ThewhileStatement
Thedo-whileStatement
Thefor(;;)Statement
Thefor(:)Statement
6.4TransferStatements
LabeledStatements
ThebreakStatement
ThecontinueStatement
ThereturnStatement
ReviewQuestions
WOW! eBook
www.wowebook.org
6.5Stack-BasedExecutionandExceptionPropagation
6.6ExceptionTypes
TheExceptionClass
TheRuntimeExceptionClass
TheErrorClass
CheckedandUncheckedExceptions
DefiningCustomizedExceptions
6.7ExceptionHandling:try,catch,andfinally
ThetryBlock
ThecatchClause
ThefinallyClause
6.8ThethrowStatement
6.9ThethrowsClause
OverridingthethrowsClause
6.10AdvantagesofExceptionHandling
ReviewQuestions
ChapterSummary
ProgrammingExercises
7Object-OrientedProgramming
7.1SingleImplementationInheritance
Relationships:is-aandhas-a
TheSupertype–SubtypeRelationship
7.2OverridingMethods
InstanceMethodOverriding
CovariantreturninOverridingMethods
OverridingversusOverloading
7.3HidingMembers
FieldHiding
StaticMethodHiding
7.4TheObjectReferencesuper
ReviewQuestions
WOW! eBook
www.wowebook.org
7.5ChainingConstructorsUsingthis()andsuper()
Thethis()ConstructorCall
Thesuper()ConstructorCall
ReviewQuestions
7.6Interfaces
DefiningInterfaces
AbstractMethodsinInterfaces
ImplementingInterfaces
ExtendingInterfaces
InterfaceReferences
DefaultMethodsinInterfaces
StaticMethodsinInterfaces
ConstantsinInterfaces
ReviewQuestions
7.7ArraysandSubtyping
ArraysandSubtypeCovariance
ArrayStoreCheck
7.8ReferenceValuesandConversions
7.9ReferenceValueAssignmentConversions
7.10MethodInvocationConversionsInvolvingReferences
OverloadedMethodResolution
7.11ReferenceCastingandtheinstanceofOperator
TheCastOperator
TheinstanceofOperator
ReviewQuestions
7.12PolymorphismandDynamicMethodLookup
7.13InheritanceversusAggregation
7.14BasicConceptsinObject-OrientedDesign
Encapsulation
Cohesion
Coupling
ReviewQuestions
WOW! eBook
www.wowebook.org
ChapterSummary
ProgrammingExercises
8FundamentalClasses
8.1Overviewofthejava.langPackage
8.2TheObjectClass
ReviewQuestions
8.3TheWrapperClasses
CommonWrapperClassConstructors
CommonWrapperClassUtilityMethods
NumericWrapperClasses
TheCharacterClass
TheBooleanClass
ReviewQuestions
8.4TheStringClass
Immutability
CreatingandInitializingStrings
TheCharSequenceInterface
ReadingCharactersfromaString
ComparingStrings
CharacterCaseinaString
ConcatenationofStrings
JoiningofCharSequenceObjects
SearchingforCharactersandSubstrings
ExtractingSubstrings
ConvertingPrimitiveValuesandObjectstoStrings
FormattedStrings
ReviewQuestions
8.5TheStringBuilderandStringBufferClasses
Thread-Safety
Mutability
ConstructingStringBuilders
ReadingandChangingCharactersinStringBuilders
WOW! eBook
www.wowebook.org
ConstructingStringsfromStringBuilders
Appending,Inserting,andDeletingCharactersinStringBuilders
ControllingStringBuilderCapacity
ReviewQuestions
ChapterSummary
ProgrammingExercises
9ObjectLifetime
9.1GarbageCollection
9.2ReachableObjects
9.3FacilitatingGarbageCollection
9.4ObjectFinalization
9.5FinalizerChaining
9.6InvokingGarbageCollectionProgrammatically
ReviewQuestions
9.7Initializers
9.8FieldInitializerExpressions
DeclarationOrderofInitializerExpressions
9.9StaticInitializerBlocks
DeclarationOrderofStaticInitializers
9.10InstanceInitializerBlocks
DeclarationOrderofInstanceInitializers
9.11ConstructingInitialObjectState
ReviewQuestions
ChapterSummary
10TheArrayList<E>ClassandLambdaExpressions
10.1TheArrayList<E>Class
Lists
DeclaringReferencesandConstructingArrayLists
ModifyinganArrayList
QueryinganArrayList
TraversinganArrayList
ConvertinganArrayListtoanArray
WOW! eBook
www.wowebook.org
SortinganArrayList
ArraysversusArrayList
ReviewQuestions
10.2LambdaExpressions
BehaviorParameterization
FunctionalInterfaces
DefiningLambdaExpressions
TypeCheckingandExecutionofLambdaExpressions
FilteringRevisited:ThePredicate<T>FunctionalInterface
ReviewQuestions
ChapterSummary
ProgrammingExercise
11DateandTime
11.1BasicDateandTimeConcepts
11.2WorkingwithTemporalClasses
CreatingTemporalObjects
QueryingTemporalObjects
ComparingTemporalObjects
CreatingModifiedCopiesofTemporalObjects
TemporalArithmetic
11.3WorkingwithPeriods
CreatingPeriods
QueryingPeriods
CreatingModifiedCopiesofPeriods
MoreTemporalArithmetic
ReviewQuestions
11.4FormattingandParsing
DefaultFormatters
PredefinedFormatters
LocalizedFormatters
CustomizedFormatters
ReviewQuestions
WOW! eBook
www.wowebook.org
ChapterSummary
ProgrammingExercise
ATakingtheJavaSE8ProgrammerIExam
A.1PreparingfortheExam
A.2RegisteringfortheExam
ContactInformation
ObtaininganExamVoucher
SigningUpfortheTest
AfterTakingtheExam
A.3HowtheExamIsConducted
TheTestingLocations
UtilizingtheAllottedTime
TheExamProgram
TheExamResult
A.4TheQuestions
AssumptionsabouttheExamQuestions
TypesofQuestionsAsked
TypesofAnswersExpected
TopicsCoveredbytheQuestions
BExamTopics:JavaSE8ProgrammerI
CAnnotatedAnswerstoReviewQuestions
DSolutionstoProgrammingExercises
EMockExam:JavaSE8ProgrammerI
FAnnotatedAnswerstoMockExamI
Index
WOW! eBook
www.wowebook.org
Figures
1.1UMLNotationforClasses
1.2UMLNotationforObjects
1.3Aliases
1.4ClassDiagramShowingStaticMembersofaClass
1.5MembersofaClass
1.6ClassDiagramDepictingInheritanceRelationship
1.7ClassDiagramDepictingAssociations
1.8ClassDiagramDepictingComposition
2.1PrimitiveDataTypesinJava
3.1ArrayofArrays
3.2ParameterPassing:PrimitiveDataValues
3.3ParameterPassing:ReferenceValues
3.4ParameterPassing:Arrays
4.1JavaSourceFileStructure
4.2PackageHierarchy
4.3FileHierarchy
4.4SearchingforClasses
4.5BlockScope
4.6PublicAccessibilityforMembers
4.7ProtectedAccessibilityforMembers
4.8DefaultAccessibilityforMembers
4.9PrivateAccessibilityforMembers
5.1WideningPrimitiveConversions
5.2ConvertingamongBinary,Octal,andHexadecimalNumbers
5.3OverflowandUnderflowinFloating-PointArithmetic
5.4NumericPromotioninArithmeticExpressions
6.1ActivityDiagramforifStatements
6.2ActivityDiagramforaswitchStatement
6.3ActivityDiagramforthewhileStatement
6.4ActivityDiagramforthedo-whileStatement
WOW! eBook
www.wowebook.org
6.5ActivityDiagramfortheforStatement
6.6EnhancedforStatement
6.7MethodExecution
6.8ExceptionPropagation
6.9PartialExceptionInheritanceHierarchy
6.10Thetry-catch-finallyConstruct
6.11ExceptionHandling(Scenario1)
6.12ExceptionHandling(Scenario2)
6.13ExceptionHandling(Scenario3)
7.1InheritanceHierarchy
7.2InheritanceHierarchyforExample7.2andExample7.3
7.3InheritanceHierarchies
7.4InheritanceRelationshipsforInterfaceConstants
7.5ReferenceTypeHierarchy:ArraysandSubtypeCovariance
7.6TypeHierarchyThatIllustratesPolymorphism
7.7ImplementingDataStructuresbyInheritanceandAggregation
8.1PartialInheritanceHierarchyinthejava.langPackage
8.2ConvertingValuesamongPrimitive,Wrapper,andStringTypes
9.1MemoryOrganizationatRuntime
10.1PartialArrayListInheritanceHierarchy
WOW! eBook
www.wowebook.org
Tables
1.1TerminologyforClassMembers
1.2FormatSpecifierExamples
2.1KeywordsinJava
2.2ReservedLiteralsinJava
2.3ReservedKeywordsNotCurrentlyinUse
2.4SeparatorsinJava
2.5ExamplesofLiterals
2.6ExamplesofDecimal,Binary,Octal,andHexadecimalLiterals
2.7ExamplesofCharacterLiterals
2.8EscapeSequences
2.9ExamplesofEscapeSequence\ddd
2.10RangeofIntegerValues
2.11RangeofCharacterValues
2.12RangeofFloating-PointValues
2.13BooleanValues
2.14SummaryofPrimitiveDataTypes
2.15DefaultValues
3.1ParameterPassingbyValue
4.1AccessingMemberswithinaClass
4.2SummaryofAccessibilityModifiersforTop-LevelTypes
4.3SummaryofNon-AccessibilityModifiersforClasses
4.4SummaryofAccessibilityModifiersforMembers
4.5SummaryofNon-AccessibilityModifiersforMembers
5.1SelectedConversionContextsandConversionCategories
5.2OperatorSummary
5.3RepresentingSignedbyteValuesUsingTwo’sComplement
5.4ExamplesofTruncatedValues
5.5ArithmeticOperators
5.6ExamplesofArithmeticExpressionEvaluation
5.7ArithmeticCompoundAssignmentOperators
WOW! eBook
www.wowebook.org
5.8RelationalOperators
5.9PrimitiveDataValueEqualityOperators
5.10ReferenceEqualityOperators
5.11TruthValuesforBooleanLogicalOperators
5.12BooleanLogicalCompoundAssignmentOperators
5.13ConditionalOperators
5.14TruthValuesforConditionalOperators
5.15IntegerBitwiseOperators
5.16ResultTableforBitwiseOperators
5.17ExamplesofBitwiseOperations
5.18BitwiseCompoundAssignmentOperators
6.1ThereturnStatement
7.1OverridingversusOverloading
7.2SameSignatureforSubclassandSuperclassMethod
7.3TypesandValues
10.1SummaryofArraysversusArrayLists
10.2SelectedFunctionalInterfacesfromthejava.util.functionPackage
11.1SelectedCommonMethodPrefixoftheTemporalClasses
11.2SelectedISO-BasedPredefinedFormattersforDateandTime
11.3FormatStylesforDateandTime
11.4CombinationofFormatStylesandLocalizedFormatters
11.5SelectedDate/TimePatternLetters
WOW! eBook
www.wowebook.org
Examples
1.1BasicElementsofaClassDeclaration
1.2StaticMembersinClassDeclaration
1.3DefiningaSubclass
1.4AnApplication
1.5FormattedOutput
2.1DefaultValuesforFields
2.2FlaggingUninitializedLocalVariablesofPrimitiveDataTypes
2.3FlaggingUninitializedLocalReferenceVariables
3.1UsingthethisReference
3.2Namespaces
3.3UsingArrays
3.4UsingAnonymousArrays
3.5UsingMultidimensionalArrays
3.6PassingPrimitiveValues
3.7PassingReferenceValues
3.8PassingArrays
3.9ArrayElementsasPrimitiveDataValues
3.10ArrayElementsasReferenceValues
3.11CallingaVariableArityMethod
3.12PassingProgramArguments
3.13UsingEnums
4.1DefiningPackagesandUsingTypeImport
4.2SingleStaticImport
4.3AvoidingtheInterfaceConstantAntipattern
4.4ImportingEnumConstants
4.5ShadowingStaticImport
4.6ConflictinImportingStaticMethodwiththeSameSignature
4.7ClassScope
4.8AccessibilityModifiersforClassesandInterfaces
4.9AbstractClasses
WOW! eBook
www.wowebook.org
4.10PublicAccessibilityofMembers
4.11AccessingStaticMembers
4.12UsingfinalModifier
4.13SynchronizedMethods
5.1EvaluationOrderofOperandsandArguments
5.2NumericPromotioninArithmeticExpressions
5.3Short-CircuitEvaluationInvolvingConditionalOperators
5.4BitwiseOperations
6.1Fall-ThroughinaswitchStatement
6.2UsingbreakinaswitchStatement
6.3NestedswitchStatement
6.4StringsinswitchStatement
6.5EnumsinswitchStatement
6.6ThebreakStatement
6.7LabeledbreakStatement
6.8continueStatement
6.9LabeledcontinueStatement
6.10ThereturnStatement
6.11MethodExecution
6.12Thetry-catchConstruct
6.13ExceptionPropagation
6.14Thetry-catch-finallyConstruct
6.15Thetry-finallyConstruct
6.16ThefinallyClauseandthereturnStatement
6.17ThrowingExceptions
6.18ThethrowsClause
7.1ExtendingClasses:InheritanceandAccessibility
7.2Overriding,Overloading,andHiding
7.3UsingthesuperKeyword
7.4ConstructorOverloading
7.5Thethis()ConstructorCall
WOW! eBook
www.wowebook.org
7.6Thesuper()ConstructorCall
7.7ImplementingInterfaces
7.8DefaultMethodsinInterfaces
7.9DefaultMethodsandMultipleInheritance
7.10StaticMethodsinInterfaces
7.11ConstantsinInterfaces
7.12InheritingConstantsinInterfaces
7.13AssigningandPassingReferenceValues
7.14ChoosingtheMostSpecificMethod(SimpleCase)
7.15OverloadedMethodResolution
7.16TheinstanceofandCastOperators
7.17UsingtheinstanceofOperator
7.18PolymorphismandDynamicMethodLookup
7.19ImplementingDataStructuresbyInheritanceandAggregation
8.1MethodsintheObjectClass
8.2StringRepresentationofIntegers
8.3StringConstructionandEquality
8.4ReadingCharactersfromaString
9.1GarbageCollectionEligibility
9.2UsingFinalizers
9.3InvokingGarbageCollection
9.4InitializerExpressionOrderandMethodCalls
9.5StaticInitializersandForwardReferences
9.6InstanceInitializersandForwardReferences
9.7ObjectStateConstruction
9.8InitializationAnomalyunderObjectStateConstruction
10.1UsinganArrayList
10.2ImplementingCustomizedMethodsforFilteringanArrayList
10.3ImplementinganInterfaceforFilteringanArrayList
10.4User-DefinedFunctionalInterfaceforFilteringanArrayList
10.5UsingthePredicate<T>FunctionalInterfaceforFilteringanArrayList
10.6AccessingMembersinanEnclosingObject
WOW! eBook
www.wowebook.org
10.7AccessingLocalVariablesinanEnclosingMethod
10.8FilteringanArrayList
11.1CreatingTemporalObjects
11.2UsingTemporalObjects
11.3TemporalArithmetic
11.4Period-BasedLoop
11.5MoreTemporalArithmetic
11.6UsingDefaultDateandTimeFormatters
11.7UsingPredefinedFormatStyleswithTime-BasedValues
11.8UsingPredefinedFormatStyleswithDate-BasedValues
11.9UsingPredefinedFormatStyleswithDateandTime-BasedValues
11.10FormattingandParsingwithLetterPatterns
11.11FormattingwithDate/TimeLetterPatterns
WOW! eBook
www.wowebook.org
Foreword
Javaisnowovertwentyyearsoldandthecurrentrelease,JDK8,despiteitsname,is
reallytheeleventhsignificantreleaseoftheplatform.Whilststayingtruetotheoriginal
ideasoftheplatform,therehavebeennumerousdevelopmentsaddingavarietyoffeatures
tothelanguagesyntaxaswellasahugenumberofAPIstothecoreclasslibraries.This
hasenableddeveloperstobecomesubstantiallymoreproductiveandhashelpedto
eliminateavarietyofcommonsituationsthatcaneasilyresultinbugs.
Javahascontinuedtogrowinpopularity,whichisinlargepartattributabletothe
continuedevolutionoftheplatform,whichkeepsitfreshandaddressesthingsthat
developerswant.Accordingtosomesources,therearemorethanninemillionJava
programmersacrosstheglobeandthisnumberlookssettocontinuetogrowasmost
universitiesuseJavaasaprimaryteachinglanguage.
WithsomanyJavaprogrammersavailabletoemployers,howdotheyensurethat
candidateshavethenecessaryskillstodevelophigh-quality,reliablecode?Theansweris
certification:astandardizedtestofadeveloper’sknowledgeaboutthewidevarietyof
featuresandtechniquesrequiredtouseJavaefficientlyandeffectively.Originally
introducedbySunMicrosystems,thecertificationprocessandexamhasbeenupdatedto
matchthefeaturesofeachreleaseofJava.OraclehascontinuedthissinceacquiringSun
in2010.
Takingandpassingtheexamsisnotasimpletask.Toensurethatdevelopersmeetahigh
standardofknowledgeaboutJava,thecandidatemustdemonstratetheabilityto
understandawidevarietyofprogrammingtechniques,acleargraspoftheJavasyntax,
andacomprehensiveknowledgeofthestandardclasslibraryAPIs.Withthereleaseof
JDK8,notonlydoJavadevelopersneedtounderstandthedetailsofimperativeand
object-orientedprogramming,theynowneedtohaveagraspoffunctionalprogramming
sotheycaneffectivelyusethekeynewfeatures:lambdaexpressionsandtheStreamsAPI.
Whichiswhy,ultimately,youneedthisbooktohelpyoupreparefortheexam.The
authorshavedoneagreatjobofpresentingthematerialyouneedtoknowtopassthe
examinanapproachableandeasy-to-graspway.Thebookstartswiththefundamental
conceptsandlanguagesyntaxandworksitswaythroughwhatyouneedtoknowabout
object-orientedprogrammingbeforeaddressingmorecomplextopicslikegenerictypes.
ThelatterpartofthebookaddressesthemostrecentchangesinJDK8,thatoflambda
expressions,theStreamsAPI,andthenewDateandTimeAPI.
HavingworkedwithJavaalmostsinceitwasfirstreleased,bothatSunMicrosystemsand
thenatOracleCorporation,Ithinkyouwillfindthisbookaninvaluableguidetohelpyou
passtheOracleCertifiedAssociateExamforJavaSE8.Iwishyouthebestofluck!
—SimonRitter
DeputyCTO,AzulSystems
WOW! eBook
www.wowebook.org
Preface
WritingThisBook
DearReader,whatyouholdinyourhandistheresultofameticuloushigh-techoperation
thattookmanymonthsandrequiredinspectingmanyparts,removingcertainparts,
retrofittingsomeoldparts,andaddingmanynewpartstoourpreviousbookonanearlier
Javaprogrammercertificationexam,untilwewerecompletelysatisfiedwiththeresult.
Afteryouhavereadthebookandpassedtheexam,wehopethatyouwillappreciatethe
TLC(tenderlovingcare)thathasgoneintothisoperation.Thisishowitallcameabout.
LearningthenamesofJavacertificationsandtherequiredexamsisthefirstitemonthe
agenda.ThisbookprovidescoveragefortheexamtoearnOracleCertifiedAssociate
(OCA),JavaSE8ProgrammerCertification(alsoknowasOCAJP8).Theexamrequired
forthiscertificationhasthenameJavaSE8ProgrammerIExam(Examnumber1Z0-
808).ItisthefirstoftwoexamsrequiredtoobtainOracleCertifiedProfessional(OCP),
JavaSE8ProgrammerCertification(alsoknownasOCPJP8).Thesecondexamrequired
forthisprofessionalcertificationhasthenameJavaSE8ProgrammerIIExam(Exam
number1Z0-809).Toreiterate,thisbookcoversonlythetopicsfortheJavaSE8
ProgrammerIExamthatisrequiredtoobtainOCAJP8certification.
AbookonthenewJavaSE8certificationwasalongtimecoming.ThemantleofJava
hadbeenpassedontoOracleandJava7hadhitthenewsstand.Westartedouttowritea
booktocoverthetopicsforthetwoexamsrequiredtoearntheOracleCertified
Professional,JavaSE7ProgrammerCertification.SoonafterthereleaseofJava8,
OracleannouncedthecertificationforJavaSE8.Wedecidedtoswitchtothenewversion.
Itwasnotadifficultdecisiontomake.Java8marksawatershedwhenthelanguagewent
frombeingapureobject-orientedlanguagetoonethatalsoincorporatesfeaturesof
functional-styleprogramming.Asthesayinggoes,Java8changedthewholeballgame.
Javapasseditstwentiethbirthdayin2015.Java8,releasedayearearlier,representeda
significantmilestoneinitshistory.Therewaslittlereasontodwellonearlierversions.
Thenextdecisionconcernedwhetheritwouldbebesttoprovidecoverageforthetwo
JavaSE8ProgrammerCertificationexamsinoneortwobooks.Pragmaticreasons
dictatedtwobooks.Itwouldtakefartoolongtocompleteabookthatcoveredboth
exams,mainlybecausethesecondexamwaslargelyrevampedandwouldrequirealotof
newmaterial.Wedecidedtocompletethebookforthefirstexam.Oncethatdecisionwas
made,ourdraftmanuscriptwentbackontheoperatingtable.
Ourapproachtowritingthisbookhasnotchangedfromtheoneweemployedforour
previousbooks,mainlybecauseithasprovedsuccessful.Nostoneswereleftunturnedto
createthisbook,asweexplainhere.
ThemostnoticeablechangesintheexamforOCAJP8aretheinclusionofthecoreclasses
inthenewDateandTimeAPIandthewritingofpredicatesusinglambdaexpressions.
Theemphasisremainsonanalyzingcodescenarios,ratherthanindividuallanguage
constructs.Theexamcontinuestorequireactualexperiencewiththelanguage,notjust
mererecitationoffacts.Westillclaimthatproficiencyinthelanguageisthekeyto
WOW! eBook
www.wowebook.org
success.
SincetheexamemphasizesthecorefeaturesofJava,thisbookprovidesin-depthcoverage
oftopicsrelatedtothosefeatures.Asinourearlierbooks,supplementarytopicsarealso
includedtoaidinmasteringtheexamtopics.
Thisbookisnodifferentfromourpreviousbooksinoneotherimportantaspect:Itisa
one-stopguide,providingamixtureoftheoryandpracticethatenablesreaderstoprepare
fortheexam.ItcanbeusedtolearnJavaandtopreparefortheexam.Aftertheexamis
passed,itcanalsocomeinhandyasalanguageguide.
Apartfromincludingcoverageofthenewtopics,ourdiscussionsofnumeroustopicsfrom
thepreviousexamwereextensivelyrevised.Allelementsfoundinourpreviousbooks
(e.g.,sections,examples,figures,tables,reviewquestions,mockexamquestions)were
closelyscrutinized.Newexamples,figures,tables,andreviewquestionswerespecifically
createdforthenewtopicsaswellasfortherevisedones.WecontinuetouseUML
(UnifiedModelingLanguage)extensivelytoillustrateconceptsandlanguageconstructs,
andallnumberedexamplescontinuetobecompleteJavaprogramsreadyfor
experimenting.
Feedbackfromreadersregardingourpreviousbookswasinvaluableinshapingthisbook.
Everyquestion,suggestion,andcommentreceivedwasdeliberatedupon.Wearegrateful
foreverysingleemailwehavereceivedovertheyears;thatinputprovedinvaluablein
improvingthisbook.
DearReader,wewishyouallthebestshouldyoudecidetogodownthepathofJava
certification.Mayyourloopsterminateandyourexceptionsgetcaught!
AboutThisBook
ThisbookprovidesextensivecoverageofthecorefeaturesoftheJavaprogramming
languageanditscoreapplicationprogramminginterface(API),withparticularemphasis
onitssyntaxandusage.Thebookisprimarilyintendedforprofessionalswhowantto
preparefortheJavaSE8ProgrammerIexam,butitisreadilyaccessibletoany
programmerwhowantstomasterthelanguage.Forbothpurposes,itprovidesin-depth
coverageofessentialfeaturesofthelanguageanditscoreAPI.
Thedemandforwell-trainedandhighlyskilledJavaprogrammersremainsunabated.
OracleoffersmanyJavacertificationsthatprofessionalscantaketovalidatetheirskills
(seehttp://education.oracle.com).Thecertificationprovidesmembersofthe
ITindustrywithastandardtousewhenhiringsuchprofessionals,anditallows
professionalstoturntheirJavaskillsintocredentialsthatareimportantforcareer
advancement.
ThebookprovidesextensivecoverageofalltheobjectivesdefinedbyOraclefortheJava
SE8ProgrammerIexam.Theexamobjectivesareselective,however,anddonotinclude
manyoftheessentialfeaturesofJava.Thisbookcoversmanyadditionaltopicsthatevery
Javaprogrammershouldmastertobetrulyproficient.Inthisregard,thebookisa
comprehensiveprimerforlearningtheJavaprogramminglanguage.Aftermasteringthe
languagebyworkingthroughthisbook,thereadercanconfidentlysitfortheexam.
WOW! eBook
www.wowebook.org
ThisbookisnotacompletereferenceforJava,asitdoesnotattempttolisteverymember
ofeveryclassfromtheJavaSEplatformAPIdocumentation.Thepurposeisnotto
documenttheJavaSEplatformAPI.TheemphasisismoreontheJavaprogramming
languagefeatures—theirsyntaxandcorrectusagethroughcodeexamples—andlesson
teachingprogrammingtechniques.
Thebookassumeslittlebackgroundinprogramming.Webelievetheexamisaccessibleto
anyprogrammerwhoworksthroughthebook.AJavaprogrammercaneasilyskipover
materialthatiswellunderstoodandconcentrateonpartsthatneedreinforcing,whereasa
programmernewtoJavawillfindtheconceptsexplainedfrombasicprinciples.
Eachtopicisexplainedanddiscussedthoroughlywithexamples,andbackedbyreview
questionsandexercisestoreinforcetheconcepts.Thebookisnotbiasedtowardany
particularplatform,butprovidesplatform-specificdetailswherenecessary.
UsingThisBook
Thereadercanchoosealinearoranonlinearroutethroughthebook,dependingonhisor
herprogrammingbackground.Non-JavaprogrammerswishingtomigratetoJavacanread
Chapter1,whichprovidesashortintroductiontoobject-orientedprogrammingconcepts,
andtheprocedureforcompilingandrunningJavaapplications.Forthosepreparingfor
JavaSE8ProgrammerIexam,thebookhasaseparateappendix(AppendixA)providing
allthepertinentinformationonpreparingforandtakingtheexam.
Cross-referencesareprovidedwherenecessarytoindicatetherelationshipsamongthe
variousconstructsofthelanguage.Tounderstandalanguageconstruct,allpertinent
detailsareprovidedwheretheconstructiscovered,butinaddition,cross-referencesare
providedtoindicateitsrelationshiptootherconstructs.Sometimesitisnecessaryto
postponediscussionofcertainaspectsofatopiciftheydependonconceptsthathavenot
yetbeencoveredinthebook.Atypicalexampleistheconsequencesofobject-oriented
programmingconcepts(forexample,inheritance)onthememberdeclarationsthatcan
occurinaclass.Thisapproachcanresultinforwardreferencesintheinitialchaptersof
thebook.
Thetableofcontents;listingsoftables,examples,andfigures;andacomprehensiveindex
facilitatelocatingtopicsdiscussedinthebook.
Inparticular,wedrawattentiontothefollowingfeaturesofthebook:
WOW! eBook
www.wowebook.org
ProgrammerIExamObjectives
0.1Examobjectivesarestatedclearlyatthebeginningofeverychapter.
0.2Thenumberinfrontoftheobjectiveidentifiestheexamobjective,asdefined
byOracle,andcanbefoundinAppendixB.
0.3Theobjectivesareorganizedintomajorsections,detailingthecurriculumfor
theexam.
0.4TheobjectivesfortheJavaSE8ProgrammerIexamarereproducedverbatim
inAppendixB,whereforeachsectionofthesyllabus,referencesareincludedto
pointthereadertorelevanttopicsinthebook.
SupplementaryObjectives
•Supplementaryobjectivescovertopicsthatarenotontheexam,butwhichwe
believeareimportantformasteringthetopicsthatareontheexam.
•Anysupplementaryobjectiveislistedasabulletatthebeginningofthechapter.
ReviewQuestions
Reviewquestionsareprovidedaftereverymajortopictotestandreinforcethematerial.
Thereviewquestionspredominantlyreflectthekindofmultiple-choicequestionsthatcan
beaskedontheactualexam.Ontheexam,theexactnumberofanswerstochooseforeach
questionisexplicitlystated.Thereviewquestionsinthisbookfollowthatpractice.
Manyquestionsontheactualexamcontaincodesnippetswithlinenumberstoindicate
thatcompleteimplementationisnotprovided,andthatthenecessarymissingcodeto
compileandrunthecodesnippetscanbeassumed.Thereviewquestionsinthisbook
providecompletecodeimplementationswherepossible,sothatthecodecanbereadily
compiledandrun.
AnnotatedanswerstothereviewquestionsareprovidedinAppendixC.
WOW! eBook
www.wowebook.org
Example0.1ExampleSourceCode
Weencouragereaderstoexperimentwiththecodeexamplestoreinforcethematerialfrom
thebook.Theseexamplescanbedownloadedfromthebookwebsite(seep.xxxiv).
Javacodeispresentedinamonospacedfont.Linesofcodeintheexamplesorin
codesnippetsarereferencedinthetextbyanumber,whichisspecifiedbyusingasingle-
linecommentinthecode.Forexample,inthefollowingcodesnippet,thecalltothe
methoddoSomethingInteresting()at(1)doessomethinginteresting:
Clickheretoviewcodeimage
//…
doSomethingInteresting();//
(1)
//…
Namesofclassesandinterfacesstartwithanuppercaseletter.Namesofpackages,
variables,andmethodsstartwithalowercaseletter.Constantsareinalluppercaseletters.
InterfacenamesbeginwiththeprefixI,whenitmakessensetodistinguishthemfrom
classnames.Codingconventionsarefollowed,exceptwhenwehavehadtodeviatefrom
theseconventionsintheinterestofspaceorclarity.
ChapterSummary
Eachchapterconcludeswithasummaryofthetopicscoveredinthechapter,pointingout
themajorconceptsthatwereintroduced.
ProgrammingExercises
Programmingexercisesattheendofeachchapterprovidetheopportunitytoputconcepts
intopractice.SolutionstotheprogrammingexercisesareprovidedinAppendixD.
MockExam
ThemockexaminAppendixEshouldbeattemptedwhenthereaderfeelsconfidentabout
thetopicsontheexam.ItishighlyrecommendedtoreadAppendixAbeforeattempting
themockexam,asAppendixAcontainspertinentinformationaboutthequestionsto
expectontheactualexam.Eachmultiple-choicequestioninthemockexamexplicitly
stateshowmanyanswersareapplicableforagivenquestion,asisthecaseontheactual
exam.AnnotatedanswerstothequestionsinthemockexamareprovidedinAppendixF.
JavaSEPlatformAPIDocumentation
Averticalgraybarisusedtohighlightmethodsandfieldsfoundintheclassesof
theJavaSEPlatformAPI.
AnyexplanationfollowingtheAPIinformationisalsosimilarlyhighlighted.
WOW! eBook
www.wowebook.org
ToobtainthemaximumbenefitfromusingthisbookinpreparingfortheJavaSE8
ProgrammerIexam,westronglyrecommendinstallingthelatestversion(Release8or
newer)oftheJDKanditsaccompanyingAPIdocumentation.Thebookfocusessolelyon
Java8,anddoesnotacknowledgepreviousversions.
BookWebsite
Thisbookisbackedbyawebsiteprovidingauxiliarymaterial:
www.ii.uib.no/~khalid/ocajp8/
Thecontentsofthewebsiteincludethefollowing:
•Sourcecodeforalltheexamplesinthebook
•Solutionstotheprogrammingexercisesinthebook
•Annotatedanswerstothereviewsquestionsinthebook
•Annotatedanswerstothemockexaminthebook
•Tableofcontents,samplechapter,andindexfromthebook
•Errataforthebook
•LinkstomiscellaneousJavaresources(e.g.,certification,discussiongroups,tools)
InformationabouttheJavaStandardEdition(SE)anditsdocumentationcanbefoundat
thefollowingwebsite:
www.oracle.com/technetwork/java/javase/overview/index.html
ThecurrentauthoritativetechnicalreferencefortheJavaprogramminglanguage,The
Java®LanguageSpecification:JavaSE8Edition(alsopublishedbyAddison-Wesley),
canbefoundatthiswebsite:
http://docs.oracle.com/javase/specs/index.html
RequestforFeedback
Considerableefforthasbeenmadetoensuretheaccuracyofthecontentofthisbook.All
codeexamples(includingcodefragments)havebeencompiledandtestedonvarious
platforms.Inthefinalanalysis,anyerrorsremainingarethesoleresponsibilityofthe
authors.
Anyquestions,comments,suggestions,andcorrectionsarewelcome.Letusknow
whetherthebookwashelpful(ornot)foryourpurpose.Anyfeedbackisvaluable.The
principalauthorcanbereachedatthefollowingemailaddress:
khalid.mughal@uib.no
RegisteryourcopyofAProgrammer’sGuidetoJava®SE8OracleCertifiedAssociate
(OCA)atinformit.comforconvenientaccesstodownloads,updates,andcorrectionsas
theybecomeavailable.Tostarttheregistrationprocess,gotoinformit.com/registerand
loginorcreateanaccount.EntertheproductISBN(9780132930215)andclickSubmit.
Oncetheprocessiscomplete,youwillfindanyavailablebonuscontentunder“Registered
WOW! eBook
www.wowebook.org
Products.”
AbouttheAuthors
KhalidA.Mughal
KhalidA.MughalisanassociateprofessorattheDepartmentofInformaticsatthe
UniversityofBergen,Norway,wherehehasbeenresponsiblefordesigningand
implementingvariouscoursesininformatics.Overtheyears,hehastaughtprogramming
(primarilyJava),softwareengineering(object-orientedsystemdevelopment),databases
(datamodelinganddatabasemanagementsystems),compilertechniques,webapplication
development,andsoftwaresecuritycourses.For15years,hewasresponsiblefor
developingandrunningweb-basedprogrammingcoursesinJava,whichwereofferedto
off-campusstudents.Hehasalsogivennumerouscoursesandseminarsatvariouslevels
inobject-orientedprogrammingandsystemdevelopmentusingJavaandJava-related
technologies,bothattheUniversityofBergenandfortheITindustry.
Mughalistheprincipalauthorandsolelyresponsibleforthecontentsofthisbook.Heis
alsotheprincipalauthorofthreebooksonpreviousversionsoftheJavaprogrammer
certification—AProgrammer’sGuidetoJava™SCJPCertification:AComprehensive
Primer,ThirdEdition(0321556054);AProgrammer’sGuidetoJava™Certification:A
ComprehensivePrimer,SecondEdition(0201728281);andAProgrammer’sGuideto
Java™Certification(0201596148)—andthreeintroductorytextbooksonprogrammingin
Java:JavaActually:AFirstCourseinProgramming(1844804186);JavaActually:A
ComprehensivePrimerinJavaProgramming(1844809331);andJavasomførste
programmeringsspråk/JavaasFirstProgrammingLanguage,ThirdEdition
(8202245540).
Mughalcurrentlyworksonsecurityissuesrelatedtomobiledatacollectionsystemsfor
deliveringhealthservicesinlow-andmiddle-incomecountries.
RolfW.Rasmussen
RolfW.RasmussenisasystemdevelopmentmanageratVizrt,acompanythatdevelops
solutionsfortheTVbroadcastindustry,includingreal-time3Dgraphicrenderers,and
contentandcontrolsystems.Rasmussenworksmainlyoncontrolandautomationsystems,
videoprocessing,typography,andreal-timevisualization.Hehasworkedonclean-room
implementationsoftheJavaclasslibrariesinthepastandisacontributortotheFree
SoftwareFoundation.
Overtheyears,Rasmussenhasworkedbothacademicallyandprofessionallywith
numerousprogramminglanguages,includingJava.Hewasprimarilyresponsiblefor
developingthereviewquestionsandanswers,theprogrammingexercisesandtheir
solutions,themockexam,andallthepracticalaspectsrelatedtotakingtheexaminour
threepreviousbooksonJavaprogrammercertification.Selectedearliercontenthasbeen
utilizedinthisbook.TogetherwithMughal,heisalsoaco-authorofthreeintroductory
textbooksonprogramminginJava.
WOW! eBook
www.wowebook.org
Acknowledgments
AtAddison-Wesley,GregDoenchwasagainoureditor,whoeffectivelymanagedthe
processofpublishingthisbook.Regulardialogwithhiminrecentmonthshelpedtokeep
thisprojectontrack.JulieNahilwasthein-housecontactatAddison-Wesley,who
professionallymanagedtheproductionofthebook.AnnaPopickwastheprojecteditor,
whodiligentlyhandledtheday-to-dayprojectmanagementforthisbook.JillHobbsdida
trulymarvelousjobcopyeditingthebook.ThefolksatTheCIPGroupperformedthe
typesettingwizardrynecessarytomaterializethebook.Wewouldliketoextendour
sincerethankstoGreg,Julie,Anna,Jill,thefolksatTheCIPGroup,andallthosebehind
thescenesatAddison-Wesley,whohelpedtoputthispublicationonthebookshelf.
Forthetechnicalreviewofthebook,wewereluckythatRoelDeNijsagreedtotakeon
thetask.IfyoudropinonCodeRanch.com,youareboundtofindhimexecutinghis
dutiesasaSheriff,especiallyhelpinggreenhornsfindtheirbearingintheJava
certificationcorrals.HeisafreelanceJavadeveloperwithmanyITcompaniesasclients
andamultitudeofJavacertificationaccoladesunderhisbelt(SCJA,SCJP,SCJD,
OCAJP7).Andnotleast,heisaTechnicalReviewerParExcellence.Withoutdoubt,Roel
hasameticulouseyefordetail.Itisnoexaggerationtosaythathisexhaustivefeedback
hasbeeninvaluableinimprovingthequalityofthisbookatalllevels.Roel,youhaveour
mostsincerethanksforyourmanyexcellentcommentsandsuggestions,andaboveall,for
weedingoutnumerouspeskyerrorsinthemanuscript.
Overtheyears,wehavealsobeenluckytohaveourownpersonalmanuscriptquality
controller:MaritSeljeflotMughal.Asdiligentlyaswithourpreviousbooks,shetirelessly
proofreadseveralchapterdraftsforthisbook,andputherfingeronmanyunmentionable
mistakesanderrorsinthemanuscript.Hervaluablecommentsandsuggestionshavealso
beeninstrumentalinimprovingthequalityofthisbook.IfMarit,whohasnoIT
background,couldmakesenseoftheJavajargonwewrote,thenwewereconfidentour
readerswouldaswell.Ourmostsincerethanks.
Greatefforthasbeenmadetoeliminatemistakesanderrorsinthisbook.Weacceptfull
responsibilityforanyremainingoversights.WehopethatwhenourDearReadersfind
any,theywillbringthemtoourattention.
Manyfamilyoccasionshavebeenmissedwhileworkingonthisbook.Withoutfamily
support,thisbookwouldnothaveseenthelightofday.Khalidisevergratefultohis
familyfortheirlove,support,andunderstanding—butespeciallywhenheisworkingona
book.Nowthatthisbookisoutthedoor,heisofftoplaywithhisthreegrandchildren.
—KhalidA.Mughal
17May2016
Bergen,Norway
WOW! eBook
www.wowebook.org
1.BasicsofJavaProgramming
1.1Introduction
BeforeembarkingontheroadtoJavaprogrammercertification,itisimportantto
understandthebasicterminologyandconceptsinobject-orientedprogramming(OOP).In
thischapter,theemphasisisonprovidinganintroductiontoOOP,ratherthanexhaustive
coverage.In-depthcoverageoftheconceptsfollowsinsubsequentchaptersofthebook.
Javasupportsthewritingofmanydifferentkindsofexecutables:applications,applets,and
servlets.ThebasicelementsofaJavaapplicationareintroducedinthischapter.Theold
adagethatpracticemakesperfectiscertainlytruewhenlearningaprogramminglanguage.
Toencourageprogrammingonthecomputer,themechanicsofcompilingandrunninga
Javaapplicationareoutlined.
1.2Classes
Oneofthefundamentalwaysinwhichwehandlecomplexityisbyusingabstractions.An
abstractiondenotestheessentialpropertiesandbehaviorsofanobjectthatdifferentiateit
fromotherobjects.TheessenceofOOPismodelingabstractions,usingclassesand
objects.Thehardpartofthisendeavorisfindingtherightabstraction.
Aclassdenotesacategoryofobjects,andactsasablueprintforcreatingobjects.Aclass
modelsanabstractionbydefiningthepropertiesandbehaviorsfortheobjectsrepresenting
theabstraction.Anobjectexhibitsthepropertiesandbehaviorsdefinedbyitsclass.The
propertiesofanobjectofaclassarealsocalledattributes,andaredefinedbyfieldsin
Java.Afieldinaclassisavariablethatcanstoreavaluethatrepresentsaparticular
WOW! eBook
www.wowebook.org
propertyofanobject.Thebehaviorsofanobjectofaclassarealsoknownasoperations,
andaredefinedusingmethodsinJava.Fieldsandmethodsinaclassdeclarationare
collectivelycalledmembers.
Animportantdistinctionismadebetweenthecontractandtheimplementationthataclass
providesforitsobjects.Thecontractdefineswhichservicesareprovided,andthe
implementationdefineshowtheseservicesareprovidedbytheclass.Clients(i.e.,other
objects)needtoknowonlythecontractofanobject,andnotitsimplementation,toavail
themselvesoftheobject’sservices.
Asanexample,wewillimplementdifferentversionsofaclassthatmodelstheabstraction
ofastackthatcanpushandpopcharacters.Thestackwilluseanarrayofcharactersto
storethecharacters,andafieldtoindicatethetopelementinthestack.UsingUnified
ModelingLanguage(UML)notation,aclasscalledCharStackisgraphicallydepicted
inFigure1.1,whichmodelstheabstraction.Bothfieldsandmethodnamesareshownin
Figure1.1a.
Figure1.1UMLNotationforClasses
DeclaringMembers:FieldsandMethods
Example1.1showsthedeclarationoftheclassCharStackdepictedinFigure1.1.Its
intentionistoillustratethesalientfeaturesofaclassdeclarationinJava,ratherthanan
effectiveimplementationofstacks.Thecharactersequence//inthecodeindicatesthe
startofasingle-linecommentthatcanbeusedtodocumentthecode.Allcharactersafter
thissequenceandtotheendofthelineareignoredbythecompiler.
Aclassdeclarationcontainsmemberdeclarationsthatdefinethefieldsandthemethodsof
theobjectstheclassrepresents.InthecaseoftheclassCharStack,ithastwofields
declaredat(1):
•stackArray,whichisanarraytoholdtheelementsofthestack(inthiscase,
characters)
•topOfStack,whichdenotesthetopelementofthestack(i.e.,theindexofthelast
characterstoredinthearray)
WOW! eBook
www.wowebook.org
TheclassCharStackhasfivemethods,declaredat(3),thatimplementtheessential
operationsonastack:
•push()pushesacharacterontothestack.
•pop()removesandreturnsthetopelementofthestack.
•peek()returnsthetopelementofthestackforinspection.
•isEmpty()determineswhetherthestackisempty.
•isFull()determineswhetherthestackisfull.
Theclassdeclarationalsohasamethod-likedeclarationat(2)withthesamenameasthe
class.Suchdeclarationsarecalledconstructors.Asweshallsee,aconstructorisexecuted
whenanobjectiscreatedfromtheclass.However,theimplementationdetailsinthe
examplearenotimportantforthepresentdiscussion.
Example1.1BasicElementsofaClassDeclaration
Clickheretoviewcodeimage
//File:CharStack.java
publicclassCharStack{//Classname
//ClassDeclarations:
//Fields:(1)
privatechar[]stackArray;//Thearrayimplementingthestack
privateinttopOfStack;//Thetopofthestack
//Constructor:(2)
publicCharStack(intcapacity){
stackArray=newchar[capacity];
topOfStack=-1;
}
//Methods:(3)
publicvoidpush(charelement){stackArray[++topOfStack]=element;}
publiccharpop(){returnstackArray[topOfStack—];}
publiccharpeek(){returnstackArray[topOfStack];}
publicbooleanisEmpty(){returntopOfStack==-1;}
publicbooleanisFull(){returntopOfStack==stackArray.length-
1;}
}
1.3Objects
ClassInstantiation,ReferenceValues,andReferences
Theprocessofcreatingobjectsfromaclassiscalledinstantiation.Anobjectisan
instanceofaclass.Theobjectisconstructedusingtheclassasablueprintandisa
concreteinstanceoftheabstractionthattheclassrepresents.Anobjectmustbecreated
beforeitcanbeusedinaprogram.
Areferencevalueisreturnedwhenanobjectiscreated.Areferencevaluedenotesa
particularobject.Avariabledenotesalocationinmemorywhereavaluecanbestored.
Anobjectreference(orsimplyreference)isavariablethatcanstoreareferencevalue.
WOW! eBook
www.wowebook.org
Thusareferenceprovidesahandletoanobject,asitcanindirectlydenoteanobjectwhose
referencevalueitholds.InJava,anobjectcanbemanipulatedonlyviaitsreferencevalue,
orequivalentlybyareferencethatholdsitsreferencevalue.
Thissetupformanipulatingobjectsrequiresthatareferencebedeclared,aclassbe
instantiatedtocreateanobject,andthereferencevalueoftheobjectcreatedbestoredin
thereference.Thesestepsareaccomplishedbyadeclarationstatement.
Clickheretoviewcodeimage
CharStackstack1=newCharStack(10);//Stacklength:10chars
Intheprecedingdeclarationstatement,theleft-handsideofthe=operatordeclaresthat
stack1isareferenceofclassCharStack.Thereferencestack1,therefore,canrefer
toobjectsofclassCharStack.
Theright-handsideofthe=operatorcreatesanobjectofclassCharStack.Thisstep
involvesusingthenewoperatorinconjunctionwithacalltoaconstructoroftheclass
(newCharStack(10)).ThenewoperatorcreatesaninstanceoftheCharStack
classandreturnsthereferencevalueofthisinstance.The=operator(calledthe
assignmentoperator)storesthereferencevalueinthereferencestack1declaredonthe
left-handsideoftheassignmentoperator.Thereferencestack1cannowbeusedto
manipulatetheobjectwhosereferencevalueisstoredinit.
Analogously,thefollowingdeclarationstatementdeclaresthereferencestack2tobeof
classCharStack,createsanobjectofclassCharStack,andassignsitsreferencevalue
tothereferencestack2:
Clickheretoviewcodeimage
CharStackstack2=newCharStack(5);//Stacklength:5chars
Eachobjectthatiscreatedhasitsowncopyofthefieldsdeclaredintheclassdeclaration
inExample1.1.Thatis,thetwostackobjects,referencedbystack1andstack2,will
havetheirownstackArrayandtopOfStackfields.
Thepurposeoftheconstructorcallontheright-handsideofthenewoperatoristo
initializethenewlycreatedobject.Inthisparticularcase,foreachnewCharStack
objectcreatedusingthenewoperator,theconstructorat(2)inExample1.1createsan
arrayofcharacters.Thelengthofthisarrayisgivenbythevalueoftheargumenttothe
constructor.TheconstructoralsoinitializesthetopOfStackfield.
Figure1.2showstheUMLnotationforobjects.Thegraphicalrepresentationofanobject
isverysimilartothatofaclass.Figure1.2showsthecanonicalnotation,wherethename
ofthereferencedenotingtheobjectisprefixedtotheclassnamewithacolon(:).Ifthe
nameofthereferenceisomitted,asinFigure1.2b,thisdenotesananonymousobject.
SinceobjectsinJavadonothavenames,butratheraredenotedbyreferences,amore
elaboratenotationisshowninFigure1.2c,wherereferencesoftheCharStackclass
explicitlyrefertoCharStackobjects.Inmostcases,themorecompactnotationwill
suffice.
WOW! eBook
www.wowebook.org
Figure1.2UMLNotationforObjects
ObjectAliases
Severalreferencescanrefertothesameobject,meaningthattheystorethereferencevalue
ofthesameobject.Suchreferencesarecalledaliases.Theobjectcanbemanipulatedvia
anyoneofitsaliases,aseachonereferstothesameobject.
Clickheretoviewcodeimage
//Createtwodistinctstacksofchars.
CharStackstackA=newCharStack(12);//Stacklength:12chars
CharStackstackB=newCharStack(6);//Stacklength:6chars
stackB=stackA;//(1)aliasesafterassignment
//ThestackpreviouslyreferencedbystackBcannowbegarbagecollected.
Twostackobjectsarecreatedintheprecedingcode.Beforetheassignmentat(1),the
situationisasdepictedinFigure1.3a.Aftertheassignmentat(1),thereferencesstackA
andstackBwilldenotethesamestack,asdepictedinFigure1.3b.Thereferencevalue
instackAisassignedtostackB.ThereferencesstackAandstackBarealiases
aftertheassignment,astheyrefertothesameobject.Whathappenstothestackobject
thatwasdenotedbythereferencestackBbeforetheassignment?Whenobjectsareno
longerinuse,theirmemoryis,ifnecessary,reclaimedandreallocatedforotherobjects.
Thisprocessiscalledautomaticgarbagecollection.GarbagecollectioninJavaistaken
careofbytheruntimeenvironment.
WOW! eBook
www.wowebook.org
Figure1.3Aliases
1.4InstanceMembers
Eachobjectcreatedwillhaveitsowncopiesofthefieldsdefinedinitsclass.Thefieldsof
anobjectarecalledinstancevariables.Thevaluesoftheinstancevariablesinanobject
constituteitsstate.Twodistinctobjectscanhavethesamestateiftheirinstancevariables
havethesamevalues.Themethodsofanobjectdefineitsbehavior;suchmethodsare
calledinstancemethods.Itisimportanttonotethatthesemethodspertaintoeachobjectof
theclass.Incontrast,theimplementationofthemethodsissharedbyallinstancesofthe
class.Instancevariablesandinstancemethods,whichbelongtoobjects,arecollectively
calledinstancemembers,todistinguishthemfromstaticmembers,whichbelongtothe
classonly.Staticmembersarediscussedin§1.5.
InvokingMethods
Objectscommunicatebymessagepassing.Asaconsequence,anobjectcanbemadeto
exhibitaparticularbehaviorbysendingtheappropriatemessagetotheobject.InJava,this
isdonebycallingamethodontheobjectusingthebinarydot(.)operator.Amethodcall
spellsoutthecompletemessage:theobjectthatisthereceiverofthemessage,themethod
tobeinvoked,andtheargumentstobepassedtothemethod,ifany.Themethodinvoked
onthereceivercanalsosendinformationbacktothesender,viaasinglereturnvalue.The
methodcalledmustbeonethatisdefinedfortheobject;otherwise,thecompilerreports
anerror.
Clickheretoviewcodeimage
CharStackstack=newCharStack(5);//Createastack
stack.push(‘J’);//(1)Character‘J’pushed
charc=stack.pop();//(2)Onecharacterpoppedandreturned:‘J’
stack.printStackElements();//(3)Compile-timeerror:Nosuchmethodin
CharStack
Thesamplecodegivenhereinvokesmethodsontheobjectdenotedbythereference
WOW! eBook
www.wowebook.org
stack.Themethodcallat(1)pushesonecharacteronthestack,andthemethodcallat
(2)popsonecharacteroffthestack.Boththepush()andpop()methodsaredefinedin
theclassCharStack.Thepush()methoddoesnotreturnanyvalue,butthepop()
methodreturnsthecharacterpopped.Tryingtoinvokeamethodnamed
printStackElementsonthestackresultsinacompile-timeerror,asnosuchmethod
isdefinedintheclassCharStack.
Thedot(.)notationcanalsobeusedwithareferencetoaccessthefieldsofanobject.
Useofthedotnotationisgovernedbytheaccessibilityofthemember.Thefieldsinthe
classCharStackhaveprivateaccessibility,indicatingthattheyarenotaccessible
fromoutsidetheclass.ThusthefollowingcodeinaclientoftheCharStackclasswill
notcompile:
Clickheretoviewcodeimage
stack.topOfStack++;//Compile-timeerror:topOfStackisnotvisible.
1.5StaticMembers
Insomecases,certainmembersshouldbelongonlytotheclass;thatis,theyshouldnotbe
partofanyinstanceoftheclass.Asanexample,supposeaclasswantstokeeptrackof
howmanyobjectsoftheclasshavebeencreated.Definingacounterasaninstance
variableintheclassdeclarationfortrackingthenumberofobjectscreateddoesnotsolve
theproblem.Eachobjectcreatedwillhaveitsowncounterfield.Whichcountershould
thenbeupdated?Thesolutionistodeclarethecounterfieldasbeingstatic.Sucha
fieldiscalledastaticvariable.Itbelongstotheclass,ratherthantoanyspecificobjectof
theclass.Astaticvariableisinitializedwhentheclassisloadedatruntime.Similarly,a
classcanhavestaticmethodsthatbelongtotheclass,ratherthantoanyspecificobjectsof
theclass.Staticvariablesandstaticmethodsarecollectivelyknownasstaticmembers,
andaredeclaredwiththekeywordstatic.
Figure1.4showstheclassdiagramfortheclassCharStack.Ithasbeenaugmentedby
twostaticmembers,whosenamesareunderlined.Theaugmenteddefinitionofthe
CharStackclassisgiveninExample1.2.Thefieldcounterisastaticvariable
declaredat(1).Itwillbeallocatedandinitializedtothedefaultvalue0whentheclassis
loaded.EachtimeanobjectoftheCharStackclassiscreated,theconstructorat(2)is
executed.Theconstructorexplicitlyincrementsthecounterintheclass.Themethod
getInstanceCount()at(3)isastaticmethodbelongingtotheclass.Itreturnsthe
countervaluewhencalled.
WOW! eBook
www.wowebook.org
Figure1.4ClassDiagramShowingStaticMembersofaClass
Example1.2StaticMembersinClassDeclaration
Clickheretoviewcodeimage
//File:CharStack.java
publicclassCharStack{
//Instancevariables:
privatechar[]stackArray;//Thearrayimplementingthestack
privateinttopOfStack;//Thetopofthestack
//Staticvariable
privatestaticintcounter;//(1)
//Constructornowincrementsthecounterforeachobjectcreated.
publicCharStack(intcapacity){//(2)
stackArray=newchar[capacity];
topOfStack=-1;
counter++;
}
//Instancemethods:
publicvoidpush(charelement){stackArray[++topOfStack]=element;}
publiccharpop(){returnstackArray[topOfStack—];}
publiccharpeek(){returnstackArray[topOfStack];}
publicbooleanisEmpty(){returntopOfStack==-1;}
publicbooleanisFull(){returntopOfStack==stackArray.length-
1;}
//Staticmethod(3)
publicstaticintgetInstanceCount(){returncounter;}
}
Figure1.5showstheclassificationofthemembersintheclassCharStack,usingthe
terminologywehaveintroducedsofar.Table1.1providesasummaryoftheterminology
usedindefiningmembersofaclass.
WOW! eBook
www.wowebook.org
Figure1.5MembersofaClass
Table1.1TerminologyforClassMembers
Clientscanaccessstaticmembersintheclassbyusingtheclassname.Thefollowingcode
invokesthegetInstanceCount()methodintheclassCharStack:
Clickheretoviewcodeimage
intcount=CharStack.getInstanceCount();//Classnametoinvokestatic
method
Staticmemberscanalsobeaccessedviaobjectreferences,althoughdoingsoisconsidered
badstyle:
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
CharStackmyStack=newCharStack(20);
intcount=myStack.getInstanceCount();//Referenceinvokesstaticmethod
Staticmembersinaclasscanbeaccessedbothbytheclassnameandviaobject
references,butinstancememberscanbeaccessedonlybyobjectreferences.
1.6Inheritance
Therearetwofundamentalmechanismsforbuildingnewclassesfromexistingones:
inheritanceandaggregation.ItmakessensetoinheritfromanexistingclassVehicleto
defineaclassCar,sinceacarisavehicle.TheclassVehiclehasseveralparts;
therefore,itmakessensetodefineacompositeobjectoftheclassVehiclethathas
constituentobjectsofsuchclassesasEngine,Axle,andGearBox,whichmakeupa
vehicle.
Inheritanceisillustratedherebyanexamplethatimplementsastackofcharactersthatcan
printitselementsontheterminal.Thisnewstackhasallthepropertiesandbehaviorsof
theCharStackclass,alongwiththeadditionalcapabilityofprintingitselements.Given
thatthisprintablestackisastackofcharacters,itcanbederivedfromtheCharStack
class.ThisrelationshipisshowninFigure1.6.TheclassPrintableCharStackis
calledthesubclass,andtheclassCharStackiscalledthesuperclass.TheCharStack
classisageneralizationforallstacksofcharacters,whereastheclass
PrintableCharStackisaspecializationofstacksofcharactersthatcanalsoprint
theirelements.
Figure1.6ClassDiagramDepictingInheritanceRelationship
InJava,derivinganewclassfromanexistingclassrequirestheuseoftheextends
clauseinthesubclassdeclaration.Asubclasscanextendonlyonesuperclass.Thesubclass
caninheritmembersofthesuperclass.Thefollowingcodefragmentimplementsthe
PrintableCharStackclass:
Clickheretoviewcodeimage
classPrintableCharStackextendsCharStack{//(1)
//Instancemethod
publicvoidprintStackElements(){//(2)
//…implementationofthemethod…
}
//Theconstructorcallstheconstructorofthesuperclassexplicitly.
publicPrintableCharStack(intcapacity){super(capacity);}//(3)
}
WOW! eBook
www.wowebook.org
ThePrintableCharStackclassextendstheCharStackclassat(1).Implementing
theprintStackElements()methodinthePrintableCharStackclassrequires
accesstothefieldstackArrayfromthesuperclassCharStack.However,thisfieldis
privateand,therefore,notaccessibleinthesubclass.Thesubclasscanaccessthesefields
iftheaccessibilityofthefieldsischangedtoprotectedintheCharStackclass.Example
1.3usesaversionoftheclassCharStack,whichhasbeenmodifiedtosupportthis
access.ImplementationoftheprintStackElements()methodisshownat(2).The
constructorofthePrintableCharStackclassat(3)callstheconstructorofthe
superclassCharStacktoinitializethestackproperly.
Example1.3DefiningaSubclass
Clickheretoviewcodeimage
//File:CharStack.java
publicclassCharStack{
//Instancevariables
protectedchar[]stackArray;//Thearraythatimplementsthestack
protectedinttopOfStack;//Thetopofthestack
//TherestofthedefinitionisthesameasinExample1.2.
}
//File:PrintableCharStack.java
publicclassPrintableCharStackextendsCharStack{//(1)
//Instancemethod
publicvoidprintStackElements(){//(2)
for(inti=0;i<=topOfStack;i++)
System.out.print(stackArray[i]);//Printeachcharonterminal
System.out.println();
}
//Constructorcallstheconstructorofthesuperclassexplicitly.
PrintableCharStack(intcapacity){super(capacity);}//(3)
}
ObjectsofthePrintableCharStackclasswillrespondjustliketheobjectsofthe
CharStackclass,buttheyalsohavetheadditionalfunctionalitydefinedinthesubclass:
Clickheretoviewcodeimage
PrintableCharStackpcStack=newPrintableCharStack(3);
pcStack.push(‘H’);
pcStack.push(‘i’);
pcStack.push(‘!’);
pcStack.printStackElements();//Prints“Hi!”ontheterminal
1.7Associations:AggregationandComposition
Anassociationdefinesastaticrelationshipbetweenobjectsoftwoclasses.Onesuch
association,calledaggregation,expresseshowanobjectusesotherobjects.Javasupports
aggregationofobjectsbyreference,sinceobjectscannotcontainotherobjectsexplicitly.
Theaggregateobjectusuallyhasfieldsthatdenoteitsconstituentobjects.Aconstituent
objectcanbesharedwithotheraggregateobjects.
WOW! eBook
www.wowebook.org
Forexample,anobjectofclassAirplanemighthaveafieldthatdenotesanobjectof
classPilot.ThisPilotobjectofanAirplaneobjectmightbesharedamongother
aggregateobjects(notnecessarilyAirplaneobjects)oncethepilothasfinisheddutyon
oneairplane.Infact,thePilotobjectcanstillbeusedevenwhenitsAirplaneobject
nolongerexists.ThisaggregationrelationshipisdepictedbytheUMLdiagraminFigure
1.7(emptydiamond),showingthateachobjectoftheAirplaneclasshaszeroorone
objectofclassPilotassociatedwithit.
Figure1.7ClassDiagramDepictingAssociations
Theaggregateassociationcanbemadestrongeriftheconstituentobjectscannotbeshared
withotheraggregateobjects—forexample,anAirplaneobjectwithtwoWingobjects.
TheWingobjectscannotbesharedandcanexistonlywiththeirAirplaneobject;that
is,theAirplaneobjecthasownershipofitsWingobjects.Conversely,theWing
objectsareapartoftheirAirplaneobject.Thisstrongeraggregationassociationis
calledcompositionandisdepictedbytheUMLdiagraminFigure1.7(filleddiamond),
showingthateachobjectoftheAirplaneclassownstwoobjectsofclassWing.
InthecaseoftheCharStackclassusedintheearlierexamples,eachobjectofthisclass
hasafieldtostorethereferencevalueofanarrayobjectthatholdsthecharacters.Itwould
notbeagoodideatosharethisarraywithotherstackobjects.Thestackownsthearrayof
characters.Therelationshipbetweenthestackobjectanditsconstituentarrayobjectcan
beexpressedbycomposition(Figure1.8),showingthateachobjectoftheCharStack
classwillownonearrayobjectoftypecharassociatedwithit.
Figure1.8ClassDiagramDepictingComposition
1.8TenetsofJava
•CodeinJavamustbeencapsulatedinclasses.
WOW! eBook
www.wowebook.org
•TherearetwokindsofvaluesinJava:objectsthatareinstancesofclassesorarrays,
andatomicvaluesofprimitivedatatypes.
•Referencesstorereferencevaluesthatdenoteobjects,andareusedtomanipulate
objects.
•ObjectsinJavacannotcontainotherobjects;theycanonlyhavereferencestoother
objects.
•Duringexecution,reclamationofobjectsthatarenolongerinuseismanagedbythe
runtimeenvironment.
ReviewQuestions
1.1Whichstatementistrueaboutmethods?
Selecttheonecorrectanswer.
(a)Amethodisanimplementationofanabstraction.
(b)Amethodisanattributedefiningthepropertyofaparticularabstraction.
(c)Amethodisacategoryofobjects.
(d)Amethodisanoperationdefiningthebehaviorforaparticularabstraction.
(e)Amethodisablueprintformakingoperations.
1.2Whichstatementistrueaboutobjects?
Selecttheonecorrectanswer.
(a)Anobjectiswhatclassesareinstantiatedfrom.
(b)Anobjectisaninstanceofaclass.
(c)Anobjectisablueprintforcreatingconcreterealizationofabstractions.
(d)Anobjectisareference.
(e)Anobjectisavariable.
1.3Whichisthefirstlineofaconstructordeclarationinthefollowingcode?
Clickheretoviewcodeimage
publicclassCounter{//(1)
intcurrent,step;
publicCounter(intstartValue,intstepValue){//(2)
setCurrent(startValue);//(3)
setStep(stepValue);
}
publicintgetCurrent(){returncurrent;}//(4)
publicvoidsetCurrent(intvalue){current=value;}//(5)
publicvoidsetStep(intstepValue){step=stepValue;}//(6)
}
Selecttheonecorrectanswer.
(a)(1)
WOW! eBook
www.wowebook.org
(b)(2)
(c)(3)
(d)(4)
(e)(5)
(f)(6)
1.4GiventhatThingisaclass,howmanyobjectsandhowmanyreferencesare
createdbythefollowingcode?
Thingitem,stuff;
item=newThing();
Thingentity=newThing();
Selectthetwocorrectanswers.
(a)Oneobjectiscreated.
(b)Twoobjectsarecreated.
(c)Threeobjectsarecreated.
(d)Onereferenceiscreated.
(e)Tworeferencesarecreated.
(f)Threereferencesarecreated.
1.5Whichstatementistrueaboutinstancemembers?
Selecttheonecorrectanswer.
(a)Aninstancememberisalsocalledastaticmember.
(b)Aninstancememberisalwaysafield.
(c)Aninstancememberisneveramethod.
(d)Aninstancememberbelongstoaninstance,nottotheclassasawhole.
(e)Aninstancememberalwaysrepresentsanoperation.
1.6HowdoobjectscommunicateinJava?
Selecttheonecorrectanswer.
(a)Theycommunicatebymodifyingeachother’sfields.
(b)Theycommunicatebymodifyingthestaticvariablesofeachother’sclasses.
(c)Theycommunicatebycallingeachother’sinstancemethods.
(d)Theycommunicatebycallingstaticmethodsofeachother’sclasses.
1.7Giventhefollowingcode,whichstatementsaretrue?
classA{
protectedintvalue1;
}
classBextendsA{
WOW! eBook
www.wowebook.org
intvalue2;
}
Selectthetwocorrectanswers.
(a)ClassAextendsclassB.
(b)ClassBisthesuperclassofclassA.
(c)ClassAinheritsfromclassB.
(d)ClassBisasubclassofclassA.
(e)ObjectsofclassAhaveafieldnamedvalue2.
(f)ObjectsofclassBhaveafieldnamedvalue1.
1.8Giventhefollowingcode,whichstatementsexpressthemostaccurateassociation?
Clickheretoviewcodeimage
classCarriage{}
classTrainDriver{}
classTrain{
privateCarriage[]carriages;
privateTrainDriverdriver;
Train(TrainDrivertrainDriver,intnoOfCarriages){
carriages=newCarriage[noOfCarriages];
driver=trainDriver;
}
voidinsertCarriage(CarriagenewCarriage){/*…*/}
}
Selectthethreecorrectanswers.
(a)ATrainobjecthasanarrayofCarriageobjects.
(b)ATrainobjectownsanarrayofCarriageobjects.
(c)ATrainobjectownsCarriageobjects.
(d)ATrainobjecthasaTrainDriverobject.
(e)ATrainobjectownsaTrainDriverobject.
(f)ATrainDriverobjectispartofaTrainobject.
(g)AnarrayofCarriageobjectsispartofaTrainobject.
(h)CarriageobjectsarepartofaTrainobject.
WOW! eBook
www.wowebook.org
1.9JavaPrograms
AJavasourcefilecancontainmorethanoneclassdeclaration.Eachsourcefilenamehas
theextension.java.TheJDK(JavaDevelopmentKit)enforcestherulethatanyclassin
thesourcefilethathaspublicaccessibilitymustbedeclaredinitsownfile,meaning
thatsuchapublicclassmustbedeclaredinasourcefilewhosefilenamecomprisesthe
nameofthispublicclasswith.javaasitsextension.Thisruleimpliesthatasourcefile
cancontainatmostonepublicclass.Ifthesourcefilecontainsapublicclass,thefile
namingruleisenforcedbytheJDK.
Eachclassdeclarationinasourcefileiscompiledintoaseparateclassfile,containing
Javabytecode.Thenameofthisfilecomprisesthenameoftheclasswith.classasits
extension.TheJDKprovidestoolsforcompilingandrunningprograms,asexplainedin
thenextsection.TheclassesintheJavaSEplatformAPIarealreadycompiled,andthe
JDKtoolsknowwheretofindthem.
1.10SampleJavaApplication
Thetermapplicationisjustasynonymforaprogram,referringtosourcecodethatis
compiledanddirectlyexecuted.TocreateanapplicationinJava,theprogrammusthavea
classthatdefinesamethodnamedmain,whichisthestartingpointfortheexecutionof
anyapplication.
EssentialElementsofaJavaApplication
Example1.4isanexampleofanapplicationinwhichaclientusestheCharStackclass
toreverseastringofcharacters.
WOW! eBook
www.wowebook.org
Example1.4AnApplication
Clickheretoviewcodeimage
//File:CharStack.java
publicclassCharStack{
//SameasinExample1.2.
}
//File:Client.java
publicclassClient{
publicstaticvoidmain(String[]args){
//Createastack.
CharStackstack=newCharStack(40);
//Createastringtopushonthestack:
Stringstr=“!notisotnuferaskcatS”;
System.out.println(“Originalstring:”+str);//(1)
intlength=str.length();
//Pushthestringcharbycharontothestack:
for(inti=0;i<length;i++){
stack.push(str.charAt(i));
}
System.out.print(“Reversedstring:“);//(2)
//Popandprinteachcharfromthestack:
while(!stack.isEmpty()){//Checkifthestackisnotempty.
System.out.print(stack.pop());
}
System.out.println();//(3)
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
Originalstring:!notisotnuferaskcatS
Reversedstring:Stacksarefuntositon!
ThepublicclassClientdefinesamethodwiththenamemain.Tostarttheapplication,
themain()methodinthispublicclassisinvokedbytheJavainterpreter,alsocalledthe
JavaVirtualMachine(JVM).Themethodheaderofthismain()methodmustbe
declaredasshowninthefollowingmethodstub:
Clickheretoviewcodeimage
publicstaticvoidmain(String[]args)//Methodheader
{/*Implementation*/}
Themain()methodhaspublicaccessibility—thatis,itisaccessiblefromanyclass.
Thekeywordstaticmeansthemethodbelongstotheclass.Thekeywordvoid
indicatesthatthemethoddoesnotreturnanyvalue.Theparameterargsisanarrayof
stringsthatcanbeusedtopassinformationtothemain()methodwhenexecutionstarts.
WOW! eBook
www.wowebook.org
CompilingandRunninganApplication
JavasourcefilescanbecompiledusingtheJavacompilertooljavac,whichispartof
theJDK.
ThesourcefileClient.javacontainsthedeclarationoftheClientclass.Thissource
filecanbecompiledbygivingthefollowingcommandatthecommandline(thecharacter
>isthecommandprompt):
>javacClient.java
ThiscommandcreatestheclassfileClient.classcontainingtheJavabytecodefor
theClientclass.TheClientclassusestheCharStackclass,andifthefile
CharStack.classdoesnotalreadyexist,thecompilerwillalsocompilethesource
fileCharStack.java.
CompiledclassescanbeexecutedbytheJavainterpreterjava,whichisalsopartofthe
JDK.TorunExample1.4,givethefollowingcommandonthecommandline:
Clickheretoviewcodeimage
>javaClient
Originalstring:!notisotnuferaskcatS
Reversedstring:Stacksarefuntositon!
Notethatonlythenameoftheclassisspecified,resultingintheexecutionstartinginthe
main()methodofthespecifiedclass.TheapplicationinExample1.4terminateswhen
theexecutionofthemain()methodiscompleted.
1.11ProgramOutput
Dataproducedbyaprogramiscalledoutput.Thisoutputcanbesenttodifferentdevices.
Theexamplespresentedinthisbooksendtheiroutputtoaterminalwindow,wherethe
outputisprintedaslineofcharacterswithacursorthatadvancesascharactersareprinted.
AJavaprogramcansenditsoutputtotheterminalwindowusinganobjectcalledstandard
out.Thisobject,whichcanbeaccessedusingthepublicstaticfinalfieldoutinthe
Systemclass,isanobjectoftheclassjava.io.PrintStreamthatprovidesmethods
forprintingvalues.Thesemethodsconvertvaluestotheirstringrepresentationandprint
theresultingstring.
Example1.4illustratestheprocessofprintingvaluestotheterminalwindow.The
argumentinthecalltotheprintln()methodat(1)isfirstevaluated,andtheresulting
stringisprintedtotheterminalwindow.Thismethodalwaysterminatesthecurrentline,
whichresultsinthecursorbeingmovedtothebeginningofthenextline:
Clickheretoviewcodeimage
System.out.println(“Originalstring:”+str);//(1)
Theprint()methodat(2)printsitsargumenttotheterminalwindow,butitdoesnot
terminatethecurrentline:
Clickheretoviewcodeimage
System.out.print(“Reversedstring:“);//(2)
WOW! eBook
www.wowebook.org
Toterminatealine,withoutprintinganyvalues,wecanusetheno-argumentprintln()
method:
Clickheretoviewcodeimage
System.out.println();//(3)
FormattedOutput
Tohavemorecontroloverhowthevaluesareprinted,wecancreateformattedoutput.The
followingmethodofthejava.io.PrintStreamclasscanbeusedforthispurpose:
Clickheretoviewcodeimage
PrintStreamprintf(Stringformat,Object…args)
TheStringparameterformatspecifieshowformattingwillbedone.Itcontains
formatspecificationsthatdeterminehoweachsubsequentvalueintheparameter
argswillbeformattedandprinted.TheparameterdeclarationObject…args
representsanarrayofzeroormoreargumentstobeformattedandprinted.The
resultingstringfromtheformattingwillbeprintedtothedestinationstream.
(System.outwillprinttothestandardoutobject.)
Anyerrorintheformatstringwillresultinaruntimeexception.
Thefollowingcalltotheprintf()methodonthestandardoutobjectformatsandprints
threevalues:
Clickheretoviewcodeimage
System.out.printf(“Formattedvalues|%5d|%8.3f|%5s|%n”,//Formatstring
2016,Math.PI,“Hi”);//Valuestoformat
Atruntime,thefollowinglineisprintedintheterminalwindow:
Clickheretoviewcodeimage
Formattedvalues|2016|3.142|Hi|
Theformatstringisthefirstargumentinthemethodcall.Itcontainsfourformat
specifiers.Thefirstthreeare%5d,%8.3f,and%5s,whichspecifyhowthethree
argumentsshouldbeprocessed.Theletterintheformatspecifierindicatesthetypeof
valuetoformat.Theirlocationintheformatstringspecifieswherethetextual
representationoftheargumentsshouldbeinserted.Thefourthformatspecifier,%n,isa
platform-specificlineseparator.Itsoccurrencecausesthecurrentlinetobeterminated,
withthecursormovingtothestartofthenextline.Allothertextintheformatstringis
fixed,includinganyotherspacesorpunctuation,andisprintedverbatim.
Intheprecedingexample,thefirstvalueisformattedaccordingtothefirstformat
specifier,thesecondvalueisformattedaccordingtothesecondformatspecifier,andso
on.The|characterhasbeenusedintheformatstringtoshowhowmanycharacter
positionsaretakenupbythetextrepresentationofeachvalue.Theoutputshowsthatthe
intvaluewaswrittenright-justified,spanningfivecharacterpositionsusingtheformat
specifier%5d;thedoublevalueofMath.PItookupeightcharacterpositionsandwas
roundedtothreedecimalplacesusingtheformatspecifier%8.3f;andtheStringvalue
WOW! eBook
www.wowebook.org
waswrittenright-justified,spanningfivecharacterpositionsusingtheformatspecifier
%5s.Theformatspecifier%nterminatesthecurrentline.Allothercharactersinthe
formatstringareprintedverbatim.
Table1.2showsexamplesofsomeselectedformatspecifiersthatcanbeusedtoformat
values.TheirusageisillustratedinExample1.5,whichprintsasimpleinvoice.
Table1.2FormatSpecifierExamples
AtthetopoftheinvoiceprintedbyExample1.5,thecompanynameisprintedat(1)with
aformatstringthatcontainsonlyfixedtext.Thedateandtimeofdayareprintedonthe
sameline,withleadingzerosat(2).Aheaderisthenprintedat(3).Thecolumnnames
WOW! eBook
www.wowebook.org
Item,Price,Quantity,andAmountarepositionedappropriatelywiththeformat
specifications%-20s,%7s,%9s,and%8s,respectively.
Beneaththeheading,theitemspurchasedareprintedat(5),(6),and(7)usingthesame
fieldwidthsasthecolumnheadings.Theformatforeachitemisdefinedbytheformat
stringat(4).Theitemnameisprintedwiththeformatstring"%-20s",resultingina20-
character-widestring,left-justified.Theitempriceandthetotalamountforeachtypeof
itemareprintedasfloating-pointvaluesusingtheformatspecifications%7.2fand
%8.2f,respectively.Thequantityisprintedasanintegerusingtheformatspecification
%9d.Thestringsareleft-justified,whileallnumbersareright-justified.Thecharactersis
theconversioncodeforobjects,whilefloating-pointandintegervaluesareprintedusing
thecodesfandd,respectively.
At(8),thetotalcostofallitemsisprintedusingtheformatspecification%8.2f.To
positionthisvaluecorrectlyunderthecolumnAmount,weprintthestring"Total:"
usingtheformat%-36s.Thewidthof36charactersisfoundbyaddingthewidthofthe
firstthreecolumnsoftheinvoice.
WOW! eBook
www.wowebook.org
Example1.5FormattedOutput
Clickheretoviewcodeimage
//File:Invoice.java
publicclassInvoice{
publicstaticvoidmain(String[]args){
System.out.printf(“SecureDataInc.”);//(1)
System.out.printf(“%02d/%02d/%04d,%02d:%02d%n%n”,//(2)
2,13,2016,11,5);
System.out.printf(“%-20s%7s%9s%8s%n”,//(3)
“Item”,“Price”,“Quantity”,“Amount”);
intquantity=4;
doubleprice=120.25,amount=quantity*price,total=amount;
StringitemFormat=“%-20s%7.2f%9d%8.2f%n”;//(4)
System.out.printf(itemFormat,
“FlashDrive,250GB”,price,quantity,amount);//(5)
quantity=2;
price=455.0;amount=quantity*price;total=total+amount;
System.out.printf(itemFormat,
“UltraHD,4TB”,price,quantity,amount);//(6)
quantity=1;
price=8.50;amount=quantity*price;total=total+amount;
System.out.printf(itemFormat,
“USB3.0cable”,price,quantity,amount);//(7)
System.out.printf(“%-36s%8.2f%n”,“Total:”,total);//(8)
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
SecureDataInc.02/13/2016,11:05
ItemPriceQuantityAmount
FlashDrive,250GB120.254481.00
UltraHD,4TB455.002910.00
USB3.0cable8.5018.50
Total:1399.50
1.12TheJavaEcosystem
SinceitsinitialreleaseasJavaDevelopmentKit1.0(JDK1.0)in1996,thenameJavahas
becomesynonymouswithathrivingecosystemthatprovidesthecomponentsandthetools
necessaryfordevelopingsystemsfortoday’smulticoreworld.Itsdiversecommunity,
comprisingamultitudeofvolunteers,organizations,andcorporations,continuestofuelits
evolutionandgrowwithitssuccess.Manyfreeopen-sourcetechnologiesnowexistthat
arewellproven,mature,andsupported,makingtheiradoptionlessdaunting.Thesetools
andframeworksprovidesupportforallphasesofthesoftwaredevelopmentlifecycleand
beyond.
TherearethreemajorJavaPlatformsfortheJavaprogramminglanguage:
•JavaSE(StandardEdition)
•JavaEE(EnterpriseEdition)
WOW! eBook
www.wowebook.org
•JavaME(MicroEdition)
Eachplatformprovidesahardware/operatingsystem–specificJVMandanAPI
(applicationprogramminginterface)todevelopapplicationsforthatplatform.TheJava
SEplatformprovidesthecorefunctionalityofthelanguage.TheJavaEEplatformisa
supersetoftheJavaSEplatformand,asthemostextensiveofthethreeplatforms,targets
enterpriseapplicationdevelopment.TheJavaMEplatformisasubsetoftheJavaSE
platform,havingthesmallestfootprint,andissuitablefordevelopingmobileand
embeddedapplications.TheupshotofthisclassificationisthataJavaprogramdeveloped
foroneJavaplatformwillnotnecessaryrunundertheJVMofanotherJavaplatform.The
JVMmustbecompatiblewiththeJavaplatformthatwasusedtodeveloptheprogram.
TheAPIandthetoolsfordevelopingandrunningJavaapplicationsarebundledtogether
asJDK.JusttheJVMandtheruntimelibrariesarealsobundledseparatelyasJRE(Java
RuntimeEnvironment).
ThesubjectofthisbookisJavaSE8.WerecommendinstallingtheappropriateJDKfor
JavaSE8(oranewerversion)dependingonthehardwareandoperatingsystem.
Therestofthissectionsummarizessomeofthefactorsthathavecontributedtothe
evolutionofJavafromanobject-orientedprogramminglanguagetoafull-fledged
ecosystemfordevelopingallsortsofsystems,includinglarge-scalebusinesssystemsand
embeddedsystemsforportablecomputingdevices.Alotofjargonisusedinthissection,
andmightbedifficulttounderstandatthefirstreading,butwerecommendcomingback
afterworkingthroughthebooktoappreciatethefactorsthathavecontributedtothe
successofJava.
Object-OrientedParadigm
TheJavaprogramminglanguagesupportstheobject-orientedparadigm,inwhichthe
propertiesofanobjectanditsbehaviorareencapsulatedintheobject.Thepropertiesand
thebehaviorarerepresentedbythefieldsandthemethodsoftheobject,respectively.The
objectscommunicatethroughmethodcallsinaproceduralmanner.Encapsulationensures
thatobjectsareimmunetotamperingexceptwhenmanipulatedthroughtheirpublic
interface.Encapsulationexposesonlywhatanobjectdoesandnothowitdoesit,sothat
itsimplementationcanbechangedwithminimumimpactonitsclients.Somebasic
conceptsofobject-orientedprogramming,suchasinheritanceandaggregation,were
introducedearlierinthischapter,andsubsequentchapterswillexpandonthistopic.
Aboveall,object-orientedsystemdevelopmentpromotescodereusewhereexisting
objectscanbereusedtoimplementnewobjects.Italsofacilitatesimplementationoflarge
systems,allowingtheirdecompositionintomanageablesubsystems.
WOW! eBook
www.wowebook.org
Interpreted:TheJVM
JavaprogramsarecompiledtobytecodethatisinterpretedbytheJVM.Various
optimizationtechnologies(e.g.,just-in-time[JIT]delivery)haveledtotheJVMbecoming
aleanandmeanvirtualmachinewithregardtoperformance,stability,andsecurity.Many
otherlanguages,suchasScala,Groovy,andClojure,nowcompiletobytecodeand
seamlesslyexecuteontheJVM.TheJVMhasthusevolvedintoanecosysteminitsown
right.
Architecture-NeutralandPortableBytecode
Theoften-citedslogan“Writeonce,runeverywhere”istrueonlyifacompatibleJVMis
availableforthehardwareandsoftwareplatform.Inotherwords,torunJavaSE
applicationsunderWindows10ona64-bithardwarearchitecture,therightJVMmustbe
installed.Fortunately,theJVMhasbeenportedtorunundermostplatformsandoperative
systemsthatexisttoday,includinghardwaredevicessuchassmartcards,mobiledevices,
andhomeappliances.
Thespecificationofthebytecodeisarchitectureneutral,meaningitisindependentofany
hardwarearchitecture.Itisexecutedbyareadilyavailablehardwareandoperating
system–specificJVM.TheportabilityoftheJavabytecodethuseasestheburdenofcross-
platformsystemdevelopment.
Simplicity
LanguagedesignofJavahasbeendrivenbyadesiretosimplifytheprogrammingprocess.
AlthoughJavaborrowsheavilyfromtheC++programminglanguage,certainfeaturesthat
weredeemedproblematicwerenotincorporatedintoitsdesign.Forexample,Javadoes
nothaveapreprocessor,anditdoesnotallowpointerhandling,user-definedoperator
overloading,ormultipleclassinheritance.
Javaoptedforautomaticgarbagecollection,whichfreestheprogrammerfromdealing
withmanyissuesrelatedtomemorymanagement,suchasmemoryleaks.
However,thejuryisstilloutonwhetherthesyntaxofnestedclassesorintroductionof
wildcardsforgenericscanbeconsideredsimple.
DynamicandDistributed
TheJVMcandynamicallyloadclasslibrariesfromthelocalfilesystemaswellasfrom
machinesonthenetwork,whenthoselibrariesareneededatruntime.Thisfeature
facilitateslinkingthecodeasandwhennecessaryduringtheexecutionofaprogram.Itis
alsopossibletoqueryprogrammaticallyaclassoranobjectatruntimeaboutitsmeta-
information,suchasitsmethodsandfields.
Javaprovidesextensivesupportfornetworkingtobuilddistributedsystems,whereobjects
areabletocommunicateacrossnetworksusingvariouscommunicationprotocolsand
technologies,suchasRemoteMethodInvocation(RMI)andsocketconnections.
WOW! eBook
www.wowebook.org
RobustandSecure
Javapromotesthedevelopmentofreliable,robust,andsecuresystems.Itisastrong
staticallytypedlanguage:Thecompilerguaranteesruntimeexecutionifthecodecompiles
withouterrors.Eliminationofpointers,runtimeindexchecksforarraysandstrings,and
automaticgarbagecollectionaresomeofthefeaturesofJavathatpromotereliability.The
exceptionhandlingfeatureofJavaiswithoutdoubtthemainfactorthatfacilitatesthe
developmentofrobustsystems.
Javaprovidesmultilevelprotectionfrommaliciouscode.Thelanguagedoesnotallow
directaccesstomemory.Abytecodeverifierdetermineswhetheranyuntrustedcode
loadedintheJVMissafe.Thesandboxmodelisusedtoconfineandexecuteany
untrustedcode,limitingthedamagethatsuchcodecancause.Thesefeatures,among
others,areprovidedbyacomprehensiveJavasecuritymodeltoensurethatapplication
codeexecutessecurelyintheJVM.
HighPerformanceandMultithreaded
TheperformanceofJavaprogramshasimprovedsignificantlywithvariousoptimizations
thatareappliedtothebytecodeatruntimebytheJVM.TheJITfeaturemonitorsthe
programatruntimetoidentifyperformance-criticalbytecode(calledhotspots)thatcanbe
optimized.Suchcodeisusuallytranslatedtomachinecodetoboostperformance.The
performanceachievedbytheJVMisabalancebetweennativecodeexecutionand
interpretationoffullyscriptedlanguages,whichfortunatelyisadequateformany
applications.
Javahasalwaysprovidedhigh-levelsupportformultithreading,allowingmultiplethreads
ofexecutiontoperformdifferenttasksconcurrentlyinanapplication.Ithasrisentothe
newchallengesthathaveemergedinrecentyearstoharnesstheincreasedcomputing
powermadeavailablebymulticorearchitectures.Functionalprogramming,inwhich
computationistreatedasside-effects–freeevaluationoffunctions,isseenasaboonto
meetthesechallenges.Java8bringselementsoffunctional-styleprogrammingintothe
language,providinglanguageconstructs(lambdaexpressionsandfunctionalinterfaces)
andAPIsupport(throughitsFork&JoinFrameworkandStreamAPI)toefficiently
utilizethemanycorestoprocesslargeamountsofdatainparallel.
ReviewQuestions
1.9WhichcommandfromtheJDKshouldbeusedtocompilethefollowingsource
codecontainedinafilenamedSmallProg.java?
Clickheretoviewcodeimage
publicclassSmallProg{
publicstaticvoidmain(String[]args){System.out.println(“Good
luck!”);}
}
Selecttheonecorrectanswer.
(a)javaSmallProg
WOW! eBook
www.wowebook.org
(b)javacSmallProg
(c)javaSmallProg.java
(d)javacSmallProg.java
(e)javaSmallProgmain
1.10WhichcommandfromtheJDKshouldbeusedtoexecutethemain()methodof
aclassnamedSmallProg?
Selecttheonecorrectanswer.
(a)javaSmallProg
(b)javacSmallProg
(c)javaSmallProg.java
(d)javaSmallProg.class
(e)javaSmallProg.main()
1.11WhichstatementistrueaboutJava?
Selecttheonecorrectanswer.
(a)AJavaprogramcanbeexecutedbyanyJVM.
(b)Javabytecodecannotbetranslatedtomachinecode.
(c)OnlyJavaprogramscanbeexecutedbyaJVM.
(d)AJavaprogramcancreateanddestroyobjects.
(e)Noneoftheabove
ChapterSummary
Thefollowingtopicswerecoveredinthischapter:
•EssentialelementsofaJavaapplication
•Accessingobjectfieldsandcallingmethods
•CompilingandrunningJavaapplications
•Formattingandprintingvaluestotheterminalwindow
•BasicterminologyandconceptsinOOP,andhowtheseconceptsaresupportedin
Java
•FactorsandfeaturesoftheJavaecosystemthathavecontributedtoitsevolutionand
success
WOW! eBook
www.wowebook.org
ProgrammingExercise
1.1ModifytheClientclassfromExample1.4tousethePrintableCharStack
class,ratherthantheCharStackclassfromExample1.2.Utilizethe
printStackElements()methodfromthePrintableCharStackclass.Is
thenewprogrambehavior-wiseanydifferentfromExample1.4?
WOW! eBook
www.wowebook.org
2.LanguageFundamentals
2.1BasicLanguageElements
Likeanyotherprogramminglanguage,theJavaprogramminglanguageisdefinedby
grammarrulesthatspecifyhowsyntacticallylegalconstructscanbeformedusingthe
languageelements,andbyasemanticdefinitionthatspecifiesthemeaningofsyntactically
legalconstructs.
LexicalTokens
Thelow-levellanguageelementsarecalledlexicaltokens(orjusttokens)andarethe
buildingblocksformorecomplexconstructs.Identifiers,numbers,operators,andspecial
charactersareallexamplesoftokensthatcanbeusedtobuildhigh-levelconstructslike
expressions,statements,methods,andclasses.
Identifiers
Anameinaprogramiscalledanidentifier.Identifierscanbeusedtodenoteclasses,
methods,variables,andlabels.
InJava,anidentifieriscomposedofasequenceofcharacters,whereeachcharactercanbe
eitheraletteroradigit.However,thefirstcharacterinanidentifiermustalwaysbea
letter,asexplainedlater.
SinceJavaprogramsarewrittenintheUnicodecharacterset(p.32),charactersallowedin
identifiernamesareinterpretedaccordingtothischaracterset.UseoftheUnicode
charactersetopensupthepossibilityofwritingidentifiernamesinmanywritingscripts
usedaroundtheworld.Asonewouldexpect,thecharactersA-Zanda-zareletters,and
charactersfrom0-9aredigits.Aconnectingpunctuationcharacter(suchasunderscore
_)andanycurrencysymbol(suchas$,¢,¥,or£)arealsoallowedaslettersinidentifier
names,butthesecharactersshouldbeusedjudiciously.
WOW! eBook
www.wowebook.org
IdentifiersinJavaarecasesensitive.Forexample,priceandPricearetwodifferent
identifiers.
ExamplesofLegalIdentifiers
Clickheretoviewcodeimage
number,Number,sum_$,bingo,$$_100,_007,mål,grüß
ExamplesofIllegalIdentifiers
48chevy,all@hands,grand-sum
Thename48chevyisnotalegalidentifierbecauseitstartswithadigit.Thecharacter@
isnotalegalcharacterinanidentifier.Itisalsonotalegaloperator,sothatall@hands
cannotbeinterpretedasalegalexpressionwithtwooperands.Thecharacter-isnota
legalcharacterinanidentifier,butitisalegaloperator;thusgrand-sumcouldbe
interpretedasalegalexpressionwithtwooperands.
Keywords
Keywordsarereservedwordsthatarepredefinedinthelanguageandcannotbeusedto
denoteotherentities.AllJavakeywordsarelowercase,andincorrectusageresultsin
compile-timeerrors.
KeywordscurrentlydefinedinthelanguagearelistedinTable2.1.Inaddition,three
identifiersarereservedaspredefinedliteralsinthelanguage:thenullreference,andthe
booleanliteralstrueandfalse(Table2.2).Keywordscurrentlyreserved,butnotin
use,arelistedinTable2.3.Areservedwordcannotbeusedasanidentifier.Theindex
containsreferencestorelevantsectionswherecurrentlyusedkeywordsareexplained.
Table2.1KeywordsinJava
Table2.2ReservedLiteralsinJava
WOW! eBook
www.wowebook.org
Table2.3ReservedKeywordsNotCurrentlyinUse
Separators
Separators(alsoknownaspunctuators)aretokensthathavemeaningdependingonthe
contextinwhichtheyareused;theyaidthecompilerinperformingsyntaxandsemantic
analysisofaprogram(Table2.4).Dependingonthecontext,brackets([]),parentheses
(()),andthedotoperator(.)canalsobeinterpretedasoperators(§5.3,p.150).Seethe
indexentriesfortheseseparatorsformoredetails.
Table2.4SeparatorsinJava
Literals
Aliteraldenotesaconstantvalue;inotherwords,thevaluethataliteralrepresents
remainsunchangedintheprogram.Literalsrepresentnumerical(integerorfloating-
point),character,boolean,orstringvalues.Inaddition,theliteralnullrepresentsthenull
reference.Table2.5showsexamplesofliteralsinJava.
Table2.5ExamplesofLiterals
IntegerLiterals
Integerdatatypescomprisethefollowingprimitivedatatypes:int,long,byte,and
short(§2.2,p.37).
Thedefaultdatatypeofanintegerliteralisalwaysint,butitcanbespecifiedaslong
byappendingthesuffixL(orl)totheintegervalue.ThesuffixLisoftenpreferred
becausethesuffixlandthedigit1canbehardtodistinguish.Withoutthesuffix,the
longliterals2000Land0Lwillbeinterpretedasintliterals.Thereisnodirectwayto
specifyashortorabyteliteral.
Inadditiontothedecimalnumbersystem,integerliteralscanbespecifiedinthebinary
(base2,digits0-1),octal(base8,digits0-7),andhexadecimal(base16,digits0-9and
a-f)numbersystems.Thedigitsatofinthehexadecimalsystemcorrespondtodecimal
values10to15.Binary,octal,andhexadecimalnumbersarespecifiedwith0b(or0B),
WOW! eBook
www.wowebook.org
0,and0x(or0X)asthebaseorradixprefix,respectively.Examplesofdecimal,binary,
octal,andhexadecimalliteralsareshowninTable2.6.Notethattheleading0(zero)digit
isnottheuppercaseletterO.Thehexadecimaldigitsfromatofcanalsobespecified
withthecorrespondinguppercaseforms(AtoF).Negativeintegers(e.g.,-90)canbe
specifiedbyprefixingtheminussign(-)tothemagnitudeoftheintegerregardlessofthe
numbersystem(e.g.,-0b1011010,-0132,or-0X5A).Integerrepresentationis
discussedin§5.5,p.154.
Table2.6ExamplesofDecimal,Binary,Octal,andHexadecimalLiterals
Floating-PointLiterals
Floating-pointdatatypescomeintwoflavors:floatordouble.
Thedefaultdatatypeofafloating-pointliteralisdouble,butitcanbeexplicitly
designatedbyappendingthesuffixD(ord)tothevalue.Afloating-pointliteralcanalso
bespecifiedtobeafloatbyappendingthesuffixF(orf).
Floating-pointliteralscanalsobespecifiedinscientificnotation,whereE(ore)standsfor
exponent.Forexample,thedoubleliteral194.9E-2inscientificnotationisinterpreted
as194.9×10-2(i.e.,1.949).
WOW! eBook
www.wowebook.org
ExamplesofdoubleLiterals
Clickheretoviewcodeimage
0.00.0d0D
0.49.49.49D
49.049.49D
4.9E+14.9E+1D4.9e1d4900e-2.49E2
ExamplesoffloatLiterals
0.0F0f
0.49F.49F
49.0F49.F49F
4.9E+1F4900e-2f.49E2F
Notethatthedecimalpointandtheexponentareoptional,andthatatleastonedigitmust
bespecified.Also,fortheexamplesoffloatliteralspresentedhere,thesuffixFis
mandatory;ifitwasomitted,theywouldbeinterpretedasdoubleliterals.
UnderscoresinNumericalLiterals
Theunderscorecharacter(_)canbeusedtoimprovethereadabilityofnumericalliterals
inthesourcecode.Anynumberofunderscorescanbeinsertedbetweenthedigitsthat
makeupthenumericalliteral.Thisrulesoutunderscoresadjacenttothesign(+,-),the
radixprefix(0b,0B,0x,0X),thedecimalpoint(.),theexponent(e,E),andthedata
typesuffix(l,L,d,D,f,F),aswellasbeforethefirstdigitandafterthelastdigit.Note
thatoctalradixprefix0ispartofthedefinitionofanoctalliteralandistherefore
consideredthefirstdigitofanoctalliteral.
Underscoresinidentifiersaretreatedasletters.Forexample,thenames_XXLand_XXL_
aretwodistinctlegalidentifiers.Incontrast,underscoresareusedasanotational
conveniencefornumericalliterals,beingignoredbythecompilerwhenusedinsuch
literals.Inotherwords,anumericalliteralcanbespecifiedinthesourcecodeusing
underscoresbetweendigits,suchthat2_0_1_5and20__15representthesame
numericalliteral2015insourcecode.
ExamplesofLegalUseofUnderscoresinNumericalLiterals
Clickheretoviewcodeimage
0b0111_1111_1111_1111_1111_1111_1111_1111
0_377_777_7770xff_ff_ff_ff
-123_456.001_2.345_678e1_2
2009__08__1349_03_01d
ExamplesofIllegalUseofUnderscoresinNumericalLiterals
Clickheretoviewcodeimage
_0_b_01111111111111111111111111111111_
_0377777777__0_x_ffffffff_
+_123456_._00__12_._345678_e_12_
_20090813__490301_d_
WOW! eBook
www.wowebook.org
BooleanLiterals
Theprimitivedatatypebooleanrepresentsthetruthvaluestrueandfalsethatare
denotedbythereservedliteralstrueandfalse,respectively.
CharacterLiterals
Acharacterliteralisquotedinsinglequotes(').Allcharacterliteralshavetheprimitive
datatypechar.
Acharacterliteralisrepresentedaccordingtothe16-bitUnicodecharacterset,which
subsumesthe8-bitISO-Latin-1andthe7-bitASCIIcharacters.InTable2.7,notethat
digits(0to9),uppercaseletters(AtoZ),andlowercaseletters(atoz)havecontiguous
Unicodevalues.AUnicodecharactercanalwaysbespecifiedasafour-digithexadecimal
number(i.e.,16bits)withtheprefix\u.
Table2.7ExamplesofCharacterLiterals
EscapeSequences
Certainescapesequencesdefinespecialcharacters,asshowninTable2.8.Theseescape
sequencescanbesingle-quotedtodefinecharacterliterals.Forexample,thecharacter
literals\tand\u0009areequivalent.However,thecharacterliterals\u000aand
\u000dshouldnotbeusedtorepresentnewlineandcarriagereturninthesourcecode.
Thesevaluesareinterpretedasline-terminatorcharactersbythecompiler,andwillcause
compile-timeerrors.Youshouldusetheescapesequences\nand\r,respectively,for
correctinterpretationofthesecharactersinthesourcecode.
WOW! eBook
www.wowebook.org
Table2.8EscapeSequences
Wecanalsousetheescapesequence\dddtospecifyacharacterliteralasanoctalvalue,
whereeachdigitdcanbeanyoctaldigit(0–7),asshowninTable2.9.Thenumberof
digitsmustbethreeorfewer,andtheoctalvaluecannotexceed\377;inotherwords,
onlythefirst256characterscanbespecifiedwiththisnotation.
Table2.9ExamplesofEscapeSequence\ddd
StringLiterals
Astringliteralisasequenceofcharactersthatmustbeenclosedindoublequotesand
mustoccuronasingleline.AllstringliteralsareobjectsoftheclassString(§8.4,p.
357).
EscapesequencesaswellasUnicodevaluescanappearinstringliterals:
Clickheretoviewcodeimage
“Herecomesatab.\tAndherecomesanotherone\u0009!”(1)
“What’sonthemenu?”(2)
“"Stringliteralsaredouble-quoted."”(3)
“Left!\nRight!”(4)
“Don’tsplit(5)
meup!”
In(1),thetabcharacterisspecifiedusingtheescapesequenceandtheUnicodevalue,
respectively.In(2),thesingleapostropheneednotbeescapedinstrings,butitwouldbeif
WOW! eBook
www.wowebook.org
specifiedasacharacterliteral('\'').In(3),thedoublequotesinthestringmustbe
escaped.In(4),weusetheescapesequence\ntoinsertanewline.Theexpressionin(5)
generatesacompile-timeerror,asthestringliteralissplitoverseverallines.Printingthe
stringsfrom(1)to(4)willgivethefollowingresult:
Clickheretoviewcodeimage
Herecomesatab.Andherecomesanotherone!
What’sonthemenu?
“Stringliteralsaredouble-quoted.”
Left!
Right!
Oneshouldalsousetheescapesequences\nand\r,respectively,forcorrect
interpretationofthecharacters\u000a(newline)and\u000d(formfeed)instring
literals.
Whitespace
Awhitespaceisasequenceofspaces,tabs,formfeeds,andlineterminatorcharactersina
Javasourcefile.Lineterminatorsincludethenewline,carriagereturn,oracarriage
return–newlinesequence.
AJavaprogramisafree-formatsequenceofcharactersthatistokenizedbythecompiler—
thatis,brokenintoastreamoftokensforfurtheranalysis.Separatorsandoperatorshelpto
distinguishtokens,butsometimeswhitespacehastobeinsertedexplicitlyasaseparator.
Forexample,theidentifierclassRoomwillbeinterpretedasasingletoken,unless
whitespaceisinsertedtodistinguishthekeywordclassfromtheidentifierRoom.
Whitespaceaidsnotonlyinseparatingtokens,butalsoinformattingtheprogramsothatit
iseasytoread.Thecompilerignoresthewhitespaceoncethetokensareidentified.
Comments
Aprogramcanbedocumentedbyinsertingcommentsatrelevantplacesinthesource
code.Thesecommentsarefordocumentationpurposesonlyandareignoredbythe
compiler.
Javaprovidesthreetypesofcommentsthatcanbeusedtodocumentaprogram:
•Asingle-linecomment://...totheendoftheline
•Amultiple-linecomment:/*...*/
•Adocumentation(Javadoc)comment:/**...*/'
Single-LineComment
Allcharactersafterthecomment-startsequence//throughtotheendoftheline
constituteasingle-linecomment.
Clickheretoviewcodeimage
//Thiscommentendsattheendofthisline.
intage;//Fromcomment-startsequencetotheendofthelineisa
comment.
WOW! eBook
www.wowebook.org
Multiple-LineComment
Amultiple-linecomment,asthenamesuggests,canspanseverallines.Suchacomment
startswiththesequence/*andendswiththesequence*/.
/*Acomment
onseveral
lines.
*/
Thecomment-startsequences(//,/*,/**)arenottreateddifferentlyfromother
characterswhenoccurringwithincomments,sotheyareignored.Thismeansthattryingto
nestmultiple-linecommentswillresultinacompile-timeerror:
Clickheretoviewcodeimage
/*Formulaforalchemy.
gold=wizard.makeGold(stone);
/*ButitonlyworksonSundays.*/
*/
Thesecondoccurrenceofthecomment-startsequence/*isignored.Thelastoccurrence
ofthesequence*/inthecodeisnowunmatched,resultinginasyntaxerror.
DocumentationComment
Adocumentationcommentisaspecial-purposemultiple-linecommentthatisusedbythe
javadoctooltogenerateHTMLdocumentationfortheprogram.Documentation
commentsareusuallyplacedinfrontofclasses,interfaces,methods,andfielddefinitions.
Specialtagscanbeusedinsideadocumentationcommenttoprovidemorespecific
information.Suchacommentstartswiththesequence/**andendswiththesequence
*/:
Clickheretoviewcodeimage
/**
*Thisclassimplementsagizmo.
*@authorK.A.M.
*@version4.0
*/
Fordetailsonthejavadoctool,seethetoolsdocumentationprovidedbytheJDK.
ReviewQuestions
2.1Whichofthefollowingisnotalegalidentifier?
Selecttheonecorrectanswer.
(a)a2z
(b)ödipus
(c)52pickup
(d)_class
(e)ca$h
WOW! eBook
www.wowebook.org
(f)_8to5
2.2WhichofthefollowingarenotlegalliteralsinJava?
Selectthefourcorrectanswers.
(a)0Xbad
(b)0B_101_101
(c)09
(d)+_825
(e)1_2e4f
(f)'\x'
(g)"what\'syourfancy?"
2.3Whichstatementistrue?
Selecttheonecorrectanswer.
(a)newanddeletearekeywordsintheJavalanguage.
(b)try,catch,andthrownarekeywordsintheJavalanguage.
(c)static,unsigned,andlongarekeywordsintheJavalanguage.
(d)exit,class,andwhilearekeywordsintheJavalanguage.
(e)return,goto,anddefaultarekeywordsintheJavalanguage.
(f)for,while,andnextarekeywordsintheJavalanguage.
2.4WhichofthefollowingisnotalegalcommentinJava?
Selecttheonecorrectanswer.
(a)/*//*/
(b)/**///
(c)///**/
(d)/*/**/
(e)/*/**/*/
(f)////
2.2PrimitiveDataTypes
Figure2.1givesanoverviewoftheprimitivedatatypesinJava.
WOW! eBook
www.wowebook.org
Figure2.1PrimitiveDataTypesinJava
PrimitivedatatypesinJavacanbedividedintothreemaincategories:
•Integraltypes—representsignedintegers(byte,short,int,long)and
unsignedcharactervalues(char)
•Floating-pointtypes(float,double)—representfractionalsignednumbers
•Booleantype(boolean)—representslogicalvalues
Primitivedatavaluesarenotobjects.Eachprimitivedatatypedefinestherangeofvalues
inthedatatype,andoperationsonthesevaluesaredefinedbyspecialoperatorsinthe
language(Chapter5,p.143).
Eachprimitivedatatypealsohasacorrespondingwrapperclassthatcanbeusedto
representaprimitivevalueasanobject.Wrapperclassesarediscussedin§8.3,p.346.
TheIntegerTypes
Theintegerdatatypesarebyte,short,int,andlong(Table2.10).Theirvaluesare
signedintegersrepresentedbytwo’scomplement(§5.5,p.155).
Table2.10RangeofIntegerValues
The Type
Thedatatypecharrepresentscharacters(Table2.11).Theirvaluesareunsignedintegers
thatdenoteallofthe65536(216)charactersinthe16-bitUnicodecharacterset.Thisset
includesletters,digits,andspecialcharacters.
WOW! eBook
www.wowebook.org
Table2.11RangeofCharacterValues
Thefirst128charactersoftheUnicodesetarethesameasthe128charactersofthe7-bit
ASCIIcharacterset,andthefirst256charactersoftheUnicodesetcorrespondtothe256
charactersofthe8-bitISOLatin-1characterset.
Theintegertypesandthechartypearecollectivelycalledintegraltypes.
TheFloating-PointTypes
Floating-pointnumbersarerepresentedbythefloatanddoubledatatypes.
Floating-pointnumbersconformtotheIEEE754-1985binaryfloating-pointstandard.
Table2.12showstherangeofvaluesforpositivefloating-pointnumbers,buttheseapply
equallytonegativefloating-pointnumberswiththeminussign(-)asaprefix.Zerocanbe
either0.0or-0.0.
Table2.12RangeofFloating-PointValues
Sincethesizeforrepresentationisafinitenumberofbits,certainfloating-pointnumbers
canberepresentedonlyasapproximations.Forexample,thevalueoftheexpression
(1.0/3.0)isrepresentedasanapproximationduetothefinitenumberofbitsusedto
representfloating-pointnumbers.
The Type
Thedatatypebooleanrepresentsthetwologicalvaluesdenotedbytheliteralstrue
andfalse(Table2.13).
Table2.13BooleanValues
Booleanvaluesareproducedbyallrelational(§5.11,p.180),conditional(§5.14,p.186),
andbooleanlogicaloperators(§5.13,p.184),andareprimarilyusedtogoverntheflow
ofcontrolduringprogramexecution.
Table2.14summarizesthepertinentfactsabouttheprimitivedatatypes:theirwidthor
WOW! eBook
www.wowebook.org
size,whichindicatesthenumberofbitsrequiredtostoreaprimitivevalue;theirrangeof
legalvalues,whichisspecifiedbytheminimumandthemaximumvaluespermissible;
andthenameofthecorrespondingwrapperclass(§8.3,p.346).
Table2.14SummaryofPrimitiveDataTypes
ReviewQuestions
2.5WhichofthefollowingdonotdenoteaprimitivedatavalueinJava?
Selectthetwocorrectanswers.
(a)"t"
(b)'k'
(c)50.5F
(d)"hello"
(e)false
2.6Whichofthefollowingprimitivedatatypesarenotintegertypes?
Selectthethreecorrectanswers.
(a)boolean
(b)byte
(c)float
(d)short
(e)double
2.7WhichintegraltypeinJavahastheexactrangefrom-2147483648(i.e.,-231)to
WOW! eBook
www.wowebook.org
2147483647(i.e.,231-1),inclusive?
Selecttheonecorrectanswer.
(a)byte
(b)short
(c)int
(d)long
(e)char
2.3VariableDeclarations
Avariablestoresavalueofaparticulartype.Avariablehasaname,atype,andavalue
associatedwithit.InJava,variablescanstoreonlyvaluesofprimitivedatatypesand
referencevaluesofobjects.Variablesthatstorereferencevaluesofobjectsarecalled
referencevariables(orobjectreferencesorsimplyreferences).
DeclaringandInitializingVariables
Variabledeclarationsareusedtospecifythetypeandthenameofvariables.This
implicitlydeterminestheirmemoryallocationandthevaluesthatcanbestoredinthem.
Examplesofdeclaringvariablesthatcanstoreprimitivevaluesfollow:
Clickheretoviewcodeimage
chara,b,c;//a,bandcarecharactervariables.
doublearea;//areaisafloating-pointvariable.
booleanflag;//flagisabooleanvariable.
Thefirstdeclarationisequivalenttothefollowingthreedeclarations:
chara;
charb;
charc;
Adeclarationcanalsobecombinedwithaninitializationexpressiontospecifyan
appropriateinitialvalueforthevariable.Suchdeclarationsarecalleddeclaration
statements.
Clickheretoviewcodeimage
inti=10,//iisanintvariablewithinitialvalue10.
j=0b101;//jisanintvariablewithinitialvalue5.
longbig=2147483648L;//bigisalongvariablewithspecifiedinitial
value.
ReferenceVariables
Areferencevariablecanstorethereferencevalueofanobject,andcanbeusedto
manipulatetheobjectdenotedbythereferencevalue.
Avariabledeclarationthatspecifiesareferencetype(i.e.,aclass,anarray,aninterface
name,oranenumtype)declaresareferencevariable.Analogoustothedeclarationof
variablesofprimitivedatatypes,thesimplestformofreferencevariabledeclaration
WOW! eBook
www.wowebook.org
specifiesthenameandthereferencetypeonly.Thedeclarationdetermineswhichobjects
canbereferencedbyareferencevariable.Beforewecanuseareferencevariableto
manipulateanobject,itmustbedeclaredandinitializedwiththereferencevalueofthe
object.
Clickheretoviewcodeimage
PizzayummyPizza;//VariableyummyPizzacanreferenceobjectsofclass
Pizza.
HamburgerbigOne,//VariablebigOnecanreferenceobjectsofclass
Hamburger,
smallOne;//andsocanvariablesmallOne.
Itisimportanttonotethattheprecedingdeclarationsdonotcreateanyobjectsofclass
PizzaorHamburger.Rather,theysimplycreatevariablesthatcanstorereference
valuesofobjectsofthespecifiedclasses.
Adeclarationcanalsobecombinedwithaninitializerexpressiontocreateanobject
whosereferencevaluecanbeassignedtothereferencevariable:
Clickheretoviewcodeimage
PizzayummyPizza=newPizza(“Hot&Spicy”);//Declarationstatement
ThereferencevariableyummyPizzacanreferenceobjectsofclassPizza.Thekeyword
new,togetherwiththeconstructorcallPizza("Hot&Spicy"),createsanobjectof
theclassPizza.Thereferencevalueofthisobjectisassignedtothevariable
yummyPizza.ThenewlycreatedobjectofclassPizzacannowbemanipulated
throughthereferencevariableyummyPizza.
2.4InitialValuesforVariables
Thissectiondiscusseswhatvalue,ifany,isassignedtoavariablewhennoexplicitinitial
valueisprovidedinthedeclaration.
DefaultValuesforFields
DefaultvaluesforfieldsofprimitivedatatypesandreferencetypesarelistedinTable
2.15.Thevalueassigneddependsonthetypeofthefield.
Table2.15DefaultValues
Ifnoexplicitinitializationisprovidedforastaticvariable,itisinitializedwiththedefault
valueofitstypewhentheclassisloaded.Similarly,ifnoinitializationisprovidedforan
instancevariable,itisinitializedwiththedefaultvalueofitstypewhentheclassis
WOW! eBook
www.wowebook.org
instantiated.Thefieldsofreferencetypesarealwaysinitializedwiththenullreference
valueifnoinitializationisprovided.
Example2.1illustratesthedefaultinitializationoffields.Notethatstaticvariablesare
initializedwhentheclassisloadedthefirsttime,andinstancevariablesareinitialized
accordinglyineveryobjectcreatedfromtheclassLight.
Example2.1DefaultValuesforFields
Clickheretoviewcodeimage
publicclassLight{
//Staticvariable
staticintcounter;//Defaultvalue0whenclassisloaded
//Instancevariables:
intnoOfWatts=100;//Explicitlysetto100
booleanindicator;//Implicitlysettodefaultvaluefalse
Stringlocation;//Implicitlysettodefaultvaluenull
publicstaticvoidmain(String[]args){
Lightbulb=newLight();
System.out.println(“Staticvariablecounter:”+Light.counter);
System.out.println(“InstancevariablenoOfWatts:”+bulb.noOfWatts);
System.out.println(“Instancevariableindicator:”+bulb.indicator);
System.out.println(“Instancevariablelocation:”+bulb.location);
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
Staticvariablecounter:0
InstancevariablenoOfWatts:100
Instancevariableindicator:false
Instancevariablelocation:null
InitializingLocalVariablesofPrimitiveDataTypes
Localvariablesarevariablesthataredeclaredinmethods,constructors,andblocks
(Chapter3,p.47).Theyarenotinitializedimplicitlywhentheyareallocatedmemoryat
methodinvocation—thatis,whentheexecutionofamethodbegins.Thesameappliesto
localvariablesinconstructorsandblocks.Localvariablesmustbeexplicitlyinitialized
beforebeingused.Thecompilerwillreportanerroronlyifanattemptismadetousean
uninitializedlocalvariable.
WOW! eBook
www.wowebook.org
Example2.2FlaggingUninitializedLocalVariablesofPrimitiveDataTypes
Clickheretoviewcodeimage
publicclassTooSmartClass{
publicstaticvoidmain(String[]args){
intweight=10,thePrice;//(1)Localvariables
if(weight<10)thePrice=1000;
if(weight>50)thePrice=5000;
if(weight>=10)thePrice=weight*10;//(2)Alwaysexecuted
System.out.println(“Thepriceis:”+thePrice);//(3)Compile-time
error!
}
}
InExample2.2,thecompilercomplainsthatthelocalvariablethePriceusedinthe
printlnstatementat(3)maynotbeinitialized.However,atruntime,thelocalvariable
thePricewillgetthevalue100inthelastifstatementat(2),beforeitisusedinthe
printlnstatement.Thecompilerdoesnotperformarigorousanalysisoftheprogramin
thisregard.Itcompilesthebodyofaconditionalstatementonlyifitcandeducethatthe
conditionistrue.Theprogramwillcompilecorrectlyifthevariableisinitializedinthe
declaration,orifanunconditionalassignmentismadetothevariable.
Replacingthedeclarationofthelocalvariablesat(1)inExample2.2withthefollowing
declarationsolvestheproblem:
Clickheretoviewcodeimage
intweight=10,thePrice=0;//(1’)Bothlocalvariables
initialized
InitializingLocalReferenceVariables
Localreferencevariablesareboundbythesameinitializationrulesaslocalvariablesof
primitivedatatypes.
Example2.3FlaggingUninitializedLocalReferenceVariables
Clickheretoviewcodeimage
publicclassVerySmartClass{
publicstaticvoidmain(String[]args){
StringimportantMessage;//Localreferencevariable
System.out.println(“Themessagelengthis:”+
importantMessage.length());//Compile-timeerror!
}
}
InExample2.3,thecompilercomplainsthatthelocalvariableimportantMessage
usedintheprintlnstatementmaynotbeinitialized.Ifthevariableimportant-
Messageissettothevaluenull,theprogramwillcompile.However,aruntimeerror
(NullPointerException)willoccurwhenthecodeisexecuted,becausethevariable
importantMessagewillnotdenoteanyobject.Thegoldenruleistoensurethata
WOW! eBook
www.wowebook.org
referencevariable,whetherlocalornot,isassignedareferencevaluedenotinganobject
beforeitisused—thatis,toensurethatitdoesnothavethevaluenull.
Theprogramcompilesandrunsifwereplacethedeclarationwiththefollowing
declarationofthelocalvariable,whichcreatesastringliteralandassignsitsreference
valuetothelocalreferencevariableimportantMessage:
Clickheretoviewcodeimage
StringimportantMessage=“Initializebeforeuse!”;
Arraysandtheirdefaultvaluesarediscussedin§3.4,p.58.
LifetimeofVariables
Thelifetimeofavariable—thatis,thetimeavariableisaccessibleduringexecution—is
determinedbythecontextinwhichitisdeclared.Thelifetimeofavariable,whichisalso
calleditsscope,isdiscussedinmoredetailin§4.4,p.114.Wedistinguishamongthe
lifetimesofvariablesinthreecontexts:
•Instancevariables—membersofaclass,whicharecreatedforeachobjectofthe
class.Inotherwords,everyobjectoftheclasswillhaveitsowncopiesofthese
variables,whicharelocaltotheobject.Thevaluesofthesevariablesatanygiven
timeconstitutethestateoftheobject.Instancevariablesexistaslongastheobject
theybelongtoisinuseatruntime.
•Staticvariables—membersofaclass,butwhicharenotcreatedforanyspecific
objectoftheclassand,therefore,belongonlytotheclass(§4.4,p.114).Theyare
createdwhentheclassisloadedatruntime,andexistaslongastheclassisavailable
atruntime.
•Localvariables(alsocalledmethodautomaticvariables)—declaredinmethods,
constructors,andblocks;andcreatedforeachexecutionofthemethod,constructor,
orblock.Aftertheexecutionofthemethod,constructor,orblockcompletes,local
(non-final)variablesarenolongeraccessible.
ReviewQuestions
2.8Whichofthefollowingdeclarationsarevalid?
Selectthethreecorrectanswers.
(a)chara='\u0061';
(b)char'a'='a';
(c)char\u0061='a';
(d)ch\u0061ra='a';
(e)ch'a'ra='a';
2.9Giventhefollowingcodewithinamethod,whichstatementistrue?
inti,j;
WOW! eBook
www.wowebook.org
j=5;
Selecttheonecorrectanswer.
(a)Localvariableiisnotdeclared.
(b)Localvariablejisnotdeclared.
(c)Localvariableiisdeclaredbutnotinitialized.
(d)Localvariablejisdeclaredbutnotinitialized.
(e)Localvariablejisinitializedbutnotdeclared.
2.10Inwhichofthesevariabledeclarationswillthevariableremainuninitializedunless
itisexplicitlyinitialized?
Selecttheonecorrectanswer.
(a)Declarationofaninstancevariableoftypeint
(b)Declarationofastaticvariableoftypefloat
(c)Declarationofalocalvariableoftypefloat
(d)DeclarationofastaticvariableoftypeObject
(e)Declarationofaninstancevariableoftypeint[]
2.11Whatwillbetheresultofcompilingandrunningthefollowingprogram?
Clickheretoviewcodeimage
publicclassInit{
Stringtitle;
booleanpublished;
staticinttotal;
staticdoublemaxPrice;
publicstaticvoidmain(String[]args){
InitinitMe=newInit();
doubleprice;
if(true)
price=100.00;
System.out.println(“|”+initMe.title+“|”+initMe.published+“|”
+
Init.total+“|”+Init.maxPrice+“|”+price+
“|”);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompile.
(b)Theprogramwillcompile,andprint|null|false|0|0.0|0.0|at
runtime.
(c)Theprogramwillcompile,andprint|null|true|0|0.0|100.0|at
runtime.
WOW! eBook
www.wowebook.org
(d)Theprogramwillcompile,andprint||false|0|0.0|0.0|atruntime.
(e)Theprogramwillcompile,andprint|null|false|0|0.0|100.0|at
runtime.
ChapterSummary
Thefollowingtopicswerecoveredinthischapter:
•Basiclanguageelements:identifiers,keywords,separators,literals,whitespace,and
comments
•Primitivedatatypes:integral,floating-point,andboolean
•Notationalrepresentationofnumbersindecimal,binary,octal,andhexadecimal
systems
•Declarationandinitializationofvariables,includingreferencevariables
•Usageofdefaultvaluesforinstancevariablesandstaticvariables
•Lifetimeofinstancevariables,staticvariables,andlocalvariables
ProgrammingExercise
2.1Thefollowingprogramhasseveralerrors.Modifytheprogramsothatitwill
compileandrunwithouterrors.
Clickheretoviewcodeimage
//File:Temperature.java
PUBLICCLASStemperature{
PUBLICvoidmain(stringargs){
doublefahrenheit=62.5;
*/Convert/*
doublecelsius=f2c(fahrenheit);
System.out.println(fahrenheit+‘F’+”=”+Celsius+‘C’);
}
doublef2c(floatfahr){
RETURN(fahr-32.0)*5.0/9.0;
}
}
WOW! eBook
www.wowebook.org
3.Declarations
3.1ClassDeclarations
Aclassdeclarationintroducesanewreferencetype.Forthepurposeofthisbook,wewill
usethefollowingsimplifiedsyntaxofaclassdeclaration:
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
class_modifiersclassclass_name
extends_clause
implements_clause//Classheader
{//Classbody
field_declarations
method_declarations
constructor_declarations
}
Intheclassheader,thenameoftheclassisprecededbythekeywordclass.Inaddition,
theclassheadercanspecifythefollowinginformation:
•Anaccessibilitymodifier(§4.5,p.118)
•Additionalclassmodifiers(§4.6,p.120)
•Anyclassitextends(§7.1,p.264)
•Anyinterfacesitimplements(§7.6,p.290)
Theclassbody,enclosedinbraces({}),cancontainmemberdeclarations.Inthisbook,
wediscussthefollowingtwokindsofmemberdeclarations:
•Fielddeclarations(§2.3,p.40)
•Methoddeclarations(§3.2,p.49)
Membersdeclaredstaticbelongtotheclassandarecalledstaticmembers.Non-static
membersbelongtotheobjectsoftheclassandarecalledinstancemembers.Inaddition,
thefollowingdeclarationscanbeincludedinaclassbody:
•Constructordeclarations(§3.3,p.53)
Thedeclarationscanappearinanyorderintheclassbody.Theonlymandatorypartsof
theclassdeclarationsyntaxarethekeywordclass,theclassname,andtheclassbody
braces({}),asexemplifiedbythefollowingclassdeclaration:
classX{}
Tounderstandwhichcodecanbelegallydeclaredinaclass,wedistinguishbetweenstatic
contextandnon-staticcontext.Astaticcontextisdefinedbystaticmethods,staticfield
initializers,andstaticinitializerblocks.Anon-staticcontextisdefinedbyinstance
methods,non-staticfieldinitializers,instanceinitializerblocks,andconstructors.Bystatic
code,wemeanexpressionsandstatementsinastaticcontext;bynon-staticcode,wemean
expressionsandstatementsinanon-staticcontext.Onecrucialdifferencebetweenthetwo
contextsisthatstaticcodecanreferonlytootherstaticmembers.
3.2MethodDeclarations
Forthepurposeofthisbook,wewillusethefollowingsimplifiedsyntaxofamethod
declaration:
Clickheretoviewcodeimage
WOW! eBook
www.wowebook.org
method_modifiersreturn_typemethod_name
(formal_parameter_list)throws_clause//Methodheader
{//Methodbody
local_variable_declarations
statements
}
Inadditiontothenameofthemethod,themethodheadercanspecifythefollowing
information:
•Scopeoraccessibilitymodifier(§4.7,p.123)
•Additionalmethodmodifiers(§4.8,p.131)
•Thetypeofthereturnvalue,orvoidifthemethoddoesnotreturnanyvalue(§6.4,
p.224)
•Aformalparameterlist
•Anyexceptionsthrownbythemethod,whicharespecifiedinathrowsclause
(§6.9,p.251)
Theformalparameterlistisacomma-separatedlistofparametersforpassinginformation
tothemethodwhenthemethodisinvokedbyamethodcall(§3.5,p.72).Anempty
parameterlistmustbespecifiedby().Eachparameterisasimplevariabledeclaration
consistingofitstypeandname:
Clickheretoviewcodeimage
optional_parameter_modifiertypeparameter_name
Theparameternamesarelocaltothemethod(§4.4,p.117).Theoptionalparameter
modifierfinalisdiscussedin§3.5,p.80.Itisrecommendedtousethe@paramtagina
Javadoccommenttodocumenttheformalparametersofamethod.
Thesignatureofamethodcomprisesthenameofthemethodandthetypesoftheformal
parametersonly.
Themethodbodyisablockcontainingthelocalvariabledeclarations(§2.3,p.40)and
thestatementsofthemethod.
Themandatorypartsofamethoddeclarationarethereturntype,themethodname,andthe
methodbodybraces({}),asexemplifiedbythefollowingmethoddeclaration:
voidnoAction(){}
Likemembervariables,membermethodscanbecharacterizedasoneoftwotypes:
•Instancemethods,whicharediscussedlaterinthissection
•Staticmethods,whicharediscussedin§4.8,p.132
WOW! eBook
www.wowebook.org
Statements
StatementsinJavacanbegroupedintovariouscategories.Variabledeclarationswith
explicitinitializationofthevariablesarecalleddeclarationstatements(§2.3,p.40,and
§3.4,p.60).Otherbasicformsofstatementsarecontrolflowstatements(§6.1,p.200)and
expressionstatements.
Anexpressionstatementisanexpressionterminatedbyasemicolon.Anyvaluereturned
bytheexpressionisdiscarded.Onlycertaintypesofexpressionshavemeaningas
statements:
•Assignments(§5.6,p.158)
•Incrementanddecrementoperators(§5.9,p.176)
•Methodcalls(§3.5,p.72)
•Objectcreationexpressionswiththenewoperator(§5.17,p.195)
Asolitarysemicolondenotestheemptystatement,whichdoesnothing.
Ablock,{},isacompoundstatementthatcanbeusedtogroupzeroormorelocal
declarationsandstatements(§4.4,p.117).Blockscanbenested,sinceablockisa
statementthatcancontainotherstatements.Ablockcanbeusedinanycontextwherea
simplestatementispermitted.Thecompoundstatementthatisembodiedinablockbegins
attheleftbrace,{,andendswithamatchingrightbrace,}.Suchablockmustnotbe
confusedwithanarrayinitializerindeclarationstatements(§3.4,p.60).
Labeledstatementsarediscussedin§6.4onpage220.
InstanceMethodsandtheObjectReference
Instancemethodsbelongtoeveryobjectoftheclassandcanbeinvokedonlyonobjects.
Allmembersdefinedintheclass,bothstaticandnon-static,areaccessibleinthecontext
ofaninstancemethod.Thereasonisthatallinstancemethodsarepassedanimplicit
referencetothecurrentobject—thatis,theobjectonwhichthemethodisbeinginvoked.
Thecurrentobjectcanbereferencedinthebodyoftheinstancemethodbythekeyword
this.Inthebodyofthemethod,thethisreferencecanbeusedlikeanyotherobject
referencetoaccessmembersoftheobject.Infact,thekeywordthiscanbeusedinany
non-staticcontext.Thethisreferencecanbeusedasanormalreferencetoreferencethe
currentobject,butthereferencecannotbemodified—itisafinalreference(§4.8,p.
133).
Thethisreferencetothecurrentobjectisusefulinsituationswherealocalvariable
hides,orshadows,afieldwiththesamename.InExample3.1,thetwoparameters
noOfWattsandindicatorintheconstructoroftheLightclasshavethesame
namesasthefieldsintheclass.Theexamplealsodeclaresalocalvariablelocation,
whichhasthesamenameasoneofthefields.Thereferencethiscanbeusedto
distinguishthefieldsfromthelocalvariables.At(1),thethisreferenceisusedto
identifythefieldnoOfWatts,whichisassignedthevalueoftheparameter
noOfWatts.Withoutthethisreferenceat(2),thevalueoftheparameterindicator
WOW! eBook
www.wowebook.org
isassignedbacktothisparameter,andnottothefieldbythesamename,resultingina
logicalerror.Similarlyat(3),withoutthethisreference,itisthelocalvariable
locationthatisassignedthevalueoftheparametersite,andnotthefieldwiththe
samename.
Example3.1UsingthethisReference
Clickheretoviewcodeimage
publicclassLight{
//Fields:
intnoOfWatts;//Wattage
booleanindicator;//Onoroff
Stringlocation;//Placement
//Constructor
publicLight(intnoOfWatts,booleanindicator,Stringsite){
Stringlocation;
this.noOfWatts=noOfWatts;//(1)Assignmenttofield
indicator=indicator;//(2)Assignmenttoparameter
location=site;//(3)Assignmenttolocalvariable
this.superfluous();//(4)
superfluous();//equivalenttocallat(4)
}
publicvoidsuperfluous(){
System.out.printf(“Currentobject:%s%n”,this);//(5)
}
publicstaticvoidmain(String[]args){
Lightlight=newLight(100,true,“loft”);
System.out.println(“No.ofwatts:”+light.noOfWatts);
System.out.println(“Indicator:”+light.indicator);
System.out.println(“Location:”+light.location);
}
}
Probableoutputfromtheprogram:
Currentobject:Light@1bc4459
Currentobject:Light@1bc4459
No.ofwatts:100
Indicator:false
Location:null
Ifamemberisnotshadowedbyalocaldeclaration,thesimplenamememberis
consideredashort-handnotationforthis.member.Inparticular,thethisreference
canbeusedexplicitlytoinvokeothermethodsintheclass.Thisusageisillustratedat(4)
inExample3.1,wherethemethodsuperfluous()iscalled.
If,forsomereason,amethodneedstopassthecurrentobjecttoanothermethod,itcando
sousingthethisreference.Thisapproachisillustratedat(5)inExample3.1,wherethe
currentobjectispassedtotheprintf()method.Theprintf()methodprintsthe
stringrepresentationofthecurrentobject(whichcomprisesthenameoftheclassofthe
currentobjectandthehexadecimalrepresentationofthecurrentobject’shashcode).(The
hashcodeofanobjectisanintvaluethatcanbeusedtostoreandretrievetheobject
WOW! eBook
www.wowebook.org
fromspecialdatastructurescalledhashtables.)
Notethatthethisreferencecannotbeusedinastaticcontext,asstaticcodeisnot
executedinthecontextofanyobject.
MethodOverloading
Eachmethodhasasignature,whichcomprisesthenameofthemethodplusthetypesand
orderoftheparametersintheformalparameterlist.Severalmethodimplementationsmay
havethesamename,aslongasthemethodsignaturesdiffer.Thispracticeiscalled
methodoverloading.Becauseoverloadedmethodshavethesamename,theirparameter
listsmustbedifferent.
Ratherthaninventingnewmethodnames,methodoverloadingcanbeusedwhenthesame
logicaloperationrequiresmultipleimplementations.TheJavaSEplatformAPImakes
heavyuseofmethodoverloading.Forexample,theclassjava.lang.Mathcontainsan
overloadedmethodmin(),whichreturnstheminimumoftwonumericvalues.
Clickheretoviewcodeimage
publicstaticdoublemin(doublea,doubleb)
publicstaticfloatmin(floata,floatb)
publicstaticintmin(inta,intb)
publicstaticlongmin(longa,longb)
Inthefollowingexamples,fiveimplementationsofthemethodmethodAareshown:
Clickheretoviewcodeimage
voidmethodA(inta,doubleb){/*…*/}//(1)
intmethodA(inta){returna;}//(2)
intmethodA(){return1;}//(3)
longmethodA(doublea,intb){returnb;}//(4)
longmethodA(intx,doubley){returnx;}//(5)NotOK.
Thecorrespondingsignaturesofthefivemethodsareasfollows:
Clickheretoviewcodeimage
methodA(int,double)1’
methodA(int)2’:Numberofparameters
methodA()3’:Numberofparameters
methodA(double,int)4’:Orderofparameters
methodA(int,double)5’:Sameas1’
ThefirstfourimplementationsofthemethodnamedmethodAareoverloadedcorrectly,
eachtimewithadifferentparameterlistand,therefore,differentsignatures.The
declarationat(5)hasthesamesignaturemethodA(int,double)asthedeclaration
at(1)and,therefore,isnotavalidoverloadingofthismethod.
Clickheretoviewcodeimage
voidbake(Cakek){/*…*/}//(1)
voidbake(Pizzap){/*…*/}//(2)
inthalfIt(inta){returna/2;}//(3)
doublehalfIt(inta){returna/2.0;}//(4)NotOK.Same
signature.
Themethodnamedbakeiscorrectlyoverloadedat(1)and(2),withtwodifferent
WOW! eBook
www.wowebook.org
parameterlists.Intheimplementation,changingjustthereturntype(asshownat(3)and
(4)intheprecedingexample),isnotenoughtooverloadamethod,andwillbeflaggedas
acompile-timeerror.Theparameterlistinthedeclarationsmustbedifferent.
Onlymethodsdeclaredinthesameclassandthosethatareinheritedbytheclasscanbe
overloaded.Overloadedmethodsshouldbeconsideredtobeindividualmethodsthatjust
happentohavethesamename.Methodswiththesamenameareallowed,sincemethods
areidentifiedbytheirsignature.Atcompiletime,therightimplementationofan
overloadedmethodischosen,basedonthesignatureofthemethodcall.Detailsofmethod
overloadingresolutioncanbefoundin§7.10onpage316.Methodoverloadingshouldnot
beconfusedwithmethodoverriding(§7.2,p.268).
3.3Constructors
Themainpurposeofconstructorsistosettheinitialstateofanobject,whentheobjectis
createdbyusingthenewoperator.
Forthepurposeofthisbook,wewillusethefollowingsimplifiedsyntaxofaconstructor:
Clickheretoviewcodeimage
accessibility_modifierclass_name(formal_parameter_list)
throws_clause//Constructorheader
{//Constructorbody
local_variable_declarations
statements
}
Constructordeclarationsareverymuchlikemethoddeclarations.However,thefollowing
restrictionsonconstructorsshouldbenoted:
•Modifiersotherthananaccessibilitymodifierarenotpermittedintheconstructor
header.Foraccessibilitymodifiersforconstructors,see§4.7,p.123.
•Constructorscannotreturnavalueand,therefore,donotspecifyareturntype,not
evenvoid,intheconstructorheader.Buttheirdeclarationcanusethereturn
statementthatdoesnotreturnavalueintheconstructorbody(§6.4,p.224).
•Theconstructornamemustbethesameastheclassname.
Classnamesandmethodnamesexistindifferentnamespaces.Thus,therearenoname
conflictsinExample3.2,whereamethoddeclaredat(2)hasthesamenameasthe
constructordeclaredat(1).Amethodmustalwaysspecifyareturntype,whereasa
constructordoesnot.However,usingsuchnamingschemesisstronglydiscouraged.
Aconstructorthathasnoparameters,liketheoneat(1)inExample3.2,iscalledano-
argumentconstructor.
WOW! eBook
www.wowebook.org
Example3.2Namespaces
Clickheretoviewcodeimage
publicclassName{
Name(){//(1)No-argumentconstructor
System.out.println(“Constructor”);
}
voidName(){//(2)Instancemethod
System.out.println(“Method”);
}
publicstaticvoidmain(String[]args){
newName().Name();//(3)Constructorcallfollowedbymethod
call
}
}
Outputfromtheprogram:
Constructor
Method
TheDefaultConstructor
Ifaclassdoesnotspecifyanyconstructors,thenadefaultconstructorisgeneratedforthe
classbythecompiler.Thedefaultconstructorisequivalenttothefollowing
implementation:
Clickheretoviewcodeimage
class_name(){super();}//Noparameters.Calls
superclassconstructor.
Adefaultconstructorisano-argumentconstructor.Theonlyactiontakenbythedefault
constructoristocallthesuperclassconstructor.Thisensuresthattheinheritedstateofthe
objectisinitializedproperly(§7.5,p.282).Inaddition,allinstancevariablesintheobject
aresettothedefaultvalueoftheirtype,barringthosethatareinitializedbyan
initializationexpressionintheirdeclaration.
Inthefollowingcode,theclassLightdoesnotspecifyanyconstructors:
Clickheretoviewcodeimage
classLight{
//Fields:
intnoOfWatts;//Wattage
booleanindicator;//Onoroff
Stringlocation;//Placement
//Noconstructors
//…
}
classGreenhouse{
//…
LightoneLight=newLight();//(1)Calltodefaultconstructor
}
WOW! eBook
www.wowebook.org
Inthiscode,thefollowingdefaultconstructoriscalledwhenaLightobjectiscreatedby
theobjectcreationexpressionat(1):
Light(){super();}
Creatinganobjectusingthenewoperatorwiththedefaultconstructor,asat(1),will
initializethefieldsoftheobjecttotheirdefaultvalues(thatis,thefieldsnoOfWatts,
indicator,andlocationinaLightobjectwillbeinitializedto0,false,and
null,respectively).
Aclasscanchoosetoprovideitsownconstructors,ratherthanrelyingonthedefault
constructor.Inthefollowingexample,theclassLightprovidesano-argument
constructorat(1).
Clickheretoviewcodeimage
classLight{
//…
Light(){//(1)No-argumentconstructor
noOfWatts=50;
indicator=true;
location=“X”;
}
//…
}
classGreenhouse{
//…
LightextraLight=newLight();//(2)Callofexplicitdefault
constructor
}
Theno-argumentconstructorensuresthatanyobjectcreatedwiththeobjectcreation
expressionnewLight(),asat(2),willhaveitsfieldsnoOfWatts,indicator,and
locationinitializedto50,true,and"X",respectively.
Ifaclassdefinesanyconstructor,itcannolongerrelyonthedefaultconstructortosetthe
stateofitsobjects.Ifsuchaclassrequiresano-argumentconstructor,itmustprovideits
ownimplementation,asintheprecedingexample.InthenextexampletheclassLight
doesnotprovideano-argumentconstructor,butratherincludesanon-zeroargument
constructorat(1).Itiscalledat(2)whenanobjectoftheclassLightiscreatedwiththe
newoperator.Anyattempttocallthedefaultconstructorwillbeflaggedasacompile-
timeerror,asshownat(3).
Clickheretoviewcodeimage
classLight{
//…
//Onlynon-zeroargumentconstructor:
Light(intnoOfWatts,booleanindicator,Stringlocation){//(1)
this.noOfWatts=noOfWatts;
this.indicator=indicator;
this.location=location;
}
//…
}
classGreenhouse{
WOW! eBook
www.wowebook.org
//…
LightmoreLight=newLight(100,true,“Greenhouse”);//(2)OK
LightfirstLight=newLight();//(3)Compile-time
error
}
OverloadedConstructors
Likemethods,constructorscanbeoverloaded.Sincetheconstructorsinaclassallhave
thesamenameastheclass,theirsignaturesaredifferentiatedbytheirparameterlists.In
thefollowingexample,theclassLightnowprovidesexplicitimplementationoftheno-
argumentconstructorat(1)andthatofanon-zeroargumentconstructorat(2).The
constructorsareoverloaded,asisevidentbytheirsignatures.Thenon-zeroargument
constructorat(2)iscalledwhenanobjectoftheclassLightiscreatedat(3),andtheno-
argumentconstructorislikewisecalledat(4).Overloadingofconstructorsallows
appropriateinitializationofobjectsoncreation,dependingontheconstructorinvoked(see
chainingofconstructorsin§7.5,p.282).Itisrecommendedtousethe@paramtagina
Javadoccommenttodocumenttheformalparametersofaconstructor.
Clickheretoviewcodeimage
classLight{
//…
//No-argumentconstructor:
Light(){//(1)
noOfWatts=50;
indicator=true;
location=“X”;
}
//Non-zeroargumentconstructor:
Light(intnoOfWatts,booleanindicator,Stringlocation){//(2)
this.noOfWatts=noOfWatts;
this.indicator=indicator;
this.location=location;
}
//…
}
classGreenhouse{
//…
LightmoreLight=newLight(100,true,“Greenhouse”);//(3)OK
LightfirstLight=newLight();//(4)OK
}
ReviewQuestions
3.1Whichoneofthesedeclarationsisavalidmethoddeclaration?
Selecttheonecorrectanswer.
(a)voidmethod1{/*...*/}
(b)voidmethod2(){/*...*/}
(c)voidmethod3(void){/*...*/}
WOW! eBook
www.wowebook.org
(d)method4(){/*...*/}
(e)method5(void){/*...*/}
3.2Whichstatements,wheninsertedat(1),willnotresultincompile-timeerrors?
Clickheretoviewcodeimage
publicclassThisUsage{
intplanets;
staticintsuns;
publicvoidgaze(){
inti;
//(1)INSERTSTATEMENTHERE
}
}
Selectthethreecorrectanswers.
(a)i=this.planets;
(b)i=this.suns;
(c)this=newThisUsage();
(d)this.i=4;
(e)this.suns=planets;
3.3Giventhefollowingpairsofmethoddeclarations,whichstatementsaretrue?
Clickheretoviewcodeimage
voidfly(intdistance){}
intfly(inttime,intspeed){returntime*speed;}
voidfall(inttime){}
intfall(intdistance){returndistance;}
voidglide(inttime){}
voidGlide(inttime){}
Selectthetwocorrectanswers.
(a)Thefirstpairofmethodswillcompile,andoverloadthemethodnamefly.
(b)Thesecondpairofmethodswillcompile,andoverloadthemethodname
fall.
(c)Thethirdpairofmethodswillcompile,andoverloadthemethodnameglide.
(d)Thefirstpairofmethodswillnotcompile.
(e)Thesecondpairofmethodswillnotcompile.
(f)Thethirdpairofmethodswillnotcompile.
3.4GivenaclassnamedBook,whichoneoftheseconstructordeclarationsisvalidfor
theclassBook?
Selecttheonecorrectanswer.
WOW! eBook
www.wowebook.org
(a)Book(Bookb){}
(b)BookBook(){}
(c)privatefinalBook(){}
(d)voidBook(){}
(e)publicstaticvoidBook(String[]args){}
(f)abstractBook(){}
3.5Whichstatementsaretrue?
Selectthetwocorrectanswers.
(a)Aclassmustdefineaconstructor.
(b)Aconstructorcanbedeclaredprivate.
(c)Aconstructorcanreturnavalue.
(d)Aconstructormustinitializeallfieldswhenaclassisinstantiated.
(e)Aconstructorcanaccessthenon-staticmembersofaclass.
3.6Whatwillbetheresultofcompilingthefollowingprogram?
Clickheretoviewcodeimage
publicclassMyClass{
longvar;
publicvoidMyClass(longparam){var=param;}//(1)
publicstaticvoidmain(String[]args){
MyClassa,b;
a=newMyClass();//(2)
b=newMyClass(5);//(3)
}
}
Selecttheonecorrectanswer.
(a)Acompile-timeerrorwilloccurat(1).
(b)Acompile-timeerrorwilloccurat(2).
(c)Acompile-timeerrorwilloccurat(3).
(d)Theprogramwillcompilewithouterrors.
3.4Arrays
Anarrayisadatastructurethatdefinesanindexedcollectionofafixednumberof
homogeneousdataelements.Thismeansthatallelementsinthearrayhavethesamedata
type.Apositioninthearrayisindicatedbyanon-negativeintegervaluecalledtheindex.
Anelementatagivenpositioninthearrayisaccessedusingtheindex.Thesizeofan
arrayisfixedandcannotbechangedafterthearrayhasbeencreated.
InJava,arraysareobjects.Arrayscanbeofprimitivedatatypesorreferencetypes.Inthe
WOW! eBook
www.wowebook.org
formercase,allelementsinthearrayareofaspecificprimitivedatatype.Inthelatter
case,allelementsarereferencesofaspecificreferencetype.Referencesinthearraycan
thendenoteobjectsofthisreferencetypeoritssubtypes.Eacharrayobjecthasapublic
finalfieldcalledlength,whichspecifiesthearraysize(i.e.,thenumberofelements
thearraycanaccommodate).Thefirstelementisalwaysatindex0andthelastelementat
indexn–1,wherenisthevalueofthelengthfieldinthearray.
Simplearraysareone-dimensionalarrays—thatis,asimplelistofvalues.Sincearrays
canstorereferencevalues,theobjectsreferencedcanalsobearrayobjects.Thus,
multidimensionalarraysareimplementedasarrayofarrays.
Passingarrayreferencesasparametersisdiscussedin§3.5,p.72.Typeconversionsfor
arrayreferencesonassignmentandonmethodinvocationarediscussedin§7.7,p.309.
DeclaringArrayVariables
Aone-dimensionalarrayvariabledeclarationhaseitherofthefollowingsyntaxes:
element_type[]array_name;
or
element_typearray_name[];
whereelement_typecanbeaprimitivedatatypeorareferencetype.Thearrayvariable
array_namehasthetypeelement_type[].Notethatthearraysizeisnotspecified.Asa
consequence,thearrayvariablearray_namecanbeassignedthereferencevalueofan
arrayofanylength,aslongasitselementshaveelement_type.
Itisimportanttounderstandthatthedeclarationdoesnotactuallycreateanarray.Instead,
itsimplydeclaresareferencethatcanrefertoanarrayobject.The[]notationcanalsobe
specifiedafteravariablenametodeclareitasanarrayvariable,butthenitappliestojust
thatvariable.
Clickheretoviewcodeimage
intanIntArray[],oneInteger;
Pizza[]mediumPizzas,largePizzas;
ThesetwodeclarationsdeclareanIntArrayandmediumPizzastobereference
variablesthatcanrefertoarraysofintvaluesandarraysofPizzaobjects,respectively.
ThevariablelargePizzascandenoteanarrayofPizzaobjects,butthevariable
oneIntegercannotdenoteanarrayofintvalues—itisasimplevariableofthetype
int.
Anarrayvariablethatisdeclaredasafieldinaclass,butisnotexplicitlyinitializedtoany
array,willbeinitializedtothedefaultreferencevaluenull.Thisdefaultinitialization
doesnotapplytolocalreferencevariablesand,therefore,doesnotapplytolocalarray
variableseither(§2.4,p.42).Thisbehaviorshouldnotbeconfusedwithinitializationof
theelementsofanarrayduringarrayconstruction.
WOW! eBook
www.wowebook.org
ConstructinganArray
Anarraycanbeconstructedforafixednumberofelementsofaspecifictype,usingthe
newoperator.Thereferencevalueoftheresultingarraycanbeassignedtoanarray
variableofthecorrespondingtype.Thesyntaxofthearraycreationexpressionisshown
ontheright-handsideofthefollowingassignmentstatement:
Clickheretoviewcodeimage
array_name=newelement_type[array_size];
Theminimumvalueofarray_sizeis0;inotherwordszero-lengtharrayscanbe
constructedinJava.Ifthearraysizeisnegative,aNegativeArraySizeException
isthrownatruntime.
Giventhedeclarations
Clickheretoviewcodeimage
intanIntArray[],oneInteger;
Pizza[]mediumPizzas,largePizzas;
thethreearraysinthedeclarationscanbeconstructedasfollows:
Clickheretoviewcodeimage
anIntArray=newint[10];//arrayfor10integers
mediumPizzas=newPizza[5];//arrayof5pizzas
largePizzas=newPizza[3];//arrayof3pizzas
Thearraydeclarationandconstructioncanbecombined.
Clickheretoviewcodeimage
element_type1[]array_name=newelement_type2[array_size];
Intheprecedingsyntax,thearraytypeelement_type2[]mustbeassignabletothearray
typeelement_type1[](§7.7,p.309).Whenthearrayisconstructed,allofitselementsare
initializedtothedefaultvalueforelement_type2.Thisistrueforbothmemberandlocal
arrayswhentheyareconstructed.
Inthenextexamples,thecodeconstructsthearray,andthearrayelementsareimplicitly
initializedtotheirdefaultvalues.Forexample,allelementsofthearrayanIntArrayget
thevalue0,andallelementsofthearraymediumPizzasgetthevaluenullwhenthe
arraysareconstructed.
Clickheretoviewcodeimage
int[]anIntArray=newint[10];//Defaultelementvalue:0
Pizza[]mediumPizzas=newPizza[5];//Defaultelementvalue:
null
Thevalueofthefieldlengthineacharrayissettothenumberofelementsspecified
duringtheconstructionofthearray;forexample,mediumPizzas.lengthhasthe
value5.
Onceanarrayhasbeenconstructed,itselementscanalsobeexplicitlyinitialized
individually—forexample,inaloop.Theexamplesintherestofthissectionmakeuseof
WOW! eBook
www.wowebook.org
alooptotraversetheelementsofanarrayforvariouspurposes.
InitializinganArray
Javaprovidesthemeansofdeclaring,constructing,andexplicitlyinitializinganarrayin
onedeclarationstatement:
Clickheretoviewcodeimage
element_type[]array_name={array_initialize_list};
Thisformofinitializationappliestofieldsaswellastolocalarrays.The
array_initialize_listisacomma-separatedlistofzeroormoreexpressions.Suchanarray
initializerresultsintheconstructionandinitializationofthearray.
Clickheretoviewcodeimage
int[]anIntArray={13,49,267,15,215};
Inthisdeclarationstatement,thevariableanIntArrayisdeclaredasareferencetoan
arrayofints.Thearrayinitializerresultsintheconstructionofanarraytoholdfive
elements(equaltothelengthofthelistofexpressionsintheblock),wherethefirst
elementisinitializedtothevalueofthefirstexpression(13),thesecondelementtothe
valueofthesecondexpression(49),andsoon.
Clickheretoviewcodeimage
Pizza[]pizzaOrder={newPizza(),newPizza(),null};
Inthisdeclarationstatement,thevariablepizzaOrderisdeclaredasareferencetoan
arrayofPizzaobjects.Thearrayinitializerconstructsanarraytoholdthreeelements.
TheinitializationcodesetsthefirsttwoelementsofthearraytorefertotwoPizza
objects,whilethelastelementisinitializedtothenullreference.Thereferencevalueof
thearrayofPizzaobjectsisassignedtothereferencepizzaOrder.Notealsothatthis
declarationstatementactuallycreatesthreeobjects:thearrayobjectwiththreereferences
andthetwoPizzaobjects.
Theexpressionsinthearray_initialize_listareevaluatedfromlefttoright,andthearray
nameobviouslycannotoccurinanyoftheexpressionsinthelist.Inthepreceding
examples,thearray_initialize_lististerminatedbytherightbrace,},oftheblock.Thelist
canalsobelegallyterminatedbyacomma.Thefollowingarrayhaslength2,andnot3:
Clickheretoviewcodeimage
Topping[]pizzaToppings={newTopping(“cheese”),newTopping(“tomato”),};
Thedeclarationstatementat(1)inthefollowingcodedefinesanarrayoffourString
objects,whilethedeclarationstatementat(2)showsthataStringobjectisnotthesame
asanarrayofchar.
Clickheretoviewcodeimage
//Arraywith4Stringobjects:
String[]pets={“crocodiles”,“elephants”,“crocophants”,“elediles”};//
(1)
//Arrayof3characters:
char[]charArray={‘a’,‘h’,‘a’};//(2)Notthesameas“aha”
WOW! eBook
www.wowebook.org
UsinganArray
Thearrayobjectisreferencedbythearrayname,butindividualarrayelementsare
accessedbyspecifyinganindexwiththe[]operator.Thearrayelementaccess
expressionhasthefollowingsyntax:
array_name[index_expression]
Eachindividualelementistreatedasasimplevariableoftheelementtype.Theindexis
specifiedbytheindex_expression,whosevalueshouldbepromotabletoanintvalue;
otherwise,acompile-timeerrorisflagged.Sincethelowerboundofanarrayindexis
always0,theupperboundis1lessthanthearraysize—thatis,array_name.length-1.
Theithelementinthearrayhasindex(i-1).Atruntime,theindexvalueis
automaticallycheckedtoensurethatitiswithinthearrayindexbounds.Iftheindexvalue
islessthan0,orgreaterthanorequaltoarray_name.length,an
ArrayIndexOutOfBoundsExceptionisthrown.Aprogramcaneithercheckthe
indexexplicitlyorcatchtheruntimeexception(§6.5,p.230),butanillegalindexis
typicallyanindicationofaprogrammingerror.
Inthearrayelementaccessexpression,thearray_namecanbeanyexpressionthatreturns
areferencetoanarray.Forexample,theexpressionontheright-handsideofthefollowing
assignmentstatementreturnsthecharacter'H'atindex1inthecharacterarrayreturned
byacalltothetoCharArray()methodoftheStringclass:
Clickheretoviewcodeimage
charletter=“AHA”.toCharArray()[1];//‘H’
Thearrayoperator[]isusedtodeclarearraytypes(Topping[]),specifythearraysize
(newTopping[3]),andaccessarrayelements(toppings[1]).Thisoperatorisnot
usedwhenthearrayreferenceismanipulated,suchasinanarrayreferenceassignment
(§7.9,p.312),orwhenthearrayreferenceispassedasanactualparameterinamethod
call(§3.5,p.77).
Example3.3showstraversalofarraysusingforloops(§6.3,p.215andp.217).A
for(;;)loopat(3)inthemain()methodinitializesthelocalarraytrialArray
declaredat(2)fivetimeswithpseudo-randomnumbers(from0.0to100.0),bycalling
themethodrandomize()declaredat(5).Theminimumvalueinthearrayisfoundby
callingthemethodfindMinimum()declaredat(6),andisstoredinthearray
storeMinimumdeclaredat(1).Bothofthesemethodsalsouseafor(;;)loop.The
loopvariableisinitializedtoastartvalue—0in(3)and(5),and1in(6).Theloop
conditiontestswhethertheloopvariableislessthanthelengthofthearray;this
guaranteesthattheloopwillterminatewhenthelastelementhasbeenaccessed.Theloop
variableisincrementedaftereachiterationtoaccessthenextelement.
Afor(:)loopat(4)inthemain()methodisusedtoprinttheminimumvaluesfrom
thetrials,aselementsarereadconsecutivelyfromthearray,withoutkeepingtrackofan
indexvalue.
WOW! eBook
www.wowebook.org
Example3.3UsingArrays
Clickheretoviewcodeimage
publicclassTrials{
publicstaticvoidmain(String[]args){
//Declareandconstructthelocalarrays:
double[]storeMinimum=newdouble[5];//(1)
double[]trialArray=newdouble[15];//(2)
for(inti=0;i<storeMinimum.length;++i){//(3)
//Initializethearray.
randomize(trialArray);
//Findandstoretheminimumvalue.
storeMinimum[i]=findMinimum(trialArray);
}
//Printtheminimumvalues:(4)
for(doubleminValue:storeMinimum)
System.out.printf(“%.4f%n”,minValue);
}
publicstaticvoidrandomize(double[]valArray){//(5)
for(inti=0;i<valArray.length;++i)
valArray[i]=Math.random()*100.0;
}
publicstaticdoublefindMinimum(double[]valArray){//(6)
//Assumethearrayhasatleastoneelement.
doubleminValue=valArray[0];
for(inti=1;i<valArray.length;++i)
minValue=Math.min(minValue,valArray[i]);
returnminValue;
}
}
Probableoutputfromtheprogram:
6.9330
2.7819
6.7427
18.0849
26.2462
AnonymousArrays
Asshownearlierinthissection,thefollowingdeclarationstatementcanbeusedto
constructarraysusinganarraycreationexpression:
Clickheretoviewcodeimage
element_type1[]array_name=newelement_type2[array_size];//(1)
int[]intArray=newint[5];
Thesizeofthearrayisspecifiedinthearraycreationexpression,whichcreatesthearray
andinitializesthearrayelementstotheirdefaultvalues.Bycomparison,thefollowing
declarationstatementbothcreatesthearrayandinitializesthearrayelementstospecific
valuesgiveninthearrayinitializer:
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
element_type[]array_name={array_initialize_list};//(2)
int[]intArray={3,5,2,8,6};
However,thearrayinitializerisnotanexpression.Javahasanotherarraycreation
expression,calledananonymousarray,whichallowstheconceptofthearraycreation
expressionfrom(1)tobecombinedwiththearrayinitializerfrom(2),soastocreateand
initializeanarrayobject:
Clickheretoviewcodeimage
newelement_type[]{array_initialize_list}
newint[]{3,5,2,8,6}
Thisconstructhasenoughinformationtocreateanamelessarrayofaspecifictype.
Neitherthenameofthearraynorthesizeofthearrayisspecified.Theconstructreturns
thereferencevalueofthenewlycreatedarray,whichcanbeassignedtoreferencesand
passedasargumentinmethodcalls.Inparticular,thefollowingdeclarationstatementsare
equivalent:
Clickheretoviewcodeimage
int[]intArray={3,5,2,8,6};//(1)
int[]intArray=newint[]{3,5,2,8,6};//(2)
In(1),anarrayinitializerisusedtocreateandinitializetheelements.In(2),an
anonymousarrayexpressionisused.Itistemptingtousethearrayinitializerasan
expression—forexample,inanassignmentstatement,asashortcutforassigningvaluesto
arrayelementsinonego.However,thisisillegal;instead,ananonymousarrayexpression
shouldbeused.Theconceptoftheanonymousarraycombinesthedefinitionandthe
creationofthearrayintooneoperation.
Clickheretoviewcodeimage
int[]daysInMonth;
daysInMonth={31,28,31,30,31,30,
31,31,30,31,30,31};//Compile-time
error
daysInMonth=newint[]{31,28,31,30,31,30,31,31,30,31,30,31};//
OK
InExample3.4,ananonymousarrayisconstructedat(1),andpassedasanactual
parametertothestaticmethodfindMinimum()definedat(2).Notethatnoarrayname
orarraysizeisspecifiedfortheanonymousarray.
WOW! eBook
www.wowebook.org
Example3.4UsingAnonymousArrays
Clickheretoviewcodeimage
publicclassAnonArray{
publicstaticvoidmain(String[]args){
System.out.println(“Minimumvalue:”+
findMinimum(newint[]{3,5,2,8,6}));//(1)
}
publicstaticintfindMinimum(int[]dataSeq){//(2)
//Assumethearrayhasatleastoneelement.
intmin=dataSeq[0];
for(intindex=1;index<dataSeq.length;++index)
if(dataSeq[index]<min)
min=dataSeq[index];
returnmin;
}
}
Outputfromtheprogram:
Minimumvalue:2
MultidimensionalArrays
Sinceanarrayelementcanbeanobjectreferenceandarraysareobjects,arrayelements
canthemselvesrefertootherarrays.InJava,anarrayofarrayscanbedefinedasfollows:
Clickheretoviewcodeimage
element_type[][]...[]array_name;
or
Clickheretoviewcodeimage
element_typearray_name[][]...[];
Infact,thesequenceofsquarebracketpairs,[],indicatingthenumberofdimensions,can
bedistributedasapostfixtoboththeelementtypeandthearrayname.Arraysofarrays
areoftencalledmultidimensionalarrays.
Thefollowingdeclarationsareallequivalent:
Clickheretoviewcodeimage
int[][]mXnArray;//2-dimensionalarray
int[]mXnArray[];//2-dimensionalarray
intmXnArray[][];//2-dimensionalarray
Itiscustomarytocombinethedeclarationwiththeconstructionofthemultidimensional
array.
Clickheretoviewcodeimage
int[][]mXnArray=newint[4][5];//4x5matrixofints
ThepreviousdeclarationconstructsanarraymXnArrayoffourelements,whereeach
elementisanarray(row)offiveintvalues.Theconceptofrowsandcolumnsisoften
usedtodescribethedimensionsofa2-dimensionalarray,whichisoftencalledamatrix.
WOW! eBook
www.wowebook.org
However,suchaninterpretationisnotdictatedbytheJavalanguage.
EachrowinthepreviousmatrixisdenotedbymXnArray[i],where0≤i<4.Each
elementintheithrow,mXnArray[i],isaccessedbymXnArray[i][j],where0≤
j<5.ThenumberofrowsisgivenbymXnArray.length,inthiscase4,andthe
numberofvaluesintheithrowisgivenbymXnArray[i].length,inthiscase5for
alltherows,where0≤i<4.
Multidimensionalarrayscanalsobeconstructedandexplicitlyinitializedusingthearray
initializersdiscussedforsimplearrays.Notethateachrowisanarraythatusesanarray
initializertospecifyitsvalues:
Clickheretoviewcodeimage
double[][]identityMatrix={
{1.0,0.0,0.0,0.0},//1.row
{0.0,1.0,0.0,0.0},//2.row
{0.0,0.0,1.0,0.0},//3.row
{0.0,0.0,0.0,1.0}//4.row
};//4x4floating-pointmatrix
Arraysinamultidimensionalarrayneednothavethesamelength;whentheydonot,they
arecalledraggedarrays.ThearrayofarrayspizzaGaloreinthefollowingcodehas
fiverows;thefirstfourrowshavedifferentlengthsbutthefifthrowisleftunconstructed:
Clickheretoviewcodeimage
Pizza[][]pizzaGalore={
{newPizza(),null,newPizza()},//1.rowisanarrayof3elements.
{null,newPizza()},//2.rowisanarrayof2elements.
newPizza[1],//3.rowisanarrayof1element.
{},//4.rowisanarrayof0elements.
null//5.rowisnotconstructed.
};
Whenconstructingmultidimensionalarrayswiththenewoperator,thelengthofthe
deeplynestedarraysmaybeomitted.Insuchacase,thesearraysareleftunconstructed.
Forexample,anarrayofarraystorepresentaroomonafloorinahotelonastreetina
citycanhavethetypeHotelRoom[][][][].Fromlefttoright,thesquarebrackets
representindicesforstreet,hotel,floor,androom,respectively.This4-dimensionalarray
ofarrayscanbeconstructedpiecemeal,startingwiththeleftmostdimensionand
proceedingtotherightmostsuccessively.
Clickheretoviewcodeimage
HotelRoom[][][][]rooms=newHotelRoom[10][5][][];//Juststreetsand
hotels.
Theprecedingdeclarationconstructsthearrayofarraysroomspartiallywithtenstreets,
whereeachstreethasfivehotels.Floorsandroomscanbeaddedtoaparticularhotelona
particularstreet:
Clickheretoviewcodeimage
rooms[0][0]=newHotelRoom[3][];//3floorsin1sthotelon1st
street.
rooms[0][0][0]=newHotelRoom[8];//8roomson1stfloorinthis
hotel.
rooms[0][0][0][0]=newHotelRoom();//Initializes1stroomonthis
WOW! eBook
www.wowebook.org
floor.
Thenextcodesnippetconstructsanarrayofarraysmatrix,wherethefirstrowhasone
element,thesecondrowhastwoelements,andthethirdrowhasthreeelements.Notethat
theouterarrayisconstructedfirst.Theseconddimensionisconstructedinaloopthat
constructsthearrayineachrow.Theelementsinthemultidimensionalarraywillbe
implicitlyinitializedtothedefaultdoublevalue(0.0D).InFigure3.1,thearrayof
arraysmatrixisdepictedaftertheelementshavebeenexplicitlyinitialized.
Clickheretoviewcodeimage
double[][]matrix=newdouble[3][];//Numberofrows.
for(inti=0;i<matrix.length;++i)
matrix[i]=newdouble[i+1];//Constructarow.
Figure3.1ArrayofArrays
Twootherwaysofinitializingsuchanarrayofarraysareshownnext.Thefirstapproach
usesarrayinitializers,andthesecondusesananonymousarrayofarrays.
Clickheretoviewcodeimage
double[][]matrix2={//Usingarrayinitializers.
{0.0},//1.row
{0.0,0.0},//2.row
{0.0,0.0,0.0}//3.row
};
double[][]matrix3=newdouble[][]{//Usingananonymousarrayofarrays.
{0.0},//1.row
{0.0,0.0},//2.row
{0.0,0.0,0.0}//3.row
};
Thetypeofthevariablematrixisdouble[][],atwo-dimensionalarrayofdouble
values.Thetypeofthevariablematrix[i](where0≤i<matrix.length)is
double[],aone-dimensionalarrayofdoublevalues.Thetypeofthevariable
matrix[i][j](where0≤i<matrix.lengthand0≤j<matrix[i].length)
isdouble,asimplevariableoftypedouble.
WOW! eBook
www.wowebook.org
Nestedloopsareanaturalmatchformanipulatingmultidimensionalarrays.InExample
3.5,arectangular4×3intmatrixisdeclaredandconstructedat(1).Theprogramfinds
theminimumvalueinthematrix.Theouterloopat(2)traversestherows
(mXnArray[i],where0≤i<mXnArray.length),andtheinnerloopat(3)
traversestheelementsineachrowinturn(mXnArray[i][j],where0≤j<
mXnArray[i].length).TheouterloopisexecutedmXnArray.lengthtimes,or4
times,andtheinnerloopisexecuted(mXnArray.length)×
(mXnArray[i].length),or12times,sinceallrowshavethesamelength3.
Thefor(:)loopalsoprovidesasafeandconvenientwayoftraversinganarray.Several
examplesofitsuseareprovidedin§6.3,p.217.
Example3.5UsingMultidimensionalArrays
Clickheretoviewcodeimage
publicclassMultiArrays{
publicstaticvoidmain(String[]args){
//DeclareandconstructtheMXNmatrix.
int[][]mXnArray={//(1)
{16,7,12},//1.row
{9,20,18},//2.row
{14,11,5},//3.row
{8,5,10}//4.row
};//4x3intmatrix
//FindtheminimumvalueinaMXNmatrix:
intmin=mXnArray[0][0];
for(inti=0;i<mXnArray.length;++i)//(2)
//FindmininmXnArray[i],intherowgivenbyindexi:
for(intj=0;j<mXnArray[i].length;++j)//(3)
min=Math.min(min,mXnArray[i][j]);
System.out.println(“Minimumvalue:”+min);
}
}
Outputfromtheprogram:
Minimumvalue:5
SortingArrays
Sortingimpliesorderingtheelementsaccordingtosomerankingcriteria,usuallybasedon
thevaluesoftheelements.Thevaluesofnumericdatatypescanbecomparedandranked
byusingtherelationaloperators.Forcomparingobjectsofaclass,theclasstypically
implementsthecompareTo()methodoftheComparableinterface.Theordering
definedbythismethodiscalledthenaturalorderingfortheobjectsoftheclass.The
wrapperclassesforprimitivevaluesandtheStringclassimplementthe
compareTo()method(§8.3,p.350,and§8.4,p.363,respectively).
Thejava.util.Arraysclassprovidesmanyoverloadedversionsofthesort()
methodtosortpracticallyanytypeofarray.
WOW! eBook
www.wowebook.org
voidsort(type[]array)
Permittedtypeforelementsincludesbyte,char,double,float,int,long,
short,andObject.Themethodsortstheelementsinthearrayaccordingtotheir
naturalordering.Inthecaseofanarrayofobjectsbeingpassedasargument,the
objectsmustbemutuallycomparable;thatis,itshouldbepossibletocompareany
twoobjectsinthearrayaccordingtothenaturalorderingdefinedbythe
compareTo()methodoftheComparableinterface.
Anappropriateimportstatementshouldbeincludedinthesourcecodetoaccessthe
java.util.Arraysclass.Inthenextcodesnippet,anarrayofstringsissorted
accordingtonaturalorderingforstrings—thatis,basedontheUnicodevaluesofthe
charactersinthestrings:
Clickheretoviewcodeimage
String[]strArray={“biggest”,“big”,“bigger”,“Bigfoot”};
Arrays.sort(strArray);//Naturalordering:[Bigfoot,big,bigger,
biggest]
Thenextexamplesillustratesortinganarrayofprimitivevalues(int)at(1),andanarray
oftypeObjectcontainingmutuallycomparableelements(String)at(2).In(3),the
numericalvaluesareautoboxedintotheircorrespondingwrapperclasses(§8.3,p.346),
buttheobjectsofdifferentwrapperclassesandtheStringclassarenotmutually
comparable.In(4),thenumericalvaluesarealsoautoboxedintotheircorresponding
wrapperclasses,butagaintheobjectsofdifferentwrapperclassesarenotmutually
comparable.AClassCastExceptionisthrownwhentheelementsarenotmutually
comparable.
Clickheretoviewcodeimage
int[]intArray={5,3,7,1};//int
Arrays.sort(intArray);//(1)Naturalordering:[1,3,
5,7]
Object[]objArray1={“I”,“am”,“OK”};//String
Arrays.sort(objArray1);//(2)Naturalordering:[I,OK,
am]
Object[]objArray2={23,“ten”,3.14};//Notmutuallycomparable
Arrays.sort(objArray2);//(3)ClassCastException
Number[]numbers={23,3.14,10L};//Notmutuallycomparable
Arrays.sort(numbers);//(4)ClassCastException
SearchingArrays
Acommonoperationonanarrayistosearchthearrayforagivenelement,calledthekey.
Thejava.util.Arraysclassprovidesoverloadedversionsofthe
binarySearch()methodtosearchinpracticallyanytypeofarraythatissorted.
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
intbinarySearch(type[]array,typekey)
Permittedtypeforelementsincludebyte,char,double,float,int,long,
short,andObject.Thearraymustbesortedinascendingorderbeforecalling
thismethod,ortheresultsareunpredictable.Inthecasewhereanarrayofobjectsis
passedasargument,theobjectsmustbesortedinascendingorderaccordingtotheir
naturalordering,asdefinedbytheComparableinterface.
Themethodreturnstheindextothekeyinthesortedarray,ifthekeyexists.The
indexisthenguaranteedtobegreaterorequalto0.Ifthekeyisnotfound,a
negativeindexisreturned,correspondingto–(insertionpoint+1),whereinsertion
pointistheindexoftheelementwherethekeywouldhavebeenfound,ifithad
beeninthearray.Ifthereareduplicateelementsequaltothekey,thereisno
guaranteewhichduplicate’sindexwillbereturned.Theelementsandthekeymust
bemutuallycomparable.
Anappropriateimportstatementshouldbeincludedinthesourcecodetoaccessthe
java.util.Arraysclass.Inthecodethatfollows,thereturnvalue–3indicatesthat
thekeywouldhavebeenfoundatindex2haditbeeninthelist:
Clickheretoviewcodeimage
//SortedStringarray(naturalordering):[Bigfoot,big,bigger,biggest]
//Searchinnaturalordering:
intindex1=Arrays.binarySearch(strArray,“bigger”);//Successful:2
intindex2=Arrays.binarySearch(strArray,“bigfeet”);//Unsuccessful:-3
intindex3=Arrays.binarySearch(strArray,“bigmouth”);//Unsuccessful:-5
Resultsareunpredictableifthearrayisnotsorted,oriftheorderingusedinthesearchis
notthesameasthesortordering.SearchinginthestrArrayusingnaturalordering
whenthearrayissortedinreversenaturalorderinggivesthewrongresult:
Clickheretoviewcodeimage
//SortedStringarray(inversenaturalordering):[biggest,bigger,big,
Bigfoot]
//Searchinnaturalordering:
intindex4=Arrays.binarySearch(strArray,“big”);//-1(INCORRECT)
AClassCastExceptionisthrownifthekeyandtheelementsarenotmutually
comparable:
Clickheretoviewcodeimage
intindex5=Arrays.binarySearch(strArray,4);//Key:4=>
ClassCastException
However,thisincompatibilityiscaughtatcompiletimeinthecaseofarrayswith
primitivevalues:
Clickheretoviewcodeimage
//Sortedintarray(naturalordering):[1,3,5,7]
intindex6=Arrays.binarySearch(intArray,4.5);//Key:4.5=>compile-time
error!
ThemethodbinarySearch()derivesitsnamefromthedivide-and-conqueralgorithm
WOW! eBook
www.wowebook.org
thatitusestoperformthesearch.Itrepeatedlydividestheremainingelementstobe
searchedintotwohalvesandselectsthehalfcontainingthekeytocontinuethesearchin,
untileitherthekeyisfoundortherearenomoreelementslefttosearch.
ReviewQuestions
3.7Giventhefollowingdeclaration,whichexpressionreturnsthesizeofthearray,
assumingthatthearrayreferencehasbeenproperlyinitialized?
int[]array;
Selecttheonecorrectanswer.
(a)array[].length()
(b)array.length()
(c)array[].length
(d)array.length
(e)array[].size()
(f)array.size()
(g)array[].size
(h)array.size
3.8Isitpossibletocreatearraysoflengthzero?
Selecttheonecorrectanswer.
(a)Yes,youcancreatearraysofanytypewithlengthzero.
(b)Yes,butonlyforprimitivedatatypes.
(c)Yes,butonlyforarraysofreferencetypes.
(d)No,youcannotcreatezero-lengtharrays,butthemain()methodmaybe
passedazero-lengtharrayofStringswhennoprogramargumentsare
specified.
(e)No,itisnotpossibletocreatearraysoflengthzeroinJava.
3.9Whichoneofthefollowingarraydeclarationstatementsisnotlegal?
Selecttheonecorrectanswer.
(a)int[]a[]=newint[4][4];
(b)inta[][]=newint[4][4];
(c)inta[][]=newint[][4];
(d)int[]a[]=newint[4][];
(e)int[][]a=newint[4][4];
WOW! eBook
www.wowebook.org
3.10Whichofthesearraydeclarationstatementsarenotlegal?
Selectthetwocorrectanswers.
(a)int[]i[]={{1,2},{1},{},{1,2,3}};
(b)inti[]=newint[2]{1,2};
(c)inti[][]=newint[][]{{1,2,3},{4,5,6}};
(d)inti[][]={{1,2},newint[2]};
(e)inti[4]={1,2,3,4};
3.11Whatwouldbetheresultofcompilingandrunningthefollowingprogram?
Clickheretoviewcodeimage
publicclassMyClass{
publicstaticvoidmain(String[]args){
intsize=20;
int[]arr=newint[size];
for(inti=0;i<size;++i){
System.out.println(arr[i]);
}
}
}
Selecttheonecorrectanswer.
(a)Thecodewillnotcompile,becausethearraytypeint[]isincorrect.
(b)Theprogramwillcompile,butwillthrowan
ArrayIndexOutOfBoundsExceptionwhenrun.
(c)Theprogramwillcompileandrunwithouterror,butwillproducenooutput.
(d)Theprogramwillcompileandrunwithouterror,andwillprintthenumbers0
through19.
(e)Theprogramwillcompileandrunwithouterror,andwillprint0twentytimes.
(f)Theprogramwillcompileandrunwithouterror,andwillprintnulltwenty
times.
3.12Whatwouldbetheresultofcompilingandrunningthefollowingprogram?
Clickheretoviewcodeimage
publicclassDefaultValuesTest{
int[]ia=newint[1];
booleanb;
inti;
Objecto;
publicstaticvoidmain(String[]args){
DefaultValuesTestinstance=newDefaultValuesTest();
instance.print();
}
publicvoidprint(){
System.out.println(ia[0]+””+b+””+i+””+o);
WOW! eBook
www.wowebook.org
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompilebecauseofuninitializedvariables.
(b)Theprogramwillthrowajava.lang.NullPointerExceptionwhen
run.
(c)Theprogramwillprint0falseNaNnull.
(d)Theprogramwillprint0false0null.
(e)Theprogramwillprintnull00null.
(f)Theprogramwillprintnullfalse0null.
3.5ParameterPassing
Objectscommunicatebycallingmethodsoneachother.Amethodcallisusedtoinvokea
methodonanobject.Parametersinthemethodcallprovideonewayofexchanging
informationbetweenthecallerobjectandthecalleeobject(whichneednotbedifferent).
Declaringmethodsisdiscussedin§3.2,p.49.Invokingstaticmethodsonclassesis
discussedin§4.8,p.132.
Thesyntaxofamethodcallcanbeanyoneofthefollowing:
Clickheretoviewcodeimage
object_reference.method_name(actual_parameter_list)
class_name.static_method_name(actual_parameter_list)
method_name(actual_parameter_list)
Theobject_referencemustbeanexpressionthatevaluatestoareferencevaluedenoting
theobjectonwhichthemethodiscalled.Ifthecallerandthecalleearethesame,object
referencecanbeomitted(seethediscussionofthethisreferencein§3.2,p.50).The
class_namecanbethefullyqualifiedname(§4.2,p.97)oftheclass.The
actual_parameter_listiscommaseparatedifthereismorethanoneparameter.The
parenthesesaremandatoryeveniftheactualparameterlistisempty.Thisdistinguishesthe
methodcallfromfieldaccess.Onecanspecifyfullyqualifiednamesforclassesand
packagesusingthedotoperator(.).
Clickheretoviewcodeimage
objRef.doIt(time,place);//Explicitobjectreference
inti=java.lang.Math.abs(-1);//Fullyqualifiedclassname
intj=Math.abs(-1);//Simpleclassname
someMethod(ofValue);//Objectorclassimplicitlyimplied
someObjRef.make().make().make();//make()returnsareferencevalue
Thedotoperator(.)hasleftassociativity.Inthelastcodeline,thefirstcallofthe
make()methodreturnsareferencevaluethatdenotestheobjectonwhichtoexecutethe
WOW! eBook
www.wowebook.org
nextcall,andsoon.Thisisanexampleofcallchaining.
Eachactualparameter(alsocalledanargument)isanexpressionthatisevaluated,and
whosevalueispassedtothemethodwhenthemethodisinvoked.Itsvaluecanvaryfrom
invocationtoinvocation.Formalparametersareparametersdefinedinthemethod
declaration(§3.2,p.49)andarelocaltothemethod(§2.4,p.44).
InJava,allparametersarepassedbyvalue—thatis,anactualparameterisevaluatedand
itsvalueisassignedtothecorrespondingformalparameter.Table3.1summarizesthe
valuethatispasseddependingonthetypeoftheparameters.Inthecaseofprimitivedata
types,thedatavalueoftheactualparameterispassed.Iftheactualparameterisa
referencetoanobject,thereferencevalueofthedenotedobjectispassedandnotthe
objectitself.Analogously,iftheactualparameterisanarrayelementofaprimitivedata
type,itsdatavalueispassed,andifthearrayelementisareferencetoanobject,thenits
referencevalueispassed.
Table3.1ParameterPassingbyValue
Itshouldalsobestressedthateachinvocationofamethodhasitsowncopiesoftheformal
parameters,asisthecaseforanylocalvariablesinthemethod(§6.5,p.230).
Theorderofevaluationintheactualparameterlistisalwaysfromlefttoright.The
evaluationofanactualparametercanbeinfluencedbyanearlierevaluationofanactual
parameter.Giventhefollowingdeclaration:
inti=4;
themethodcall
leftRight(i++,i);
iseffectivelythesameas
leftRight(4,5);
andnotthesameas
leftRight(4,4);
Anoverviewoftheconversionsthatcantakeplaceinamethodinvocationcontextis
providedin§5.2,p.148.Methodinvocationconversionsforprimitivevaluesare
discussedinthenextsubsection(p.73),andthoseforreferencetypesarediscussedin
§7.10,p.315.Callingvariablearitymethodsisdiscussedin§3.6,p.81.
Forthesakeofsimplicity,theexamplesinsubsequentsectionsprimarilyshowmethod
invocationonthesameobjectorthesameclass.Theparameterpassingmechanismisno
differentwhendifferentobjectsorclassesareinvolved.
WOW! eBook
www.wowebook.org
PassingPrimitiveDataValues
Anactualparameterisanexpressionthatisevaluatedfirst,withtheresultingvaluethen
beingassignedtothecorrespondingformalparameteratmethodinvocation.Theuseof
thisvalueinthemethodhasnoinfluenceontheactualparameter.Inparticular,whenthe
actualparameterisavariableofaprimitivedatatype,thevalueofthevariableiscopiedto
theformalparameteratmethodinvocation.Sinceformalparametersarelocaltothe
method,anychangesmadetotheformalparameterwillnotbereflectedintheactual
parameterafterthecallcompletes.
Legaltypeconversionsbetweenactualparametersandformalparametersofprimitivedata
typesaresummarizedherefromTable5.1,p.147:
•Wideningprimitiveconversion
•Unboxingconversion,followedbyanoptionalwideningprimitiveconversion
Theseconversionsareillustratedbyinvokingthefollowingmethod
Clickheretoviewcodeimage
staticvoiddoIt(longi){/*…*/}
withthefollowingcode:
Clickheretoviewcodeimage
IntegerintRef=34;
LonglongRef=34L;
doIt(34);//(1)Primitivewideningconversion:long<—int
doIt(longRef);//(2)Unboxing:long<—Long
doIt(intRef);//(3)Unboxing,followedbyprimitivewideningconversion:
//long<—int<—Integer
However,forparameterpassing,therearenoimplicitnarrowingconversionsforinteger
constantexpressions(§5.2,p.148).
WOW! eBook
www.wowebook.org
Example3.6PassingPrimitiveValues
Clickheretoviewcodeimage
publicclassCustomerOne{
publicstaticvoidmain(String[]args){
PizzaFactorypizzaHouse=newPizzaFactory();
intpricePrPizza=15;
System.out.println(“ValueofpricePrPizzabeforecall:”+pricePrPizza);
doubletotPrice=pizzaHouse.calcPrice(4,pricePrPizza);//
(1)
System.out.println(“ValueofpricePrPizzaaftercall:”+pricePrPizza);
}
}
classPizzaFactory{
publicdoublecalcPrice(intnumberOfPizzas,doublepizzaPrice){//
(2)
pizzaPrice=pizzaPrice/2.0;//Changesprice.
System.out.println(“Changedpizzapriceinthemethod:”+pizzaPrice);
returnnumberOfPizzas*pizzaPrice;
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
ValueofpricePrPizzabeforecall:15
Changedpizzapriceinthemethod:7.5
ValueofpricePrPizzaaftercall:15
InExample3.6,themethodcalcPrice()isdefinedintheclassPizzaFactoryat
(2).ItiscalledfromtheCustomerOne.main()methodat(1).Thevalueofthefirst
actualparameter,4,iscopiedtotheintformalparameternumberOfPizzas.Notethat
thesecondactualparameterpricePrPizzaisofthetypeint,whilethecorresponding
formalparameterpizzaPriceisofthetypedouble.Beforethevalueoftheactual
parameterpricePrPizzaiscopiedtotheformalparameterpizzaPrice,itis
implicitlywidenedtoadouble.ThepassingofprimitivevaluesisillustratedinFigure
3.2.
Figure3.2ParameterPassing:PrimitiveDataValues
ThevalueoftheformalparameterpizzaPriceischangedinthecalcPrice()
method,butthisdoesnotaffectthevalueoftheactualparameterpricePrPizzaon
WOW! eBook
www.wowebook.org
return:Itstillhasthevalue15.Thebottomlineisthattheformalparameterisalocal
variable,andchangingitsvaluedoesnotaffectthevalueoftheactualparameter.
PassingReferenceValues
Iftheactualparameterexpressionevaluatestoareferencevalue,theresultingreference
valueisassignedtothecorrespondingformalparameterreferenceatmethodinvocation.
Inparticular,ifanactualparameterisareferencetoanobject,thereferencevaluestored
intheactualparameterispassed.Consequently,boththeactualparameterandtheformal
parameterarealiasestotheobjectdenotedbythisreferencevalueduringtheinvocationof
themethod.Inparticular,thisimpliesthatchangesmadetotheobjectviatheformal
parameterwillbeapparentafterthecallreturns.
Typeconversionsbetweenactualandformalparametersofreferencetypesarediscussed
in§7.10,p.315.
InExample3.7,aPizzaobjectiscreatedat(1).AnyobjectoftheclassPizzacreated
usingtheclassdeclarationat(5)alwaysresultsinabeefpizza.Inthecalltothebake()
methodat(2),thereferencevalueoftheobjectreferencedbytheactualparameter
favoritePizzaisassignedtotheformalparameterpizzaToBeBakedinthe
declarationofthebake()methodat(3).
Example3.7PassingReferenceValues
Clickheretoviewcodeimage
publicclassCustomerTwo{
publicstaticvoidmain(String[]args){
PizzafavoritePizza=newPizza();//(1)
System.out.println(“Meatonpizzabeforebaking:”+favoritePizza.meat);
bake(favoritePizza);//(2)
System.out.println(“Meatonpizzaafterbaking:”+favoritePizza.meat);
}
publicstaticvoidbake(PizzapizzaToBeBaked){//(3)
pizzaToBeBaked.meat=“chicken”;//Changethemeatonthepizza.
pizzaToBeBaked=null;//(4)
}
}
classPizza{//(5)
Stringmeat=“beef”;
}
Outputfromtheprogram:
Clickheretoviewcodeimage
Meatonpizzabeforebaking:beef
Meatonpizzaafterbaking:chicken
Oneparticularconsequenceofpassingreferencevaluestoformalparametersisthatany
changesmadetotheobjectviaformalparameterswillbereflectedbackinthecalling
methodwhenthecallreturns.Inthiscase,thereferencefavoritePizzawillshowthat
chickenhasbeensubstitutedforbeefonthepizza.Settingtheformalparameter
WOW! eBook
www.wowebook.org
pizzaToBeBakedtonullat(4)doesnotchangethereferencevalueintheactual
parameterfavoritePizza.Thesituationatmethodinvocation,andjustbeforethe
returnfrommethodbake(),isillustratedinFigure3.3.
Figure3.3ParameterPassing:ReferenceValues
Insummary,theformalparametercanonlychangethestateoftheobjectwhosereference
valuewaspassedtothemethod.
TheparameterpassingstrategyinJavaiscallbyvalueandnotcallbyreference,
regardlessofthetypeoftheparameter.Callbyreferencewouldhaveallowedvaluesinthe
actualparameterstobechangedviaformalparameters;thatis,thevaluein
pricePrPizzawouldbehalvedinExample3.6andfavoritePizzawouldbeset
tonullinExample3.7.However,thiscannotbedirectlyimplementedinJava.
WOW! eBook
www.wowebook.org
PassingArrays
Thediscussionofpassingreferencevaluesintheprevioussectionisequallyvalidfor
arrays,asarraysareobjectsinJava.Methodinvocationconversionsforarraytypesare
discussedalongwiththoseforotherreferencetypesin§7.10,p.315.
InExample3.8,theideaistorepeatedlyswapneighboringelementsinanintegerarray
untilthelargestelementinthearraypercolatestothelastpositioninthearray.
Example3.8PassingArrays
Clickheretoviewcodeimage
publicclassPercolate{
publicstaticvoidmain(String[]args){
int[]dataSeq={8,4,6,2,1};//Createandinitializeanarray.
//Writearraybeforepercolation:
printIntArray(dataSeq);
//Percolate:
for(intindex=1;index<dataSeq.length;++index)
if(dataSeq[index-1]>dataSeq[index])
swap(dataSeq,index-1,index);//(1)
//Writearrayafterpercolation:
printIntArray(dataSeq);
}
publicstaticvoidswap(int[]intArray,inti,intj){//(2)
inttmp=intArray[i];intArray[i]=intArray[j];intArray[j]=tmp;
}
publicstaticvoidswap(intv1,intv2){//(3)Logical
error!
inttmp=v1;v1=v2;v2=tmp;
}
publicstaticvoidprintIntArray(int[]array){//(4)
for(intvalue:array)
System.out.print(””+value);
System.out.println();
}
}
Outputfromtheprogram:
84621
46218
Notethatinthedeclarationofthemethodswap()at(2),theformalparameter
intArrayisofthearraytypeint[].Theswap()methodiscalledinthemain()
methodat(1),whereoneoftheactualparametersisthearrayvariabledataSeq.The
referencevalueofthearrayvariabledataSeqisassignedtothearrayvariable
intArrayatmethodinvocation.Afterreturnfromthecalltotheswap()method,the
arrayvariabledataSeqwillreflectthechangesmadetothearrayviathecorresponding
formalparameter.ThissituationisdepictedinFigure3.4atthefirstcallandreturnfrom
WOW! eBook
www.wowebook.org
theswap()method,indicatinghowthevaluesoftheelementsatindices0and1inthe
arrayhavebeenswapped.
Figure3.4ParameterPassing:Arrays
However,thedeclarationoftheswap()methodat(3)willnotswaptwovalues.The
methodcall
Clickheretoviewcodeimage
swap(dataSeq[index-1],dataSeq[index]);
willhavenoeffectonthearrayelements,astheswappingisdoneonthevaluesofthe
formalparameters.
ThemethodprintIntArray()at(4)alsohasaformalparameterofarraytype
int[].Notethattheformalparameterisspecifiedasanarrayreferenceusingthe[]
notation,butthisnotationisnotusedwhenanarrayispassedasanactualparameter.
ArrayElementsasActualParameters
Arrayelements,likeothervariables,canstorevaluesofprimitivedatatypesorreference
valuesofobjects.Inthelattercase,theycanalsobearrays—thatis,arraysofarrays(§3.4,
p.63).Ifanarrayelementisofaprimitivedatatype,itsdatavalueispassed;ifitisa
referencetoanobject,thereferencevalueispassed.Themethodinvocationconversions
applytothevaluesofarrayelementsaswell.
WOW! eBook
www.wowebook.org
Example3.9ArrayElementsasPrimitiveDataValues
Clickheretoviewcodeimage
publicclassFindMinimum{
publicstaticvoidmain(String[]args){
int[]dataSeq={6,4,8,2,1};
intminValue=dataSeq[0];
for(intindex=1;index<dataSeq.length;++index)
minValue=minimum(minValue,dataSeq[index]);//(1)
System.out.println(“Minimumvalue:”+minValue);
}
publicstaticintminimum(inti,intj){//(2)
return(i<=j)?i:j;
}
}
Outputfromtheprogram:
Minimumvalue:1
InExample3.9,thevalueofallbutoneelementofthearraydataSeqisretrievedand
passedconsecutivelyat(1)totheformalparameterjoftheminimum()methoddefined
at(2).Thediscussionin§3.5,p.73,onpassingprimitivevaluesalsoappliestoarray
elementsthathaveprimitivevalues.
InExample3.10,theformalparameterseqofthefindMinimum()methoddefinedat
(4)isanarrayvariable.Thevariablematrixdenotesanarrayofarraysdeclaredat(1)
simulatingamultidimensionalarray,whichhasthreerows,whereeachrowisasimple
array.Thefirstrow,denotedbymatrix[0],ispassedtothefindMinimum()method
inthecallat(2).Eachremainingrowispassedbyitsreferencevalueinthecalltothe
findMinimum()methodat(3).
WOW! eBook
www.wowebook.org
Example3.10ArrayElementsasReferenceValues
Clickheretoviewcodeimage
publicclassFindMinimumMxN{
publicstaticvoidmain(String[]args){
int[][]matrix={{8,4},{6,3,2},{7}};//(1)
intmin=findMinimum(matrix[0]);//(2)
for(inti=1;i<matrix.length;++i){
intminInRow=findMinimum(matrix[i]);//(3)
min=Math.min(min,minInRow);
}
System.out.println(“Minimumvalueinmatrix:”+min);
}
publicstaticintfindMinimum(int[]seq){//(4)
intmin=seq[0];
for(inti=1;i<seq.length;++i)
min=Math.min(min,seq[i]);
returnmin;
}
}
Outputfromtheprogram:
Minimumvalueinmatrix:2
Parameters
Aformalparametercanbedeclaredwiththekeywordfinalprecedingtheparameter
declarationinthemethoddeclaration.Afinalparameterisalsoknownasablankfinal
variable;thatis,itisblank(uninitialized)untilavalueisassignedtoit,(e.g.,atmethod
invocation)andthenthevalueinthevariablecannotbechangedduringthelifetimeofthe
variable(seealsothediscussionin§4.8,p.133).Thecompilercantreatfinalvariables
asconstantsforcodeoptimizationpurposes.Declaringparametersasfinalprevents
theirvaluesfrombeingchangedinadvertently.Aformalparameter’sdeclarationas
finaldoesnotaffectthecaller’scode.
ThedeclarationofthemethodcalcPrice()fromExample3.6isshownnext,withthe
formalparameterpizzaPricedeclaredasfinal:
Clickheretoviewcodeimage
publicdoublecalcPrice(intnumberOfPizzas,finaldoublepizzaPrice){//
(2’)
pizzaPrice=pizzaPrice/2.0;//(3)Notallowed
returnnumberOfPizzas*pizzaPrice;
}
IfthisdeclarationofthecalcPrice()methodiscompiled,thecompilerwillnotallow
thevalueofthefinalparameterpizzaPricetobechangedat(3)inthebodyofthe
method.
Asanotherexample,thedeclarationofthemethodbake()fromExample3.7isshown
here,withtheformalparameterpizzaToBeBakeddeclaredasfinal:
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
publicstaticvoidbake(finalPizzapizzaToBeBaked){//(3)
pizzaToBeBaked.meat=“chicken”;//(3a)Allowed
pizzaToBeBaked=null;//(4)Notallowed
}
Ifthisdeclarationofthebake()methodiscompiled,thecompilerwillnotallowthe
referencevalueofthefinalparameterpizzaToBeBakedtobechangedat(4)inthe
bodyofthemethod.Notethatthisappliestothereferencevalueinthefinalparameter,
butnottotheobjectdenotedbythisparameter.Thestateoftheobjectcanbechangedas
before,asshownat(3a).
3.6VariableArityMethods
Afixedaritymethodmustbecalledwiththesamenumberofactualparameters(also
calledarguments)asthenumberofformalparametersspecifiedinitsdeclaration.Ifthe
methoddeclarationspecifiestwoformalparameters,everycallofthismethodmust
specifyexactlytwoarguments.Wesaythatthearityofthismethodis2.Inotherwords,
thearityofsuchamethodisfixed,anditisequaltothenumberofformalparameters
specifiedinthemethoddeclaration.
Javaalsoallowsdeclarationofvariablearitymethods,meaningthatthenumberof
argumentsinitscallcanbevaried.Asweshallsee,invocationsofsuchamethodmay
containmoreactualparametersthanformalparameters.Variablearitymethodsareheavily
employedinformattingtextrepresentationofvalues,asdemonstratedbythevariablearity
methodSystem.out.printf()thatisusedinmanyexamplesforthispurpose.
Thelastformalparameterinavariablearitymethoddeclarationisdeclaredasfollows:
type...formal_parameter_name
Theellipsis(...)isspecifiedbetweenthetypeandtheformal_parameter_name.The
typecanbeaprimitivetype,areferencetype,oratypeparameter.Whitespacecanbe
specifiedonbothsidesoftheellipsis.Suchaparameterisusuallycalledavariablearity
parameter(alsoknownasvarargs).
Apartfromthevariablearityparameter,avariablearitymethodisidenticaltoafixedarity
method.Themethodpublish()isavariablearitymethod:
Clickheretoviewcodeimage
publicstaticvoidpublish(intn,String…data){//(int,String[])
System.out.println(“n:”+n+“,datasize:”+data.length);
}
Thevariablearityparameterinavariablearitymethodisalwaysinterpretedashavingan
arraytype:
type[]
Inthebodyofthepublish()method,thevariablearityparameterdatahasthetype
String[],soitisasimplearrayofStrings.
Onlyonevariablearityparameterispermittedintheformalparameterlist,anditisalways
thelastparameterintheformalparameterlist.Giventhatthemethoddeclarationhasn
WOW! eBook
www.wowebook.org
formalparameters,andthemethodcallhaskactualparameters,kmustbeequaltoor
greaterthann–1.Thelastk–n+1actualparametersareevaluatedandstoredinanarray
whosereferencevalueispassedasthevalueoftheactualparameter.Inthecaseofthe
publish()method,nisequalto2,sokcanbe1,2,3,andsoon.Thefollowing
invocationsofthepublish()methodshowwhichargumentsarepassedineachmethod
call:
Clickheretoviewcodeimage
publish(1);//(1,newString[]{})
publish(2,“two”);//(2,newString[]{“two”})
publish(3,“two”,“three”);//(3,newString[]{“two”,“three”})
Eachmethodcallresultsinanimplicitarraybeingcreatedandpassedasanargument.
Thisarraycancontainzeroormoreargumentvaluesthatdonotcorrespondtotheformal
parametersprecedingthevariablearityparameter.Thisarrayisreferencedbythevariable
arityparameterdatainthemethoddeclaration.Theprecedingcallswouldresultinthe
publish()methodprintingthefollowingoutput:
n:1,datasize:0
n:2,datasize:1
n:3,datasize:2
Tooverloadavariablearitymethod,itisnotenoughtochangethetypeofthevariable
arityparametertoanexplicitarraytype.Thecompilerwillcomplainifanattemptismade
tooverloadthemethodtransmit(),asshowninthefollowingcode:
Clickheretoviewcodeimage
publicstaticvoidtransmit(String…data){}//Compile-timeerror!
publicstaticvoidtransmit(String[]data){}//Compile-timeerror!
Thesedeclarationswouldresultintwomethodswithequivalentsignaturesinthesame
class,whichisnotpermitted.
Overloadingandoverridingofmethodswithvariablearityarediscussedin§7.10,p.316.
CallingaVariableArityMethod
Example3.11illustratesvariousaspectsofcallingavariablearitymethod.Themethod
flexiPrint()intheVarargsDemoclasshasavariablearityparameter:
Clickheretoviewcodeimage
publicstaticvoidflexiPrint(Object…data){//Object[]
//…
}
ThevariablearitymethodprintsthenameoftheClassobjectrepresentingtheactual
arraythatispassedatruntime.Itprintsthenumberofelementsinthisarrayaswellasthe
textrepresentationofeachelementinthearray.
ThemethodflexiPrint()iscalledinthemain()method.Firstwiththevaluesof
primitivetypesandStrings((1)to(8)),thenitiscalledwiththeprogramarguments(p.
85)suppliedinthecommandline,((9)to(11)).
Compilingtheprogramresultsinawarningat(9),whichweignoreforthetimebeing.
Theprogramcanstillberun,asshowninExample3.11.Thenumbersattheendofthe
WOW! eBook
www.wowebook.org
linesintheoutputrelatetonumbersinthecode,andarenotprintedbytheprogram.
Example3.11CallingaVariableArityMethod
Clickheretoviewcodeimage
publicclassVarargsDemo{
publicstaticvoidflexiPrint(Object…data){//Object[]
//PrintthenameoftheClassobjectforthevarargsparameter.
System.out.print(“Type:”+data.getClass().getName());
System.out.println(“No.ofelements:”+data.length);
System.out.print(“Elementvalues:“);
for(Objectelement:data)
System.out.print(element+”“);
System.out.println();
}
publicstaticvoidmain(String…args){
intday=13;
StringmonthName=“August”;
intyear=2009;
//Passingprimitivesandnon-arraytypes:
flexiPrint();//(1)newObject[]{}
flexiPrint(day);//(2)newObject[]
{Integer.valueOf(day)}
flexiPrint(day,monthName);//(3)newObject[]
{Integer.valueOf(day),
//monthName}
flexiPrint(day,monthName,year);//(4)newObject[]
{Integer.valueOf(day),
//monthName,
//Integer.valueOf(year)}
System.out.println();
//Passinganarraytype:
Object[]dateInfo={day,//(5)newObject[]
{Integer.valueOf(day),
monthName,//monthName,
year};//Integer.valueOf(year)}
flexiPrint(dateInfo);//(6)Non-varargscall
flexiPrint((Object)dateInfo);//(7)newObject[]{(Object)
dateInfo}
flexiPrint(newObject[]{dateInfo});//(8)Non-varargscall
System.out.println();
//Explicitvarargsornon-varargscall:
flexiPrint(args);//(9)Warning!
flexiPrint((Object)args);//(10)Explicitvarargscall
flexiPrint((Object[])args);//(11)Explicitnon-varargscall
}
}
Compilingtheprogram:
Clickheretoviewcodeimage
>javacVarargsDemo.java
VarargsDemo.java:41:warning:non-varargscallofvarargsmethodwithinexact
argumenttypeforlastparameter;
flexiPrint(args);//(9)Warning!
WOW! eBook
www.wowebook.org
^
casttoObjectforavarargscall
casttoObject[]foranon-varargscallandtosuppressthiswarning
1warning
Runningtheprogram:
Clickheretoviewcodeimage
>javaVarargsDemoToargornottoarg
Type:[Ljava.lang.Object;No.ofelements:0(1)
Elementvalues:
Type:[Ljava.lang.Object;No.ofelements:1(2)
Elementvalues:13
Type:[Ljava.lang.Object;No.ofelements:2(3)
Elementvalues:13August
Type:[Ljava.lang.Object;No.ofelements:3(4)
Elementvalues:13August2009
Type:[Ljava.lang.Object;No.ofelements:3(6)
Elementvalues:13August2009
Type:[Ljava.lang.Object;No.ofelements:1(7)
Elementvalues:[Ljava.lang.Object;@1eed786
Type:[Ljava.lang.Object;No.ofelements:1(8)
Elementvalues:[Ljava.lang.Object;@1eed786
Type:[Ljava.lang.String;No.ofelements:6(9)
Elementvalues:Toargornottoarg
Type:[Ljava.lang.Object;No.ofelements:1(10)
Elementvalues:[Ljava.lang.String;@187aeca
Type:[Ljava.lang.String;No.ofelements:6(11)
Elementvalues:Toargornottoarg
VariableArityandFixedArityMethodCalls
Thecallsin(1)to(4)inExample3.11areallvariablearitycalls,asanimplicitObject
arrayiscreated,inwhichthevaluesoftheactualparametersarestored.Thereference
valueofthisarrayispassedtothemethod.Theprintoutshowsthatthetypeofthe
parameterisactuallyanarrayofObjects([Ljava.lang.Object;).
Thecallat(6)differsfromthepreviouscalls,inthattheactualparameterisanarraythat
hasthesametype(Object[])asthevariablearityparameter,withouthavingtocreate
animplicitarray.Insuchacase,noimplicitarrayiscreated,andthereferencevalueofthe
arraydateInfoispassedtothemethod.Seealsotheresultfromthiscallat(6)inthe
output.Thecallat(6)isafixedaritycall(alsocalledanon-varargscall),whereno
implicitarrayiscreated:
Clickheretoviewcodeimage
flexiPrint(dateInfo);//(6)Non-varargscall
However,iftheactualparameteriscasttothetypeObjectasin(7),avariablearitycall
isexecuted:
Clickheretoviewcodeimage
flexiPrint((Object)dateInfo);//(7)newObject[]{(Object)dateInfo}
Thetypeoftheactualargumentisnownotthesameasthatofthevariablearityparameter,
WOW! eBook
www.wowebook.org
resultinginanarrayofthetypeObject[]beingcreated,inwhichthearraydateInfo
isstoredasanelement.Theprintoutat(7)showsthatonlythetextrepresentationofthe
dateInfoarrayisprinted,andnotitselements,asitisthesoleelementoftheimplicit
array.
Thecallat(8)isafixedaritycall,forthesamereasonasthecallin(6).Now,however,the
arraydateInfoisexplicitlystoredasanelementinanarrayofthetypeObject[]that
matchesthetypeofthevariablearityparameter:
Clickheretoviewcodeimage
flexiPrint(newObject[]{dateInfo});//(8)Non-varargscall
Theoutputfrom(8)isthesameastheoutputfrom(7),wherethearraydateInfowas
passedasanelementinanimplicitlycreatedarrayoftypeObject[].
Thecompilerissuesawarningforthecallat(9):
Clickheretoviewcodeimage
flexiPrint(args);//(9)Warning!
TheactualparameterargsisanarrayofthetypeString[],whichisasubtypeof
Object[]—thetypeofthevariablearityparameter.Thearrayargscanbepassedina
fixedaritycallasanarrayofthetypeString[],orinavariablearitycallasanelement
inanimplicitlycreatedarrayofthetypeObject[].Bothcallsarefeasibleandvalidin
thiscase.Notethatthecompilerchoosesafixedaritycallratherthanavariablearitycall,
butalsoissuesawarning.Theresultat(9)confirmsthiscourseofaction.
ThearrayargsofthetypeString[]isexplicitlypassedasanObjectinavariable
aritycallat(10),similartothecallat(7):
Clickheretoviewcodeimage
flexiPrint((Object)args);//(10)Explicitvarargscall
ThearrayargsoftypeString[]isexplicitlypassedasanarrayofthetype
Object[]inafixedaritycallat(11).Thiscallisequivalenttothecallat(9),wherethe
wideningreferenceconversionisimplicit,butnowwithoutawarningatcompiletime.
Thetwocallsprintthesameinformation,asisevidentfromtheoutputat(9)and(11):
Clickheretoviewcodeimage
flexiPrint((Object[])args);//(11)Explicitnon-varargscall
3.7The Method
ThemechanicsofcompilingandrunningJavaapplicationsusingtheJDKareoutlinedin
§1.10,p.16.Thejavacommandexecutesamethodcalledmainintheclassspecified
onthecommandline.Anyclasscanhaveamain()method,butonlythemain()
methodoftheclassspecifiedinthejavacommandstartstheexecutionofaJava
application.
Themain()methodmusthavepublicaccessibilitysothattheJVMcancallthis
method(§4.7,p.123).Itisastaticmethodbelongingtotheclass,sothatnoobjectof
theclassisrequiredtostarttheexecution(§4.8,p.132).Itdoesnotreturnavalue;thatis,
WOW! eBook
www.wowebook.org
itisdeclaredasvoid(§6.4,p.224).ItalwayshasanarrayofStringobjectsasitsonly
formalparameter.Thisarraycontainsanyargumentspassedtotheprogramonthe
commandline(seethenextsubsection).Thefollowingmethodheaderdeclarationsfitthe
bill,andanyoneofthemcanbeusedforthemain()method:
Clickheretoviewcodeimage
publicstaticvoidmain(String[]args)//Methodheader
publicstaticvoidmain(String…args)//Methodheader
Thethreemodifierscanoccurinanyorderinthemethodheader.Therequirementsgiven
intheseexamplesdonotexcludespecificationofadditionalmodifiers(§4.8,p.131)or
anythrowsclause(§6.9,p.251).Themain()methodcanalsobeoverloadedlikeany
othermethod(§3.2,p.52).TheJVMensuresthatthemain()methodhavingthe
previouslymentionedmethodheaderisthestartingpointofprogramexecution.
ProgramArguments
Anyargumentspassedtotheprogramonthecommandlinecanbeaccessedinthe
main()methodoftheclassspecifiedonthecommandline:
>javaColorsredgreenblue
Theseargumentsarecalledprogramarguments.Notethatthecommandname,java,and
theclassnameColorsarenotpassedtothemain()methodoftheclassColors,nor
areanyotheroptionsthatarespecifiedonthecommandlinepassedtothismethod.
Sincetheformalparameterofthemain()methodisanarrayofStringobjects,
individualStringelementsinthearraycanbeaccessedbyusingthe[]operator.
InExample3.12,thethreeargumentsred,green,andbluecanbeaccessedinthe
main()methodoftheColorsclassasargs[0],args[1],andargs[2],
respectively.ThetotalnumberofargumentsisgivenbythefieldlengthoftheString
arrayargs.Notethatprogramargumentscanbepassedonlyasstrings,andmustbe
explicitlyconvertedtoothervaluesbytheprogram,ifnecessary.
Whennoargumentsarespecifiedonthecommandline,anarrayofzeroString
elementsiscreatedandpassedtothemain()method.Thusthereferencevalueofthe
formalparameterinthemain()methodisnevernull.
Programargumentssupplyinformationtotheapplication,whichcanbeusedtotailorthe
runtimebehavioroftheapplicationaccordingtouserrequirements.
WOW! eBook
www.wowebook.org
Example3.12PassingProgramArguments
Clickheretoviewcodeimage
publicclassColors{
publicstaticvoidmain(String[]args){
System.out.println(“No.ofprogramarguments:”+args.length);
for(inti=0;i<args.length;i++)
System.out.println(“Argumentno.”+i+”(”+args[i]+“)has”+
args[i].length()+”characters.”);
}
}
Runningtheprogram:
Clickheretoviewcodeimage
>javaColorsredgreenblue
No.ofprogramarguments:3
Argumentno.0(red)has3characters.
Argumentno.1(green)has5characters.
Argumentno.2(blue)has4characters.
3.8EnumeratedTypes
Inthissectionweprovideabasicintroductiontoenumeratedtypes.Anenumeratedtype
definesafinitesetofsymbolicnamesandtheirvalues.Thesesymbolicnamesareusually
calledenumconstantsornamedconstants.
Onewaytodefineconstantsistodeclarethemasfinal,staticvariablesinaclass(or
interface)declaration:
Clickheretoviewcodeimage
publicclassMachineState{
publicstaticfinalintBUSY=1;
publicstaticfinalintIDLE=0;
publicstaticfinalintBLOCKED=-1;
}
Suchconstantsarenottype-safe,asanyintvaluecanbeusedwhereweneedtousea
constantdeclaredintheMachineStateclass.Suchaconstantmustbequalifiedbythe
class(orinterface)name,unlesstheclassisextended(ortheinterfaceisimplemented).
Whensuchaconstantisprinted,onlyitsvalue(forexample,0),andnotitsname(for
example,IDLE),isprinted.Aconstantalsoneedsrecompilingifitsvalueischanged,as
thevaluesofsuchconstantsarecompiledintotheclientcode.
AnenumeratedtypeinJavaisaspecialkindofclasstypethatismuchmorepowerfulthan
theapproachoutlinedearlierfordefiningcollectionsofnamedconstants.
DeclaringType-safeEnums
Thecanonicalformofdeclaringanenumtypeisshownhere:
Clickheretoviewcodeimage
publicenumMachineState//Enumheader
{//Enumbody
BUSY,IDLE,BLOCKED//Enumconstants
WOW! eBook
www.wowebook.org
}
Thekeywordenumisusedtodeclareanenumtype,asopposedtothekeywordclass
foraclassdeclaration.Thebasicnotationrequirestheenumtypenameinenumheader,
andacomma-separatedlistofenumconstantscanbespecifiedintheenumbody.
Optionally,anaccessmodifiercanalsobespecifiedintheenumheader,asfora(top-
level)class.Intheexampleenumdeclaration,thenameoftheenumtypeis
MachineState.Itdefinesthreeenumconstantswithexplicitnames.Anenumconstant
canbeanylegalJavaidentifier,buttheconventionistouseuppercaselettersinthename.
Essentially,anenumdeclarationdefinesareferencetypethathasafinitenumberof
permissiblevaluesreferencedbytheenumconstants,andthecompilerensurestheyare
usedinatype-safemanner.
Othermemberdeclarationscanbespecifiedinthebodyofanenumtype,butthe
canonicalformsufficesforthepurposeofthisbook.Analogoustoaclassdeclaration,an
enumtypeiscompiledtoJavabytecodethatisplacedinaseparateclassfile.
Theenumtypesjava.time.Monthandjava.time.DayOfWeekaretwoexamples
ofenumtypesfromtheJavaSEplatformAPI.Aswewouldexpect,theMonthenum
typerepresentsthemonthsfromJANUARYtoDECEMBER,andtheDayOfWeekenum
typerepresentsthedaysoftheweekfromMONDAYtoSUNDAY.Examplesoftheirusage
canbefoundin§11.2,p.462.
Someadditionalexamplesofenumtypesfollow:
Clickheretoviewcodeimage
publicenumMarchingOrders{LEFT,RIGHT}
publicenumTrafficLightState{RED,YELLOW,GREEN}
enumMealType{BREAKFAST,LUNCH,DINNER}
UsingType-safeEnums
Example3.13illustratestheuseofenumconstants.Anenumtypeisessentiallyusedin
thesamewayasanyotherreferencetype.Enumconstantsareactuallypublic,
static,finalfieldsoftheenumtype,andtheyareimplicitlyinitializedwithinstances
oftheenumtypewhentheenumtypeisloadedatruntime.Sincetheenumconstantsare
staticmembers,theycanbeaccessedusingthenameoftheenumtype—analogousto
accessingstaticmembersinaclassoraninterface.
Example3.13showsamachineclientthatusesamachinewhosestateisanenum
constant.Inthisexample,weseethatanenumconstantcanbepassedasanargument,as
shownas(1),andwecandeclarereferenceswhosetypeisanenumtype,asshownas(3),
butwecannotcreatenewconstants(thatis,objects)oftheenumtypeMachineState.
Anattempttodoso,at(5),resultsinacompile-timeerror.
Thestringrepresentationofanenumconstantisitsname,asshownat(4).Notethatitis
notpossibletopassatypeofvalueotherthanaMachineStateenumconstantinthe
calltothemethodsetState()oftheMachineclass,asshownat(2).
WOW! eBook
www.wowebook.org
Example3.13UsingEnums
Clickheretoviewcodeimage
//File:MachineState.java
publicenumMachineState{BUSY,IDLE,BLOCKED}
//File:Machine.java
publicclassMachine{
privateMachineStatestate;
publicvoidsetState(MachineStatestate){this.state=state;}
publicMachineStategetState(){returnthis.state;}
}
//File:MachineClient.java
publicclassMachineClient{
publicstaticvoidmain(String[]args){
Machinemachine=newMachine();
machine.setState(MachineState.IDLE);//(1)Passedasavalue.
//machine.setState(1);//(2)Compile-time
error!
MachineStatestate=machine.getState();//(3)Declaringa
reference.
System.out.println(
“Currentmachinestate:”+state//(4)Printingtheenum
name.
);
//MachineStatenewState=newMachineState();//(5)Compile-time
error!
System.out.println(“Allmachinestates:”);
for(MachineStatems:MachineState.values()){//(6)Traversingover
enum
System.out.println(ms+“:”+ms.ordinal());//contants.
}
System.out.println(“Comparison:”);
MachineStatestate1=MachineState.BUSY;
MachineStatestate2=state1;
MachineStatestate3=MachineState.BLOCKED;
System.out.println(state1+”==”+state2+“:”+
(state1==state2));//(7)
System.out.println(state1+”isequalto”+state2+“:”+
(state1.equals(state2)));//(8)
System.out.println(state1+”islessthan”+state3+“:”+
(state1.compareTo(state3)<0));//(9)
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
Currentmachinestate:IDLE
Allmachinestates:
BUSY:0
IDLE:1
WOW! eBook
www.wowebook.org
BLOCKED:2
Comparison:
BUSY==BUSY:true
BUSYisequaltoBUSY:true
BUSYislessthanBLOCKED:true
SelectedMethodsforEnumTypes
Allenumtypesimplicitlyhavethefollowingusefulmethod:
Clickheretoviewcodeimage
staticEnumTypeName[]values()
Returnsanarraycontainingtheenumconstantsofthisenumtype,intheorderthey
arespecified.
Theloopat(6)inExample3.13illustratestraversingoveralltheMachineStateenum
constantsintheordertheyarespecified.AnarraycontainingalltheMachineState
constantsisobtainedbycallingthestaticmethodvalues()ontheenumtype.
Allenumtypesaresubtypesofthejava.lang.Enumclass,whichprovidesthedefault
behavior.Allenumtypesinheritthefollowingselectedmethodsfromthe
java.lang.Enumclass:
Clickheretoviewcodeimage
finalbooleanequals(Objectother)
Thismethodreturnstrueifthespecifiedobjectisequaltothisenumconstant.
finalintcompareTo(Eother)
Thenaturalorderoftheenumconstantsinanenumtypeisbasedontheirordinal
values(seetheordinal()methodnext).ThecompareTo()methodofthe
Comparableinterfacereturnsthevaluezeroifthisenumconstantisequaltothe
otherenumconstant,avaluelessthanzeroifthisenumconstantislessthanthe
otherenumconstant,oravaluegreaterthanzeroifthisenumconstantisgreater
thantheotherenumconstant.
finalintordinal()
Thismethodreturnstheordinalvalueofthisenumconstant(thatis,itspositionin
itsenumtypedeclaration).Thefirstenumconstantisassignedanordinalvalueof
zero.Iftheordinalvalueofanenumconstantislessthantheordinalvalueof
anotherenumconstantofthesameenumtype,theformeroccursbeforethelatterin
theenumtypedeclaration.
Notethattheequalitytestimplementedbytheequals()methodisbasedonreference
equality(==)oftheenumconstants,notonvalueequality.Anenumtypehasafinite
numberofdistinctobjects.Comparingtwoenumreferencesforequalitymeans
determiningwhethertheystorethereferencevalueofthesameenumconstant—inother
words,whetherthereferencesarealiases.Thus,foranytwoenumreferencesstate1
WOW! eBook
www.wowebook.org
andstate2,theexpressionsstate1.equals(state2)andstate1==state2
areequivalent,asshownat(7)and(8)inExample3.13.
Theordinalvalueoftheconstantsinanenumtypedeterminestheresultofcomparing
suchconstantswiththecompareTo()method,asshownat(9)inExample3.13.
ReviewQuestions
3.13Whatwillthefollowingprogramprintwhenrun?
Clickheretoviewcodeimage
publicclassParameterPass{
publicstaticvoidmain(String[]args){
inti=0;
addTwo(i++);
System.out.println(i);
}
staticvoidaddTwo(inti){
i+=2;
}
}
Selecttheonecorrectanswer.
(a)0
(b)1
(c)2
(d)3
3.14Whatwillbetheresultofcompilingandrunningthefollowingprogram?
Clickheretoviewcodeimage
publicclassPassing{
publicstaticvoidmain(String[]args){
inta=0;intb=0;
int[]bArr=newint[1];bArr[0]=b;
inc1(a);inc2(bArr);
System.out.println(“a=”+a+”b=”+b+”bArr[0]=”+bArr[0]);
}
publicstaticvoidinc1(intx){x++;}
publicstaticvoidinc2(int[]x){x[0]++;}
}
Selecttheonecorrectanswer.
(a)Thecodewillfailtocompile,sincex[0]++;isnotalegalstatement.
(b)Thecodewillcompileandwillprinta=1b=1bArr[0]=1atruntime.
(c)Thecodewillcompileandwillprinta=0b=1bArr[0]=1atruntime.
(d)Thecodewillcompileandwillprinta=0b=0bArr[0]=1atruntime.
WOW! eBook
www.wowebook.org
(e)Thecodewillcompileandwillprinta=0b=0bArr[0]=0atruntime.
3.15Whichstatements,wheninsertedat(1),willresultinacompile-timeerror?
Clickheretoviewcodeimage
publicclassParameterUse{
staticvoidmain(String[]args){
inta=0;
finalintb=1;
int[]c={2};
finalint[]d={3};
useArgs(a,b,c,d);
}
staticvoiduseArgs(finalinta,intb,finalint[]c,int[]d){
//(1)INSERTSTATEMENTHERE.
}
}
Selectthetwocorrectanswers.
(a)a++;
(b)b++;
(c)b=a;
(d)c[0]++;
(e)d[0]++;
(f)c=d;
3.16Whichofthefollowingmethoddeclarationsarevaliddeclarations?
Selectthethreecorrectanswers.
(a)voidcompute(int…is){}
(b)voidcompute(intis…){}
(c)voidcompute(int…is,inti,String…ss){}
(d)voidcompute(String…ds){}
(e)voidcompute(String…ss,intlen){}
(f)voidcompute(char[]ca,int…is){}
3.17Giventhefollowingcode:
Clickheretoviewcodeimage
publicclassRQ810A40{
staticvoidprint(Object…obj){
System.out.println(“Object…:”+obj[0]);
}
publicstaticvoidmain(String[]args){
//(1)INSERTMETHODCALLHERE.
}
}
Whichmethodcall,wheninsertedat(1),willnotresultinthefollowingoutput
WOW! eBook
www.wowebook.org
fromtheprogram:
Object…:9
Selecttheonecorrectanswer.
(a)print("9","1","1");
(b)print(9,1,1);
(c)print(newint[]{9,1,1});
(d)print(newInteger[]{9,1,1});
(e)print(newString[]{"9","1","1"});
(f)print(newObject[]{"9","1","1"});
(g)Noneoftheabove.
ChapterSummary
Thefollowingtopicswerecoveredinthischapter:
•Anoverviewofdeclarationsthatcanbespecifiedinaclass
•Declarationofmethods,usageofthethisreferenceinaninstancemethod,and
methodoverloading
•Declarationofconstructors,usageofthedefaultconstructor,andoverloadingof
constructors
•Explanationofdeclaration,construction,initialization,andusageofbothone-
dimensionalandmultidimensionalarrays,includinganonymousarrays
•Sortingandsearchingarrays
•Parameterpassing,bothprimitivevaluesandobjectreferences,includingarraysand
arrayelements;anddeclaringfinalparameters
•Declaringandcallingmethodswithvariablearity
•Declarationofthemain()methodwhoseexecutionstartstheapplication
•Passingprogramargumentstothemain()method
•Declaringandusingsimpleenumtypes
ProgrammingExercise
3.1Writeaprogramtogradeashortmultiple-choicequiz.Thecorrectanswersforthe
quizare
1.C5.B
2.A6.C
3.B7.C
4.D8.A
WOW! eBook
www.wowebook.org
Assumethatthepassingmarksareatleast5outof8.Theprogramstoresthe
correctanswersinanarray.Thesubmittedanswersarespecifiedasprogram
arguments.LetXrepresentaquestionthatwasnotansweredonthequiz.Usean
enumtypetorepresenttheresultofansweringaquestion.
Exampleofrunningtheprogram:
Clickheretoviewcodeimage
>javaQuizGraderCBBDBCAX
QuestionSubmittedAns.CorrectAns.Result
1CCCORRECT
2BAWRONG
3BBCORRECT
4DDCORRECT
5BBCORRECT
6CCCORRECT
7ACWRONG
8XAUNANSWERED
No.ofcorrectanswers:5
No.ofwronganswers:2
No.ofquestionsunanswered:1
ThecandidatePASSED.
WOW! eBook
www.wowebook.org
4.AccessControl
4.1JavaSourceFileStructure
ThestructureofaskeletalJavasourcefileisdepictedinFigure4.1.AJavasourcefilecan
havethefollowingelementsthat,ifpresent,mustbespecifiedinthefollowingorder:
1.Anoptionalpackagedeclarationtospecifyapackagename.Packagesare
discussedin§4.2.
2.Zeroormoreimportdeclarations.Sinceimportdeclarationsintroducetypeor
staticmembernamesinthesourcecode,theymustbeplacedbeforeanytype
declarations.Bothtypeandstaticimportdeclarationsarediscussedin§4.2.
3.Anynumberoftop-leveltypedeclarations.Class,enum,andinterfacedeclarations
arecollectivelyknownastypedeclarations.Sincethesedeclarationsbelongtothe
samepackage,theyaresaidtobedefinedatthetoplevel,whichisthepackagelevel.
Thetypedeclarationscanbedefinedinanyorder.Technically,asourcefileneednot
haveanysuchdeclarations,butthatishardlyuseful.
TheJDKimposestherestrictionthatatmostonepublicclassdeclarationper
WOW! eBook
www.wowebook.org
sourcefilecanbedefined.Ifapublicclassisdefined,thefilenamemustmatch
thispublicclass.Forexample,ifthepublicclassnameisNewApp,thefile
namemustbeNewApp.java.
Classesarediscussedin§3.1,p.48;enumsarediscussedin§3.8,p.87;and
interfacesarediscussedin§7.6,p.290.
Figure4.1JavaSourceFileStructure
Notethatexceptforthepackageandtheimportstatements,allcodeisencapsulated
inclasses,interfaces,andenums.Nosuchrestrictionappliestocommentsandwhitespace.
4.2Packages
ApackageinJavaisanencapsulationmechanismthatcanbeusedtogrouprelated
classes,interfaces,enums,andsubpackages.
Figure4.2showsanexampleofapackagehierarchy,comprisingapackagecalled
wizardthatcontainstwootherpackages:pandorasboxandspells.Thepackage
pandorasboxhasaclasscalledClownthatimplementsaninterfacecalledMagic,
alsofoundinthesamepackage.Inaddition,thepackagepandorasboxhasaclass
calledLovePotionandasubpackagecalledartifactscontainingaclasscalled
Ailment.Thepackagespellshastwoclasses:BaldnessandLovePotion.The
classBaldnessisasubclassofclassAilmentfoundinthesubpackageartifacts
inthepackagepandorasbox.
WOW! eBook
www.wowebook.org
Figure4.2PackageHierarchy
Thedot(.)notationisusedtouniquelyidentifypackagemembersinthepackage
hierarchy.Theclasswizard.pandorasbox.LovePotion,forexample,isdifferent
fromtheclasswizard.spells.LovePotion.TheAilmentclasscanbeeasily
identifiedbythenamewizard.pandorasbox.artifacts.Ailment,whichis
knownasthefullyqualifiednameofthetype.Notethatthefullyqualifiednameofthe
typeinanamedpackagecomprisesthefullyqualifiednameofthepackageandthesimple
nameofthetype.ThesimpletypenameAilmentandthefullyqualifiedpackagename
wizard.pandorasbox.artifactstogetherdefinethefullyqualifiedtypename
wizard.pandorasbox.artifacts.Ailment.Analogously,thefullyqualified
nameofasubpackagecomprisesthefullyqualifiednameoftheparentpackageandthe
simplenameofthesubpackage.
Javaprogrammingenvironmentsusuallymapthefullyqualifiednameofpackagestothe
underlying(hierarchical)filesystem.Forexample,onaUnixsystem,theclassfile
LovePotion.classcorrespondingtothefullyqualifiedname
wizard.pandorasbox.LovePotionwouldbefoundunderthedirectory
wizard/pandorasbox.
Conventionally,aglobalnamingschemebasedontheInternetdomainnamesisusedto
uniquelyidentifypackages.Ifthepackagewizardwasimplementedbyacompany
calledSorcerersLimitedthatownsthedomainsorcerersltd.com,itsfullyqualified
namewouldbe
com.sorcerersltd.wizard
Becausedomainnamesareunique,packageswiththisnamingschemeareglobally
identifiable.Itisnotadvisabletousethetop-levelpackagenamesjavaandsun,as
thesearereservedfortheJavadesigners.
Thesubpackagewizard.pandorasbox.artifactscouldeasilyhavebeenplaced
WOW! eBook
www.wowebook.org
elsewhere,aslongasitwasuniquelyidentified.Subpackagesinapackagedonotaffect
theaccessibilityoftheotherpackagemembers.Forallintentsandpurposes,subpackages
aremoreanorganizationalfeatureratherthanalanguagefeature.Accessibilityof
membersinapackageisdiscussedin§4.4.Accessibilityofmembersdefinedintype
declarationsisdiscussedin§4.7.
DefiningPackages
ApackagehierarchyrepresentsanorganizationoftheJavaclassesandinterfaces.Itdoes
notrepresentthesourcecodeorganizationoftheclassesandinterfaces.Thesourcecodeis
ofnoconsequenceinthisregard.EachJavasourcefile(alsocalledcompilationunit)can
containzeroormoretypedeclarations,butthecompilerproducesaseparateclassfile
containingtheJavabytecodeforeachofthem.AtypedeclarationcanindicatethatitsJava
bytecodeshouldbeplacedinaparticularpackage,usingapackagedeclaration.
Thepackagestatementhasthefollowingsyntax:
Clickheretoviewcodeimage
packagefully_qualified_package_name;
Atmostonepackagedeclarationcanappearinasourcefile,anditmustbethefirst
statementinthesourcefile.ThepackagenameissavedintheJavabytecodeforthetypes
containedinthepackage.Javanamingconventionsrecommendwritingpackagenamesin
lowercaseletters.
Notethatthisschemehastwoconsequences.First,alltheclassesandinterfacesina
sourcefilewillbeplacedinthesamepackage.Second,severalsourcefilescanbeusedto
specifythecontentsofapackage.
Ifapackagedeclarationisomittedinacompilationunit,theJavabytecodeforthe
declarationsinthecompilationunitwillbelongtoanunnamedpackage(alsocalledthe
defaultpackage),whichistypicallysynonymouswiththecurrentworkingdirectoryonthe
hostsystem.
Example4.1illustrateshowthepackagesinFigure4.2canbedefinedusingthepackage
declaration.Therearefourcompilationunits.Eachcompilationunithasapackage
declaration,ensuringthatthetypedeclarationsarecompiledintothecorrectpackage.The
completecodecanbefoundinExample4.8onpage118.
WOW! eBook
www.wowebook.org
Example4.1DefiningPackagesandUsingTypeImport
Clickheretoviewcodeimage
//Filename:Clown.java
packagewizard.pandorasbox;//Packagedeclaration
importwizard.pandorasbox.artifacts.Ailment;//Importingspecificclass
publicclassClownimplementsMagic{/*…*/}
interfaceMagic{/*…*/}
//Filename:LovePotion.java
packagewizard.pandorasbox;//Packagedeclaration
publicclassLovePotion{/*…*/
//Filename:Ailment.java
packagewizard.pandorasbox.artifacts;//Packagedeclaration
publicclassAilment{/*…*/}
//Filename:Baldness.java
packagewizard.spells;//Packagedeclaration
importwizard.pandorasbox.*;//(1)Type-import-on-demand
importwizard.pandorasbox.artifacts.*;//(2)Importfromsubpackage
publicclassBaldnessextendsAilment{//SimplenameforAilment
wizard.pandorasbox.LovePotiontlcOne;//(3)Fullyqualifiedclass
name
LovePotiontlcTwo;//Classinsamepackage
//…
}
classLovePotion{/*…*/}
UsingPackages
TheimportfacilityinJavamakesiteasiertousethecontentsofpackages.Thissubsection
discussesimportingreferencetypesandstaticmembersofreferencetypesfrompackages.
ImportingReferenceTypes
Theaccessibilityoftypes(classes,interfaces,andenums)inapackagedeterminestheir
accessfromotherpackages.Givenareferencetypethatisaccessiblefromoutsidea
package,thereferencetypecanbeaccessedintwoways.Onewayistousethefully
qualifiednameofthetype.However,writinglongnamescanbecometedious.Thesecond
wayistousetheimportdeclarationthatprovidesashorthandnotationforspecifying
thenameofthetype,oftencalledtypeimport.
Theimportdeclarationsmustbethefirststatementafteranypackagedeclarationina
sourcefile.Thesimpleformoftheimportdeclarationhasthefollowingsyntax:
Clickheretoviewcodeimage
WOW! eBook
www.wowebook.org
importfully_qualified_type_name;
Thisiscalledsingle-type-import.Asthenameimplies,suchanimportdeclaration
providesashorthandnotationforasingletype.Thesimplenameofthetype(thatis,its
identifier)cannowbeusedtoaccessthisparticulartype.Giventheimportdeclaration
Clickheretoviewcodeimage
importwizard.pandorasbox.Clown;
thesimplenameClowncanbeusedinthesourcefiletorefertothisclass.
Alternatively,thefollowingformoftheimportdeclarationcanbeused:
Clickheretoviewcodeimage
importfully_qualified_package_name.*;
Thisiscalledtype-import-on-demand.Itallowsanytypefromthespecifiedpackagetobe
accessedbyitssimplename.
Animportdeclarationdoesnotrecursivelyimportsubpackages.Thedeclarationalso
doesnotresultininclusionofthesourcecodeofthetypes;rather,itsimplyimportstype
names(thatis,itmakestypenamesavailabletothecodeinacompilationunit).
Allcompilationunitsimplicitlyimportthejava.langpackage(§8.1,p.342).Thisis
thereasonwhywecanrefertotheclassStringbyitssimplename,andneednotuseits
fullyqualifiednamejava.lang.Stringallthetime.
Example4.1showsseveralusagesoftheimportstatement.Herewewilldrawattention
totheclassBaldnessinthefileBaldness.java.Thisclassreliesontwoclassesthat
havethesamesimplenameLovePotionbutareindifferentpackages:
wizard.pandorasboxandwizard.spells,respectively.Todistinguishbetween
thetwoclasses,wecanusetheirfullyqualifiednames.However,sinceoneofthemisin
thesamepackageastheclassBaldness,itisenoughtofullyqualifytheclassfromthe
otherpackage.ThissolutionisusedinExample4.1at(3).Notethattheimportofthe
wizard.pandorasboxpackageat(1)becomesredundant.Suchnameconflictscan
usuallyberesolvedbyusingvariationsoftheimportstatementtogetherwithfully
qualifiednames.
TheclassBaldnessextendstheclassAilment,whichisinthesubpackage
artifactsofthewizard.pandorasboxpackage.Theimportdeclarationat(2)
isusedtoimportthetypesfromthesubpackageartifacts.
Thefollowingexampleshowshowasingle-type-importdeclarationcanbeusedto
disambiguateatypenamewhenaccesstothetypeisambiguousbyitssimplename.The
followingimportstatementallowsthesimplenameListtobeusedasshorthandfor
thejava.awt.Listtypeasexpected:
Clickheretoviewcodeimage
importjava.awt.*;//importsallreferencetypesfromjava.awt
Giventhetwoimportdeclarations
Clickheretoviewcodeimage
WOW! eBook
www.wowebook.org
importjava.awt.*;//importsalltypenamesfromjava.awt
importjava.util.*;//importsalltypenamesfromjava.util
thesimplenameListisnowambiguous,becauseboththetypesjava.util.List
andjava.awt.Listmatch.
Addingasingle-type-importdeclarationforthejava.awt.Listtypeallowsthesimple
nameListtobeusedasashorthandnotationforthistype:
Clickheretoviewcodeimage
importjava.awt.*;//importsalltypenamesfromjava.awt
importjava.util.*;//importsalltypenamesfromjava.util
importjava.awt.List;//importsthetypeListfromjava.awt
explicitly
ImportingStaticMembersofReferenceTypes
Analogoustothetypeimportfacility,Javaalsoallowsimportofstaticmembersof
referencetypesfrompackages,oftencalledstaticimport.
Staticimportallowsaccessiblestaticmembersdeclaredinatypetobeimported,sothat
theycanbeusedbytheirsimplenames,andthereforeneednotbequalified.Theimport
appliestothewholecompilationunit,andimportingfromtheunnamedpackageisnot
permissible.
Thetwoformsofstaticimportareshownhere:
Clickheretoviewcodeimage
//Single-static-import:importsaspecificstaticmemberfromthedesignated
type
importstaticfully_qualified_type_name.static_member_name;
//Static-import-on-demand:importsallstaticmembersinthedesignatedtype
importstaticfully_qualified_type_name.*;
Bothformsrequiretheuseofthekeywordimportfollowedbythekeywordstatic,
althoughthefeatureiscalledstaticimport.Inbothcases,thefullyqualifiednameofthe
referencetypeweareimportingfromisrequired.
Thefirstformallowssinglestaticimportofindividualstaticmembers,andis
demonstratedinExample4.2.TheconstantPI,whichisastaticfieldinthe
classjava.lang.Math,isimportedat(1).Notetheuseofthefullyqualifiednameof
thetypeinthestaticimportstatement.Thestaticmethodnamedsqrtfromthe
classjava.lang.Mathisimportedat(2).Onlythenameofthestaticmethodis
specifiedinthestaticimportstatement;noparametersarelisted.Useofanyotherstatic
memberfromtheMathclassrequiresthatthefullyqualifiednameoftheclassbe
specified.Sincetypesfromthejava.langpackageareimportedimplicitly,thefully
qualifiednameoftheMathclassisnotnecessary,asshownat(3).
Staticimportondemandiseasilydemonstratedbyreplacingthetwoimportstatements
inExample4.2bythefollowingimportstatement:
Clickheretoviewcodeimage
importstaticjava.lang.Math.*;
WOW! eBook
www.wowebook.org
WecanalsodispensewiththeuseoftheclassnameMathin(3),asallstaticmembers
fromtheMathclassarenowimported:
Clickheretoviewcodeimage
doublehypotenuse=hypot(x,y);//(3’)Typenamecannowbeomitted.
Example4.2SingleStaticImport
Clickheretoviewcodeimage
importstaticjava.lang.Math.PI;//(1)Staticfield
importstaticjava.lang.Math.sqrt;//(2)Staticmethod
//Onlyspecifiedstaticmembersareimported.
publicclassCalculate3{
publicstaticvoidmain(String[]args){
doublex=3.0,y=4.0;
doublesquareroot=sqrt(y);//Simplenameofstaticmethod
doublehypotenuse=Math.hypot(x,y);//(3)Requirestypename
doublearea=PI*y*y;//Simplenameofstaticfield
System.out.printf(“Squareroot:%.2f,hypotenuse:%.2f,area:%.2f%n”,
squareroot,hypotenuse,area);
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
Squareroot:2.00,hypotenuse:5.00,area:50.27
Example4.3illustrateshowstaticimportcanbeusedtoaccessinterfaceconstants(§7.6,
p.302).Thestaticimportstatementat(1)allowstheinterfaceconstantsinthepackage
mypkgtobeaccessedbytheirsimplenames.Thestaticimportfacilityavoidsthe
MyFactoryclasshavingtoimplementtheinterfacesoastoaccesstheconstantsbytheir
simplename(oftenreferredtoastheinterfaceconstantantipattern):
Clickheretoviewcodeimage
publicclassMyFactoryimplementsmypkg.IMachineState{
//…
}
WOW! eBook
www.wowebook.org
Example4.3AvoidingtheInterfaceConstantAntipattern
Clickheretoviewcodeimage
packagemypkg;
publicinterfaceIMachineState{
//Fieldsarepublic,staticandfinal.
intBUSY=1;
intIDLE=0;
intBLOCKED=-1;
}
importstaticmypkg.IMachineState.*;//(1)Staticimportinterface
constants
publicclassMyFactory{
publicstaticvoidmain(String[]args){
int[]states={IDLE,BUSY,IDLE,BLOCKED};
for(ints:states)
System.out.print(s+”“);
}
}
Outputfromtheprogram:
010-1
Staticimportisidealforimportingenumconstantsfrompackages,assuchconstantsare
staticmembersofanenumtype.Example4.4combinestypeandstaticimports.Theenum
constantscanbeaccessedat(5)usingtheirsimplenamesbecauseofthestaticimport
statementat(2).Thetypeimportat(1)isrequiredtoaccesstheenumtypeStatebyits
simplenameat(4)and(6).
WOW! eBook
www.wowebook.org
Example4.4ImportingEnumConstants
Clickheretoviewcodeimage
packagemypkg;
publicenumState{BUSY,IDLE,BLOCKED}
//File:Factory.java(inunnamedpackage)
importmypkg.State;//(1)Singletypeimport
importstaticmypkg.State.*;//(2)Staticimportondemand
importstaticjava.lang.System.out;//(3)Singlestaticimport
publicclassFactory{
publicstaticvoidmain(String[]args){
State[]states={//(4)Usingtypeimportimpliedby(1)
IDLE,BUSY,IDLE,BLOCKED//(5)Usingstaticimportimpliedby
(2)
};
for(States:states)//(6)Usingtypeimportimpliedby(1)
out.print(s+”“);//(7)Usingstaticimportimpliedby
(3)
}
}
Outputfromtheprogram:
IDLEBUSYIDLEBLOCKED
Identifiersinaclasscanshadowstaticmembersthatareimported.Example4.5illustrates
thecasewheretheparameteroutofthemethodwriteInfo()hasthesamenameas
thestaticallyimportedfieldjava.lang.System.out.Thetypeoftheparameteris
ShadowImportandthatofthestaticallyimportedfieldisPrintStream.Bothclasses
PrintStreamandShadowImportdefinethemethodprintln()thatiscalledin
theprogram.Theonlywaytoaccesstheimportedfieldoutinthemethod
writeInfo()istouseitsfullyqualifiedname.
WOW! eBook
www.wowebook.org
Example4.5ShadowingStaticImport
Clickheretoviewcodeimage
importstaticjava.lang.System.out;//(1)Staticimport
publicclassShadowImport{
publicstaticvoidmain(String[]args){
out.println(“Callingprintln()injava.lang.System.out”);
ShadowImportsbi=newShadowImport();
writeInfo(sbi);
}
//Parametershadowsjava.lang.System.out:
publicstaticvoidwriteInfo(ShadowImportout){
out.println(“Callingprintln()intheparameterout”);
System.out.println(“Callingprintln()injava.lang.System.out”);//
Qualify
}
publicvoidprintln(Stringmsg){
out.println(msg+”oftypeShadowImport”);
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
Callingprintln()injava.lang.System.out
Callingprintln()intheparameteroutoftypeShadowImport
Callingprintln()injava.lang.System.out
Thenextcodesnippetillustratesacommonconflictthatoccurswhenastaticfieldwiththe
samenameisimportedbyseveralstaticimportstatements.Thisconflictisreadily
resolvedbyusingthefullyqualifiednameofthefield.Inthecaseshownhere,wecanuse
thesimplenameofclassinwhichthefieldisdeclared,asthejava.langpackageis
implicitlyimportedbyallcompilationunits.
Clickheretoviewcodeimage
importstaticjava.lang.Integer.MAX_VALUE;
importstaticjava.lang.Double.MAX_VALUE;
publicclassStaticFieldConflict{
publicstaticvoidmain(String[]args){
System.out.println(MAX_VALUE);//(1)Ambiguous!Compile-time
error!
System.out.println(Integer.MAX_VALUE);//OK
System.out.println(Double.MAX_VALUE);//OK
}
}
Conflictscanalsooccurwhenastaticmethodwiththesamesignatureisimportedby
severalstaticimportstatements.InExample4.6,amethodnamedbinarySearchis
imported21timesbythestaticimportstatements.Thismethodisoverloadedtwiceinthe
java.util.Collectionsclassand18timesinthejava.util.Arraysclass,in
additiontoonedeclarationinthemypkg.Auxiliaryclass.Theclasses
java.util.Arraysandmypkg.Auxiliaryhaveadeclarationofthismethodwith
WOW! eBook
www.wowebook.org
thesamesignaturethatmatchesthemethodcallat(2),resultinginasignatureconflictthat
isflaggedasacompile-timeerror.Theconflictcanagainberesolvedbyspecifyingthe
fullyqualifiednameofthemethod.
Ifthestaticimportstatementat(1)isremoved,thereisnoconflict,asonlytheclass
java.util.Arrayshasamethodthatmatchesthemethodcallat(2).Ifthe
declarationofthemethodbinarySearch()at(3)isallowed,thereisalsonoconflict,
asthismethoddeclarationwillshadowtheimportedmethodwhosesignatureitmatches.
Example4.6ConflictinImportingStaticMethodwiththeSameSignature
Clickheretoviewcodeimage
packagemypkg;
publicclassAuxiliary{
publicstaticintbinarySearch(int[]a,intkey){//Samein
java.util.Arrays
//Implementationisomitted.
return-1;
}
}
//File:MultipleStaticImport.java(inunnamedpackage)
importstaticjava.util.Collections.binarySearch;//2overloadedmethods
importstaticjava.util.Arrays.binarySearch;//+18overloadedmethods
importstaticmypkg.Auxiliary.binarySearch;//(1)Causessignatureconflict
publicclassMultipleStaticImport{
publicstaticvoidmain(String[]args){
intindex=binarySearch(newint[]{10,50,100},50);//(2)Ambiguous!
System.out.println(index);
}
//publicstaticintbinarySearch(int[]a,intkey){//(3)
//return-1;
//}
}
CompilingCodeintoPackages
Conventionsforspecifyingpathnamesvaryondifferentplatforms.Inthischapter,wewill
usepathnameconventionsusedonaUnixplatform.Whiletryingouttheexamplesinthis
section,attentionshouldbepaidtoplatformdependenciesinthisregard—especiallythe
factthattheseparatorcharactersinfilepathsfortheUnixandWindowsplatformsare/
and\,respectively.
Asmentionedearlier,apackagecanbemappedonahierarchicalfilesystem.Wecanthink
ofapackagenameasapathnameinthefilesystem.ReferringtoExample4.1,the
packagenamewizard.pandorasboxcorrespondstothepathname
wizard/pandorasbox.TheJavabytecodeforalltypesdeclaredinthesourcefiles
Clown.javaandLovePotion.javawillbeplacedinthepackagedirectorywiththe
pathnamewizard/pandorasbox,asthesesourcefileshavethefollowingpackage
declaration:
WOW! eBook
www.wowebook.org
packagewizard.pandorasbox;
Thelocationinthefilesystemwherethepackagedirectoryshouldbecreatedisspecified
usingthedoption(dfordestination)ofthejavaccommand.Thetermdestination
directoryisasynonymforthislocationinthefilesystem.Thecompilerwillcreatethe
packagedirectorywiththepathnamewizard/pandorasbox(includingany
subdirectoriesrequired)underthespecifiedlocation,andplacetheJavabytecodeforthe
typesdeclaredinthesourcefilesClown.javaandLovePotion.javainsidethe
packagedirectory.
Assumingthatthecurrentdirectory(.)isthedirectory/pgjc/work,andthefour
sourcefilesinExample4.1arefoundinthisdirectory,thefollowingcommandissuedin
thecurrentdirectorywillcreateafilehierarchyunderthisdirectory(Figure4.3)that
mirrorsthepackagehierarchyinFigure4.2:
Clickheretoviewcodeimage
>javac-d.Clown.javaLovePotion.javaAilment.javaBaldness.java
WOW! eBook
www.wowebook.org
Figure4.3FileHierarchy
Notethesubdirectoriesthatarecreatedforafullyqualifiedpackagename,andwherethe
classfilesarelocated.Inthiscommandline,thespacebetweenthe-doptionandits
argumentismandatory.
Wecanspecifyanyrelativepathnamethatdesignatesthedestinationdirectory,orits
absolutepathname:
Clickheretoviewcodeimage
>javac-d/pgjc/workClown.javaLovePotion.javaAilment.javaBaldness.java
Wecan,ofcourse,specifydestinationsotherthanthecurrentdirectorywheretheclass
fileswiththebytecodeshouldbestored.Thefollowingcommandinthecurrentdirectory
/pgjc/workwillcreatethenecessarypackageswiththeclassfilesunderthedestination
WOW! eBook
www.wowebook.org
directory/pgjc/myapp:
Clickheretoviewcodeimage
>javac-d../myappClown.javaLovePotion.javaAilment.javaBaldness.java
Withoutthe-doption,thedefaultbehaviorofthejavaccompileristoplaceallclass
filesdirectlyunderthecurrentdirectory(wherethesourcefilesarelocated),ratherthanin
theappropriatesubdirectoriescorrespondingtothepackages.
Thecompilerwillreportanerrorifthereisanyproblemwiththedestinationdirectory
specifiedwiththe-doption(e.g.,ifitdoesnotexistordoesnothavetherightfile
permissions).
RunningCodefromPackages
ReferringtoExample4.1,ifthecurrentdirectoryhastheabsolutepathname
/pgjc/workandwewanttorunClown.classinthedirectorywiththepathname
./wizard/pandorasbox,thefullyqualifiednameoftheClownclassmustbe
specifiedinthejavacommand:
Clickheretoviewcodeimage
>javawizard.pandorasbox.Clown
ThiswillloadthebytecodeoftheclassClownfromthefilewiththepathname
./wizard/pandorasbox/Clown.class,andstarttheexecutionofitsmain()
method.
4.3SearchingforClasses
ThedocumentationfortheJDKtoolsexplainshowtoorganizepackagesinmoreelaborate
schemes.Inparticular,theCLASSPATHenvironmentvariablecanbeusedtospecifythe
classsearchpath(usuallyabbreviatedtojustclasspath),whicharepathnamesor
locationsinthefilesystemwhereJDKtoolsshouldlookwhensearchingforclassesand
otherresourcefiles.Alternatively,the-classpathoption(oftenabbreviatedto-cp)of
theJDKtoolcommandscanbeusedforthesamepurpose.TheCLASSPATHenvironment
variableisnotrecommendedforthispurpose,asitsclasspathvalueaffectsallJava
applicationsonthehostplatform,andanyapplicationcanmodifyit.However,the-cp
optioncanbeusedtosettheclasspathforeachapplicationindividually.Thisway,an
applicationcannotmodifytheclasspathforotherapplications.Theclasspathspecifiedin
the-cpoptionsupersedesthepathorpathssetbytheCLASSPATHenvironmentvariable
whiletheJDKtoolcommandisrunning.WewillnotdiscusstheCLASSPATH
environmentvariablehere,andassumeittobeundefined.
Basically,theJDKtoolsfirstlookinthedirectorieswheretheJavastandardlibrariesare
installed.Iftheclassisnotfoundinthestandardlibraries,thetoolsearchesintheclass
path.Whennoclasspathisdefined,thedefaultvalueoftheclasspathisassumedtobe
thecurrentdirectory.Ifthe-cpoptionisusedandthecurrentdirectoryshouldbe
searchedbytheJDKtool,thecurrentdirectorymustbespecifiedasanentryintheclass
path,justlikeanyotherdirectorythatshouldbesearched.Thisismostconvenientlydone
WOW! eBook
www.wowebook.org
byincluding'.'asoneoftheentriesintheclasspath.
WewillusethefilehierarchiesshowninFigure4.4toillustratesomeoftheintricacies
involvedwhensearchingforclasses.Thecurrentdirectoryhastheabsolutepathname
/top/src,wherethesourcefilesarestored.Thepackagepkgwillbecreatedunderthe
directorywiththeabsolutepathname/top/bin.Thesourcecodeinthetwosourcefiles
A.javaandB.javaisalsoshowninFigure4.4.
Figure4.4SearchingforClasses
ThefilehierarchybeforeanyfilesarecompiledisshowninFigure4.4a.SincetheclassB
doesnotuseanyotherclasses,wecompileitfirstwiththefollowingcommand,resulting
inthefilehierarchyshowninFigure4.4b:
>javac-d../binB.java
Next,wetrytocompilethefileA.java,andgetthefollowingresults:
>javac-d../binA.java
A.java:3:cannotfindsymbol
symbol:classB
location:classpkg.A
publicclassA{Bb;}
^
1error
ThecompilercannotfindtheclassB—thatis,thefileB.classcontainingtheJava
bytecodefortheclassB.InFigure4.4b,wecanseethatitisinthepackagepkgunderthe
directorybin,butthecompilercannotfindit.Thisishardlysurprising,asthereisno
WOW! eBook
www.wowebook.org
bytecodefilefortheclassBinthecurrentdirectory,whichisthedefaultvalueoftheclass
path.Thefollowingcommandsetsthevalueoftheclasspathtobe/top/bin,and
compilationissuccessful(Figure4.4c):
Clickheretoviewcodeimage
>javac-cp/top/bin-d../binA.java
ItisveryimportanttounderstandthatwhenwewanttheJDKtooltosearchinanamed
package,itisthelocationofthepackagethatisspecified;inotherwords,theclasspath
indicatesthedirectorythatcontainsthefirstelementofthefullyqualifiedpackagename.
InFigure4.4c,thepackagepkgiscontainedunderthedirectorywhoseabsolutepathis
/top/bin.Thefollowingcommandwillnotwork,asthedirectory/top/bin/pkg
doesnotcontainapackagewiththenamepkgthathasaclassB:
Clickheretoviewcodeimage
>javac-cp/top/bin/pkg-d../binA.java
Also,thecompilerisnotusingtheclasspathtofindthesourcefile(s)thatarespecifiedin
thecommandline.Intheprecedingcommand,thesourcefilehastherelativepathname
./A.java.Consequently,thecompilerlooksforthesourcefileinthecurrentdirectory.
TheclasspathisusedtofindtheclassesusedbytheclassA.
GiventhefilehierarchyinFigure4.3,thefollowing-cpoptionsetstheclasspathsothat
allpackages(wizard.pandorasbox,wizard.pandorasbox.artifacts,
wizard.spells)inFigure4.3willbesearched,asallpackagesarelocatedunderthe
specifieddirectory:
-cp/pgjc/work
However,thefollowing-cpoptionwillnothelpinfindinganyofthepackagesinFigure
4.3,asnoneofthepackagesarelocatedunderthespecifieddirectory:
Clickheretoviewcodeimage
>java-cp/pgjc/work/wizardpandorasbox.Clown
Thiscommandalsoillustratesanimportantpointaboutpackagenames:Thefullyqualified
packagenameshouldnotbesplit.Thepackagenamefortheclass
wizard.pandorasbox.Clowniswizard.pandorasbox,andmustbespecified
fully.ThefollowingcommandwillsearchallpackagesinFigure4.3forclassesthatare
usedbytheclasswizard.pandorasbox.Clown:
Clickheretoviewcodeimage
>java-cp/pgjc/workwizard.pandorasbox.Clown
Theclasspathcanspecifyseveralentries(i.e.,severallocations),andtheJDKtool
searchesthemintheordertheyarespecified,fromlefttoright.
-cp/pgjc/work:/top/bin:.
Wehaveusedthepath-separatorcharacter':'forUnixplatformstoseparatetheentries,
andalsoincludedthecurrentdirectory(.)asanentry.Thereshouldbenowhitespaceon
eithersideofthepath-separatorcharacter.
Thesearchintheclasspathentriesstopsoncetherequiredclassfileisfound.Therefore,
WOW! eBook
www.wowebook.org
theorderinwhichentriesarespecifiedcanbesignificant.IfaclassBisfoundina
packagepkglocatedunderthedirectory/ext/lib1,andalsoinapackagepkglocated
underthedirectory/ext/lib2,theorderinwhichtheentriesarespecifiedinthetwo-
cpoptionsshownnextissignificant.Theywillresultintheclasspkg.Bbeingfound
under/ext/lib1and/ext/lib2,respectively.
-cp/ext/lib1:/ext/lib2
-cp/ext/lib2:/ext/lib1
Theexamplessofarhaveusedabsolutepathnamesforclasspathentries.Wecan,of
course,userelativepathnamesaswell.Ifthecurrentdirectoryhastheabsolutepathname
/pgjc/workinFigure4.3,thefollowingcommandwillsearchthepackagesunderthe
currentdirectory:
Clickheretoviewcodeimage
>java-cp.wizard.pandorasbox.Clown
Ifthecurrentdirectoryhastheabsolutepathname/top/srcinFigure4.4,thefollowing
commandwillcompilethefile./A.java:
Clickheretoviewcodeimage
>javac-cp../bin-d../binA.java
Ifthenameofanentryintheclasspathincludeswhitespace,thenameshouldbedouble
quotedsothatitwillbeinterpretedcorrectly:
-cp“../newbin”
ReviewQuestions
4.1GiventhesourcefileA.java:
//File:A.java
packagenet.alphabet;
importjava.util.ArrayList;
publicclassA{}
classB{}
Selectthetwocorrectanswers.
(a)BothclassAandclassBwillbeplacedinthepackagenet.alphabet.
(b)OnlyclassAwillbeplacedinthepackagenet.alphabet.ClassBwillbe
placedinthedefaultpackage.
(c)BothclassAandclassBcanaccesstheimportedclass
java.util.ArrayListbyitssimplename.
(d)OnlyclassAcanaccesstheimportedclassjava.util.ArrayListbyits
simplename.
4.2Whichimportstatement,wheninsertedindependentlyat(1),willmakethecode
compile?
Clickheretoviewcodeimage
//File:Window.java
WOW! eBook
www.wowebook.org
packageapp;
publicclassWindow{
finalstaticStringframe=“Top-frame”;
}
___________________________________________________________________________
//File:Canvas.java
packageapp;
//(1)INSERTIMPORTSTATEMENTHERE.
publicclassCanvas{
privateStringstr=frame;
}
Selecttheonecorrectanswer.
(a)importapp.*;
(b)importapp.Window;
(c)importjava.lang.*;
(d)importjava.lang.String;
(e)importstaticapp.Window.frame;
4.3Whichimportstatements,wheninsertedindependentlyat(1),willmakethecode
compile?
Clickheretoviewcodeimage
//File:Window.java
packagemainpkg.subpkg1;
publicclassWindow{}
___________________________________________________________________________
//File:Window.java
packagemainpkg.subpkg2;
publicclassWindow{}
___________________________________________________________________________
//File:Screen.java
packagemainpkg;
//(1)INSERTIMPORTSTATEMENTSHERE.
publicclassScreen{
privateWindowwin;
}
Selectthefourcorrectanswers.
(a)importmainpkg.*;
(b)importmainpkg.subpkg1.*;
(c)importmainpkg.subpkg2.*;
(d)
Clickheretoviewcodeimage
importmainpkg.subpkg1.*;
importmainpkg.subpkg2.Window;
WOW! eBook
www.wowebook.org
(e)
Clickheretoviewcodeimage
importmainpkg.subpkg1.Window;
importmainpkg.subpkg2.*;
(f)
importmainpkg.subpkg1.*;
importmainpkg.subpkg2.*;
(g)
Clickheretoviewcodeimage
importmainpkg.subpkg1.Window;
importmainpkg.subpkg2.Window;
4.4Giventhefollowingcode:
Clickheretoviewcodeimage
//(1)INSERTONEIMPORTSTATEMENTHERE
publicclassRQ700A20{
publicstaticvoidmain(String[]args){
System.out.println(sqrt(49));
}
}
Whichimportstatements,wheninsertedindependentlyat(1),willmakethe
programprint7,whentheprogramiscompiledandrun?
Selectthetwocorrectanswers.
(a)importstaticMath.*;
(b)importstaticMath.sqrt;
(c)importstaticjava.lang.Math.sqrt;
(d)importstaticjava.lang.Math.sqrt();
(e)importstaticjava.lang.Math.*;
4.5GiventhesourcefileA.java:
packagetop.sub;
publicclassA{}
andthefollowingdirectoryhierarchy:
Clickheretoviewcodeimage
/proj
|–src
||–top
||–sub
||–A.java
|–bin
Assumingthatthecurrentdirectoryis/proj/src,whichofthefollowing
statementsaretrue?
Selectthethreecorrectanswers.
WOW! eBook
www.wowebook.org
(a)Thefollowingcommandwillcompile,andplacethebytecodeoftheclass
top.sub.Aunder/proj/bin:
javac-d.top/sub/A.java
(b)Thefollowingcommandwillcompile,andplacethebytecodeoftheclass
top.sub.Aunder/proj/bin:
Clickheretoviewcodeimage
javac-d/proj/bintop/sub/A.java
(c)Thefollowingcommandwillcompile,andplacethebytecodeoftheclass
top.sub.Aunder/proj/bin:
Clickheretoviewcodeimage
javac-D/proj/bin./top/sub/A.java
(d)Thefollowingcommandwillcompile,andplacethebytecodeoftheclass
top.sub.Aunder/proj/bin:
Clickheretoviewcodeimage
javac-d../bintop/sub/A.java
(e)Aftersuccessfulcompilation,theabsolutepathnameofthefileA.classwill
be:
/proj/bin/A.class
(f)Aftersuccessfulcompilation,theabsolutepathnameofthefileA.classwill
be:
/proj/bin/top/sub/A.class
4.6Giventhefollowingdirectorystructure:
Clickheretoviewcodeimage
/top
|–wrk
|–pkg
|–A.java
|–B.java
AssumethatthetwofilesA.javaandB.javacontainthefollowingcode,
respectively:
Clickheretoviewcodeimage
//File:A.java
packagepkg;
classA{Bb;}
___________________________________________________________________________
//File:B.java
packagepkg;
classB{…}
Forwhichcombinationsofcurrentdirectoryandcommandisthecompilation
successful?
Selectthetwocorrectanswers.
(a)
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
Currentdirectory:/top/wrk
Command:javac-cp.:pkgA.java
(b)
Clickheretoviewcodeimage
Currentdirectory:/top/wrk
Command:javac-cp.pkg/A.java
(c)
Currentdirectory:/top/wrk
Command:javac-cppkgA.java
(d)
Clickheretoviewcodeimage
Currentdirectory:/top/wrk
Command:javac-cp.:pkgpkg/A.java
(e)
Clickheretoviewcodeimage
Currentdirectory:/top/wrk/pkg
Command:javacA.java
(f)
Clickheretoviewcodeimage
Currentdirectory:/top/wrk/pkg
Command:javac-cp.A.java
4.7Giventhefollowingdirectorystructure:
Clickheretoviewcodeimage
/proj
|–src
||–A.java
|
|
|–bin
|–top
|–sub
|–A.class
Assumethatthecurrentdirectoryis/proj/src.Whichclasspathspecifications
willfindthefileA.classoftheclasstop.sub.Adeclaredinthefile
/proj/src/A.java?
Selectthetwocorrectanswers.
(a)-cp/proj/bin/top
(b)-cp/proj/bin/top/sub
(c)-cp/proj/bin/top/sub/A.class
(d)-cp.:../bin
(e)-cp/proj
WOW! eBook
www.wowebook.org
(f)-cp/proj/bin
4.4ScopeRules
Javaprovidesexplicitaccessibilitymodifierstocontroltheaccessibilityofmembersina
classbyexternalclients(§4.7,p.123),butintwoareasaccessisgovernedbyspecific
scoperules:
•Classscopeformembers:howmemberdeclarationsareaccessedwithintheclass.
•Blockscopeforlocalvariables:howlocalvariabledeclarationsareaccessedwithin
ablock.
ClassScopeforMembers
Classscopeconcernsaccessingmembers(includinginheritedones)fromcodewithina
class.Table4.1givesanoverviewofhowstaticandnon-staticcodeinaclasscanaccess
membersoftheclass,includingthosethatareinherited.Table4.1assumesthefollowing
declarations:
Clickheretoviewcodeimage
classSuperName{
intinstanceVarInSuper;
staticintstaticVarInSuper;
voidinstanceMethodInSuper(){/*…*/}
staticvoidstaticMethodInSuper(){/*…*/}
//…
}
classClassNameextendsSuperName{
intinstanceVar;
staticintstaticVar;
voidinstanceMethod(){/*…*/}
staticvoidstaticMethod(){/*…*/}
//…
}
WOW! eBook
www.wowebook.org
Table4.1AccessingMemberswithinaClass
Thegoldenruleisthatstaticcodecanonlyaccessotherstaticmembersbytheirsimple
names.Staticcodeisnotexecutedinthecontextofanobject,sothereferencesthisand
superarenotavailable.Anobjecthasknowledgeofitsclass,sostaticmembersare
alwaysaccessibleinanon-staticcontext.
Notethatusingtheclassnametoaccessstaticmemberswithintheclassisnodifferent
fromhowexternalclientsaccessthesestaticmembers.
Thefollowingfactorscanallinfluencethescopeofamemberdeclaration:
•Shadowingofafielddeclaration,eitherbylocalvariables(§4.4,p.117)orby
declarationsinthesubclass(§7.3,p.275)
•Overridinganinstancemethodfromasuperclass(§7.2,p.268)
•Hidingastaticmethoddeclaredinasuperclass(§7.3,p.275)
WOW! eBook
www.wowebook.org
Withinaclass,referencesoftheclasscanbedeclaredandusedtoaccessallmembersin
theclass,regardlessoftheiraccessibilitymodifiers.InExample4.7,themethod
duplicateLightat(1)intheclassLighthastheparameteroldLightandthe
localvariablenewLightthatarereferencesoftheclassLight.Eventhoughthefields
oftheclassareprivate,theyareaccessiblethroughthetworeferences(oldLight
andnewLight)inthemethodduplicateLight()asshownat(2),(3),and(4).
Example4.7ClassScope
Clickheretoviewcodeimage
classLight{
//Instancevariables:
privateintnoOfWatts;//Wattage
privatebooleanindicator;//Onoroff
privateStringlocation;//Placement
//Instancemethods:
publicvoidswitchOn(){indicator=true;}
publicvoidswitchOff(){indicator=false;}
publicbooleanisOn(){returnindicator;}
publicstaticLightduplicateLight(LightoldLight){//(1)
LightnewLight=newLight();
newLight.noOfWatts=oldLight.noOfWatts;//(2)
newLight.indicator=oldLight.indicator;//(3)
newLight.location=oldLight.location;//(4)
returnnewLight;
}
}
BlockScopeforLocalVariables
Declarationsandstatementscanbegroupedintoablockusingbraces,{}.Blockscanbe
nested,andscoperulesapplytolocalvariabledeclarationsinsuchblocks.Alocal
declarationcanappearanywhereinablock.Thegeneralruleisthatavariabledeclaredin
ablockisinscopeinsidetheblockinwhichitisdeclared,butitisnotaccessibleoutside
ofthisblock.Itisnotpossibletoredeclareavariableifalocalvariableofthesamename
isalreadydeclaredinthecurrentscope.
Localvariablesofamethodincludetheformalparametersofthemethodandvariables
thataredeclaredinthemethodbody.Thelocalvariablesinamethodarecreatedeachtime
themethodisinvoked,andarethereforedistinctfromlocalvariablesinotherinvocations
ofthesamemethodthatmightbeexecuting(§6.5,p.230).
Figure4.5illustratesblockscope(alsoknownaslexicalscope)forlocalvariables.A
methodbodyisablock.Parameterscannotberedeclaredinthemethodbody,asshownat
(1)inBlock1.
WOW! eBook
www.wowebook.org
Figure4.5BlockScope
Alocalvariable—alreadydeclaredinanenclosingblockand,therefore,visibleinanested
block—cannotberedeclaredinthenestedblock.Thesecasesareshownat(3),(5),and
(6).
Alocalvariableinablockcanberedeclaredinanotherblockiftheblocksaredisjoint—
thatis,theydonotoverlap.Thisisthecaseforvariableiat(2)inBlock3andat(4)in
Block4,asthesetwoblocksaredisjoint.
Thescopeofalocalvariabledeclarationbeginsfromwhereitisdeclaredintheblockand
endswherethisblockterminates.Thescopeoftheloopvariableindexistheentire
Block2.EventhoughBlock2isnestedinBlock1,thedeclarationofthevariableindex
at(7)inBlock1isvalid.Thescopeofthevariableindexat(7)spansfromits
declarationtotheendofBlock1,anditdoesnotoverlapwiththatoftheloopvariable
indexinBlock2.
4.5AccessibilityModifiersforTop-LevelTypeDeclarations
Theaccessibilitymodifierpubliccanbeusedtodeclaretop-leveltypes(thatis,classes,
enums,andinterfaces)inapackagetobeaccessiblefromeverywhere,bothinsidetheir
ownpackageandinsideotherpackages.Iftheaccessibilitymodifierisomitted,theywill
beaccessibleonlyintheirownpackageandnotinanyotherpackagesorsubpackages.
Thisiscalledpackageordefaultaccessibility.
Example4.8AccessibilityModifiersforClassesandInterfaces
Clickheretoviewcodeimage
WOW! eBook
www.wowebook.org
//File:Clown.java
packagewizard.pandorasbox;//Packagedeclaration
importwizard.pandorasbox.artifacts.Ailment;//ImportingclassAilment
publicclassClownimplementsMagic{//(1)
LovePotiontlc;//Classinsamepackage
Ailmentproblem;//Simpleclassname
Clown(){
tlc=newLovePotion(“passion”);
problem=newAilment(“flu”);//Simpleclassname
}
@Overridepublicvoidlevitate(){//(2)
System.out.println(“Levitating”);
}
publicvoidmixPotion(){System.out.println(“Mixing”+tlc);}
publicvoidhealAilment(){System.out.println(“Healing”+problem);}
publicstaticvoidmain(String[]args){
Clownjoker=newClown();
joker.levitate();
joker.mixPotion();
joker.healAilment();
}
}
interfaceMagic{voidlevitate();}//(3)
//File:LovePotion.java
packagewizard.pandorasbox;//Packagedeclaration
publicclassLovePotion{//(4)Accessibleoutside
package
StringpotionName;
publicLovePotion(Stringname){potionName=name;}
publicStringtoString(){returnpotionName;}
}
//File:Ailment.java
packagewizard.pandorasbox.artifacts;//Packagedeclaration
publicclassAilment{//Accessibleoutsidepackage
StringailmentName;
publicAilment(Stringname){ailmentName=name;}
publicStringtoString(){returnailmentName;}
}
//File:Baldness.java
packagewizard.spells;//Packagedeclaration
importwizard.pandorasbox.*;//Redundant
importwizard.pandorasbox.artifacts.*;//Importofsubpackage
publicclassBaldnessextendsAilment{//SimplenameforAilment
wizard.pandorasbox.LovePotiontlcOne;//Fullyqualifiedname
LovePotiontlcTwo;//Classinsamepackage
Baldness(Stringname){
super(name);
tlcOne=newwizard.pandorasbox.//Fullyqualifiedname
LovePotion(“romance”);
tlcTwo=newLovePotion();//Classinsamepackage
WOW! eBook
www.wowebook.org
}
}
classLovePotion/*implementsMagic*/{//(5)Magicisnotaccessible
//@Overridepublicvoidlevitate(){}//(6)Cannotoverridemethod
}
Compilingandrunningtheprogramfromthecurrentdirectorygivesthefollowingresults:
Clickheretoviewcodeimage
>javac-d.Clown.javaLovePotion.javaAilment.javaBaldness.java
>javawizard.pandorasbox.Clown
Levitating
Mixingpassion
Healingflu
InExample4.8,theclassClownat(1)andtheinterfaceMagicat(3)areplacedina
packagecalledwizard.pandorasbox.ThepublicclassClownisaccessiblefrom
everywhere.TheMagicinterfacehasdefaultaccessibility,andcanbeaccessedonly
withinthepackagewizard.pandorasbox.Itisnotaccessiblefromotherpackages,
notevenfromsubpackages.
TheclassLovePotionat(4)isalsoplacedinthepackagecalled
wizard.pandorasbox.Theclasshaspublicaccessibilityand,therefore,is
accessiblefromotherpackages.ThetwofilesClown.javaandLovePotion.java
demonstratehowseveralcompilationunitscanbeusedtogroupclassesinthesame
package.
InthefileClown.java,theclassClownat(1)implementstheinterfaceMagicat(3)
fromthesamepackage.Wehaveusedtheannotation@Overrideinfrontofthe
declarationofthelevitate()methodat(2)sothatthecompilercanaidinchecking
thatthismethodisdeclaredcorrectlyasrequiredbytheinterfaceMagic.
InthefileBaldness.java,theclassLovePotionat(5)wishestoimplementthe
interfaceMagicat(3)fromthepackagewizard.pandorasbox,butcannotdoso,
althoughthesourcefileimportsfromthispackage.ThereasonisthattheinterfaceMagic
hasdefaultaccessibilityandcan,therefore,beaccessedonlywithinthepackage
wizard.pandorasbox.Themethodlevitate()oftheMagicinterfacetherefore
cannotbeoverriddeninclassLovePotionat(6).
Justbecauseareferencetypeisaccessibledoesnotnecessarilymeanthatmembersofthe
typearealsoaccessible.Memberaccessibilityisgovernedseparatelyfromtype
accessibility,asexplainedin§4.7,p.123.Table4.2givesasummaryofaccessibility
modifiersfortop-leveltypes.
WOW! eBook
www.wowebook.org
Table4.2SummaryofAccessibilityModifiersforTop-LevelTypes
4.6Non-AccessibilityModifiersforClasses
Thenon-accessibilitymodifiersabstractandfinalcanbeappliedtotop-level
classes.
Classes
Aclasscanbedeclaredwiththekeywordabstracttoindicatethatitcannotbe
instantiated.Aclassmightchoosetodothisiftheabstractionitrepresentsissogeneral
thatitneedstobespecializedtobeofpracticaluse.TheclassVehiclemightbe
specifiedasabstracttorepresentthegeneralabstractionofavehicle,ascreating
instancesoftheclasswouldnotmakemuchsense.Creatinginstancesofnon-abstract
subclasses,likeCarandBus,wouldmakemoresense,asthiswouldmakethe
abstractionmoreconcrete.
Anynormalclass(thatis,aclassdeclaredwiththekeywordclass)canbedeclaredas
abstract.However,ifsuchaclasshasoneormoreabstractmethods(§4.8,p.136),
itmustbedeclaredasabstract.Obviously,suchclassescannotbeinstantiated,astheir
implementationmightbeonlypartial.Aclassmightchoosethisstrategytodictatecertain
behavior,butallowitssubclassesthefreedomtoprovidetherelevantimplementation.In
otherwords,subclassesoftheabstractclasshavetotakeastandandprovide
implementationsofanyinheritedabstractmethodsbeforeinstancescanbecreated.A
subclassthatdoesnotprovideanimplementationofitsinheritedabstractmethods
mustalsobedeclaredasabstractorthecodewillnotcompile.
InExample4.9,thedeclarationoftheabstractclassLighthasanabstract
methodnamedkwhPriceat(1).Thisforcesitsconcrete(i.e.,non-abstract)subclassesto
provideanimplementationforthismethod.Suchaclassprovidesimplementationsofall
itsmethods.TheconcretesubclassTubeLightprovidesanimplementationforthe
methodkwhPrice()at(2).TheclassFactorycreatesaninstanceoftheclass
TubeLightat(3).Referencesofanabstractclasscanbedeclared,asshownat(4),
butanabstractclasscannotbeinstantiated,asshownat(5).Referencesofan
abstractclasscanrefertoobjectsofthesubclasses,asshownat(6).
WOW! eBook
www.wowebook.org
Example4.9AbstractClasses
Clickheretoviewcodeimage
abstractclassLight{
//Fields:
intnoOfWatts;//Wattage
booleanindicator;//Onoroff
Stringlocation;//Placement
//Instancemethods:
publicvoidswitchOn(){indicator=true;}
publicvoidswitchOff(){indicator=false;}
publicbooleanisOn(){returnindicator;}
//Abstractinstancemethod
publicabstractdoublekwhPrice();//(1)Nomethodbody
}
//______________________________________________________________________________
classTubeLightextendsLight{
//Field
inttubeLength;
//Implementationofinheritedabstractmethod.
@OverridepublicdoublekwhPrice(){return2.75;}//(2)
}
//______________________________________________________________________________
publicclassFactory{
publicstaticvoidmain(String[]args){
TubeLightcellarLight=newTubeLight();//(3)OK
LightnightLight;//(4)OK
//LighttableLight=newLight();//(5)Compile-time
error
nightLight=newTubeLight();//(6)OK
System.out.println(“KWHprice:$”+nightLight.kwhPrice());
}
}
Outputfromtheprogram:
KWHprice:$2.75
Classes
Aclasscanbedeclaredasfinaltoindicatethatitcannotbeextended;thatis,one
cannotdeclaresubclassesofafinalclass.Thisimpliesthatonecannotoverrideany
methodsdeclaredinsuchaclass.Inotherwords,theclassbehaviorcannotbechangedby
extendingtheclass.Afinalclassmarksthelowerboundaryofitsimplementation
inheritancehier-archy(§7.1,p.264).Onlyaconcreteclasscanbedeclaredasfinal.
Afinalclassmustbecomplete,whereasanabstractclassisconsideredincomplete.
Classes,therefore,cannotbebothfinalandabstractatthesametime.Interfacesare
inherentlyabstract,astheycanspecifymethodsthatareabstract,andthereforecannot
bedeclaredasfinal.Afinalclassandaninterfacerepresenttwoextremeswhenit
comestoprovidinganimplementation.Anabstractclassrepresentsacompromise
betweenthesetwoextremes.Table4.3providesasummaryofnon-accessibilitymodifiers
forclasses.
WOW! eBook
www.wowebook.org
Table4.3SummaryofNon-AccessibilityModifiersforClasses
TheJavaSEplatformAPIincludesmanyfinalclasses—forexample,the
java.lang.Stringclassandthewrapperclassesforprimitivevalues.
IfitisdecidedthattheclassTubeLightinExample4.9maynotbeextended,itcanbe
declaredasfinal:
Clickheretoviewcodeimage
finalclassTubeLightextendsLight{
//…
}
Discussionoffinalmethods,fields,andlocalvariablescanbefoundin§4.8,p.133.
ReviewQuestions
4.8Giventhefollowingclass,whichofthesealternativesarevalidwaysofreferringto
theclassfromoutsideofthepackagenet.basemaster?
packagenet.basemaster;
publicclassBase{
//…
}
Selectthetwocorrectanswers.
(a)BysimplyreferringtotheclassasBase
(b)Bysimplyreferringtotheclassasbasemaster.Base
(c)Bysimplyreferringtotheclassasnet.basemaster.Base
(d)Byimportingwithnet.basemaster.*,andreferringtotheclassasBase
(e)Byimportingwithnet.*,andreferringtotheclassasbasemaster.Base
4.9Whichoneofthefollowingclassdeclarationsisavaliddeclarationofaclassthat
cannotbeinstantiated?
Selecttheonecorrectanswer.
(a)classGhost{abstractvoidhaunt();}
(b)abstractclassGhost{voidhaunt();}
WOW! eBook
www.wowebook.org
(c)abstractclassGhost{voidhaunt(){};}
(d)abstractGhost{abstractvoidhaunt();}
(e)abstractclassGhost{abstracthaunt();}
4.10Whichoneofthefollowingclassdeclarationsisavaliddeclarationofaclassthat
cannotbeextended?
Selecttheonecorrectanswer.
(a)classLink{}
(b)abstractclassLink{}
(c)nativeclassLink{}
(d)finalclassLink{}
(e)abstractfinalclassLink{}
4.7MemberAccessibilityModifiers
Byspecifyingmemberaccessibilitymodifiers,aclasscancontrolwhichinformationis
accessibletoclients(thatis,otherclasses).Thesemodifiershelpaclasstodefinea
contractsothatclientsknowexactlywhichservicesareofferedbytheclass.
Theaccessibilityofmemberscanbeoneofthefollowing:
public
protected
Defaultaccessibility(alsoknownaspackageaccessibility),meaningthatno
accessibilitymodifierisspecified
private
Inthefollowingdiscussionofaccessibilitymodifiersformembersofaclass,keepinmind
thatthememberaccessibilitymodifierhasmeaningonlyiftheclass(oroneofits
subclasses)isaccessibletotheclient.Also,notethatonlyoneaccessibilitymodifiercan
bespecifiedforamember.
Thediscussioninthissectionappliestobothinstanceandstaticmembersoftop-level
classes.Itappliesequallytoconstructorsaswell.
InUMLnotation,theprefixes+,#,and-,whenappliedtoamembername,indicate
public,protected,andprivatememberaccessibility,respectively.Noprefix
indicatesdefaultorpackageaccessibility.
Members
Publicaccessibilityistheleastrestrictiveofalltheaccessibilitymodifiers.Apublic
memberisaccessiblefromanywhere,bothinthepackagecontainingitsclassandinother
packageswherethisclassisvisible.
WOW! eBook
www.wowebook.org
Example4.10containstwosourcefiles,shownat(1)and(6).Thepackagehierarchy
definedbythesourcefilesisdepictedinFigure4.6,showingthetwopackages,
packageAandpackageB,containingtheirrespectiveclasses.Theclassesin
packageBuseclassesfrompackageA.TheclassSuperclassAinpackageAhas
twosubclasses:SubclassAinpackageAandSubclassBinpackageB.
Figure4.6PublicAccessibilityforMembers
WOW! eBook
www.wowebook.org
Example4.10PublicAccessibilityofMembers
Clickheretoviewcodeimage
//File:SuperclassA.java(1)
packagepackageA;
publicclassSuperclassA{
publicintsuperclassVarA;//(2)
publicvoidsuperclassMethodA(){/*…*/}//(3)
}
classSubclassAextendsSuperclassA{
voidsubclassMethodA(){superclassVarA=10;}//(4)OK
}
classAnyClassA{
SuperclassAobj=newSuperclassA();
voidanyClassMethodA(){
obj.superclassMethodA();//(5)OK
}
}
//File:SubclassB.java(6)
packagepackageB;
importpackageA.*;
publicclassSubclassBextendsSuperclassA{
voidsubclassMethodB(){superclassMethodA();}//(7)OK
}
classAnyClassB{
SuperclassAobj=newSuperclassA();
voidanyClassMethodB(){
obj.superclassVarA=20;//(8)OK
}
}
AccessibilityisillustratedinExample4.10bytheaccessibilitymodifiersforthefield
superclassVarAandthemethodsuperclassMethodA()at(2)and(3),
respectively,definedintheclassSuperclassA.Thesemembersareaccessedfromfour
differentclientsinExample4.10.
•Client1:Fromasubclassinthesamepackage,whichaccessesaninheritedfield
fromtheclassSuperclassA.SubclassAissuchaclient,anddoesthisat(4).
•Client2:Fromanon-subclassinthesamepackage,whichinvokesamethodonan
instanceoftheSuperclassAclass.AnyClassAissuchaclient,anddoesthisat
(5).
•Client3:Fromasubclassinanotherpackage,whichinvokesaninheritedmethod
fromtheclassSuperclassA.SubclassBissuchaclient,anddoesthisat(7).
•Client4:Fromanon-subclassinanotherpackage,whichaccessesafieldinan
instanceoftheSuperclassAclass.AnyClassBissuchaclient,anddoesthisat
(8).
WOW! eBook
www.wowebook.org
InExample4.10,thefieldsuperclassVarAandthemethod
superclassMethodA()havepublicaccessibilityintheSuperclassAclass,and
areaccessiblebyallfouroftheseclients.Subclassescanaccesstheirinheritedpublic
membersbytheirsimplenames,andallclientscanaccesspublicmembersinaninstance
oftheSuperclassAclass.PublicaccessibilityisdepictedinFigure4.6.
Members
Aprotectedmemberisaccessibleinallclassesinthesamepackage,andbyallsubclasses
ofitsclassinanypackagewherethisclassisvisible.Inotherwords,non-subclassesin
otherpackagescannotaccessprotectedmembersfromotherpackages.Thiskindof
accessibilityismorerestrictivethanpublicmemberaccessibility.
InExample4.10,ifthefieldsuperclassVarAandthemethod
superclassMethodA()oftheclassSuperclassAhaveprotectedaccessibility,
theyareaccessiblewithinpackageA,andonlyaccessiblebysubclassesinanyother
packages.
Clickheretoviewcodeimage
publicclassSuperclassA{
protectedintsuperclassVarA;//(2)Protectedmember
protectedvoidsuperclassMethodA(){/*…*/}//(3)Protectedmember
}
Client4inpackageBcannotaccessthesemembers,asshowninFigure4.7.
Figure4.7ProtectedAccessibilityforMembers
Animportantcaveatisthatasubclassinanotherpackagecanaccessonlyprotected
membersinthesuperclassviareferencesofitsowntypeoritssubtypes.Thefollowing
newdeclarationofSubclassBinpackageBfromExample4.10illustratesthepoint:
Clickheretoviewcodeimage
//File:SubclassB.java
packagepackageB;
importpackageA.*;
WOW! eBook
www.wowebook.org
publicclassSubclassBextendsSuperclassA{//InpackageB
SuperclassAobjRefA=newSuperclassA();//(1)
voidsubclassMethodB(SubclassBobjRefB){
objRefB.superclassMethodA();//(2)OK
objRefB.superclassVarA=5;//(3)OK
objRefA.superclassMethodA();//(4)NotOK
objRefA.superclassVarA=10;//(5)NotOK
}
}
TheclassSubclassBdeclaresthefieldobjRefAoftypeSuperclassAat(1).The
methodsubclassMethodB()hastheformalparameterobjRefBoftype
SubclassB.AccessispermittedtoaprotectedmemberofSuperclassAin
packageAbyareferenceofthesubclass,asshownat(2)and(3),butnotbyareference
ofitssuperclass,asshownat(4)and(5).AccesstothefieldsuperclassVarAandthe
calltothemethodsuperclassMethodA()occurinSubclassB.Thesemembersare
declaredinSuperclassA.SubclassBisnotinvolvedintheimplementationof
SuperclassA,whichisthetypeofthereferenceobjRefA.Hence,accesstoprotected
membersat(4)and(5)isnotpermittedasthesearenotmembersofanobjectthatcanbe
guaranteedtobeimplementedbythecodeaccessingthem.
Accessibilitytoprotectedmembersofthesuperclasswouldalsobepermittedviaany
referencewhosetypeisasubclassofSubclassB.Thepreviouslymentionedrestriction
helpstoensurethatsubclassesinpackagesdifferentfromtheirsuperclasscanaccess
protectedmembersofthesuperclassonlyintheirpartoftheimplementationinheritance
hierarchy.Inotherwords,aprotectedmemberofasuperclassisaccessibleinasubclass
thatisinanotherpackageonlyifthememberisinheritedbyanobjectofthesubclass(or
byanobjectofasubclassofthissubclass).
DefaultAccessibilityforMembers
Whennomemberaccessibilitymodifierisspecified,thememberisaccessibleonlyto
otherclassesinitsownclass’spackage.Evenifitsclassisvisibleinanother(possibly
nested)package,thememberisnotaccessibleelsewhere.Defaultmemberaccessibilityis
morerestrictivethanprotectedmemberaccessibility.
InExample4.10,ifthefieldsuperclassVarAandthemethod
superclassMethodA()aredefinedwithnoaccessibilitymodifier,theyareaccessible
withinpackageA,butnotinanyotherpackages.
Clickheretoviewcodeimage
publicclassSuperclassA{
intsuperclassVarA;//(2)Default
accessibility
voidsuperclassMethodA(){/*…*/}//(3)Defaultaccessibility
}
TheclientsinpackageB(thatis,Clients3and4)cannotaccessthesemembers.This
situationisdepictedinFigure4.8.
WOW! eBook
www.wowebook.org
Figure4.8DefaultAccessibilityforMembers
Members
Theprivatemodifieristhemostrestrictiveofalltheaccessibilitymodifiers.Private
membersarenotaccessiblefromanyotherclasses.Thisalsoappliestosubclasses,
whethertheyareinthesamepackageornot.Sincetheyarenotaccessiblebytheirsimple
namesinasubclass,theyarealsonotinheritedbythesubclass.Astandarddesignstrategy
foraclassistomakeallfieldsprivateandprovidepublicaccessormethodsforthem.
Auxiliarymethodsareoftendeclaredasprivate,astheydonotconcernanyclient.
InExample4.10,ifthefieldsuperclassVarAandthemethod
superclassMethodA()haveprivateaccessibility,theyarenotaccessiblebyany
otherclients.
Clickheretoviewcodeimage
publicclassSuperclassA{
privateintsuperclassVarA;//(2)Privatemember
privatevoidsuperclassMethodA(){/*…*/}//(3)Privatemember
}
NoneoftheclientsinFigure4.9canaccessthesemembers.Table4.4providesasummary
ofaccessibilitymodifiersformembers.
WOW! eBook
www.wowebook.org
Figure4.9PrivateAccessibilityforMembers
Table4.4SummaryofAccessibilityModifiersforMembers
ReviewQuestions
4.11Giventhefollowingdeclarationofaclass,whichfieldisaccessiblefromoutside
thepackagecom.corporation.project?
Clickheretoviewcodeimage
packagecom.corporation.project;
publicclassMyClass{
inti;
publicintj;
protectedintk;
privateintl;
}
Selecttheonecorrectanswer.
(a)Fieldiisaccessibleinallclassesinotherpackages.
(b)Fieldjisaccessibleinallclassesinotherpackages.
(c)Fieldkisaccessibleinallclassesinotherpackages.
WOW! eBook
www.wowebook.org
(d)Fieldkisaccessibleinsubclassesonlyinotherpackages.
(e)Fieldlisaccessibleinallclassesinotherpackages.
(f)Fieldlisaccessibleinsubclassesonlyinotherpackages.
4.12Howrestrictiveisthedefaultaccessibilitycomparedtopublic,protected,
andprivateaccessibility?
Selecttheonecorrectanswer
(a)Lessrestrictivethanpublic
(b)Morerestrictivethanpublic,butlessrestrictivethanprotected
(c)Morerestrictivethanprotected,butlessrestrictivethanprivate
(d)Morerestrictivethanprivate
(e)Lessrestrictivethanprotectedfromwithinapackage,andmorerestrictive
thanprotectedfromoutsideapackage
4.13Whichstatementistrueabouttheaccessibilityofmembers?
Selecttheonecorrectanswer.
(a)Aprivatememberisalwaysaccessiblewithinthesamepackage.
(b)Aprivatemembercanbeaccessedonlywithintheclassofthemember.
(c)Amemberwithdefaultaccessibilitycanbeaccessedbyanysubclassofthe
classinwhichitisdeclared.
(d)Aprivatemembercannotbeaccessedatall.
(e)Package/defaultaccessibilityforamembercanbedeclaredusingthekeyword
default.
4.14Whichlinesthataremarkedwillcompileinthefollowingcode?
Clickheretoviewcodeimage
//Filename:A.java
packagepackageA;
publicclassA{
protectedintpf;
}
//Filename:B.java
packagepackageB;
importpackageA.A;
publicclassBextendsA{
voidaction(Aobj1,Bobj2,Cobj3){
pf=10;//(1)
obj1.pf=10;//(2)
obj2.pf=10;//(3)
obj3.pf=10;//(4)
}
}
WOW! eBook
www.wowebook.org
classCextendsB{
voidaction(Aobj1,Bobj2,Cobj3){
pf=10;//(5)
obj1.pf=10;//(6)
obj2.pf=10;//(7)
obj3.pf=10;//(8)
}
}
classD{
voidaction(Aobj1,Bobj2,Cobj3){
pf=10;//(9)
obj1.pf=10;//(10)
obj2.pf=10;//(11)
obj3.pf=10;//(12)
}
}
Selectthefivecorrectanswers.
(a)(1)
(b)(2)
(c)(3)
(d)(4)
(e)(5)
(f)(6)
(g)(7)
(h)(8)
(i)(9)
(j)(10)
(k)(11)
(l)(12)
4.8Non-AccessibilityModifiersforMembers
Thefollowingkeywordscanbeusedtospecifycertainaspectsofmembersinatype
declaration:
static
final
abstract
synchronized
native
WOW! eBook
www.wowebook.org
transient
volatile
Members
Staticmembersbelongtotheclassinwhichtheyaredeclaredandarenotpartofany
instanceoftheclass.Thedeclarationofstaticmembersisprefixedbythekeyword
statictodistinguishthemfrominstancemembers.Dependingontheaccessibility
modifiersofthestaticmembersinaclass,clientscanaccessthesemembersbyusingthe
classnameorthroughobjectreferencesoftheclass.Theclassneednotbeinstantiatedto
accessitsstaticmembers.
Staticvariables(alsocalledclassvariables)existonlyintheclassinwhichtheyare
defined.Theyarenotinstantiatedwhenaninstanceoftheclassiscreated.Inotherwords,
thevaluesofthesevariablesarenotapartofthestateofanyobject.Whentheclassis
loaded,staticvariablesareinitializedtotheirdefaultvaluesifnoexplicitinitialization
expressionisspecified.
Staticmethodsarealsoknownasclassmethods.Astaticmethodinaclasscandirectly
accessotherstaticmembersintheclass.Itcannotaccessinstance(i.e.,non-static)
membersoftheclassdirectly,asthereisnonotionofanobjectassociatedwithastatic
method.
Atypicalstaticmethodmightperformsometaskonbehalfofthewholeclassorfor
objectsoftheclass.InExample4.11,thestaticvariablecounterkeepstrackofthe
numberofinstancesoftheLightclassthathavebeencreated.Theexampleshowsthat
thestaticmethodwriteCount()canaccessstaticmembersdirectly,asshownat(2),
butnotnon-staticmembers,asshownat(3).Thestaticvariablecounterat(1)willbe
initializedtothedefaultvalue0whentheclassisloadedatruntime.Themain()method
at(4)intheclassWarehouseshowshowstaticmembersoftheclassLightcanbe
accessedusingtheclassnameandviaobjectreferencesofthetypeLight.
Asummaryofhowstaticmembersareaccessedinstaticandnon-staticcodeisgivenin
Table4.1,p.115.
WOW! eBook
www.wowebook.org
Example4.11AccessingStaticMembers
Clickheretoviewcodeimage
classLight{
//Fields:
intnoOfWatts;//Wattage
booleanindicator;//Onoroff
Stringlocation;//Placement
//Staticvariable
staticintcounter;//NumberofLightobjectscreated(1)
//Non-zeroargumentconstructor
Light(intnoOfWatts,booleanindicator,Stringlocation){
this.noOfWatts=noOfWatts;
this.indicator=indicator;
this.location=location;
++counter;//Incrementcounter.
}
//Staticmethod
publicstaticvoidwriteCount(){
System.out.println(“Numberoflights:”+counter);//(2)
//Compile-timeerror.FieldnoOfWattsisnotaccessible:
//System.out.println(“NumberofWatts:”+noOfWatts);//(3)
}
}
//______________________________________________________________________________
publicclassWarehouse{
publicstaticvoidmain(String[]args){//(4)
Light.writeCount();//Invokedusingclass
name
Lightlight1=newLight(100,true,“basement”);//Createanobject
System.out.println(
“Valueofcounter:”+Light.counter//Accessedviaclass
name
);
Lightlight2=newLight(200,false,“garage”);//Createanotherobject
light2.writeCount();//Invokedusing
reference
Lightlight3=newLight(300,true,“kitchen”);//Createanotherobject
System.out.println(
“Valueofcounter:”+light3.counter//Accessedvia
reference
);
}
}
Outputfromtheprogram:
Numberoflights:0
Valueofcounter:1
Numberoflights:2
Valueofcounter:3
WOW! eBook
www.wowebook.org
Members
Afinalvariableisaconstantdespitebeingcalledavariable.Itsvaluecannotbe
changedonceithasbeeninitialized.Instanceandstaticvariablescanbedeclaredas
final.Notethatthekeywordfinalcanalsobeappliedtolocalvariables,including
formalparametersofamethod.Declaringavariableasfinalhasthefollowing
implications:
•Afinalvariableofaprimitivedatatypecannotchangeitsvalueonceithasbeen
initialized.
•Afinalvariableofareferencetypecannotchangeitsreferencevalueonceithas
beeninitialized.Thiseffectivelymeansthatafinalreferencewillalwaysreferto
thesameobject.However,thekeywordfinalhasnobearingonwhetherthestate
oftheobjectdenotedbythereferencecanbechanged.
•Aftertheconstructorexits,thefinalfieldsofaobjectareallguaranteedtobe
initialized.Thecompilerensuresthattheclassprovidestheappropriatecodeto
initializethefinalfields.
Afinalvariablemustbeexplicitlyinitializedonlyoncewithaninitializerexpression,
eitherinitsdeclarationorinaninitializerblock(§9.7,p.399).Afinalinstancevariable
canalsobeinitializedinaconstructor.
Notethatafinallocalvariableneednotbeinitializedinitsdeclaration,butitmustbe
initializedinthecodeoncebeforeitisused.Thesevariablesarealsoknownasblankfinal
variables.Foradiscussionoffinalparameters,see§3.5,p.80.
Afinalmethodinaclassisaconcretemethod(thatis,hasanimplementation)and
cannotbeoverriddeninanysubclass(§7.2,p.268).
Variablesdeclaredasfinalensurethatvaluescannotbechangedandmethodsdeclared
asfinalensurethatbehaviorcannotbechanged.Classesdeclaredasfinalare
discussedin§4.6,p.122.
Thecompilermaybeabletoperformcodeoptimizationsforfinalmembers,because
certainassumptionscanbemadeaboutsuchmembers.
Staticfinalvariablesarecommonlyusedtodefinemanifestconstants(alsocallednamed
constants)—forexample,Integer.MAX_VALUE,whichisthemaximumintvalue.
Variablesdefinedinaninterfaceareimplicitlyfinal(§7.6,p.290).
InExample4.12,theclassLightdefinestwopublicstaticfinalvariablesat
(1)and(2).ThepublicstaticfinalvariableKWH_PRICEisinitializedinthe
declarationat(1),andthepublicstaticfinalvariableMANUFACTURERis
initializedinthestaticinitializerblockat(3).Anattempttochangethevalueofthe
publicstaticfinalvariableKWH_PRICEat(9)resultsinacompile-timeerror.
TheclassLightalsodefinestwofinalinstancevariablesat(4)and(5).Thefinal
instancevariablecolorisinitializedintheinstanceinitializerblockat(6),andthe
WOW! eBook
www.wowebook.org
finalinstancevariableenergyRatingisinitializedintheconstructorat(7).
TheclassLightalsodefinesafinalmethodat(8).ThesubclassTubeLight
attemptstooverridethefinalmethodsetWatts()fromthesuperclassLightat
(10),whichisnotpermitted.
TheclassWarehousealsodefinesafinallocalreferenceworkLightat(11).The
stateoftheobjectdenotedbythereferenceworkLightischangedat(12),butits
referencevaluecannotbechangedasattemptedat(13).Anotherfinallocalreference
alarmLightisdeclaredat(14),butitisnotinitialized.Thecompilerreportsanerror
whenanattemptismadetousethisreferenceat(15).
Example4.12UsingfinalModifier
Clickheretoviewcodeimage
classLight{
//Staticfinalvariables
publicstaticfinaldoubleKWH_PRICE=3.25;//(1)
publicstaticfinalStringMANUFACTURER;//(2)
static{//Staticinitializerblock
MANUFACTURER=“Ozam”;//(3)Initializes(2)
}
//Instancevariables
intnoOfWatts;
finalStringcolor;//(4)
finalStringenergyRating;//(5)
{//Instanceinitializer
block
color=“offwhite”;//(6)Initializes(4)
}
//Constructor
Light(){
energyRating=“A++”;//(7)Initializes(5)
}
//Finalinstancemethod(8)
finalpublicvoidsetWatts(intwatt){
noOfWatts=watt;
}
publicvoidsetKWH(){
//KWH_PRICE=4.10;//(9)NotOK.Cannotbechanged.
}
}
//______________________________________________________________________________
classTubeLightextendsLight{
//Finalmethodinsuperclasscannotbeoverridden.
//Thismethodwillnotcompile.
/*
@Override
publicvoidsetWatts(intwatt){//(10)Attempttooverride.
noOfWatts=2*watt;
}
*/
WOW! eBook
www.wowebook.org
}
//______________________________________________________________________________
publicclassWarehouse{
publicstaticvoidmain(String[]args){
finalLightworkLight=newLight();//(11)Finallocalvariable.
workLight.setWatts(100);//(12)OK.Changingobjectstate.
//workLight=newLight();//(13)NotOK.Changingfinal
reference.
finalLightalarmLight;//(14)Notinitialized.
//alarmLight.setWatts(200);//(15)NotOK.
System.out.println(“KWH_PRICE:”+Light.KWH_PRICE);
System.out.println(“MANUFACTURER:”+Light.MANUFACTURER);
System.out.println(“noOfWatts:”+workLight.noOfWatts);
System.out.println(“color:”+workLight.color);
System.out.println(“energyRating:”+workLight.energyRating);
}
}
Outputfromtheprogram:
KWH_PRICE:3.25
MANUFACTURER:Ozam
noOfWatts:100
color:offwhite
energyRating:A++
Methods
Anabstractmethodinanabstractclasshasthefollowingsyntax:
Clickheretoviewcodeimage
accessibility_modifierabstractreturn_typemethod_name
(formal_parameter_list)
throws_clause;
Anabstractmethoddoesnothaveanimplementation;thatis,nomethodbodyisdefined
foranabstractmethod,andonlythemethodheaderisprovidedintheclassdeclaration.
Thekeywordabstractismandatoryintheheaderofanabstractmethoddeclaredina
class.Itsclassisthenincompleteandmustbeexplicitlydeclaredasabstract(§4.6,p.
120).Subclassesofanabstractclassmustthenprovidethemethodimplementation;
otherwise,theymustalsobedeclaredasabstract.Theaccessibilityofanabstract
methoddeclaredinatop-levelclasscannotbeprivate,assubclasseswouldnotbeable
tooverridethemethodandprovideanimplementation.See§4.6,whereExample4.9also
illustratestheuseofabstractmethods.
Onlyaninstancemethodcanbedeclaredasabstract.Sincestaticmethodscannotbe
overridden,declaringanabstractstaticmethodmakesnosense,andthecompilerwill
reportanerror.Afinalmethodcannotbeabstract(i.e.,cannotbeincomplete),and
viceversa.Thekeywordabstractcanbespecifiedonlyincombinationwiththe
publicorprotectedaccessibilitymodifier.
Abstractmethodsspecifiedinatop-levelinterfaceareimplicitlyabstract,andthe
WOW! eBook
www.wowebook.org
keywordabstractisseldomspecifiedintheirmethodheaders.Thesemethodscan
haveonlypublicaccessibility.See§7.6,p.291,foradiscussionofabstractmethodsin
top-levelinterfaces.
Methods
Athreadisanindependentpathofexecutioninaprogram.Severalthreadscanbe
executinginaprogram.Theymighttrytoexecuteseveralmethodsonthesameobject
simultaneously.Methodscanbedeclaredassynchronizedifitisdesiredthatonlyone
threadatatimebeabletoexecuteamethodoftheobject.Theirexecutionisthenmutually
exclusiveamongallthreads.Atanygiventime,atmostonethreadcanbeexecutinga
synchronizedmethodonanobject.Thisdiscussionalsoappliestostatic
synchronizedmethodsofaclass.
InExample4.13,boththepush()method,declaredat(1),andthepop()method,
declaredat(2),aresynchronizedintheclassStackImpl.Onlyonethreadatatime
canexecuteasynchronizedmethodinanobjectoftheclassStackImpl.
Consequently,itisnotpossibleforthestateofanobjectoftheclassStackImpltobe
corrupted,forexample,whileonethreadispushinganelementandanotherisattempting
topopthestack.
Example4.13SynchronizedMethods
Clickheretoviewcodeimage
classStackImpl{//Non-genericpartialimplementation
privateObject[]stackArray;
privateinttopOfStack;
//…
synchronizedpublicvoidpush(Objectelem){//(1)
stackArray[++topOfStack]=elem;
}
synchronizedpublicObjectpop(){//(2)
Objectobj=stackArray[topOfStack];
stackArray[topOfStack]=null;
topOfStack—;
returnobj;
}
//Othermethods,etc.
publicObjectpeek(){returnstackArray[topOfStack];}
}
WOW! eBook
www.wowebook.org
Methods
NativemethodsaremethodswhoseimplementationisnotdefinedinJavabutratherin
anotherprogramminglanguage,suchasCorC++.Suchamethodcanbedeclaredasa
memberinaJavaclassdeclaration.Sinceitsimplementationappearselsewhere,onlythe
methodheaderisspecifiedintheclassdeclaration.Thekeywordnativeismandatoryin
themethodheader.Anativemethodcanalsospecifycheckedexceptionsinathrows
clause(§6.9,p.251),butthecompilercannotcheckthem,sincethemethodisnot
implementedinJava.
TheJavaNativeInterface(JNI)isaspecialAPIthatallowsJavamethodstoinvokenative
functionsimplementedinC.
Inthefollowingexample,anativemethodintheclassNativeisdeclaredat(2).The
classalsousesastaticinitializerblocktoloadthenativelibrarywhentheclassisloaded.
ClientsoftheNativeclasscancallthenativemethodlikeanyanothermethod,asat
(3).
Clickheretoviewcodeimage
classNative{
/*
*Thestaticblockensuresthatthenativemethodlibrary
*isloadedbeforethenativemethodiscalled.
*/
static{
System.loadLibrary(“NativeMethodLib”);//(1)Loadnativelibrary.
}
nativevoidnativeMethod();//(2)Nativemethodheader.
//…
}
classClient{
//…
publicstaticvoidmain(String[]args){
NativetrueNative=newNative();
trueNative.nativeMethod();//(3)Nativemethodcall.
}
//…
}
Fields
Oftenitisdesirabletosavethestateofanobject—forexample,onafile.Suchobjectsare
saidtobepersistent.InJava,thestateofanobjectcanbestoredusingserialization.
Serializationtransformsobjectsintoanoutputformatthatisconduciveforstoringobjects.
Objectscanlaterberetrievedinthesamestateaswhentheywereserialized,meaningthat
allfieldsincludedintheserializationwillhavethesamevaluesasatthetimeof
serialization.
Sometimesthevalueofafieldinanobjectshouldnotbesaved,inwhichcasethefield
canbespecifiedastransientintheclassdeclaration.Thisdesignationimpliesthatits
valueshouldnotbesavedwhenobjectsoftheclassarewrittentopersistentstorage.Inthe
WOW! eBook
www.wowebook.org
followingexample,thefieldcurrentTemperatureisdeclaredastransientat(1),
becausethecurrenttemperatureismostlikelytohavechangedwhentheobjectisrestored
atalaterdate.However,thevalueofthefieldmass,declaredat(2),islikelytoremain
unchanged.WhenobjectsoftheclassExperimentareserialized,thevalueofthefield
currentTemperaturewillnotbesaved,butthatofthefieldmasswillbe,aspartof
thestateoftheserializedobject.
Clickheretoviewcodeimage
classExperimentimplementsSerializable{
//…
//ThevalueofcurrentTemperaturewillnotpersist.
transientintcurrentTemperature;//(1)Transientvalue.
doublemass;//(2)Persistentvalue.
}
Specifyingthetransientmodifierforstaticvariablesisredundantand,therefore,
discouraged.Staticvariablesarenotpartofthepersistentstateofaserializedobject.
Fields
Duringexecution,compiledcodemightcachethevaluesoffieldsforefficiencyreasons.
Sincemultiplethreadscanaccessthesamefield,itisvitalthatcachingisnotallowedto
causeinconsistencieswhenreadingandwritingthevalueinthefield.Thevolatile
modifiercanbeusedtoinformthecompilerthatitshouldnotattempttoperform
optimizationsonthefield,whichcouldcauseunpredictableresultswhenthefieldis
accessedbymultiplethreads.
Inthesimpleexamplethatfollows,thevalueofthefieldclockReadingmightbe
changedunexpectedlybyanotherthreadwhileonethreadisperformingataskthat
involvesalwaysusingthecurrentvalueofthefieldclockReading.Declaringthefield
asvolatileensuresthatawriteoperationwillalwaysbeperformedonthemasterfield
variable,andareadoperationwillalwaysreturnthecorrectcurrentvalue.
Clickheretoviewcodeimage
classVitalControl{
//…
volatilelongclockReading;
//Twosuccessivereadsmightgivedifferentresults.
}
Table4.5providesasummaryofnon-accessibilitymodifiersformembers.
WOW! eBook
www.wowebook.org
Table4.5SummaryofNon-AccessibilityModifiersforMembers
ReviewQuestions
4.15Whichstatementsabouttheuseofmodifiersaretrue?
Selectthetwocorrectanswers.
(a)Ifnoaccessibilitymodifier(public,protected,orprivate)isspecified
foramemberdeclaration,thememberisaccessibleonlybyclassesinthe
packageofitsclassandbysubclassesofitsclassinanypackage.
(b)Youcannotspecifyaccessibilityoflocalvariables.Theyareaccessibleonly
withintheblockinwhichtheyaredeclared.
(c)Subclassesofaclassmustresideinthesamepackageastheclasstheyextend.
(d)Localvariablescanbedeclaredasstatic.
(e)Theobjectsthemselvesdonothaveanyaccessibilitymodifiers;onlyfield
referencesdo.
4.16Giventhefollowingsourcecode,whichcommentlinecanbeuncommented
withoutintroducingerrors?
Clickheretoviewcodeimage
abstractclassMyClass{
abstractvoidf();
finalvoidg(){}
//finalvoidh(){}//(1)
WOW! eBook
www.wowebook.org
protectedstaticinti;
privateintj;
}
finalclassMyOtherClassextendsMyClass{
//MyOtherClass(intn){m=n;}//(2)
publicstaticvoidmain(String[]args){
MyClassmc=newMyOtherClass();
}
voidf(){}
voidh(){}
//voidk(){i++;}//(3)
//voidl(){j++;}//(4)
intm;
}
Selecttheonecorrectanswer.
(a)(1)
(b)(2)
(c)(3)
(d)(4)
4.17Whichstatementistrue?
Selecttheonecorrectanswer.
(a)Astaticmethodcancallothernon-staticmethodsinthesameclassbyusingthe
thiskeyword.
(b)Aclassmaycontainbothstaticandnon-staticvariables,andbothstaticand
non-staticmethods.
(c)Eachobjectofaclasshasitsowninstanceofthestaticvariablesdeclaredinthe
class.
(d)Instancemethodsmayaccesslocalvariablesofstaticmethods.
(e)Allmethodsinaclassareimplicitlypassedthethisreferenceasanargument,
wheninvoked.
4.18Whichoneoftheseisnotalegalmemberdeclarationwithinaclass?
Selecttheonecorrectanswer.
(a)staticinta;
(b)finalObject[]fudge={null};
(c)abstractintt;
(d)nativevoidsneeze();
(e)staticfinalprivatedoublePI=
WOW! eBook
www.wowebook.org
3.14159265358979323846;
4.19Whichstatementsaboutmodifiersaretrue?
Selectthetwocorrectanswers.
(a)Abstractclassescandeclarefinalmethods.
(b)Fieldscanbedeclaredasnative.
(c)Non-abstractmethodscanbedeclaredinabstractclasses.
(d)Classescanbedeclaredasnative.
(e)Abstractclassescanbedeclaredasfinal.
4.20Whichstatementistrue?
Selecttheonecorrectanswer.
(a)Thevaluesoftransientfieldswillnotbesavedduringserialization.
(b)Constructorscanbedeclaredasabstract.
(c)Theinitialstateofanarrayobjectconstructedwiththestatementint[]a=
newint[10]willdependonwhetherthearrayvariableaisalocalvariable
orafield.
(d)Asubclassofaclasswithanabstractmethodmustprovidean
implementationfortheabstractmethod.
(e)Onlystaticmethodscanaccessstaticmembers.
ChapterSummary
Thefollowingtopicswerecoveredinthischapter:
•ThestructureofaJavasourcefile
•Defining,using,anddeployingpackages
•Classscopeformembers,andblockscopeforlocalvariables
•Accessibility(default,public)andothermodifiers(abstract,final)for
referencetypes
•Applicabilityofmemberaccessibility(default,public,protected,private)
andothermembermodifiers(static,final,abstract,synchronized,
native,transient,volatile)
ProgrammingExercise
4.1Designaclassforabankdatabase.Thedatabaseshouldsupportthefollowing
operations:
Depositacertainamountintoanaccount
WOW! eBook
www.wowebook.org
Withdrawacertainamountfromanaccount
Getthebalance(i.e.,thecurrentamount)inanaccount
Transferanamountfromoneaccounttoanother
Theamountinthetransactionsisavalueoftypedouble.Theaccountsare
identifiedbyinstancesoftheclassAccountthatisinthe
packagecom.megabankcorp.records.Thedatabaseclassshouldbeplaced
inapackagecalledcom.megabankcorp.system.
Thedeposit,withdraw,andbalanceoperationsshouldnothaveanyimplementation,
butshouldallowsubclassestoprovidetheimplementation.Thetransferoperation
shouldusethedepositandwithdrawoperationstoimplementthetransfer.Itshould
notbepossibletoalterthisoperationinanysubclass,andonlyclasseswithinthe
packagecom.megabankcorp.systemshouldbeallowedtousethisoperation.
Thedepositandwithdrawoperationsshouldbeaccessibleinallpackages.The
balanceoperationshouldbeaccessibleonlyinsubclassesandclasseswithinthe
packagecom.megabankcorp.system.
WOW! eBook
www.wowebook.org
5.OperatorsandExpressions
5.1Conversions
Inthissectionwefirstdiscussthedifferentkindsoftypeconversionsthatcanbeapplied
tovalues;inthenextsectionwediscussthecontextsinwhichtheseconversionsare
permitted.Sometypeconversionsmustbeexplicitlystatedintheprogram,whileothers
areperformedimplicitly.Sometypeconversionscanbecheckedatcompiletimeto
guaranteetheirvalidityatruntime,whileotherswillrequireanextracheckatruntime.
WOW! eBook
www.wowebook.org
WideningandNarrowingPrimitiveConversions
Fortheprimitivedatatypes,thevalueofanarrowerdatatypecanbeconvertedtoavalue
ofawiderdatatype.Thisiscalledawideningprimitiveconversion.Wideningconversions
fromoneprimitivetypetothenextwiderprimitivetypearesummarizedinFigure5.1.
Theconversionsshownaretransitive.Forexample,anintcanbedirectlyconvertedtoa
doublewithoutfirsthavingtoconvertittoalongandafloat.
Figure5.1WideningPrimitiveConversions
Notethatthetargettypeofawideningprimitiveconversionhasawiderrangeofvalues
thanthesourcetype—forexample,therangeofthelongtypesubsumestherangeofthe
inttype.Inwideningconversionsbetweenintegraltypes,thesourcevalueremains
intact,withnolossofmagnitudeinformation.However,awideningconversionfroman
intoralongvaluetoafloatvalue,orfromalongvaluetoadoublevalue,may
resultinalossofprecision.Thefloating-pointvalueinthetargettypeisthenacorrectly
roundedapproximationoftheintegervalue.Notethatprecisionrelatestothenumberof
significantbitsinthevalue,andmustnotbeconfusedwithmagnitude,whichrelateshow
bigavaluecanberepresented.
Convertingfromawiderprimitivetypetoanarrowerprimitivetypeiscalledanarrowing
primitiveconversion;itcanresultinlossofmagnitudeinformation,andpossiblyinaloss
ofprecisionaswell.Anyconversionthatisnotawideningprimitiveconversionaccording
toFigure5.1isanarrowingprimitiveconversion.Thetargettypeofanarrowingprimitive
conversionhasanarrowerrangeofvaluesthanthesourcetype—forexample,therange
oftheinttypedoesnotincludeallthevaluesintherangeofthelongtype.
Notethatallconversionsbetweencharandthetwointegertypesbyteandshortare
considerednarrowingprimitiveconversions.Thereasonisthattheconversionsbetween
theunsignedtypecharandthesignedtypesbyteorshortcanresultinlossof
information.Thesenarrowingconversionsaredoneintwosteps:firstconvertingthe
sourcevaluetotheinttype,andthenconvertingtheintvaluetothetargettype.
Wideningprimitiveconversionsareusuallydoneimplicitly,whereasnarrowingprimitive
conversionsusuallyrequireacast(§5.2,p.148).Itisnotillegaltouseacastfora
wideningconversion.However,thecompilerwillflaganyconversionthatrequiresacast
ifnonehasbeenspecified.Regardlessofanylossofmagnitudeorprecision,wideningand
narrowingprimitiveconversionsneverresultinaruntimeexception.
Ampleexamplesofwideningandnarrowingprimitiveconversionscanbefoundinthis
chapter.
WOW! eBook
www.wowebook.org
WideningandNarrowingReferenceConversions
Thesubtype–supertyperelationshipbetweenreferencetypesdetermineswhich
conversionsarepermissiblebetweenthem.Conversionsupthetypehierarchyarecalled
wideningreferenceconversions(alsocalledupcasting).Suchaconversionconvertsfroma
subtypetoasupertype:
Clickheretoviewcodeimage
Objectobj=“Upcastme”;//Widening:Object<–—String
Conversionsdownthetypehierarchyrepresentnarrowingreferenceconversions(also
calleddowncasting):
Clickheretoviewcodeimage
Stringstr=(String)obj;//Narrowingrequirescast:String<–—Object
Asubtypeisanarrowertypethanitssupertypeinthesensethatitisaspecializationofits
supertype.Contextsunderwhichreferenceconversionscanoccurarediscussedin§7.8,p.
311.
Wideningreferenceconversionsareusuallydoneimplicitly,whereasnarrowingreference
conversionsusuallyrequireacast,asillustratedintheseconddeclarationstatementinthis
subsection.Thecompilerwillrejectcaststhatarenotlegalorissueanuncheckedwarning
undercertaincircumstancesiftypesafetycannotbeguaranteed.
Wideningreferenceconversionsdonotrequireanyruntimechecksandneverresultinan
exceptionduringexecution.Thisisnotthecasefornarrowingreferenceconversions,
whichrequirearuntimecheckandcanthrowaClassCastExceptionifthe
conversionisnotlegal.
BoxingandUnboxingConversions
Boxingandunboxingconversionsallowinteroperabilitybetweenprimitivevaluesand
theirrepresentationasobjectsofthewrappertypes(§8.3,p.346).
Aboxingconversionconvertsthevalueofaprimitivetypetoacorrespondingvalueofits
wrappertype.IfpisavalueofaprimitiveType,boxingconversionconvertspintoa
referencerofthecorrespondingWrapperType,suchthatr.primitiveTypeValue()==
p.Inthecodethatfollows,theintvalue10resultsinanobjectofthetypeInteger
implicitlybeingcreated;thisobjectcontainstheintvalue10.Wesaythattheintvalue
10hasbeenboxedinanobjectofthewrappertypeInteger.Theterminology
autoboxedisalsousedforthisconversion.
Clickheretoviewcodeimage
IntegeriRef=10;//Boxing:Integer<–—int
System.out.println(iRef.intValue()==10);//true
Anunboxingconversionconvertsthevalueofawrappertypetoavalueofits
correspondingprimitivetype.IfrisareferenceofaWrapperType,anunboxing
conversionconvertsthereferencerintor.primitiveTypeValue(),whereprimitiveType
istheprimitivetypecorrespondingtotheWrapperType.Inthenextcodesnippet,thevalue
intheIntegerobjectreferencedbyiRefisimplicitlyconvertedtotheinttype.We
WOW! eBook
www.wowebook.org
saythatthewrapperobjecthasbeenunboxedtoitscorrespondingprimitivetype.
Clickheretoviewcodeimage
inti=iRef;//Unboxing:int<–—Integer
System.out.println(iRef.intValue()==i);//true
Notethatbothboxingandunboxingaredoneimplicitlyintherightcontext.Boxing
allowsprimitivevaluestobeusedwhereanobjectoftheirwrappertypeisexpected,and
unboxingallowstheconverse.UnboxingmakesitpossibletouseaBooleanwrapper
objectasabooleanvalueinabooleanexpression,andtouseanintegralwrapperobject
asanintegralprimitivevalueinanarithmeticexpression.Unboxingawrapperreference
thathasthenullvalueresultsinaNullPointerException.Ampleexamplesof
boxingandunboxingcanbefoundinthischapterandin§7.8,p.311.
OtherConversions
Webrieflymentionsomeotherconversions,andidentifywheretheyarecoveredinthis
book.
•Identityconversionsarealwayspermitted,astheyallowconversionsfromatypeto
thatsametype.Anidentityconversionisalwayspermitted.
Clickheretoviewcodeimage
inti=(int)10;//int<–-int
Stringstr=(String)“Hi”;//String<–-String
•StringconversionsallowavalueofanyothertypetobeconvertedtoaString
typeinthecontextofthestringconcatenationoperator+(§5.8,p.174).
•Uncheckedconversionsarepermittedtofacilitateoperabilitybetweenlegacyand
genericcode(§10.1,p.416).
5.2TypeConversionContexts
Selectedconversioncontextsandtheconversionsthatareapplicableinthesecontextsare
summarizedinTable5.1.Theconversionsshownineachcontextoccurimplicitly,without
theprogramhavingtotakeanyspecialaction.Forotherconversioncontexts,see§5.1,p.
146.
WOW! eBook
www.wowebook.org
Table5.1SelectedConversionContextsandConversionCategories
AssignmentContext
Assignmentconversionsthatcanoccurinanassignmentcontextareshowninthesecond
columnofTable5.1.Anassignmentconversionconvertsthetypeofanexpressiontothe
typeofatargetvariable.
Anexpression(oritsvalue)isassignabletothetargetvariable,ifthetypeofthe
expressioncanbeconvertedtothetypeofthetargetvariablebyanassignment
conversion.Equivalently,thetypeoftheexpressionisassignmentcompatiblewiththe
typeofthetargetvariable.
Forassignmentconversioninvolvingprimitivedatatypes,see§5.6,p.158.Notethe
specialcasewhereanarrowingconversionoccurswhenassigninganon-longinteger
constantexpression:
Clickheretoviewcodeimage
byteb=10;//Narrowingconversion:byte<–int
WOW! eBook
www.wowebook.org
Forassignmentconversionsinvolvingreferencetypes,see§7.8,p.311.
MethodInvocationContext
Methodinvocationconversionsthatcanoccurinamethodinvocationcontextareshown
inthethirdcolumnofTable5.1.Notethatmethodinvocationandassignmentconversions
differinonerespect:Methodinvocationconversionsdonotincludetheimplicitnarrowing
conversionperformedfornon-longintegralconstantexpressions.
Clickheretoviewcodeimage
//Assignment:(1)Implicitnarrowingfollowedby(2)boxing.
Characterspace1=32;//Character<-(2)—char<-(1)—int
//Invocationofmethodwithsignature:valueOf(char)
Characterspace2=Character.valueOf(32);//Compile-timeerror!
//Callsignature:
valueOf(int)
Characterspace3=Character.valueOf((char)32);//OK!
//Callsignature:
valueOf(char)
Amethodinvocationconversioninvolvesconvertingeachargumentvalueinamethodor
constructorcalltothetypeofthecorrespondingformalparameterinthemethodor
constructordeclaration.
Methodinvocationconversionsinvolvingparametersofprimitivedatatypesarediscussed
in§3.5,p.73,andthoseinvolvingreferencetypesarediscussedin§7.8,p.311.
CastingContextoftheUnaryTypeCastOperator:(type)
Java,beingastronglytypedlanguage,checksfortypecompatibility(i.e.,itchecksifa
typecansubstituteforanothertypeinagivencontext)atcompiletime.However,some
checksarepossibleonlyatruntime(e.g.,whichtypeofobjectareferenceactuallydenotes
duringexecution).Incaseswhereanoperatorwouldhaveincompatibleoperands(e.g.,
assigningadoubletoanint),Javademandsthatatypecastbeusedtoexplicitly
indicatethetypeconversion.Thetypecastconstructhasthefollowingsyntax:
(type)expression
Thecastoperator(type)isappliedtothevalueoftheexpression.Atruntime,acast
resultsinanewvalueoftype,whichbestrepresentsthevalueoftheexpressionintheold
type.Weusethetermcastingtomeanapplyingthecastoperatorforexplicittype
conversion.
However,inthecontextofcasting,implicitcastingconversionscantakeplace.These
castingconversionsareshowninthefourthcolumnofTable5.1.Castingconversions
includemoreconversioncategoriesthantheassignmentorthemethodinvocation
conversions.Inthecodethatfollows,thecommentsindicatethecategoryofthe
conversionthattakesplacebecauseofthecastoperatorontheright-handsideofeach
assignment—althoughcastsareonlynecessaryforthesakeoftheassignmentat(1)and
(2).
Clickheretoviewcodeimage
WOW! eBook
www.wowebook.org
longl=(long)10;//Wideningprimitiveconversion:long<–int
inti=(int)l;//(1)Narrowingprimitiveconversion:int<–long
Objectobj=(Object)“7Up”;//Wideningrefconversion:Object<–String
Stringstr=(String)obj;//(2)Narrowingrefconversion:String<–
Object
IntegeriRef=(Integer)i;//Boxing:Integer<–int
i=(int)iRef;//Unboxing:int<–Integer
Acastingconversionisappliedtothevalueoftheoperandexpressionofacastoperator.
Castingcanbeappliedtoprimitivevaluesaswellasreferences.Castingbetween
primitivedatatypesandreferencetypesisnotpermitted,exceptwhereboxingand
unboxingisapplicable.Booleanvaluescannotbecasttootherdatavalues,andviceversa.
Thereferenceliteralnullcanbecasttoanyreferencetype.
Examplesofcastingbetweenprimitivedatatypesareprovidedinthischapter.Casting
referencevaluesisdiscussedin§7.11,p.320.
NumericPromotionContext
Numericoperatorsallowonlyoperandsofcertaintypes.Numericpromotionresultsin
conversionsbeingappliedtotheoperandstoconvertthemtopermissibletypes.Numeric
promotionconversionsthatcanoccurinanumericpromotioncontextareshowninthe
fifthcolumnofTable5.1.Permissibleconversioncategoriesarewideningprimitive
conversionsandunboxingconversions.Adistinctionismadebetweenunaryandbinary
numericpromotion.
UnaryNumericPromotion
Unarynumericpromotionproceedsasfollows:
•IfthesingleoperandisoftypeByte,Short,Character,orInteger,itis
unboxed.Iftheresultingvalueisnarrowerthanint,itispromotedtoavalueof
typeintbyawideningconversion.
•Otherwise,ifthesingleoperandisoftypeLong,Float,orDouble,itisunboxed.
•Otherwise,ifthesingleoperandisofatypenarrowerthanint,itsvalueis
promotedtoavalueoftypeintbyawideningconversion.
•Otherwise,theoperandremainsunchanged.
Inotherwords,unarynumericpromotionresultsinanoperandvaluethatiseitherintor
wider.
Unarynumericpromotionisappliedinthefollowingexpressions:
•Operandoftheunaryarithmeticoperators+and-(§5.7,p.163)
•Arraycreationexpression;forexample,newint[20],wherethedimension
expression(inthiscase20)mustevaluatetoanintvalue(§3.4,p.59)
•Indexingarrayelements;forexample,objArray['a'],wheretheindex
expression(inthiscase'a')mustevaluatetoanintvalue(§3.4,p.61)
WOW! eBook
www.wowebook.org
BinaryNumericPromotion
Binarynumericpromotionimplicitlyappliesappropriatewideningprimitiveconversions
sothatapairofoperandshavethewidestnumerictypeofthetwo,whichisalwaysatleast
int.IfTisthewidestnumerictypeofthetwooperandsafteranyunboxingconversions
havebeenperformed,theoperandsarepromotedasfollowsduringbinarynumeric
promotion:
IfTiswiderthanint,bothoperandsareconvertedtoT;otherwise,bothoperandsare
convertedtoint.
Thismeansthattheresultingtypeoftheoperandsisatleastint.
Binarynumericpromotionisappliedinthefollowingexpressions:
•Operandsofthearithmeticoperators*,/,%,+,and-(§5.7,p.163)
•Operandsoftherelationaloperators<,<=,>,and>=(§5.11,p.180)
•Operandsofthenumericalequalityoperators==and!=(§5.12,p.181)
•Operandsoftheconditionaloperator?:,undercertaincircumstances(§5.16,p.
194)
5.3PrecedenceandAssociativityRulesforOperators
Precedenceandassociativityrulesarenecessaryfordeterministicevaluationof
expressions.TheoperatorsaresummarizedinTable5.2.Themajorityofthemare
discussedinsubsequentsectionsinthischapter.Seealsotheindexentriesforthese
operators.
WOW! eBook
www.wowebook.org
Table5.2OperatorSummary
ThefollowingremarksapplytoTable5.2:
•Theoperatorsareshownwithdecreasingprecedencefromthetopofthetable.
•Operatorswithinthesamerowhavethesameprecedence.
•Parentheses,(),canbeusedtooverrideprecedenceandassociativity.
•Theunaryoperators,whichrequireoneoperand,includethefollowing:thepostfix
increment(++)anddecrement(--)operatorsfromthefirstrow,alltheprefix
operators(+,-,++,--,~,!)inthesecondrow,andtheprefixoperators(object
creationoperatornew,castoperator(type))inthethirdrow.
•Theconditionaloperator(?:)isternary—thatis,itrequiresthreeoperands.
•Alloperatorsnotidentifiedpreviouslyasunaryorternaryarebinary—thatis,they
requiretwooperands.
•Allbinaryoperators,exceptfortherelationalandassignmentoperators,associate
fromlefttoright.Therelationaloperatorsarenonassociative.
•Exceptforunarypostfixincrementanddecrementoperators,allunaryoperators,all
assignmentoperators,andtheternaryconditionaloperatorassociatefromrightto
left.
WOW! eBook
www.wowebook.org
Dependingonthecontext,brackets([]),parentheses(()),colon(:)andthedotoperator
(.)canalsobeinterpretedasseparators(§2.1,p.29).Seetheindexentriesforthese
separatorsformoredetails.
Precedencerulesareusedtodeterminewhichoperatorshouldbeappliedfirstifthereare
twooperatorswithdifferentprecedence,andtheseoperatorsfolloweachotherinthe
expression.Insuchacase,theoperatorwiththehighestprecedenceisappliedfirst.
Theexpression2+3*4isevaluatedas2+(3*4)(withtheresult14)since*
hashigherprecedencethan+.
Associativityrulesareusedtodeterminewhichoperatorshouldbeappliedfirstifthereare
twooperatorswiththesameprecedence,andtheseoperatorsfolloweachotherinthe
expression.
Leftassociativityimpliesgroupingfromlefttoright:Theexpression7-4+2is
interpretedas((7-4)+2),sincethebinaryoperators+and-bothhavesame
precedenceandleftassociativity.
Rightassociativityimpliesgroupingfromrighttoleft:Theexpression--4is
interpretedas(-(-4))(withtheresult4),sincetheunaryoperator-hasright
associativity.
Theprecedenceandassociativityrulestogetherdeterminetheevaluationorderofthe
operators.
5.4EvaluationOrderofOperands
Tounderstandtheresultreturnedbyanoperator,itisimportanttounderstandthe
evaluationorderofitsoperands.Ingeneral,theoperandsofoperatorsareevaluatedfrom
lefttoright.Theevaluationorderalsorespectsanyparentheses,andtheprecedenceand
associativityrulesofoperators.
Examplesillustratinghowtheoperandevaluationorderinfluencestheresultreturnedby
anoperator,canbefoundin§5.6and§5.9.
Left-HandOperandEvaluationFirst
Theleft-handoperandofabinaryoperatorisfullyevaluatedbeforetheright-handoperand
isevaluated.
Theevaluationoftheleft-handoperandcanhavesideeffectsthatcaninfluencethevalue
oftheright-handoperand.Forexample,inthecode
Clickheretoviewcodeimage
intb=10;
System.out.println((b=3)+b);
thevalueprintedwillbe6andnot13.Theevaluationproceedsasfollows:
Clickheretoviewcodeimage
(b=3)+b
3+bbisassignedthevalue3
3+3
WOW! eBook
www.wowebook.org
6
Ifevaluationoftheleft-handoperandofabinaryoperatorthrowsanexception(§6.5,p.
230),wecannotrelyonthepresumptionthattheright-handoperandhasbeenevaluated.
OperandEvaluationbeforeOperationExecution
Javaguaranteesthatalloperandsofanoperatorarefullyevaluatedbeforetheactual
operationisperformed.Thisruledoesnotapplytotheshort-circuitconditionaloperators
&&,||,and?:.
Thisrulealsoappliestooperatorsthatthrowanexception(theintegerdivisionoperator/
andtheintegerremainderoperator%).Theoperationisperformedonlyiftheoperands
evaluatenormally.Anysideeffectsoftheright-handoperandwillhavebeeneffectuated
beforetheoperatorthrowsanexception.
Example5.1illustratestheevaluationorderoftheoperandsandprecedencerulesfor
arithmeticexpressions.Weusetheeval()methodat(3)inExample5.1todemonstrate
integerexpressionevaluation.Thefirstargumenttothismethodistheoperandvaluethat
isreturnedbythemethod,andthesecondargumentisastringtoidentifytheevaluation
order.
Theargumenttotheprintln()methodinthestatementat(1)isanintegerexpression
toevaluate2+3*4.Theevaluationofeachoperandintheexpressionat(1)resultsina
calloftheeval()methoddeclaredat(3).
Clickheretoviewcodeimage
out.println(eval(j++,”+“)+eval(j++,”*“)*eval(j,“\n”));//(1)
TheoutputfromExample5.1showsthattheoperandswereevaluatedfirst,fromleftto
right,beforeoperatorexecution,andthattheexpressionwasevaluatedas(2+(3*
4)),respectingtheprecedencerulesforarithmeticexpressionevaluation.Notehowthe
valueofvariablejchangessuccessivelyfromlefttorightasthefirsttwooperandsare
evaluated.
WOW! eBook
www.wowebook.org
Example5.1EvaluationOrderofOperandsandArguments
Clickheretoviewcodeimage
importstaticjava.lang.System.out;
publicclassEvalOrder{
publicstaticvoidmain(String[]args){
intj=2;
out.println(“Evaluationorderofoperands:”);
out.println(eval(j++,”+“)+eval(j++,”*“)*eval(j,“\n”));//
(1)
inti=1;
out.println(“Evaluationorderofarguments:”);
add3(eval(i++,“,“),eval(i++,“,“),eval(i,“\n”));//(2)Three
arguments.
}
publicstaticinteval(intoperand,Stringstr){//(3)
out.print(operand+str);//PrintintoperandandStringstr.
returnoperand;//Returnintoperand.
}
publicstaticvoidadd3(intoperand1,intoperand2,intoperand3){//
(4)
out.print(operand1+operand2+operand3);
}
}
Outputfromtheprogram:
Evaluationorderofoperands:
2+3*4
14
Evaluationorderofarguments:
1,2,3
6
Left-to-RightEvaluationofArgumentLists
Inamethodorconstructorinvocation,eachargumentexpressionintheargumentlistis
fullyevaluatedbeforeanyargumentexpressiontoitsright.
Ifevaluationofanargumentexpressiondoesnotcompletenormally,wecannotpresume
thatanyargumentexpressiontoitsrighthasbeenevaluated.
Wecanusetheadd3()methodat(4)inExample5.1,whichtakesthreearguments,to
demonstratetheorderinwhichtheargumentsinamethodcallareevaluated.Themethod
callat(2)
Clickheretoviewcodeimage
add3(eval(i++,“,“),eval(i++,“,“),eval(i,“\n”));//(2)Three
arguments.
resultsinthefollowingoutput,clearlyindicatingthattheargumentswereevaluatedfrom
lefttoright,beforebeingpassedtothemethod:
1,2,3
WOW! eBook
www.wowebook.org
6
Notehowthevalueofvariableichangessuccessivelyfromlefttorightasthefirsttwo
argumentsareevaluated.
5.5RepresentingIntegers
IntegerdatatypesinJavarepresentsignedintegervalues,meaningbothpositiveand
negativeintegervalues.Thevaluesofchartypecaneffectivelyberegardedasunsigned
16-bitintegers.
ValuesoftypebytearerepresentedasshowninTable5.3.Avalueoftypebyte
requires8bits.With8bits,wecanrepresent28or256values.Javausestwo’s
complement(explainedlater)tostoresignedvaluesofintegerdatatypes.Forthebyte
datatype,thismeansvaluesareintherange–128(i.e.,–27)to+127(i.e.,27–1),inclusive.
Table5.3RepresentingSignedbyteValuesUsingTwo’sComplement
Bitsinanintegralvalueareusuallynumberedfromrighttoleft,startingwiththeleast
significantbit0(alsocalledtherightmostbit).Therepresentationofthesignedtypessets
WOW! eBook
www.wowebook.org
themostsignificantbitto1,indicatingnegativevalues.Adding1tothemaximumint
value2147483647resultsintheminimumvalue-2147483648,suchthatthevalues
wraparoundforintegersandnooverfloworunderflowisindicated.
CalculatingTwo’sComplement
Beforewelookatthetwo’scomplement,weneedtounderstandtheone’scomplement.
Theone’scomplementofabinaryintegeriscomputedbyinvertingthebitsinthenumber.
Thus,theone’scomplementofthebinarynumber00101001is11010110.Theone’s
complementofabinarynumberN2isdenotedas~N2.Thefollowingrelationshold
betweenabinaryintegerN2,itsone’scomplement~N2,anditstwo’scomplement–N2:
–N2=~N2+1
0=–N2+N2
IfN2isapositivebinaryinteger,then–N2denotesitsnegativebinaryvalue,andvice
versa.ThesecondrelationstatesthataddingabinaryintegerN2toitstwo’scomplement–
N2equals0.
Givenapositivebytevalue,say41,thebinaryrepresentationof-41canbefoundas
follows:
AddinganumberN2toitstwo’scomplement–N2gives0,andthecarrybitfromthe
additionofthemostsignificantbits(afteranynecessaryextensionoftheoperands)is
ignored:
Subtractionbetweentwointegersisalsocomputedasadditionwithtwo’scomplement:
N2–M2=N2+(–M2)
Forexample,theexpression4110–310(withthecorrectresult3810)iscomputedas
follows:
WOW! eBook
www.wowebook.org
Thepreviousdiscussionofbytevaluesappliesequallytovaluesofotherintegertypes:
short,int,andlong.Thesetypeshavetheirvaluesrepresentedbytwo’scomplement
in16,32,and64bits,respectively.
ConvertingBinaryNumberstoDecimals
Abinarynumbercanbeconvertedtoitsequivalentdecimalvaluebycomputingthe
positionalvaluesofitsdigits.Eachdigitinthebinarynumbercontributestothefinal
decimalvaluebyvirtueofitsposition,startingwithposition0(units)fortherightmost
digitinthenumber.Thepositionalvalueofeachdigitisgivenby
digit×baseposition
Thenumber1010012correspondsto4110inthedecimalnumbersystem:
Thesametechniquecanbeusedtoconvertanumberfromanybase,forexample,octal
(base8)orhexadecimal(base16),toitsequivalentrepresentationinthedecimalnumber
system.
ConvertingDecimalstoBinaryNumbers
Toconvertdecimalstobinaries,wereversetheprocessoutlinedpreviouslyforconverting
abinarytoadecimal.
Thedivisorusedinthesestepsisthebaseofthetargetnumbersystem(binary,base2).
Thebinaryvalue,1010012,isrepresentedbytheremainders,withthelastremainderas
WOW! eBook
www.wowebook.org
theleftmostbit.
Analogously,wecanapplythisprocedureforconvertinganoctal(base8)orhexadecimal
(base16)numbertoitsbinaryequivalent.
RelationshipsamongBinary,Octal,andHexadecimalNumbers
Weneed3bitstorepresentalltheoctaldigits(8=23)and4bitstorepresentallthe
hexadecimaldigits(16=24).Wecanusethisfacttoconvertamongthebinary,octal,and
hexadecimalsystems,asshowninFigure5.2.
Figure5.2ConvertingamongBinary,Octal,andHexadecimalNumbers
Theprocedureforconvertinganoctaltoabinaryisshownbythearrowmarked(a).We
canconvertanoctalnumbertoitsequivalentbinarynumberbyreplacingeachdigitinthe
octalnumberbyits3-bitequivalentbinaryvalue.
Analogously,wecanconvertahexadecimalnumbertoitsequivalentbinarynumberby
replacingeachdigitinthehexadecimalnumberbyits4-bitequivalentbinaryvalue,as
shownbythearrowmarked(b).
Toconvertabinarytoitsoctalequivalent,wereversetheprocedureoutlinedearlier
(arrowmarked(c)inFigure5.2).Thebitsinthebinarynumberaregroupedinto3-bit
groupsfromrighttoleft.Eachsuchgroupisreplacedbyitsequivalentoctaldigit.
Analogously,wecanconvertabinarytoahexadecimalnumberbyreplacingeach4-bit
groupbyitsequivalenthexadecimaldigit(arrowmarked(d)inFigure5.2).
5.6TheSimpleAssignmentOperator
Theassignmentstatementhasthefollowingsyntax:
variable=expression
whichcanbereadas“thetarget,variable,getsthevalueofthesource,expression.”The
previousvalueofthetargetvariableisoverwrittenbytheassignmentoperator=.
Thetargetvariableandthesourceexpressionmustbeassignmentcompatible.Thetarget
WOW! eBook
www.wowebook.org
variablemustalsohavebeendeclared.Sincevariablescanstoreeitherprimitivevaluesor
referencevalues,expressionevaluatestoeitheraprimitivevalueorareferencevalue.
AssigningPrimitiveValues
Thefollowingexamplesillustrateassignmentofprimitivevalues:
Clickheretoviewcodeimage
intj,k;
j=0b10;//jgetsthevalue2.
j=5;//jgetsthevalue5.Previousvalueisoverwritten.
k=j;//kgetsthevalue5.
Theassignmentoperatorhasthelowestprecedence,sothattheexpressionontheright-
handsideisevaluatedbeforetheassignmentisdone.
Clickheretoviewcodeimage
inti;
i=5;//igetsthevalue5.
i=i+1;//igetsthevalue6.+hashigherprecedencethan=.
i=20-i*2;//igetsthevalue8:(20-(i*2))
AssigningReferences
Copyingreferencevaluesbyassignmentcreatesaliases,whicharediscussedin§1.3,p.6.
Thefollowingexamplerecapitulatesthatdiscussion:
Clickheretoviewcodeimage
Pizzapizza1=newPizza(“Hot&Spicy”);
Pizzapizza2=newPizza(“Sweet&Sour”);
pizza2=pizza1;
Thevariablepizza1isareferencetoapizzathatishotandspicy,andpizza2isa
referencetoapizzathatissweetandsour.Assigningpizza1topizza2meansthat
pizza2nowreferstothesamepizzaaspizza1,thehotandspicyone.Afterthe
assignment,thesevariablesarealiasesandeitheronecanbeusedtomanipulatethehot
andspicyPizzaobject.
Assigningareferencevaluedoesnotcreateacopyofthesourceobjectdenotedbythe
referencevariableontheright-handside.Itmerelyassignsthereferencevalueofthe
variableontheright-handsidetothevariableontheleft-handside,sothattheydenotethe
sameobject.Referenceassignmentalsodoesnotcopythestateofthesourceobjecttoany
objectdenotedbythereferencevariableontheleft-handside.
Amoredetaileddiscussionofreferenceassignmentcanbefoundin§7.8,p.311.
MultipleAssignments
Theassignmentstatementisanexpressionstatement,whichmeansthatapplicationofthe
binaryassignmentoperatorreturnsthevalueoftheexpressionontheright-handside.
Clickheretoviewcodeimage
intj,k;
j=10;//jgetsthevalue10,whichisreturned
WOW! eBook
www.wowebook.org
k=j;//kgetsthevalueofj,whichis10,andthisvalueis
returned
Thelasttwoassignmentscanbewrittenasmultipleassignments,illustratingtheright
associativityoftheassignmentoperator:
Clickheretoviewcodeimage
k=j=10;//(k=(j=10))
Multipleassignmentsareequallyvalidwithreferences:
Clickheretoviewcodeimage
PizzapizzaOne,pizzaTwo;
pizzaOne=pizzaTwo=newPizza(“Supreme”);//Aliases
Thefollowingexampleshowstheeffectofoperandevaluationorder:
Clickheretoviewcodeimage
int[]a={10,20,30,40,50};//Anarrayofint
intindex=4;
a[index]=index=2;//(1)
Whatisthevalueofindex,andwhicharrayelementa[index]isassignedavaluein
themultipleassignmentstatementat(1)?Theevaluationproceedsasfollows:
Clickheretoviewcodeimage
a[index]=index=2;
a[4]=index=2;
a[4]=(index=2);//indexgetsthevalue2.=isright
associative.
a[4]=2;//Thevalueofa[4]ischangedfrom50to2.
Thefollowingdeclarationstatementwillnotcompile,asthevariablev2hasnotbeen
declared:
Clickheretoviewcodeimage
intv1=v2=2016;//Onlyv1isdeclared.Compile-timeerror!
TypeConversionsinanAssignmentContext
Ifthetargetandthesourcehavethesametypeinanassignment,then,obviously,the
sourceandthetargetareassignmentcompatibleandthesourcevalueneednotbe
converted.Otherwise,ifawideningprimitiveconversionispermissible,thenthewidening
conversionisappliedimplicitly;thatis,thesourcetypeisconvertedtothetargettypein
anassignmentcontext.
Clickheretoviewcodeimage
//WideningPrimitiveConversions
intsmallOne=1234;//Nowideningnecessary.
longbigOne=2000;//Widening:inttolong.
doublelargeOne=bigOne;//Widening:longtodouble.
doublehugeOne=(double)bigOne;//Castredundantbutallowed.
Awideningprimitiveconversioncanresultinlossofprecision.Inthenextexample,the
precisionoftheleastsignificantbitsofthelongvaluemaybelostwhenitisconverting
toafloatvalue:
Clickheretoviewcodeimage
WOW! eBook
www.wowebook.org
longbigInteger=98765432112345678L;
floatfpNum=bigInteger;//Wideningbutlossofprecision:9.8765436E16
Additionally,implicitnarrowingprimitiveconversionsonassignmentcanoccurincases
whereallofthefollowingconditionsarefulfilled:
•Thesourceisaconstantexpressionofeitherbyte,short,char,orinttype.
•Thetargettypeiseitherbyte,short,orchartype.
•Thevalueofthesourceisdeterminedtobeintherangeofthetargettypeatcompile
time.
AconstantexpressionisanexpressionthatdenoteseitheraprimitiveoraStringliteral,
andiscomposedofoperandsthatcanbeonlyliteralsorconstantvariables,andoperators
thatcanbeevaluatedonlyatcompiletime(forexample,arithmeticandnumerical
comparisonoperators,butnotincrement/decrementoperatorsandmethodcalls).A
constantvariableisafinalvariableofeitheraprimitivetypeorStringtypethatis
initializedwithaconstantexpression.
Clickheretoviewcodeimage
intresult=100;//Notaconstantvariable.Notdeclared
final.
finalcharfinalGrade=‘A’;//Constantvariable.
System.out.printf(“%d%n%s%n%d%n%.2f%n%b%n%d%n%d%n”,
2106,//Constantexpression.
“Trust”+“me!”,//Constantexpression.
2+3*4,//Constantexpression.
Math.PI*Math.PI*10.0,//Constantexpression.
finalGrade==‘A’,//Constantexpression.
Math.min(2015,2016),//Notconstantexpression.Methodcall.
++result//Notconstantexpression.Increment
operator.
);
Herearesomeexamplesthatillustratehowtheconditionsmentionedpreviouslyaffect
narrowingprimitiveconversions:
Clickheretoviewcodeimage
//Conditionsfulfilledforimplicitnarrowingprimitiveconversions.
shorts1=10;//intvalueinrange.
shorts2=‘a’;//charvalueinrange.
charc1=32;//intvalueinrange.
charc2=(byte)35;//bytevalueinrange.(intvalueinrange,without
cast.)
byteb1=40;//intvalueinrange.
byteb2=(short)40;//shortvalueinrange.(intvalueinrange,without
cast.)
finalinti1=20;//Constantvariable
byteb3=i1;//finalvalueofi1inrange.
Allothernarrowingprimitiveconversionswillproduceacompile-timeerroron
assignmentandwillexplicitlyrequireacast.Herearesomeexamples:
Clickheretoviewcodeimage
//Conditionsnotfulfilledforimplicitnarrowingprimitiveconversions.
//Acastisrequired.
inti2=-20;//i2isnotaconstantvariable.i2isnotfinal.
finalinti3=i2;//i3isnotaconstantvariable,sincei2isnot.
WOW! eBook
www.wowebook.org
finalinti4=200;//i4isaconstantvariable.
finalinti5;//i5isnotaconstantvariable.
shorts3=(short)i2;//Notconstantexpression.
charc3=(char)i3;//Finalvalueofi3notdeterminableatcompile
time.
charc4=(char)i2;//Notconstantexpression.
byteb4=(byte)128;//intvaluenotinrange.
byteb5=(byte)i4;//Valueofconstantvariablei4isnotinrange.
i5=100;//Initializedatruntime.
shorts4=(short)i5;//Finalvalueofi5notdeterminableatcompile
time.
Floating-pointvaluesaretruncatedwhencasttointegralvalues.
Clickheretoviewcodeimage
//Thevalueistruncatedtofitthesizeofthetargettype.
floathuge=(float)1.7976931348623157d;//doubletofloat.
longgiant=(long)4415961481999.03D;//(1)doubletolong.
intbig=(int)giant;//(2)longtoint.
shortsmall=(short)big;//(3)inttoshort.
bytetiny=(byte)small;//(4)shorttobyte.
charsymbol=(char)112.5F;//(5)floattochar.
Table5.4showshowthevaluesaretruncatedforassignmentsfrom(1)to(5).
Table5.4ExamplesofTruncatedValues
Thediscussionofnumericassignmentconversionsalsoappliestonumericparameter
valuesatmethodinvocation(§3.5,p.73),exceptforthenarrowingconversions,which
alwaysrequireacast.
Thefollowingexamplesillustrateboxingandunboxinginanassignmentcontext:
Clickheretoviewcodeimage
BooleanboolRef=true;//Boxing.
BytebRef=2;//Constantinrange:narrowing,thenboxing.
//BytebRef2=257;//Constantnotinrange.Compile-timeerror!
shorts=10;//Narrowingfrominttoshort.
//IntegeriRef1=s;//shortnotassignabletoInteger.
IntegeriRef3=(int)s;//Explicitwideningwithcasttointandboxing
booleanbv1=boolRef;//Unboxing.
byteb1=bRef;//Unboxing.
intiVal=bRef;//Unboxingandwidening.
IntegeriRefVal=null;//Alwaysallowed.
//intj=iRefVal;//NullPointerExceptionatruntime.
if(iRef3!=null)iVal=iRef3;//Avoidexceptionatruntime.
WOW! eBook
www.wowebook.org
ReviewQuestions
5.1Giventhefollowingdeclaration:
charc=‘A’;
Whatisthesimplestwaytoconvertthecharactervalueinctoanint?
Selecttheonecorrectanswer.
(a)inti=c;
(b)inti=(int)c;
(c)inti=Character.getNumericValue(c);
5.2Whatwillbetheresultofcompilingandrunningthefollowingprogram?
Clickheretoviewcodeimage
publicclassAssignment{
publicstaticvoidmain(String[]args){
inta,b,c;
b=10;
a=b=c=20;
System.out.println(a);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompile,sincethecompilerwillreportthatthevariable
cinthemultipleassignmentstatementa=b=c=20;hasnotbeen
initialized.
(b)Theprogramwillfailtocompile,becausethemultipleassignmentstatementa
=b=c=20;isillegal.
(c)Thecodewillcompile,andprint10atruntime.
(d)Thecodewillcompile,andprint20atruntime.
5.3Whatwillbetheresultofcompilingandrunningthefollowingprogram?
Clickheretoviewcodeimage
publicclassMyClass{
publicstaticvoidmain(String[]args){
Stringa,b,c;
c=newString(“mouse”);
a=newString(“cat”);
b=a;
a=newString(“dog”);
c=b;
System.out.println(c);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompile.
WOW! eBook
www.wowebook.org
(b)Theprogramwillprintmouseatruntime.
(c)Theprogramwillprintcatatruntime.
(d)Theprogramwillprintdogatruntime.
(e)Theprogramwillrandomlyprinteithercatordogatruntime.
5.7ArithmeticOperators: , , , ,
Arithmeticoperatorsareusedtoconstructmathematicalexpressionsasinalgebra.Their
operandsareofnumerictype(whichincludesthechartype).
ArithmeticOperatorPrecedenceandAssociativity
InTable5.5,theprecedenceoftheoperatorsappearsindecreasingorder,startingfromthe
toprow,whichhasthehighestprecedence.Unarysubtractionhashigherprecedencethan
multiplication.Theoperatorsinthesamerowhavethesameprecedence.Binary
multiplication,division,andremainderoperatorshavethesameprecedence.Theunary
operatorshaverightassociativity,andthebinaryoperatorshaveleftassociativity.
Table5.5ArithmeticOperators
EvaluationOrderinArithmeticExpressions
Javaguaranteesthattheoperandsarefullyevaluatedfromlefttorightbeforeanarithmetic
binaryoperatorisapplied.Ifevaluationofanoperandresultsinanerror,thesubsequent
operandswillnotbeevaluated.
Intheexpressiona+b*c,theoperandawillalwaysbefullyevaluatedbeforethe
operandb,whichwillalwaysbefullyevaluatedbeforetheoperandc.However,the
multiplicationoperator*willbeappliedbeforetheadditionoperator+,respectingthe
precedencerules.Notethata,b,andcarearbitraryarithmeticexpressionsthathavebeen
determinedtobetheoperandsoftheoperators.
Example5.1,p.153,illustratestheevaluationorderandprecedencerulesforarithmetic
expressions.
RangeofNumericValues
Aswehaveseen,allnumerictypeshavearangeofvalidvalues(§2.2,p.37).Thisrangeis
givenbytheconstantsnamedMAX_VALUEandMIN_VALUE,whicharedefinedineach
numericwrappertype.
Thearithmeticoperatorsareoverloaded,meaningthattheoperationofanoperatorvaries
dependingonthetypeofitsoperands.Floating-pointarithmeticisperformedifany
WOW! eBook
www.wowebook.org
operandofanoperatorisoffloating-pointtype;otherwise,integerarithmeticis
performed.
Valuesthatareoutofrangeoraretheresultsofinvalidexpressionsarehandleddifferently
dependingonwhetherintegerorfloating-pointarithmeticisperformed.
IntegerArithmetic
Integerarithmeticalwaysreturnsavaluethatisinrange,exceptinthecaseofinteger
divisionbyzeroandremainderbyzero,whichcauseanArithmeticException(see
thelaterdiscussionofthedivisionoperator/andtheremainderoperator%).Avalidvalue
doesnotnecessarilymeanthattheresultiscorrect,asdemonstratedbythefollowing
examples:
Clickheretoviewcodeimage
inttooBig=Integer.MAX_VALUE+1;//-2147483648whichis
Integer.MIN_VALUE.
inttooSmall=Integer.MIN_VALUE-1;//2147483647whichis
Integer.MAX_VALUE.
Theseresultsshouldbevaluesthatareoutofrange.However,integerarithmeticwraps
roundiftheresultisoutofrange;thatis,theresultisreducedmodulointherangeofthe
resulttype.Toavoidwrappingroundofout-of-rangevalues,programsshouldeitheruse
explicitchecksorawidertype.Ifthetypelongisusedintheearlierexamples,the
resultswouldbecorrectinthelongrange:
Clickheretoviewcodeimage
longnotTooBig=Integer.MAX_VALUE+1L;//2147483648Linrange.
longnotTooSmall=Integer.MIN_VALUE-1L;//-2147483649Linrange.
Floating-PointArithmetic
Certainfloating-pointoperationsresultinvaluesthatareoutofrange.Typically,addingor
multiplyingtwoverylargefloating-pointnumberscanresultinanoutof-rangevaluethat
isrepresentedbyinfinity(Figure5.3).Attemptingfloating-pointdivisionbyzeroalso
returnsinfinity.Thefollowingexamplesshowhowthisvalueisprintedassignedinfinity:
Clickheretoviewcodeimage
System.out.println(4.0/0.0);//Prints:Infinity
System.out.println(-4.0/0.0);//Prints:-Infinity
WOW! eBook
www.wowebook.org
Figure5.3OverflowandUnderflowinFloating-PointArithmetic
Bothpositiveandnegativeinfinityrepresentoverflowtoinfinity;thatis,thevalueistoo
largetoberepresentedasadoubleorfloat(Figure5.3).Signedinfinityisrepresented
bythenamedconstantsPOSITIVE_INFINITYandNEGATIVE_INFINITYinthe
wrapperclassesjava.lang.Floatandjava.lang.Double.Avaluecanbe
comparedwiththeseconstantstodetectoverflow.
Floating-pointarithmeticcanalsoresultinunderflowtozero,whenthevalueistoosmall
toberepresentedasadoubleorfloat(Figure5.3).Underflowoccursinthefollowing
situations:
•TheresultisbetweenDouble.MIN_VALUE(orFloat.MIN_VALUE)andzero,
aswiththeresultof(5.1E-324-4.9E-324).Underflowthenreturnspositive
zero0.0(or0.0F).
•Theresultisbetween-Double.MIN_VALUE(or-Float.MIN_VALUE)and
zero,aswiththeresultof(-Double.MIN_VALUE*1E-1).Underflowthen
returnsnegativezero-0.0(or-0.0F).
Negativezerocomparesequaltopositivezero;inotherwords,(-0.0==0.0)is
true.
Certainoperationshavenomathematicalresult,andarerepresentedbyNaN(Nota
Number).Forexample,calculatingthesquarerootof-1resultsinNaN.Anotherexample
is(floating-point)dividingzerobyzero:
Clickheretoviewcodeimage
WOW! eBook
www.wowebook.org
System.out.println(0.0/0.0);//Prints:NaN
NaNisrepresentedbytheconstantnamedNaNinthewrapperclasses
java.lang.Floatandjava.lang.Double.AnyoperationinvolvingNaN
producesNaN.Anycomparison(exceptinequality!=)involvingNaNandanyother
value(includingNaN)returnsfalse.AninequalitycomparisonofNaNwithanother
value(includingNaN)alwaysreturnstrue.However,therecommendedwayofchecking
avalueforNaNistousethestaticmethodisNaN()definedinbothwrapperclasses,
java.lang.Floatandjava.lang.Double.
StrictFloating-PointArithmetic:strictfp
Althoughfloating-pointarithmeticinJavaisdefinedinaccordancewiththeIEEE-75432-
bit(float)and64-bit(double)standardformats,thelanguagedoesallowJVM
implementationstouseotherextendedformatsforintermediateresults.Thismeansthat
floating-pointarithmeticcangivedifferentresultsonsuchJVMs,withpossiblelossof
precision.Suchabehavioristermednon-strict,incontrasttobeingstrictandadheringto
thestandardformats.
ToensurethatidenticalresultsareproducedonallJVMs,thekeywordstrictfpcanbe
usedtoenforcestrictbehaviorforfloating-pointarithmetic.Themodifierstrictfpcan
beappliedtoclasses,interfaces,andmethods.Astrictfpmethodensuresthatallcode
inthemethodisexecutedstrictly.Ifaclassorinterfaceisdeclaredtobestrictfp,then
allcode(inmethods,initializers,andnestedclassesandinterfaces)isexecutedstrictly.If
theexpressionisdeterminedtobeinastrictfpconstruct,itisexecutedstrictly.
Strictness,however,isnotinheritedbythesubclassesorsubinterfaces.Constant
expressionsarealwaysevaluatedstrictlyatcompiletime.
UnaryArithmeticOperators: ,
Theunaryoperatorshavethehighestprecedenceofallthearithmeticoperators.Theunary
operator-negatesthenumericvalueofitsoperand.Thefollowingexampleillustratesthe
rightassociativityoftheunaryoperators:
Clickheretoviewcodeimage
intvalue=--10;//(-(-10))is10
Noticetheblankneededtoseparatetheunaryoperators;otherwise,thesewouldbe
interpretedasthedecrementoperator--(§5.9,p.176),whichwouldresultinacompile-
timeerrorbecausealiteralcannotbedecremented.Theunaryoperator+hasnoeffecton
theevaluationoftheoperandvalue.
MultiplicativeBinaryOperators: , ,
MultiplicationOperator:*
Themultiplicationoperator*multipliestwonumbers.
Clickheretoviewcodeimage
intsameSigns=-4*-8;//result:32
WOW! eBook
www.wowebook.org
doubleoppositeSigns=4*-8.0;//Wideningofint4todouble.result:
-32.0
intzero=0*-0;//result:0
DivisionOperator:/
Thedivisionoperator/isoverloaded.Ifitsoperandsareintegral,theoperationresultsin
integerdivision.
Clickheretoviewcodeimage
inti1=4/5;//result:0
inti2=8/8;//result:1
doubled1=12/8;//result:1.0;integerdivision,thenwidening
conversion
Integerdivisionalwaysreturnsthequotientasanintegervalue;thatis,theresultis
truncatedtowardzero.Notethatthedivisionperformedisintegerdivisioniftheoperands
haveintegralvalues,eveniftheresultwillbestoredinafloating-pointtype.Theinteger
valueissubjectedtoawideningconversionintheassignmentcontext.
AnArithmeticExceptionisthrownwhenintegerdivisionwithzeroisattempted,
meaningthatintegerdivisionbyzeroisanillegaloperation.
Ifanyoftheoperandsisafloating-pointtype,theoperationperformsfloating-point
division,whererelevantoperandvaluesundergobinarynumericpromotion:
Clickheretoviewcodeimage
doubled2=4.0/8;//result:0.5
doubled3=8/8.0;//result:1.0
floatd4=12.0F/8;//result:1.5F
doubleresult1=12.0/4.0*3.0;//((12.0/4.0)*3.0)whichis9.0
doubleresult2=12.0*3.0/4.0;//((12.0*3.0)/4.0)whichis9.0
RemainderOperator:%
Inmathematics,whenwedivideanumber(thedividend)byanothernumber(thedivisor),
theresultcanbeexpressedintermsofaquotientandaremainder.Forexample,when7is
dividedby5,thequotientis1andtheremainderis2.Theremainderoperator%returnsthe
remainderofthedivisionperformedontheoperands.
Clickheretoviewcodeimage
intquotient=7/5;//Integerdivisionoperation:1
intremainder=7%5;//Integerremainderoperation:2
Forintegerremainderoperation,whereonlyintegeroperandsareinvolved,evaluationof
theexpression(x%y)alwayssatisfiesthefollowingrelation:
x==(x/y)*y+(x%y)
Inotherwords,theright-handsideyieldsavaluethatisalwaysequaltothevalueofthe
dividend.Thefollowingexamplesshowhowwecancalculatetheremaindersothatthis
relationissatisfied:
WOW! eBook
www.wowebook.org
Theremaindercanbenegativeonlyifthedividendisnegative,andthesignofthedivisor
isirrelevant.Ashortcuttoevaluatingtheremainderinvolvingnegativeoperandsisthe
following:ignorethesignsoftheoperands,calculatetheremainder,andnegatethe
remainderifthedividendisnegative.
Clickheretoviewcodeimage
intr0=7%7;//0
intr1=7%5;//2
longr2=7L%-5L;//2L
intr3=-7%5;//-2
longr4=-7L%-5L;//-2L
booleanrelation=-7L==(-7L/-5L)*-5L+r4;//true
AnArithmeticExceptionisthrownifthedivisorevaluatestozero.
Notethattheremainderoperatoracceptsnotonlyintegraloperands,butalsofloating-point
operands.Thefloating-pointremainderrisdefinedbytherelation
r==a-(b*q)
whereaandbarethedividendandthedivisor,respectively,andqistheintegerquotient
of(a/b).Thefollowingexamplesillustrateafloating-pointremainderoperation:
Clickheretoviewcodeimage
doubledr0=7.0%7.0;//0.0
floatfr1=7.0F%5.0F;//2.0F
doubledr1=7.0%-5.0;//2.0
floatfr2=-7.0F%5.0F;//-2.0F
doubledr2=-7.0%-5.0;//-2.0
booleanfpRelation=dr2==(-7.0)-(-5.0)*(long)(-7.0/-5.0);//true
floatfr3=-7.0F%0.0F;//NaN
WOW! eBook
www.wowebook.org
AdditiveBinaryOperators: ,
Theadditionoperator+andthesubtractionoperator-behaveastheirnamesimply:They
addandsubtractvalues,respectively.Thebinaryoperator+alsoactsasstring
concatenationifanyofitsoperandsisastring(§5.8,p.174).
Additiveoperatorshavelowerprecedencethanalltheotherarithmeticoperators.Table5.6
includesexamplesthatshowhowprecedenceandassociativityareusedinarithmetic
expressionevaluation.
Table5.6ExamplesofArithmeticExpressionEvaluation
NumericPromotionsinArithmeticExpressions
Unarynumericpromotionisappliedtothesingleoperandoftheunaryarithmetic
operators-and+.Whenaunaryarithmeticoperatorisappliedtoanoperandwhosetype
isnarrowerthanint,theoperandispromotedtoavalueoftypeint,withtheoperation
resultinginanintvalue.Iftheconditionsforimplicitnarrowingconversionarenot
fulfilled(p.160),assigningtheintresulttoavariableofanarrowertypewillrequirea
cast.Thisisdemonstratedbythefollowingexample,wherethebyteoperandbis
promotedtoanintintheexpression(-b):
Clickheretoviewcodeimage
byteb=3;//intliteralinrange.Narrowingconversion.
b=(byte)-b;//Castrequiredonassignment.
Binarynumericpromotionisappliedtooperandsofbinaryarithmeticoperators.Its
applicationleadstotypepromotionfortheoperands,asexplainedin§5.2,p.149.The
resultisofthepromotedtype,whichisalwaystypeintorwider.Fortheexpressionat
(1)inExample5.2,numericpromotionsproceedasshowninFigure5.4.Notetheinteger
divisionperformedinevaluatingthesubexpression(c/s).
WOW! eBook
www.wowebook.org
Figure5.4NumericPromotioninArithmeticExpressions
Example5.2NumericPromotioninArithmeticExpressions
Clickheretoviewcodeimage
publicclassNumPromotion{
publicstaticvoidmain(String[]args){
byteb=32;
charc=‘z’;//Unicodevalue122(\u007a)
shorts=256;
inti=10000;
floatf=3.5F;
doubled=0.5;
doublev=(d*i)+(f*-b)-(c/s);//(1)4888.0D
System.out.println(“Valueofv:”+v);
}
}
Outputfromtheprogram:
Valueofv:4888.0
Inadditiontothebinarynumericpromotionsinarithmeticexpressionevaluation,the
resultingvaluecanundergoanimplicitwideningconversionifassignedtoavariable.In
WOW! eBook
www.wowebook.org
thefirsttwodeclarationstatementsthatfollow,onlyassignmentconversionstakeplace.
Numericpromotionstakeplaceintheevaluationoftheright-handexpressionintheother
declarationstatements.
Clickheretoviewcodeimage
Byteb=10;//Constantinrange:narrowingandboxingon
assignment.
Shorts=20;//Constantinrange:narrowingandboxingon
assignment.
charc=‘z’;//122(\u007a)
inti=s*b;//Valuesinsandbpromotedtoint:unboxing,
widening.
longn=20L+s;//Valueinspromotedtolong:unboxing,widening.
floatr=s+c;//Valueinsisunboxed.Thisshortvalueandthechar
//valueincarepromotedtoint,followedbyimplicit
//wideningconversionofinttofloatonassignment.
doubled=r+i;//Valueinipromotedtofloat,followedbyimplicit
//wideningconversionoffloattodoubleonassignment.
Binarynumericpromotionforoperandsofbinaryoperatorsimpliesthateachoperandofa
binaryoperatorispromotedtotypeintorabroadernumerictype,ifnecessary.Aswith
unaryoperators,caremustbeexercisedinassigningthevalueresultingfromapplyinga
binaryoperatortooperandsofthesetypes.
Clickheretoviewcodeimage
shorth=40;//OK:intconvertedtoshort.Implicitnarrowing.
h=h+2;//Error:cannotassignaninttoshort.
Thevalueoftheexpressionh+2isoftypeint.Althoughtheresultoftheexpression
isintherangeofshort,thiscannotbedeterminedatcompiletime.Theassignment
requiresacast.
h=(short)(h+2);//OK
Noticethatapplyingthecastoperator(short)totheindividualoperandsdoesnotwork:
Clickheretoviewcodeimage
h=(short)h+(short)2;//Theresultingvalueshouldbecast.
Neitherdoesthefollowingapproach,whichresultsinacompile-timeerror:
Clickheretoviewcodeimage
h=(short)h+2;//Theresultingvalueshouldbecast.
Inthiscase,binarynumericpromotionleadstoanintvalueastheresultofevaluating
theexpressionontheright-handsideand,therefore,requiresanadditionalcasttonarrow
ittoashortvalue.
ArithmeticCompoundAssignmentOperators: , , , ,
Acompoundassignmentoperatorhasthefollowingsyntax:
variableop=expression
andthefollowingsemantics:
Clickheretoviewcodeimage
WOW! eBook
www.wowebook.org
variable=(type)((variable)op(expression))
Thetypeofthevariableistypeandthevariableisevaluatedonlyonce.Notethecastand
theparenthesesimpliedinthesemantics.Hereop=canbeanyofthecompound
assignmentoperatorsspecifiedinTable5.2.Thecompoundassignmentoperatorshavethe
lowestprecedenceofalltheoperatorsinJava,allowingtheexpressionontheright-hand
sidetobeevaluatedbeforetheassignment.Table5.7definesthearithmeticcompound
assignmentoperators.
Table5.7ArithmeticCompoundAssignmentOperators
Theimpliedcastoperator,(T),inthecompoundassignmentsbecomesnecessarywhen
theresultmustbenarrowedtothetargettype.Thisisillustratedbythefollowing
examples:
Clickheretoviewcodeimage
inti=2;
i*=i+4;//(1)Evaluatedasi=(int)((i)*(i+4)).
IntegeriRef=2;
iRef*=iRef+4;//(2)EvaluatedasiRef=(Integer)((iRef)*(iRef
+4)).
byteb=2;
b+=10;//(3)Evaluatedasb=(byte)(b+10).
b=b+10;//(4)Willnotcompile.Castisrequired.
At(1)thesourceintvalueisassignedtothetargetintvariable,andthecastoperator
(int)inthiscaseisanidentityconversion(i.e.,conversionfromatypetothesame
type).Suchcastsarepermitted.Theassignmentat(2)entailsunboxingtoevaluatethe
expressionontheright-handside,followedbyboxingtoassigntheintvalue.However,
at(3),asthesourcevalueisanintvaluebecausethebytevalueinbispromotedto
inttocarryouttheaddition,assigningittoatargetbytevariablerequiresanimplicit
narrowingconversion.Thesituationat(4)withsimpleassignmentwillnotcompile,
becauseimplicitnarrowingconversionisnotapplicable.
Thevariableisevaluatedonlyonceintheexpression,nottwice,asonemightinferfrom
thedefinitionofthecompoundassignmentoperator.Inthefollowingassignment,a[i]is
evaluatedjustonce:
Clickheretoviewcodeimage
int[]a=newint[]{2015,2016,2017};
inti=2;
a[i]+=1;//Evaluatesasa[2]=a[2]+1,anda[2]getsthevalue
WOW! eBook
www.wowebook.org
2018.
Implicitnarrowingconversionsarealsoappliedtoincrementanddecrementoperators
(§5.9,p.176).
Booleanlogicalcompoundassignmentoperatorsarecoveredin§5.13,p.184.
ReviewQuestions
5.4Whichofthefollowingexpressionswillbeevaluatedusingfloating-point
arithmetic?
Selectthethreecorrectanswers.
(a)2.0*3.0
(b)2*3
(c)2/3+5/7
(d)2.4+1.6
(e)0x10*1L*300.0
5.5Whatisthevalueoftheexpression(1/2+3/2+0.1)?
Selecttheonecorrectanswer.
(a)1
(b)1.1
(c)1.6
(d)2
(e)2.1
5.6Whatwillbetheresultofcompilingandrunningthefollowingprogram?
Clickheretoviewcodeimage
publicclassIntegers{
publicstaticvoidmain(String[]args){
System.out.println(0x10+10+010+0b10);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile.
(b)Whenrun,theprogramwillprint28.
(c)Whenrun,theprogramwillprint30.
(d)Whenrun,theprogramwillprint34.
(e)Whenrun,theprogramwillprint36.
(f)Whenrun,theprogramwillprint10101010.
WOW! eBook
www.wowebook.org
5.7Whichofthefollowingexpressionsarevalid?
Selectthethreecorrectanswers.
(a)(-1-)
(b)(++1)
(c)(+-+-+-1)
(d)(—1)
(e)(1**1)
(f)(--1)
5.8Whatisthevalueofevaluatingthefollowingexpression:(--1-3*10/5-
1)?
Selecttheonecorrectanswer.
(a)–8
(b)–6
(c)7
(d)8
(e)10
(f)Noneoftheabove
5.9Whichoftheseassignmentsarevalid?
Selectthefourcorrectanswers.
(a)shorts=12;
(b)longl=012;
(c)intother=(int)true;
(d)floatf=-123;
(e)doubled=0x12345678;
5.8TheBinaryStringConcatenationOperator
Thebinaryoperator+isoverloadedinthesensethattheoperationperformedis
determinedbythetypeoftheoperands.WhenoneoftheoperandsisaStringobject,a
stringconcatenationisperformedratherthannumericaddition.Stringconcatenation
resultsinanewlycreatedStringobjectinwhichthecharactersinthestring
representationoftheleft-handoperandprecedethecharactersinthestringrepresentation
oftheright-handoperand.Itmightbenecessarytoperformastringconversiononthe
non-Stringoperandbeforethestringconcatenationcanbeperformed.TheString
classisdiscussedin§8.4,p.357.
Astringconversionisperformedonthenon-Stringoperandasfollows:
WOW! eBook
www.wowebook.org
•Foranoperandofaprimitivedatatype,itsvalueisconvertedtoastring
representation.
•Forallreferencevalueoperands,astringrepresentationisconstructedbycallingthe
no-argumenttoString()methodonthereferredobject.Mostclassesoverride
thismethodfromtheObjectclasssoastoprovideamoremeaningfulstring
representationoftheirobjects.DiscussionofthetoString()methodcanbe
foundin§8.2,p.342.
•Valuesliketrue,false,andnullhavestringrepresentationsthatcorrespondto
theirnames.Areferencevariablewiththevaluenullalsohasthestring
representation"null"inthiscontext.
Theoperator+isleftassociativeandhasthesameprecedencelevelastheadditive
operators,whetheritisperformedasastringconcatenationorasanumericaddition.
Clickheretoviewcodeimage
StringstrVal=””+2016;//(1)“2016”
StringtheName=”Uranium”;
theName=”Pure”+theName;//(2)”PureUranium”
Stringtrademark1=100+“%”+theName;//(3)“100%PureUranium”
Sincethe+operatorisleft-associative,theevaluationin(3)proceedsasfollows:Theint
value100isconcatenatedwiththestringliteral"%",followedbyconcatenationwiththe
contentsoftheStringobjectreferredtobytheNamereference.
Notethatusingthecharacterliteral'%',insteadofthestringliteral"%"inline(2),does
notgivethesameresult:
Clickheretoviewcodeimage
Stringtrademark2=100+‘%’+theName;//(4)“137PureUranium”
Integeradditionisperformedbythefirst+operator:100+'%';thatis,(100+37).
Cautionshouldbeexercisedbecausethe+operatormightnotbeappliedasintended,as
shownbythefollowingexample:
Clickheretoviewcodeimage
System.out.println(“Wecanputtwoandtwotogetherandget”+2+2);//
(5)
Thisstatementprints"Wecanputtwoandtwotogetherandget22".
Stringconcatenationproceedsfromlefttoright:TheStringliteralisconcatenatedwith
thefirstintliteral2,followedbyconcatenationwiththesecondintliteral2.Both
occurrencesofthe+operatoraretreatedasstringconcatenation.Toconveytheintended
meaningofthesentence,parenthesesarenecessary:
Clickheretoviewcodeimage
System.out.println(“Wecanputtwoandtwotogetherandget”+(2+2));//
(6)
Thisstatementprints"Wecanputtwoandtwotogetherandget4",
sincetheparenthesesenforceintegeradditionintheexpression(2+2)beforestring
concatenationisperformedwiththecontentsoftheStringoperand.
WOW! eBook
www.wowebook.org
Thefollowingstatementwillprintthecorrectresult,evenwithouttheparentheses,
becausethe*operatorhashigherprecedencethanthe+operator:
Clickheretoviewcodeimage
System.out.println(“2*2=”+2*2);//(7)2*2=4
CreationoftemporaryStringobjectsmightbenecessarytostoretheresultsof
performingsuccessivestringconcatenationsinaString-valuedexpression.Fora
String-valuedconstantexpression((1),(5),(6)and(7)intheprecedingexamples),the
compilercomputessuchanexpressionatcompiletime,andtheresultistreatedasastring
literalintheprogram.Thecompilerusesastringbuildertoavoidtheoverheadof
temporaryStringobjectswhenapplyingthestringconcatenationoperator(+)in
String-valuednon-constantexpressions((2),(3)and(4)intheprecedingexamples),as
explainedin§8.5,p.378.
5.9VariableIncrementandDecrementOperators: ,
Variableincrement(++)anddecrement(--)operatorscomeintwoflavors:prefixand
postfix.Theseunaryoperatorshavethesideeffectofchangingthevalueofthearithmetic
operand,whichmustevaluatetoavariable.Dependingontheoperatorused,thevariable
iseitherincrementedordecrementedby1.
Theseoperatorscannotbeappliedtoavariablethatisdeclaredfinalandthathasbeen
initialized,asthesideeffectwouldchangethevalueinsuchavariable.
Theseoperatorsareveryusefulforupdatingvariablesinloopswhereonlythesideeffect
oftheoperatorisofinterest.
TheIncrementOperator
Theprefixincrementoperatorhasthefollowingsemantics:++iadds1tothevalueini,
andstoresthenewvalueini.Itreturnsthenewvalueasthevalueoftheexpression.Itis
equivalenttothefollowingstatements:
i+=1;
result=i;
returnresult;
Thepostfixincrementoperatorhasthefollowingsemantics:j++adds1tothevalueinj,
andstoresthenewvalueinj.Itreturnstheoriginalvaluethatwasinjasthevalueofthe
expression.Itisequivalenttothefollowingstatements:
result=j;
j+=1;
returnresult;
TheDecrementOperator
Theprefixdecrementoperatorhasthefollowingsemantics:--isubtracts1fromthe
valueofi,andstoresthenewvalueini.Itreturnsthenewvalueasthevalueofthe
expression.Itisequivalenttothefollowingstatements:
i-=1;
WOW! eBook
www.wowebook.org
result=i;
returnresult;
Thepostfixdecrementoperatorhasthefollowingsemantics:j--subtracts1fromthe
valueofj,andstoresthenewvalueinj.Itreturnstheoriginalvaluethatwasinjasthe
valueoftheexpression.Itisequivalenttothefollowingstatements:
result=j;
j-=1;
returnresult;
Thisbehaviorofdecrementandincrementoperatorsappliestoanyvariablewhosetypeis
anumericprimitivetypeoritscorrespondingnumericwrappertype.Necessarynumeric
promotionsareperformedonthevalue1andthevalueofthevariable.Beforethenew
valueisassignedtothevariable,itissubjectedtoanynarrowingprimitiveconversion
and/orboxingthatmightbenecessary.
Herearesomeexamplesthatillustratethebehaviorofincrementanddecrementoperators:
Clickheretoviewcodeimage
//(1)Prefixorder:increment/decrementoperandbeforeuse.
inti=10;
intk=++i+—i;//((++i)+(—i)).kgetsthevalue21andibecomes10.
—i;//Onlysideeffectutilized.iis9.(expression
statement)
IntegeriRef=11;//Boxingonassignment
—iRef;//Onlysideeffectutilized.iRefreferstoanInteger
//objectwiththevalue10.(expressionstatement)
k=++iRef+—iRef;//((++iRef)+(—iRef)).kgetsthevalue21and
//iRefreferstoanIntegerobjectwiththevalue10.
//(2)Postfixorder:increment/decrementoperandafteruse.
longj=10;
longn=j+++j—;//((j++)+(j—)).ngetsthevalue21Landjbecomes10L.
j++;//Onlysideeffectutilized.jis11L.(expression
statement)
Anincrementordecrementoperator,togetherwithitsoperand,canbeusedasan
expressionstatement(§3.2,p.50).
Executionoftheassignmentintheseconddeclarationstatementunder(1)proceedsas
follows:
Executionoftheexpressionstatement--iRef;under(1)proceedsasfollows:
•ThevalueintheIntegerobjectreferredtobythereferenceiRefisunboxed,
resultingintheintvalue11.
•Thevalue11isdecremented,resultinginthevalue10.
•Thevalue10isboxedinanIntegerobject,andthisobject’sreferencevalueis
assignedtothereferenceiRef.
WOW! eBook
www.wowebook.org
•Theintvalue10oftheexpressionstatementisdiscarded.
Expressionswherevariablesaremodifiedmultipletimesduringtheevaluationshouldbe
avoided,becausetheorderofevaluationisnotalwaysimmediatelyapparent.
Wecannotassociateincrementanddecrementoperators.Giventhataisavariable,we
cannotwrite(++(++a)).Thereasonisthatanyoperandto++mustevaluatetoa
variable,buttheevaluationof(++a)resultsinavalue.
Inthenextexample,bothbinarynumericpromotionandanimplicitnarrowingconversion
areperformedtoachievethesideeffectofmodifyingthevalueoftheoperand.Theint
valueoftheexpression(++b)(thatis,11),isassignedtotheintvariablei.Theside
effectofincrementingthevalueofthebytevariablebrequiresbinarynumeric
promotiontoperformintaddition,followedbyanimplicitnarrowingconversionofthe
intvaluetobytetoperformtheassignment.
Clickheretoviewcodeimage
byteb=10;
inti=++b;//iis11,andsoisb.
Thefollowingexampleillustratesapplyingtheincrementoperatortoafloating-point
operand.Thesideeffectofthe++operatorisoverwrittenbytheassignment.
Clickheretoviewcodeimage
doublex=4.5;
x=x+++x;//xgetsthevalue10.0.
ReviewQuestions
5.10Whichstatementsaretrue?
Selectthethreecorrectanswers.
(a)Theexpression(1+2+"3")evaluatestothestring"33".
(b)Theexpression("1"+2+3)evaluatestothestring"15".
(c)Theexpression(4+1.0f)evaluatestothefloatvalue5.0f.
(d)Theexpression(10/9)evaluatestotheintvalue1.
(e)Theexpression('a'+1)evaluatestothecharvalue'b'.
5.11Whathappenswhenyoutrytocompileandrunthefollowingprogram?
Clickheretoviewcodeimage
publicclassProg1{
publicstaticvoidmain(String[]args){
intk=1;
inti=++k+k++++k;//(1)
System.out.println(i);
}
}
Selecttheonecorrectanswer.
WOW! eBook
www.wowebook.org
(a)Theprogramwillnotcompile,becauseoferrorsintheexpressionat(1).
(b)Theprogramwillcompileandprintthevalue3atruntime.
(c)Theprogramwillcompileandprintthevalue4atruntime.
(d)Theprogramwillcompileandprintthevalue7atruntime.
(e)Theprogramwillcompileandprintthevalue8atruntime.
5.12Whichisthefirstlinethatwillcauseacompile-timeerrorinthefollowing
program?
Clickheretoviewcodeimage
publicclassMyClass{
publicstaticvoidmain(String[]args){
charc;
inti;
c=‘a’;//(1)
i=c;//(2)
i++;//(3)
c=i;//(4)
c++;//(5)
}
}
Selecttheonecorrectanswer.
(a)(1)
(b)(2)
(c)(3)
(d)(4)
(e)(5)
(f)Noneoftheabove.Thecompilerwillnotreportanyerrors.
5.13Whatistheresultofcompilingandrunningthefollowingprogram?
Clickheretoviewcodeimage
publicclassCast{
publicstaticvoidmain(String[]args){
byteb=128;
inti=b;
System.out.println(i);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile,becauseabytevaluecannotbeassignedtoan
intvariablewithoutusingacast.
(b)Theprogramwillcompile,andprint128atruntime.
(c)Theprogramwillnotcompile,becausethevalue128isnotintherangeof
valuesforthebytetype.
WOW! eBook
www.wowebook.org
(d)Theprogramwillcompile,butwillthrowaClassCastExceptionat
runtime.
(e)Theprogramwillcompile,andprint255atruntime.
5.14Whatwillbetheresultofcompilingandrunningthefollowingprogram?
Clickheretoviewcodeimage
publicclassEvaluationOrder{
publicstaticvoidmain(String[]args){
int[]array={4,8,16};
inti=1;
array[++i]=—i;
System.out.println(array[0]+array[1]+array[2]);
}
}
Selecttheonecorrectanswer.
(a)13
(b)14
(c)20
(d)21
(e)24
5.10BooleanExpressions
Asthenameimplies,abooleanexpressionhasthebooleandatatypeandcanevaluate
toonlythevaluestrueorfalse.Booleanexpressions,whenusedasconditionalsin
controlstatements,allowtheprogramflowtobecontrolledduringexecution.
Booleanexpressionscanbeformedusingrelationaloperators(§5.11,p.180),equality
operators(§5.12,p.181),booleanlogicaloperators(§5.13,p.184),conditionaloperators
(§5.14,p.186),theassignmentoperator(§5.6,p.158),andtheinstanceofoperator
(§7.11,p.321).
5.11RelationalOperators: , , ,
Giventhataandbrepresentnumericexpressions,therelational(alsocalledcomparison)
operatorsaredefinedasshowninTable5.8.
Table5.8RelationalOperators
Allrelationaloperatorsarebinaryoperatorsandtheiroperandsarenumericexpressions.
Binarynumericpromotionisappliedtotheoperandsoftheseoperators.Theevaluation
WOW! eBook
www.wowebook.org
resultsinabooleanvalue.Relationaloperatorshaveprecedencelowerthanarithmetic
operators,buthigherthanthatoftheassignmentoperators.
Clickheretoviewcodeimage
doublehours=45.5;
Doubletime=18.0;//Boxingofdoublevalue.
booleanovertime=hours>=35;//true.Binarynumericpromotion:double<—
int.
booleanbeforeMidnight=time<24.0;//true.Unboxingofvalueintime
reference.
charletterA=‘A’;
booleanorder=letterA<‘a’;//true.Binarynumericpromotion:int<—
char.
Relationaloperatorsarenonassociative.Mathematicalexpressionslikea≤b≤cmustbe
writtenusingrelationalandbooleanlogical/conditionaloperators.
Clickheretoviewcodeimage
inta=1,b=7,c=10;
booleanillegal=a<=b<=c;//(1)Illegal.
booleanvalid2=a<=b&&b<=c;//(2)OK.
Sincerelationaloperatorshaveleftassociativity,theevaluationoftheexpressiona<=b
<=cat(1)intheseexampleswouldproceedasfollows:((a<=b)<=c).
Evaluationof(a<=b)wouldyieldabooleanvaluethatisnotpermittedasan
operandofarelationaloperator;thatis,(booleanvalue<=c)wouldbeillegal.
5.12Equality
Wedistinguishbetweenprimitivedataequality,objectreferenceequality,andobjectvalue
equality.
Theequalityoperatorshavelowerprecedencethantherelationaloperators,buthigher
precedencethantheassignmentoperators.
PrimitiveDataValueEquality: ,
Giventhataandbrepresentoperandsofprimitivedatatypes,theprimitivedatavalue
equalityoperatorsaredefinedasshowninTable5.9.
Table5.9PrimitiveDataValueEqualityOperators
Theequalityoperator==andtheinequalityoperator!=canbeusedtocompareprimitive
datavalues,includingbooleanvalues.Binarynumericpromotionisappliedtothenon-
booleanoperandsoftheseequalityoperators.
Clickheretoviewcodeimage
intyear=2002;
booleanisEven=year%2==0;//true.
WOW! eBook
www.wowebook.org
booleancompare=‘1’==1;//false.Binarynumericpromotion
applied.
booleantest=compare==false;//true.
Caremustbeexercisedwhencomparingfloating-pointnumbersforequality,asaninfinite
numberoffloating-pointvaluescanbestoredonlyasapproximationsinafinitenumberof
bits.Forexample,theexpression(1.0-2.0/3.0==1.0/3.0)returnsfalse,
althoughmathematicallytheresultshouldbetrue.
Analogoustothediscussionforrelationaloperators,mathematicalexpressionslikea=b
=cmustbewrittenusingrelationalandlogical/conditionaloperators.Sinceequality
operatorshaveleftassociativity,theevaluationoftheexpressiona==b==cwould
proceedasfollows:((a==b)==c).Evaluationof(a==b)wouldyielda
booleanvaluethatispermittedasanoperandofadatavalueequalityoperator,but
(booleanvalue==c)wouldbeillegalifchadanumerictype.Thisproblemis
illustratedinthefollowingexamples.Theexpressionat(1)isillegal,butthoseat(2)and
(3)arelegal.
Clickheretoviewcodeimage
inta,b,c;
a=b=c=5;
booleanillegal=a==b==c;//(1)Illegal.
booleanvalid2=a==b&&b==c;//(2)Legal.
booleanvalid3=a==b==true;//(3)Legal.
ObjectReferenceEquality: ,
Theequalityoperator==andtheinequalityoperator!=canbeappliedtoreference
variablestotestwhethertheyrefertothesameobject.Giventhatrandsarereference
variables,thereferenceequalityoperatorsaredefinedasshowninTable5.10.
Table5.10ReferenceEqualityOperators
Theoperandsmustbecastcompatible:Itmustbepossibletocastthereferencevalueof
theoneintotheother’stype;otherwise,itisacompile-timeerror.Castingofreferencesis
discussedin§7.8,p.311.
Clickheretoviewcodeimage
PizzapizzaA=newPizza(“Sweet&Sour”);//newobject
PizzapizzaB=newPizza(“Sweet&Sour”);//newobject
PizzapizzaC=newPizza(“Hot&Spicy”);//newobject
Stringbanner=“Comeandgetit!”;//newobject
booleantest=banner==pizzaA;//(1)Compile-timeerror
booleantest1=pizzaA==pizzaB;//false
booleantest2=pizzaA==pizzaC;//false
pizzaA=pizzaB;//Denotethesameobject;are
WOW! eBook
www.wowebook.org
aliases
booleantest3=pizzaA==pizzaB;//true
Thecomparisonbanner==pizzaAin(1)isillegal,becausetheStringand
Pizzatypesarenotrelatedandthereforethereferencevalueofonetypecannotbecast
totheothertype.Thevaluesoftest1andtest2arefalsebecausethethree
referencesdenotedifferentobjects,regardlessofthefactthatpizzaAandpizzaBare
bothsweetandsourpizzas.Thevalueoftest3istruebecausenowbothpizzaAand
pizzaBdenotethesameobject.
Theequalityandinequalityoperatorsareappliedtoobjectreferencestocheckwhether
tworeferencesdenotethesameobject.Thestateoftheobjectsthatthereferencesdenote
isnotcompared.Thisisthesameastestingwhetherthereferencesarealiases,meaning
thattheydenotethesameobject.
Thenullliteralcanbeassignedtoanyreferencevariable,andthereferencevalueina
referencevariablecanbecomparedforequalitywiththenullliteral.Thecomparison
canbeusedtoavoidinadvertentuseofareferencevariablethatdoesnotdenoteany
object.
if(objRef!=null){
//…useobjRef…
}
Notethatonlywhenthetypeofbothoperandsiseitherareferencetypeorthenulltype,
dotheseoperatorstestforobjectreferenceequality.Otherwise,theytestforprimitivedata
equality(seealso§8.3,p.350).Inthefollowingcodesnippet,binarynumericpromotion
involvingunboxingisperformedat(2):
Clickheretoviewcodeimage
IntegeriRef=10;
booleanb1=iRef==null;//(1)Objectreferenceequality
booleanb2=iRef==10;//(2)Primitivedataequality
booleanb3=null==10;//Compile-timeerror!
ObjectValueEquality
TheObjectclassprovidesthemethodpublicbooleanequals(Objectobj),
whichcanbeoverridden(§7.2,p.268)togivetherightsemanticsofobjectvalueequality.
ThedefaultimplementationofthismethodintheObjectclassreturnstrueonlyifthe
objectiscomparedwithitself,asiftheequalityoperator==hadbeenusedtocompare
aliasesofanobject.Consequently,ifaclassdoesnotoverridethesemanticsofthe
equals()methodfromtheObjectclass,objectvalueequalityisthesameasobject
referenceequality.
CertainclassesinthestandardAPIoverridetheequals()method,suchas
java.lang.Stringandthewrapperclassesfortheprimitivedatatypes.Fortwo
Stringobjects,valueequalitymeanstheycontainidenticalcharactersequences.Forthe
wrapperclasses,valueequalitymeansthatthewrapperobjectshavethesameprimitive
valueandareofthesamewrappertype(seealso§8.3,p.350).
Clickheretoviewcodeimage
WOW! eBook
www.wowebook.org
//EqualityforStringobjectsmeansidenticalcharactersequences.
Stringmovie1=newString(“TheRevengeoftheExceptionHandler”);
Stringmovie2=newString(“HighNoonattheJavaCorral”);
Stringmovie3=newString(“TheRevengeoftheExceptionHandler”);
booleantest0=movie1.equals(movie2);//false.
booleantest1=movie1.equals(movie3);//true.
//Equalityforwrapperclassesmeanssametypeandsameprimitivevalue.
Booleanflag1=true;//Boxing.
Booleanflag2=false;//Boxing.
booleantest2=flag1.equals(“true”);//false.Notsametype.
booleantest3=flag1.equals(!flag2);//true.Sametypeand
value.
IntegeriRef=100;//Boxing.
ShortsRef=100;//Boxing.
booleantest4=iRef.equals(100);//true.Sametypeand
value.
booleantest5=iRef.equals(sRef);//false.Notsametype.
booleantest6=iRef.equals(3.14);//false.Notsametype.
//ThePizzaclassdoesnotoverridetheequals()method,sowecanuse
either
//equals()methodinheritedfromtheObjectclassorequalityoperator==.
Pizzapizza1=newPizza(“VeggiesDelight”);
Pizzapizza2=newPizza(“VeggiesDelight”);
Pizzapizza3=newPizza(“CheeseDelight”);
booleantest7=pizza1.equals(pizza2);//false.
booleantest8=pizza1.equals(pizza3);//false.
booleantest9=pizza1==pizza2;//false.
pizza1=pizza2;//Createsaliases.
booleantest10=pizza1.equals(pizza2);//true.
booleantest11=pizza1==pizza2;//true.
5.13BooleanLogicalOperators: , , ,
Booleanlogicaloperatorsincludetheunaryoperator!(logicalcomplement)andthe
binaryoperators&(logicalAND),|(logicalinclusiveOR),and^(logicalexclusiveOR,
alsocalledlogicalXOR).TheseoperatorscanbeappliedtobooleanorBoolean
operands,returningabooleanvalue.Theoperators&,|,and^canalsobeappliedto
integraloperandstoperformbitwiselogicaloperations,butarenotinthescopeofthis
book.
Giventhatxandyrepresentbooleanexpressions,thebooleanlogicaloperatorsaredefined
inTable5.11.Theprecedenceoftheoperatorsdecreasesfromlefttorightinthetable.
Table5.11TruthValuesforBooleanLogicalOperators
WOW! eBook
www.wowebook.org
Theseoperatorsalwaysevaluateboththeoperands,unliketheircounterpartconditional
operators&&and||(§5.14,p.186).Unboxingisappliedtotheoperandvalues,if
necessary.TruthvaluesforbooleanlogicaloperatorsareshowninTable5.11.
OperandEvaluationforBooleanLogicalOperators
IntheevaluationofbooleanexpressionsinvolvingbooleanlogicalAND,XOR,andOR
operators,boththeoperandsareevaluated.Theorderofoperandevaluationisalways
fromlefttoright.
Clickheretoviewcodeimage
if(i>0&i++<10){/*…*/}//iwillbeincremented,regardlessofvalue
ini.
Thebinarybooleanlogicaloperatorshaveprecedencelowerthanthearithmeticand
relationaloperators,buthigherprecedencethantheassignment,conditionalAND,andOR
operators(§5.14,p.186).Thisisillustratedinthefollowingexamples:
Clickheretoviewcodeimage
booleanb1,b2,b3=false,b4=false;
Booleanb5=true;
b1=4==2&1<4;//false,evaluatedas(b1=((4==2)&(1<
4)))
b2=b1|!(2.5>=8);//true
b3=b3^b5;//true,unboxingconversiononb5
b4=b4|b1&b2;//false
Here,theorderofevaluationisillustratedforthelastexpressionstatement:
Clickheretoviewcodeimage
(b4=(b4|(b1&b2)))
(b4=(false|(b1&b2)))
(b4=(false|(false&b2)))
(b4=(false|(false&true)))
(b4=(false|false))
(b4=false)
false
Notethatb2wasevaluatedalthough,strictlyspeaking,itwasnotnecessary.Thisbehavior
isguaranteedforbooleanlogicaloperators.
BooleanLogicalCompoundAssignmentOperators: , ,|
CompoundassignmentoperatorsforthebooleanlogicaloperatorsaredefinedinTable
5.12.Theleft-handoperandmustbeabooleanvariable,andtheright-handoperandmust
beabooleanexpression.Anidentityconversionisappliedimplicitlyonassignment.
Theseoperatorscanalsobeappliedtointegraloperandstoperformbitwisecompound
assignments,butarenotcoveredinthisbook.Seealsothediscussiononarithmetic
compoundassignmentoperatorsin§5.7,p.172.
WOW! eBook
www.wowebook.org
Table5.12BooleanLogicalCompoundAssignmentOperators
Herearesomeexamplestoillustratethebehaviorofbooleanlogicalcompound
assignmentoperators:
Clickheretoviewcodeimage
booleanb1=false,b2=true,b3=false;
Booleanb4=false;
b1|=true;//true
b4^=b1;//(1)true,unboxingin(b4^(b1)),boxingon
assignment
b3&=b1|b2;//(2)false,b3=(b3&(b1|b2))
b3=b3&b1|b2;//(3)true,b3=((b3&b1)|b2)
Theassignmentat(1)entailsunboxingtoevaluatetheexpressionontheright-handside,
followedbyboxingtoassignthebooleanresult.Itisalsoinstructivetocomparehow
theassignmentsat(2)and(3)areperformed,astheyleadtodifferentresultswiththesame
valuesoftheoperands,showinghowtheprecedenceaffectstheevaluation.
5.14ConditionalOperators: ,
Theconditionaloperators&&and||aresimilartotheircounterpartlogicaloperators&
and|,exceptthattheirevaluationisshort-circuited.Giventhatxandyrepresentvalues
ofbooleanorBooleanexpressions,theconditionaloperatorsaredefinedinTable
5.13.Inthetable,theoperatorsarelistedindecreasingprecedenceorder.
Table5.13ConditionalOperators
Unliketheirlogicalcounterparts&and|,whichcanalsobeappliedtointegraloperands
forbitwiseoperations,theconditionaloperators&&and||canbeappliedonlyto
booleanoperands.Theirevaluationresultsinabooleanvalue.Truthvaluesfor
conditionaloperatorsareshowninTable5.14.Notsurprisingly,theconditionaloperators
havethesametruthvaluesastheircounterpartlogicaloperators.However,unlikewith
theirlogicalcounterparts,therearenocompoundassignmentoperatorsfortheconditional
operators.
WOW! eBook
www.wowebook.org
Table5.14TruthValuesforConditionalOperators
Short-CircuitEvaluation
InevaluationofbooleanexpressionsinvolvingconditionalANDandOR,theleft-hand
operandisevaluatedbeforetheright-handoperand,andtheevaluationisshort-circuited
(i.e.,iftheresultofthebooleanexpressioncanbedeterminedfromtheleft-handoperand,
theright-handoperandisnotevaluated).Inotherwords,theright-handoperandis
evaluatedconditionally.
Thebinaryconditionaloperatorshavelowerprecedencethanthearithmetic,relational,
andlogicaloperators,buthigherprecedencethantheassignmentoperators.Unboxingof
theoperandvaluetakesplacewhennecessary,beforetheoperationisperformed.The
followingexamplesillustrateusageofconditionaloperators:
Clickheretoviewcodeimage
Booleanb1=4==2&&1<4;//false,short-circuitevaluatedas
//(b1=((4==2)&&(1<4)))
booleanb2=!b1||2.5>8;//true,short-circuitevaluatedas
//(b2=((!b1)||(2.5>8)))
Booleanb3=!(b1&&b2);//true
booleanb4=b1||!b3&&b2;//false,short-circuitevaluatedas
//(b4=(b1||((!b3)&&b2)))
Theorderofevaluationforcomputingthevaluestoredinthebooleanvariableb4
proceedsasfollows:
Clickheretoviewcodeimage
(b4=(b1||((!b3)&&b2)))
(b4=(false||((!b3)&&b2)))
(b4=(false||((!true)&&b2)))
(b4=(false||((false)&&b2)))
(b4=(false||false))
(b4=false)
Notethatb2isnotevaluated,short-circuitingtheevaluation.Example5.3illustratesthe
short-circuitevaluationoftheinitializationexpressionsinthedeclarationstatementsgiven
intheearliercodesnippet.Inaddition,itshowsanevaluation(seethedeclarationofb5)
involvingbooleanlogicaloperatorsthatalwaysevaluatebothoperands.SeealsoExample
5.1,p.153,whichusesasimilarapproachtoillustratetheorderofoperandevaluationin
arithmeticexpressions.
WOW! eBook
www.wowebook.org
Example5.3Short-CircuitEvaluationInvolvingConditionalOperators
Clickheretoviewcodeimage
publicclassShortCircuit{
publicstaticvoidmain(String[]args){
//Booleanb1=4==2&&1<4;
Booleanb1=operandEval(1,4==2)&&operandEval(2,1<4);
System.out.println();
System.out.println(“Valueofb1:”+b1);
//booleanb2=!b1||2.5>8;
booleanb2=!operandEval(1,b1)||operandEval(2,2.5>8);
System.out.println();
System.out.println(“Valueofb2:”+b2);
//Booleanb3=!(b1&&b2);
Booleanb3=!(operandEval(1,b1)&&operandEval(2,b2));
System.out.println();
System.out.println(“Valueofb3:”+b3);
//booleanb4=b1||!b3&&b2;
booleanb4=operandEval(1,b1)||!operandEval(2,b3)&&operandEval(3,
b2);
System.out.println();
System.out.println(“Valueofb4:”+b4);
//booleanb5=b1|!b3&b2;//Usingbooleanlogicaloperators
booleanb5=operandEval(1,b1)|!operandEval(2,b3)&operandEval(3,
b2);
System.out.println();
System.out.println(“Valueofb5:”+b5);
}
staticbooleanoperandEval(intopNum,booleanoperand){//
(1)
System.out.print(opNum);
returnoperand;
}
}
Outputfromtheprogram:
1
Valueofb1:false
1
Valueofb2:true
1
Valueofb3:true
12
Valueofb4:false
123
Valueofb5:false
Short-circuitevaluationcanbeusedtoensurethatareferencevariabledenotesanobject
beforeitisused.
Clickheretoviewcodeimage
if(objRef!=null&&objRef.equals(other)){/*…*/}
Themethodcallisnowconditionallydependentontheleft-handoperandandwillnotbe
WOW! eBook
www.wowebook.org
executedifthevariableobjRefhasthenullreference.Ifweusethelogical&operator
andthevariableobjRefhasthenullreference,evaluationoftheright-handoperand
willresultinaNullPointerException.
Insummary,weemploytheconditionaloperators&&and||iftheevaluationoftheright-
handoperandisconditionallydependentontheleft-handoperand.Weusetheboolean
logicaloperators&and|ifbothoperandsmustbeevaluated.Thesubtletyofconditional
operatorsisillustratedbythefollowingexamples:
Clickheretoviewcodeimage
if(i>0&&i++<10){/*…*/}//iisnotincrementedifi>0isfalse.
if(i>0||i++<10){/*…*/}//iisnotincrementedifi>0istrue.
5.15IntegerBitwiseOperators: , , ,
Areviewofintegerrepresentation(§5.5,p.154)isrecommendedbeforecontinuingwith
thissectiononhowintegerbitwiseoperatorscanbeappliedtovaluesofintegraldata
types.
Integerbitwiseoperatorsincludetheunaryoperator~(bitwisecomplement)andthe
binaryoperators&(bitwiseAND),|(bitwiseinclusiveOR),and^(bitwiseexclusiveOR,
alsoknownasbitwiseXOR).Theoperators&,|,and^areoverloaded,astheycanbe
appliedtobooleanorBooleanoperandstoperformbooleanlogicaloperations(§5.13,
p.184).AlthoughtheintegerbitwiseoperatorsarenotontheOCAJP8exam,theyare
includedheretocontrasttheirevaluationwiththatoftheirbooleancounterparts.
Thebinarybitwiseoperatorsperformbitwiseoperationsbetweencorrespondingindividual
bitvaluesintheoperands.Unarynumericpromotionisappliedtotheoperandoftheunary
bitwisecomplementoperator~,andbinarynumericpromotionisappliedtotheoperands
ofthebinarybitwiseoperators.Theresultisanewintegervalueofthepromotedtype,
whichcanbeeitherintorlong.
GiventhatAandBarecorrespondingbitvalues(either0or1)intheleft-handandright-
handoperands,respectively,thesebitwiseoperatorsaredefinedasshowninTable5.15.
Theoperatorsarelistedindecreasingprecedenceorder.
Table5.15IntegerBitwiseOperators
Theresultofapplyingbitwiseoperatorsbetweentwocorrespondingbitsintheoperandsis
showninTable5.16,whereAandBarecorrespondingbitvaluesintheleft-handright-
handoperands,respectively.Table5.16isanalogoustoTable5.11forbooleanlogical
WOW! eBook
www.wowebook.org
operators,ifweconsiderbitvalue1torepresenttrueandbitvalue0torepresent
false.
Table5.16ResultTableforBitwiseOperators
ExamplesofBitwiseOperatorApplication
Clickheretoviewcodeimage
charv1=‘)’;//Unicodevalue41
bytev2=13;
intresult1=~v1;//-42
intresult2=v1&v2;//9
intresult3=v1|v2;//45
intresult4=v1^v2;//36
Table5.17showshowtheresultiscalculated.Unaryandbinarynumericpromotionsare
appliedfirst,convertingtheoperandstointinthesecases.Notethattheoperator
semanticsisappliedtocorrespondingindividualbits—thatis,firstbitofleft-handoperand
andfirstbitofright-handoperand,secondbitofleft-handoperandandsecondbitofright-
handoperand,andsoon.
Table5.17ExamplesofBitwiseOperations
Itisinstructivetorunexamplesandprinttheresultofabitwiseoperationindifferent
notations,asshowninExample5.4.Theintegerbitwiseoperatorssupportaprogramming
techniquecalledbitmasking.Thevaluev2isusuallycalledabitmask.Dependingonthe
bitwiseoperationperformedonthevaluev1andthemaskv2,weseehowtheresulting
valuereflectsthebitwiseoperationperformedbetweentheindividualcorrespondingbits
ofthevaluev1andthemaskv2.Bychoosingappropriatevaluesforthebitsinthemask
v2andtherightbitwiseoperation,itispossibletoextract,set,andtogglespecificbitsin
thevaluev1.
Methodsforconvertingintegerstostringsindifferentnotationscanbefoundinthe
WOW! eBook
www.wowebook.org
Integerclass(§8.3,p.353).Convertingintegerstodifferentnumbersystemsis
discussedin§5.5,p.154.
Example5.4BitwiseOperations
Clickheretoviewcodeimage
publicclassBitOperations{
publicstaticvoidmain(String[]args){
charv1=‘)’;//Unicodevalue41
bytev2=13;
printIntToStr(“v1:”,v1);//41
printIntToStr(“v2:”,v2);//13
printIntToStr(“~v1:”,~v1);//-42
printIntToStr(“v1&v2:”,v1&v2);//9
printIntToStr(“v1|v2:”,v1|v2);//45
printIntToStr(“v1^v2:”,v1^v2);//36
}
publicstaticvoidprintIntToStr(Stringlabel,intresult){
System.out.println(label);
System.out.println(“Binary:”+Integer.toBinaryString(result));
System.out.println(“Hex:”+Integer.toHexString(result));
System.out.println(“Decimal:”+result);
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
v1:
Binary:101001
Hex:29
Decimal:41
v2:
Binary:1101
Hex:d
Decimal:13
~v1:
Binary:11111111111111111111111111010110
Hex:ffffffd6
Decimal:-42
v1&v2:
Binary:1001
Hex:9
Decimal:9
v1|v2:
Binary:101101
Hex:2d
Decimal:45
v1^v2:
Binary:100100
Hex:24
Decimal:36
WOW! eBook
www.wowebook.org
BitwiseCompoundAssignmentOperators: , ,
BitwisecompoundassignmentoperatorsforthebitwiseoperatorsaredefinedinTable
5.18.Typeconversionsfortheseoperators,whenappliedtointegraloperands,arethe
sameasforothercompoundassignmentoperators:animplicitnarrowingconversionis
performedonassignmentwhenthedestinationdatatypeiseitherbyte,short,or
char.Theseoperatorscanalsobeappliedtobooleanoperandstoperformlogical
compoundassignments(§5.13,p.185).
Table5.18BitwiseCompoundAssignmentOperators
ExamplesofBitwiseCompoundAssignment
Clickheretoviewcodeimage
intv0=-42;
charv1=‘)’;//41
bytev2=13;
v0&=15;//1…11010110&0…00001111=>0…00000110(=6)
v1|=v2;//(1)0…00101001|0…00001101=>0…00101101(=45,‘-‘)
At(1)intheseexamples,boththecharvalueinv1andthebytevalueinv2arefirst
promotedtoint.Theresultisimplicitlynarrowedtothedestinationtypecharon
assignment.
ReviewQuestions
5.15Whichofthefollowingexpressionsevaluatetotrue?
Selectthetwocorrectanswers.
(a)(false|true)
(b)(null!=null)
(c)(4<=4)
(d)(!true)
(e)(true&false)
5.16Whichofthefollowingstatementsaretrue?
Selectthetwocorrectanswers.
(a)Theremainderoperator%canbeusedonlywithintegraloperands.
(b)Short-circuitevaluationoccurswithbooleanlogicaloperators.
WOW! eBook
www.wowebook.org
(c)Thearithmeticoperators*,/,and%havethesamelevelofprecedence.
(d)Ashortvaluerangesfrom-128to+127,inclusive.
(e)(+15)isalegalexpression.
5.17Whichstatementsaretrueaboutthelinesofoutputprintedbythefollowing
program?
Clickheretoviewcodeimage
publicclassBoolOp{
staticvoidop(booleana,booleanb){
booleanc=a!=b;
booleand=a^b;
booleane=c==d;
System.out.println(e);
}
publicstaticvoidmain(String[]args){
op(false,false);
op(true,false);
op(false,true);
op(true,true);
}
}
Selectthethreecorrectanswers.
(a)Alllinesprintedarethesame.
(b)Atleastonelinecontainsfalse.
(c)Atleastonelinecontainstrue.
(d)Thefirstlinecontainsfalse.
(e)Thelastlinecontainstrue.
5.18Whatistheresultofrunningthefollowingprogram?
Clickheretoviewcodeimage
publicclassOperandOrder{
publicstaticvoidmain(String[]args){
inti=0;
int[]a={3,6};
a[i]=i=9;
System.out.println(i+””+a[0]+””+a[1]);
}
}
Selecttheonecorrectanswer.
(a)Whenrun,theprogramthrowsanArrayIndexOutOfBoundsException.
(b)Whenrun,theprogramwillprint996.
(c)Whenrun,theprogramwillprint906.
(d)Whenrun,theprogramwillprint936.
(e)Whenrun,theprogramwillprint939.
WOW! eBook
www.wowebook.org
5.19Whichstatementsaretrueabouttheoutputfromthefollowingprogram?
Clickheretoviewcodeimage
publicclassLogic{
publicstaticvoidmain(String[]args){
inti=0;
intj=0;
booleant=true;
booleanr;
r=(t&0<(i+=1));
r=(t&&0<(i+=2));
r=(t|0<(j+=1));
r=(t||0<(j+=2));
System.out.println(i+””+j);
}
}
Selectthetwocorrectanswers.
(a)Thefirstdigitprintedis1.
(b)Thefirstdigitprintedis2.
(c)Thefirstdigitprintedis3.
(d)Theseconddigitprintedis1.
(e)Theseconddigitprintedis2.
(f)Theseconddigitprintedis3.
5.16TheConditionalOperator:
Theternaryconditionaloperator?:allowsconditionalexpressionstobedefined.The
conditionalexpressionhasthefollowingsyntax:
Clickheretoviewcodeimage
condition?expression1:expression2
Itiscalledternarybecauseithasthreeoperands.Ifthebooleanexpressionconditionis
true,thenexpression1isevaluated;otherwise,expression2isevaluated.Both
expression1andexpression2mustevaluatetovaluesthatcanbeconvertedtothetypeof
theconditionalexpression.Thistypeisdeterminedfromthetypesofthetwoexpressions.
Thevalueoftheexpressionevaluatedisconvertedtothetypeoftheconditional
expression,andmayinvolveautoboxingandunboxing.
Evaluationofaconditionalexpressionisanexampleofshort-circuitevaluation.Asonly
oneofthetwoexpressionsisevaluated,oneshouldbewaryofanysideeffectsina
conditionalexpression.
Inthefollowingcodesnippetat(1),bothexpressionsintheconditionalexpressionareof
typebyte.Thetypeoftheconditionalexpressionisthereforebyte.Thatavalueoftype
bytecanbeconvertedtoanintbyanimplicitwideningnumericconversiontobe
assignmentcompatiblewiththeintvariabledaysInFebruaryissecondaryin
WOW! eBook
www.wowebook.org
determiningthetypeoftheconditionalexpression.Notethattheconditionaloperatorat
(1)hashigherprecedencethantheassignmentoperator=,makingitunnecessaryto
enclosetheconditionalexpressioninparentheses.
Clickheretoviewcodeimage
booleanleapYear=false;
bytev29=29;
bytev28=28;
intdaysInFebruary=leapYear?v29:v28;//(1)
Thefollowingexamplesillustratetheuseofconditionalexpressions.Thetypeofthe
conditionalexpressionat(2)isint,andnoconversionofanyexpressionvalueis
necessary.Thetypeoftheconditionalexpressionat(3)isdouble,duetobinarynumeric
promotion:Theintvalueofthefirstexpressionsispromotedtoadouble.The
compilerreportsanerrorbecauseadoublecannotbeassignedtoanintvariable.The
typeoftheconditionalexpressionat(4)isalsodoubleasin(3),butnowthedouble
valueisassignmentcompatiblewiththedoublevariableminDoubleValue.
Clickheretoviewcodeimage
inti=3;
intj=4;
intminValue1=i<j?i:j;//(2)int
intminValue2=i<j?i:Double.MIN_VALUE;//(3)double.NotOK.
doubleminDoubleValue=i<j?i:Double.MIN_VALUE;//(4)double
Inthefollowingcodesnippetin(5),theprimitivevaluesoftheexpressionscanbeboxed
andassignedtoanObjectreference.In(6),theintvalueofthefirstexpressioncanbe
boxedinanInteger.Theprintln()methodcreatesandprintsastring
representationofanyobjectwhosereferencevalueispassedasparameter.
Clickheretoviewcodeimage
//Assumeiandjareoftypeintandinitializedcorrectly.
Objectobj=i<j?i:true;//(5)valueofiboxedinIntegeror
//literaltrueboxedinBoolean
System.out.println(i<j?i:“Hi”);//(6)valueofiboxedinIntegeror
//Stringobject“Hi”
Theconditionalexpressionisnotanexpressionstatement.Thefollowingcodewillnot
compile:
Clickheretoviewcodeimage
(i<j)?i:j;//Compile-timeerror!
Theconditionalexpressioncanbenested,andtheconditionaloperatorassociatesfrom
righttoleft.
Clickheretoviewcodeimage
a?b:c?d:e?f:gevaluatesas(a?b:(c?d:(e?f:g)))
Thevalueofthisconditionalexpressionisgif,andonlyif,a,c,andearefalse.A
nestedconditionalexpressionisusedinthenextexample.Asaconvention,thecondition
inaconditionalexpressionisenclosedinparenthesestoaidreadingthecode.Typically,a
conditionalexpressionisusedwhenitmakesthecodeeasiertoread,especiallywhenthe
expressionsareshortandwithoutsideeffects.
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
intn=3;
Stringmsg=(n==0)?“nocookies.”:(n==1)?“onecookie.”:“many
cookies.”;
System.out.println(“Youget”+msg);//Yougetmanycookies.
Theconditionaloperatoristheexpressionequivalentoftheif-elsestatement(§6.2,p.
201).
5.17OtherOperators: , , ,->
Thenewoperatorisusedtocreateobjects,suchasinstancesofclassesandarrays.Itis
usedwithaconstructorcalltoinstantiateclasses(§3.3,p.53)andwiththe[]notationto
createarrays(§3.4,p.59).Itisalsousedtoinstantiateanonymousarrays(§3.4,p.63).
Clickheretoviewcodeimage
PizzaonePizza=newPizza();//CreateaninstanceofthePizzaclass.
The[]notationisusedtodeclareandconstructarrays,andisalsotoaccessarray
elements(§3.4,p.58).
Clickheretoviewcodeimage
int[]anArray=newint[5];//Declareandconstructanintarrayof5
elements.
anArray[4]=anArray[3];//Elementatindex4getsvalueofelementat
index3.
Theboolean,binary,andinfixoperatorinstanceofisusedtotestthetypeofanobject
(§7.11,p.320).
Clickheretoviewcodeimage
PizzamyPizza=newPizza();
booleantest1=myPizzainstanceofPizza;//true.
booleantest2=“Pizza”instanceofPizza;//Compileerror.Stringisnot
Pizza.
booleantest3=nullinstanceofPizza;//Alwaysfalse.nullisnotan
instance.
Thearrowoperator->isusedinthedefinitionofalambdaexpression(§10.2,p.444).
Clickheretoviewcodeimage
java.util.function.Predicate<String>predicate=str->str.length()%2==
0;
booleantest4=predicate.test(“Thelambdastrikesback!”);//true.
ReviewQuestions
5.20WhichofthefollowingarenotoperatorsinJava?
Selectthetwocorrectanswers.
(a)%
(b)&&
(c)%=
WOW! eBook
www.wowebook.org
(d)&&=
(e)<=
(f)%%
(g)->
5.21Whichstatementswheninsertedat(1)willnotresultinacompile-timeerror?
Clickheretoviewcodeimage
publicclassRQ05A200{
publicstaticvoidmain(String[]args){
inti=20;
intj=30;
//(1)INSERTSTATEMENTHERE.
}
}
Selectthethreecorrectanswers.
(a)intresult1=i<j?i:j*10D;
(b)intresult2=i<j?{++i}:{++j};
(c)Numbernumber=i<j?i:j*10D;
(d)System.out.println(i<j?i);
(e)System.out.println(i<j?++i:++j);
(f)System.out.println(i==j?i==j:"inotequalto
j");
5.22Whichstatementsaretrueaboutthefollowingcode?
Clickheretoviewcodeimage
publicclassRQ05A100{
publicstaticvoidmain(String[]args){
intn1=10,n2=10;
intm1=20,m2=30;
intresult=n1!=n2?n1:m1!=m2?m1:m2;
System.out.println(result);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile.
(b)Whenrun,theprogramthrowsanArithmeticExceptionatruntime.
(c)Whenrun,theprogramwillprint10.
(d)Whenrun,theprogramwillprint20.
(e)Whenrun,theprogramwillprint30.
WOW! eBook
www.wowebook.org
ChapterSummary
Thefollowingtopicswerecoveredinthischapter:
•Typeconversioncategoriesandconversioncontexts,andwhichconversionsare
permissibleineachconversioncontext.
•Definingandevaluatingarithmeticandbooleanexpressions,andtheorderinwhich
operandsandoperatorsareevaluated.
•Representingintegersindifferentnumbersystemsandinmemory.
•OperatorsinJava,includingprecedenceandassociativityrules.
ProgrammingExercise
5.1Thefollowingprogramissupposedtocalculateandprintthetimeittakesforlight
totravelfromthesuntotheearth.Itcontainssomelogicalerrors.Fixtheprogram
sothatitwillcompile,compute,andprintthecorrectresultwhenrun.
Clickheretoviewcodeimage
//File:Sunlight.java
publicclassSunlight{
publicstaticvoidmain(String[]args){
//Distancefromsun(150millionkilometers)
intkmFromSun=150_000_000;
intlightSpeed=299_792_458;//meterspersecond
//Convertdistancetometers.
intmFromSun=kmFromSun*1000;
intseconds=mFromSun/lightSpeed;
System.out.print(“Lightwilluse“);
printTime(seconds);
System.out.println(”totravelfromthesuntotheearth.”);
}
publicstaticvoidprintTime(intsec){
intmin=sec/60;
sec=sec-(min*60);
System.out.print(min+”minute(s)and”+sec+”second(s)”);
}
}
WOW! eBook
www.wowebook.org
6.ControlFlow
6.1OverviewofControlFlowStatements
Controlflowstatementsgoverntheflowofcontrolinaprogramduringexecution,
meaningtheorderinwhichstatementsareexecutedinarunningprogram.Therearethree
maincategoriesofcontrolflowstatements:
WOW! eBook
www.wowebook.org
•Selectionstatements:if,if-else,andswitch.
•Iterationstatements:while,do-while,basicfor,andenhancedfor.
•Transferstatements:break,continue,return,try-catch-finally,
throw,andassert.
Onlythebasicformofthetry-catch-finallyconstructiscoveredhere,andthe
assertfacilityisnotinthescopeofthisbook.
6.2SelectionStatements
Javaprovidesselectionstatementsthatallowtheprogramtochoosebetweenalternative
actionsduringexecution.Thechoiceisbasedoncriteriaspecifiedintheselection
statement.Theseselectionstatementsare
•Simpleifstatement
•if-elsestatement
•switchstatement
TheSimple Statement
Thesimpleifstatementhasthefollowingsyntax:
if(condition)
statement
Itisusedtodecidewhetheranactionistobeperformedornot,basedonacondition.The
actiontobeperformedisspecifiedbystatement,whichcanbeasinglestatementoracode
block.TheconditionmustevaluatetoabooleanorBooleanvalue.Inthelattercase,
theBooleanvalueisunboxedtothecorrespondingbooleanvalue.
Thesemanticsofthesimpleifstatementarestraightforward.Theconditionisevaluated
first.Ifitsvalueistrue,statement(calledtheifblock)isexecutedandthenexecution
continueswiththerestoftheprogram.Ifthevalueisfalse,theifblockisskippedand
executioncontinueswiththerestoftheprogram.Thesemanticsareillustratedbythe
activitydiagraminFigure6.1a.
WOW! eBook
www.wowebook.org
Figure6.1ActivityDiagramforifStatements
Inthefollowingexamplesoftheifstatement,itisassumedthatthevariablesandthe
methodshavebeenappropriatelydefined:
Clickheretoviewcodeimage
if(emergency)//emergencyisabooleanvariable
operate();
if(temperature>critical)
soundAlarm();
if(isLeapYear()&&endOfCentury())
celebrate();
if(catIsAway()){//Block
getFishingRod();
goFishing();
}
Notethatstatementcanbeablock,andtheblocknotationisnecessaryifmorethanone
statementistobeexecutedwhentheconditionistrue.
Sincetheconditionevaluatestoabooleanvalue,itavoidsacommonprogramming
error:usinganexpressionoftheform(a=b)asthecondition,whereinadvertentlyan
assignmentoperatorisusedinsteadofarelationaloperator.Thecompilerwillflagthisas
anerror,unlessbothaandbareboolean.
Notethattheifblockcanbeanyvalidstatement.Inparticular,itcanbetheempty
statement(;)ortheemptyblock({}).Acommonprogrammingerrorisinadvertentuse
oftheemptystatement.
Clickheretoviewcodeimage
if(emergency);//Emptyifblock
operate();//Executedregardlessofwhetheritwasanemergency
The Statement
Theif-elsestatementisusedtodecidebetweentwoactions,basedonacondition.It
hasthefollowingsyntax:
WOW! eBook
www.wowebook.org
if(condition)
statement1
else
statement2
Theconditionisevaluatedfirst.Ifitsvalueistrue(orunboxedtotrue),statement1
(theifblock)isexecutedandthenexecutioncontinueswiththerestoftheprogram.If
thevalueisfalse(orunboxedtofalse),statement2(theelseblock)isexecutedand
thenexecutioncontinueswiththerestoftheprogram.Inotherwords,oneoftwomutually
exclusiveactionsisperformed.Theelseclauseisoptional;ifomitted,theconstructis
equivalenttothesimpleifstatement.Thesemanticsareillustratedbytheactivity
diagraminFigure6.1b.
Inthefollowingexamplesoftheif-elsestatement,itisassumedthatallvariablesand
methodshavebeenappropriatelydefined:
if(emergency)
operate();
else
joinQueue();
if(temperature>critical)
soundAlarm();
else
businessAsUsual();
if(catIsAway()){
getFishingRod();
goFishing();
}else
playWithCat();
Sinceactionscanbearbitrarystatements,theifstatementscanbenested.
Clickheretoviewcodeimage
if(temperature>=upperLimit){//(1)
if(danger)//(2)Simpleif.
soundAlarm();
if(critical)//(3)
evacuate();
else//Goeswithifat(3).
turnHeaterOff();
}else//Goeswithifat(1).
turnHeaterOn();
Theuseoftheblocknotation,{},canbecriticaltotheexecutionofifstatements.The
ifstatements(A)and(B)inthefollowingexamplesdonothavethesamemeaning.The
ifstatements(B)and(C)arethesame,withextraindentationusedin(C)tomakethe
meaningevident.Leavingouttheblocknotationinthiscasecouldhavecatastrophic
consequences:Theheatercouldbeturnedonwhenthetemperatureisabovetheupper
limit.
Clickheretoviewcodeimage
//(A):
if(temperature>upperLimit){//(1)Blocknotation.
if(danger)soundAlarm();//(2)
WOW! eBook
www.wowebook.org
}else//Goeswithifat(1).
turnHeaterOn();
//(B):
if(temperature>upperLimit)//(1)Withoutblocknotation.
if(danger)soundAlarm();//(2)
elseturnHeaterOn();//Goeswithifat(2).
//(C):
if(temperature>upperLimit)//(1)
if(danger)//(2)
soundAlarm();
else//Goeswithifat(2).
turnHeaterOn();
Theruleformatchinganelseclauseisthatanelseclausealwaysreferstothenearest
ifthatisnotalreadyassociatedwithanotherelseclause.Blocknotationandproper
indentationcanbeusedtomakethemeaningobvious.
Cascadingif-elsestatementscompriseasequenceofnestedif-elsestatements
wheretheifblockofthenextif-elsestatementisjoinedtotheelseclauseofthe
previousone.Thedecisiontoexecuteablockisthenbasedonalltheconditionsevaluated
sofar.
Clickheretoviewcodeimage
if(temperature>=upperLimit){//(1)
soundAlarm();
turnHeaterOff();
}elseif(temperature<lowerLimit){//(2)
soundAlarm();
turnHeaterOn();
}elseif(temperature==(upperLimit-lowerLimit)/2){//(3)
doingFine();
}else//(4)
noCauseToWorry();
Theblockcorrespondingtothefirstifconditionthatevaluatestotrueisexecuted,and
theremainingifstatementsareskipped.Intheprecedingexample,theblockat(3)will
executeonlyiftheconditionsat(1)and(2)arefalseandtheconditionat(3)istrue.
Ifnoneoftheconditionsistrue,theblockassociatedwiththelastelseclauseis
executed.Ifthereisnolastelseclause,noactionsareperformed.
The Statement
Conceptually,theswitchstatementcanbeusedtochooseoneamongmanyalternative
actions,basedonthevalueofanexpression.Itsgeneralformisasfollows:
switch(switch_expression){
caselabel1:statement1
caselabel2:statement2
…
caselabeln:statementn
default:statement
}//endswitch
Thesyntaxoftheswitchstatementcomprisesaswitchexpressionfollowedbythe
WOW! eBook
www.wowebook.org
switchbody,whichisablockofstatements.Theswitchexpressionmustevaluatetoa
valueofthefollowingtypes:
•Oneofthefollowingprimitivedatatypes:char,byte,short,orint
•Oneofthefollowingwrappertypes:Character,Byte,Short,orInteger
•Stringtype
•Anenumeratedtype
Notethatthetypeoftheswitchexpressioncannotbeboolean,long,orfloating-
point.Thestatementsintheswitchbodycanbelabeled,therebydefiningentrypointsin
theswitchbodywherecontrolcanbetransferreddependingonthevalueofthe
switchexpression.Theexecutionoftheswitchstatementisasfollows:
•Theswitchexpressionisevaluatedfirst.Ifthevalueisawrappertype,an
unboxingconversionisperformed.
•Thevalueoftheswitchexpressioniscomparedwiththecaselabels.Controlis
transferredtothestatementassociatedwiththecaselabelthatisequaltothevalue
oftheswitchexpression.Afterexecutionoftheassociatedstatement,controlfalls
throughtothenextstatementunlessthiswasthelaststatementdeclaredorcontrol
wastransferredoutoftheswitchstatement.
•Ifnocaselabelisequaltothevalueoftheswitchexpression,thestatement
associatedwiththedefaultlabelisexecuted.Afterexecutionoftheassociated
statement,controlfallsthroughtothenextstatementunlessthiswasthelast
statementdeclaredorcontrolwastransferredoutoftheswitchstatement.
Figure6.2illustratestheflowofcontrolthroughaswitchstatementwherethe
defaultlabelisdeclaredlast.
Figure6.2ActivityDiagramforaswitchStatement
Alllabels(includingthedefaultlabel)areoptional,andcanbedefinedinanyorderin
WOW! eBook
www.wowebook.org
theswitchbody.Atmostonedefaultlabelcanbepresentinaswitchstatement.If
novalidcaselabelsarefoundandthedefaultlabelisomitted,thewholeswitch
statementisskipped.
Thecaselabelsareconstantexpressionswhosevaluesmustbeunique,meaningno
duplicatevaluesareallowed.Infact,acaselabelmustbeacompile-timeconstant
expressionwhosevalueisassignabletothetypeoftheswitchexpression(§5.2,p.147).
Inparticular,allcaselabelvaluesmustbeintherangeofthetypeoftheswitch
expression.Thetypeofthecaselabelcannotbeboolean,long,orfloating-point.
Thecompilerisabletogenerateefficientcodeforaswitchstatement,asthisstatement
onlytestsforequalitybetweentheswitchexpressionandtheconstantvalueofthe
caselabels,soastodeterminewhichcodetoexecuteatruntime.Incontrast,asequence
ofifstatementsdeterminestheflowofcontrolatruntime,basedonarbitraryconditions
whosevaluemightbepossibletodetermineonlyatruntime.
InExample6.1,dependingonthevalueofthehowMuchAdviceparameter,different
adviceisprintedintheswitchstatementat(1)inthemethoddispenseAdvice().
TheexampleshowstheoutputwhenthevalueofthehowMuchAdviceparameteris
LOTS_OF_ADVICE.Intheswitchstatement,theassociatedstatementat(2)is
executed,givingonepieceofadvice.Controlthenfallsthroughtothestatementat(3),
givingthesecondadvice.Controlnextfallsthroughto(4),dispensingthethirdpieceof
advice,andfinallyexecutionofthebreakstatementat(5)causescontroltoexitthe
switchstatement.Withoutthebreakstatementat(5),controlwouldcontinuetofall
throughtheremainingstatements—inthiscase,tothestatementat(6)beingexecuted.
Executionofthebreakstatementinaswitchbodytransferscontroloutofthe
switchstatement(§6.4,p.221).IftheparameterhowMuchAdvicehasthevalue
MORE_ADVICE,thentheadviceatboth(3)and(4)isgiven.Thevalue
LITTLE_ADVICEresultsinonlyonepieceofadviceat(4)beinggiven.Anyothervalue
resultsinthedefaultaction,whichannouncesthatthereisnoadvice.
Theassociatedstatementofacaselabelcanbealistofstatements(whichneednotbea
statementblock).Thecaselabelisprefixedtothefirststatementineachcase.Thisis
illustratedbytheassociatedstatementforthecaselabelLITTLE_ADVICEinExample
6.1,whichcomprisesstatements(4)and(5).
WOW! eBook
www.wowebook.org
Example6.1Fall-ThroughinaswitchStatement
Clickheretoviewcodeimage
publicclassAdvice{
privatestaticfinalintLITTLE_ADVICE=0;
privatestaticfinalintMORE_ADVICE=1;
privatestaticfinalintLOTS_OF_ADVICE=2;
publicstaticvoidmain(String[]args){
dispenseAdvice(LOTS_OF_ADVICE);
}
publicstaticvoiddispenseAdvice(inthowMuchAdvice){
switch(howMuchAdvice){//(1)
caseLOTS_OF_ADVICE:
System.out.println(“Seenoevil.”);//(2)
caseMORE_ADVICE:
System.out.println(“Speaknoevil.”);//(3)
caseLITTLE_ADVICE:
System.out.println(“Hearnoevil.”);//(4)
break;//(5)
default:
System.out.println(“Noadvice.”);//(6)
}
}
}
Outputfromtheprogram:
Seenoevil.
Speaknoevil.
Hearnoevil.
Example6.2makesuseofabreakstatementinsideaswitchstatementtoconverta
charvaluerepresentingadigittothecorrespondingwordinEnglish.Notethatthe
breakstatementisthelaststatementinthelistofstatementsassociatedwitheachcase
label.Itiseasytothinkthatthebreakstatementisapartoftheswitchstatement
syntax,buttechnicallyitisnot.
WOW! eBook
www.wowebook.org
Example6.2UsingbreakinaswitchStatement
Clickheretoviewcodeimage
publicclassDigits{
publicstaticvoidmain(String[]args){
System.out.println(digitToString(‘7’)+””+digitToString(‘8’)+””+
digitToString(‘6’));
System.out.println(digitToString(‘2’)+””+digitToString(‘a’)+””+
digitToString(‘5’));
}
publicstaticStringdigitToString(chardigit){
Stringstr=””;
switch(digit){
case‘1’:str=“one”;break;
case‘2’:str=“two”;break;
case‘3’:str=“three”;break;
case‘4’:str=“four”;break;
case‘5’:str=“five”;break;
case‘6’:str=“six”;break;
case‘7’:str=“seven”;break;
case‘8’:str=“eight”;break;
case‘9’:str=“nine”;break;
case‘0’:str=“zero”;break;
default:System.out.println(digit+”isnotadigit!”);
}
returnstr;
}
}
Outputfromtheprogram:
seveneightsix
aisnotadigit!
twofive
Severalcaselabelscanprefixthesamestatement.Theywillallresultintheassociated
statementbeingexecuted.ThisbehaviorisillustratedinExample6.3fortheswitch
statementat(1).
Thefirststatementintheswitchbodymusthaveacaseordefaultlabel,or
otherwiseitwillbeunreachable.Thisstatementwillneverbeexecuted,becausecontrol
canneverbetransferredtoit.Thecompilerwillflagthisasanerror.Anemptyswitch
blockisperfectlylegal,butnotofmuchuse.
Sinceeachactionassociatedwithacaselabelcanbeanarbitrarystatement,itcanbe
anotherswitchstatement.Inotherwords,switchstatementscanbenested.Sincea
switchstatementdefinesitsownlocalblock,thecaselabelsinaninnerblockdonot
conflictwithanycaselabelsinanouterblock.Labelscanberedefinedinnestedblocks;
incontrast,variablescannotberedeclaredinnestedblocks(§4.4,p.117).InExample6.3,
aninnerswitchstatementisdefinedat(2),whichallowsfurtherrefinementoftheaction
totakeonthevalueoftheswitchexpressionincaseswheremultiplelabelsareusedin
theouterswitchstatement.Abreakstatementterminatestheinnermostswitch
statementinwhichitisexecuted.
WOW! eBook
www.wowebook.org
Example6.3NestedswitchStatement
Clickheretoviewcodeimage
publicclassSeasons{
publicstaticvoidmain(String[]args){
intmonthNumber=11;
switch(monthNumber){//(1)Outer
case12:case1:case2:
System.out.println(“Snowinthewinter.”);
break;
case3:case4:case5:
System.out.println(“Greengrassinthespring.”);
break;
case6:case7:case8:
System.out.println(“Sunshineinthesummer.”);
break;
case9:case10:case11://(2)
switch(monthNumber){//Nestedswitch(3)Inner
case10:
System.out.println(“Halloween.”);
break;
case11:
System.out.println(“Thanksgiving.”);
break;
}//Endnestedswitch
//Alwaysprintedforcaselabels9,10,11
System.out.println(“Yellowleavesinthefall.”);//(4)
break;
default:
System.out.println(monthNumber+”isnotavalidmonth.”);
}
}
}
Outputfromtheprogram:
Thanksgiving.
Yellowleavesinthefall.
Example6.4illustratesusingstringsinaswitchstatement.Thethingtonoteiswhat
constitutesaconstantstringexpressionthatcanbeusedasacaselabel.Thecaselabels
in(3),(4),(5),and(6)areallvalidconstantstringexpressions,asthecompilercanfigure
outtheirvaluesatcompiletime.Stringliterals,usedin(3)and(6),andconstantfield
values,declaredin(1)and(2a),andusedin(4)and(5),areallvalidcaselabels.In
contrast,theHOTreferencefromdeclarations(2b)and(2c)cannotbeusedasacase
label.Fromthedeclarationin(2a),thecompilercannotguaranteethatthevalueofthe
referencewillnotchangeatruntime.Fromthedeclarationin(2c),itcannotdeducethe
valueatcompiletime,astheconstructormustberuntoconstructthevalue.
Switchingonstringsisessentiallybasedonequalitycomparisonofintegervaluesthatare
hashvaluesofstrings,followedbyanobjectequalitytesttoruleoutthepossibilityof
collisionbetweentwodifferentstringshavingthesamehashvalue.Switchingonstrings
shouldbeusedjudiciously,asitislessefficientthanswitchingonintegers.Switchingon
stringsisnotadvisableifthevaluesbeingswitchedonarenotalreadystrings.
WOW! eBook
www.wowebook.org
Example6.4StringsinswitchStatement
Clickheretoviewcodeimage
publicclassSwitchingOnAString{
publicstaticfinalStringMEDIUM=“Medium”;//(1)
publicstaticfinalStringHOT=“Hot”;//(2a)
//publicstaticStringHOT=“Hot”;//(2b)NotOKascase
lablel
//publicstaticfinalStringHOT=newString(“Hot”);//(2c)NotOKascase
lablel
publicstaticvoidmain(String[]args){
StringspiceLevel=“Medium_Hot”;
switch(spiceLevel){
case“Mild”://(3)
caseMEDIUM+“_”+HOT://(4)
System.out.println(“Enjoyyourmeal!”);
break;
caseHOT://(5)
System.out.println(“Havefun!”);
break;
case“Suicide”://(6)
System.out.println(“Goodluck!”);
break;
default:
System.out.println(“Youbeingfunny?”);
}
}
}
Outputfromtheprogram:
Enjoyyourmeal!
Example6.5illustratestheuseofenumtypesinaswitchstatement.Theenumtype
SpiceGradeisdefinedat(1).ThetypeoftheswitchexpressionisSpiceGrade.
Notethattheenumconstantsarenotspecifiedwiththeirfullyqualifiedname(see(2a)).
Usingthefullyqualifiednameresultsinacompile-timeerror,asshownat(2b).Only
enumconstantsthathavethesameenumtypeastheswitchexpressioncanbespecified
ascaselabelvalues.
Thesemanticsoftheswitchstatementarethesameasdescribedearlier.However,ifa
switchexpressionevaluatestothenullreference,aNullPointerExceptionwill
bethrown.Switchingonenumeratedvaluesisessentiallybasedonequalitycomparisonof
uniqueintegervaluesthatareordinalvaluesassignedbythecompilertotheconstantsof
anenumtype.
WOW! eBook
www.wowebook.org
Example6.5EnumsinswitchStatement
Clickheretoviewcodeimage
enumSpiceGrade{//(1)
MILD,MEDIUM_HOT,HOT,SUICIDE;
}
publicclassSwitchingFun{
publicstaticvoidmain(String[]args){
SpiceGradespicing=SpiceGrade.HOT;
switch(spicing){
caseHOT://(2a)OK!
//caseSpiceGrade.HOT://(2b)Compile-timeerror!
System.out.println(“Havefun!”);
break;
caseSUICIDE:
System.out.println(“Goodluck!”);
break;
default://CanonlybeMILDor
MEDIUM_HOT.
System.out.println(“Enjoyyoumeal!”);
}
}
}
Outputfromtheprogram:
Havefun!
ReviewQuestions
6.1Whatwillbetheresultofattemptingtocompileandrunthefollowingclass?
Clickheretoviewcodeimage
publicclassIfTest{
publicstaticvoidmain(String[]args){
if(true)
if(false)
System.out.println(“a”);
else
System.out.println(“b”);
}
}
Selecttheonecorrectanswer.
(a)Thecodewillfailtocompilebecausethesyntaxoftheifstatementis
incorrect.
(b)Thecodewillfailtocompilebecausethecompilerwillnotbeabletodetermine
whichifstatementtheelseclausebelongsto.
(c)Thecodewillcompilecorrectly,anddisplaytheletteraatruntime.
(d)Thecodewillcompilecorrectly,anddisplaytheletterbatruntime.
(e)Thecodewillcompilecorrectly,butwillnotdisplayanyoutput.
WOW! eBook
www.wowebook.org
6.2Whichofthefollowingstatementsaretrue?
Selectthethreecorrectanswers.
(a)Theconditioninanifstatementcanhavemethodcalls.
(b)IfaandbareoftypebooleanorBoolean,theexpression(a=b)can
betheconditionofanifstatement.
(c)Anifstatementcanhaveeitheranifclauseoranelseclause.
(d)Thestatementif(false);else;isillegal.
(e)Onlyexpressionsthatevaluateorcanbeunboxedtoabooleanvaluecanbe
usedastheconditioninanifstatement.
6.3What,ifanything,iswrongwiththefollowingcode?
voidtest(intx){
switch(x){
case1:
case2:
case0:
default:
case4:
}
}
Selecttheonecorrectanswer.
(a)Thevariablexdoesnothavetherighttypeforaswitchexpression.
(b)Thecaselabel0mustprecedethecaselabel1.
(c)Eachcasesectionmustendwithabreakstatement.
(d)Thedefaultlabelmustbethelastlabelintheswitchstatement.
(e)Thebodyoftheswitchstatementmustcontainatleastonestatement.
(f)Thereisnothingwrongwiththecode.
6.4Whatwillbetheresultofattemptingtocompileandrunthefollowingprogram?
Clickheretoviewcodeimage
publicclassSwitching{
publicstaticvoidmain(String[]args){
finalintiLoc=3;
switch(6){
case1:
caseiLoc:
case2*iLoc:
System.out.println(“IamnotOK.”);
default:
System.out.println(“YouareOK.”);
case4:
System.out.println(“It’sOK.”);
}
}
}
WOW! eBook
www.wowebook.org
Selecttheonecorrectanswer.
(a)Thecodewillfailtocompilebecauseofthecaselabelvalue2*iLoc.
(b)Thecodewillfailtocompilebecausethedefaultlabelisnotspecifiedlast
intheswitchstatement.
(c)Thecodewillcompilecorrectlyandwillprintthefollowingatruntime:
IamnotOK.
YouareOK.
It’sOK.
(d)Thecodewillcompilecorrectlyandwillprintthefollowingatruntime:
YouareOK.
It’sOK.
(e)Thecodewillcompilecorrectlyandwillprintthefollowingatruntime:
It’sOK.
6.5Whatwillbetheresultofattemptingtocompileandrunthefollowingprogram?
Clickheretoviewcodeimage
publicclassMoreSwitching{
publicstaticvoidmain(String[]args){
finalintiLoc=3;
IntegeriRef=5;
switch(iRef){
default:
System.out.println(“YouareOK.”);
case1:
caseiLoc:
case2*iLoc:
System.out.println(“IamnotOK.”);
break;
case4:
System.out.println(“It’sOK.”);
}
}
}
Selecttheonecorrectanswer.
(a)Thecodewillfailtocompilebecausethetypeoftheswitchexpressionisnot
valid.
(b)Thecodewillcompilecorrectlyandwillprintthefollowingatruntime:
YouareOK.
IamnotOK.
(c)Thecodewillcompilecorrectlyandwillprintthefollowingatruntime:
YouareOK.
IamnotOK.
It’sOK.
(d)Thecodewillcompilecorrectlyandwillprintthefollowingatruntime:
It’sOK.
6.6Whichcaselabeldeclarationcanbeinsertedat(1)sothatthefollowingprogram
WOW! eBook
www.wowebook.org
willcompile,run,andprintHi,TomTom!?
Clickheretoviewcodeimage
publicclassSwitcheroo{
publicstaticvoidmain(String[]args){
finalStringTOM1=“Tom”;
StringTOM2=“Tom”;
finalStringTOM3=newString(“Tom”);
switch(“TomTom”){
default:
System.out.println(“Whatever!”);
break;
//(1)INSERTcaseLABELDECLARATIONHERE.
System.out.println(“Hi,TomTom!”);
}
}
}
Selectthefourcorrectanswers.
(a)case"TomTom":
(b)caseTOM1+TOM1:
(c)caseTOM1+TOM2:
(d)caseTOM1+TOM3:
(e)caseTOM2+TOM3:
(f)case"Tom"+TOM1:
(g)case"Tom"+TOM2:
(h)case"Tom"+TOM3:
(i)case'T'+'o'+'m'+TOM1:
(j)case"T"+'o'+'m'+TOM1:
6.3IterationStatements
Loopsallowablockofstatementstobeexecutedrepeatedly(thatis,iterated).Aboolean
condition(calledtheloopcondition)iscommonlyusedtodeterminewhentoterminatethe
loop.Thestatementsexecutedintheloopconstitutetheloopbody.Theloopbodycanbea
singlestatementorablock.
Javaprovidesthreelanguageconstructsforloopconstruction:
•Thewhilestatement
•Thedo-whilestatement
•Thebasicforstatement
Theseloopsdifferintheorderinwhichtheyexecutetheloopbodyandtesttheloop
condition.Thewhileloopandthebasicforlooptesttheloopconditionbefore
executingtheloopbody,whereasthedo-whileloopteststheloopconditionafter
WOW! eBook
www.wowebook.org
executionoftheloopbody.
Inadditiontothebasicforloop,aspecializedloopcalledtheenhancedforloop(also
calledthefor-eachloop)simplifiesiteratingoverarraysandcollections.Wewillusethe
notationsfor(;;)andfor(:)todesignatethebasicforloopandtheenhancedfor
loop,respectively.
The Statement
Thesyntaxofthewhileloopis
while(loop_condition)
loop_body
Theloopconditionisevaluatedbeforeexecutingtheloopbody.Thewhilestatement
executestheloopbodyaslongastheloopconditionistrue.Whentheloopcondition
becomesfalse,theloopisterminatedandexecutioncontinueswiththestatement
immediatelyfollowingtheloop.Iftheloopconditionisfalsetobeginwith,theloop
bodyisnotexecutedatall.Inotherwords,awhileloopcanexecutezeroormoretimes.
TheloopconditionmustevaluatetoabooleanoraBooleanvalue.Inthelattercase,
thereferencevalueisunboxedtoabooleanvalue.Theflowofcontrolinawhile
statementisshowninFigure6.3.
Figure6.3ActivityDiagramforthewhileStatement
Thewhilestatementisnormallyusedwhenthenumberofiterationsisnotknown.
while(noSignOfLife())
keepLooking();
Sincetheloopbodycanbeanyvalidstatement,inadvertentlyterminatingeachlinewith
theemptystatement(;)cangiveunintendedresults.Alwaysusingablockstatementas
theloopbodyhelpstoavoidsuchproblems.
Clickheretoviewcodeimage
while(noSignOfLife());//Emptystatementasloopbody!
keepLooking();//Statementnotintheloopbody.
The Statement
Thesyntaxofthedo-whileloopis
do
loop_body
while(loop_condition);
Inado-whilestatement,theloopconditionisevaluatedafterexecutingtheloopbody.
WOW! eBook
www.wowebook.org
TheloopconditionmustevaluatetoabooleanorBooleanvalue.Thevalueofthe
loopconditionissubjectedtounboxingifitisofthetypeBoolean.Thedo-while
statementexecutestheloopbodyuntiltheloopconditionbecomesfalse.Whentheloop
conditionbecomesfalse,theloopisterminatedandexecutioncontinueswiththe
statementimmediatelyfollowingtheloop.Notethattheloopbodyisexecutedatleast
once.Figure6.4illustratestheflowofcontrolinado-whilestatement.
Figure6.4ActivityDiagramforthedo-whileStatement
Theloopbodyinado-whileloopisinvariablyastatementblock.Itisinstructiveto
comparethewhileanddo-whileloops.Intheexamplesthatfollow,themicemight
nevergettoplayifthecatisnotaway,asintheloopat(1).Themicedogettoplayat
leastonce(attheperiloflosingtheirlife)intheloopat(2).
Clickheretoviewcodeimage
while(cat.isAway()){//(1)
mice.play();
}
do{//(2)
mice.play();
}while(cat.isAway());
The Statement
Thefor(;;)loopisthemostgeneralofalltheloops.Itismostlyusedforcounter-
controlledloops,inwhichthenumberofiterationsisknownbeforehand.
Thesyntaxoftheloopisasfollows:
Clickheretoviewcodeimage
for(initialization;loop_condition;update_expression)
loop_body
Theinitializationusuallydeclaresandinitializesaloopvariablethatcontrolsthe
executionoftheloopbody.TheloopconditionmustevaluatetoabooleanorBoolean
value.Inthelattercase,thereferencevalueisconvertedtoabooleanvalueby
unboxing.Theloopconditionusuallyinvolvestheloopvariable,andiftheloopcondition
istrue,theloopbodyisexecuted;otherwise,executioncontinueswiththestatement
followingthefor(;;)loop.Aftereachiteration(thatis,executionoftheloopbody),
theupdateexpressionisexecuted.Thisusuallymodifiesthevalueoftheloopvariableto
ensureeventuallooptermination.Theloopconditionisthentestedtodeterminewhether
theloopbodyshouldbeexecutedagain.Notethattheinitializationisexecutedonlyonce,
WOW! eBook
www.wowebook.org
onentryintotheloop.Thesemanticsofthefor(;;)loopareillustratedinFigure6.5,
andaresummarizedbythefollowingequivalentwhileloopcodetemplate:
initialization
while(loop_condition){
loop_body
update_expression
}
Figure6.5ActivityDiagramfortheforStatement
Thefollowingcodecreatesanintarrayandsumsthevaluesinthearray:
Clickheretoviewcodeimage
intsum=0;
int[]array={12,23,5,7,19};
for(intindex=0;index<array.length;index++)//(1)
sum+=array[index];
Theloopvariableindexisdeclaredandinitializedintheinitializationsectionofthe
loop.Itisincrementedintheupdateexpressionsection.Thisloopisanexampleofa
forwardfor(;;)loop,wheretheloopvariableisincremented.
Thenextcodesnippetisanexampleofabackwardfor(;;)loop,wheretheloop
variableisdecrementedtosumthevaluesinthearray:
Clickheretoviewcodeimage
intsum=0;
int[]array={12,23,5,7,19};
for(intindex=array.length-1;index>=0;index—)
sum+=array[index];
Itisinstructivetocomparethespecificationoftheloopheaderintheforward
andbackwardfor(;;)loopsintheseexamples.
Thefor(;;)loopdefinesalocalblocksothatthescopeofthisdeclarationisthe
for(;;)block,whichcomprisestheinitialization,theloopcondition,theloopbody,
andtheupdateexpressionsections.Anyvariabledeclaredinthefor(;;)block,
therefore,isnotaccessibleafterthefor(;;)loopterminates.Theloopat(1)earlier
showedhowadeclarationstatementcanbespecifiedintheinitializationsection.Sucha
WOW! eBook
www.wowebook.org
declarationstatementcanalsospecifyacomma-separatedlistofvariables:
Clickheretoviewcodeimage
for(inti=0,j=1,k=2;…;…)…;//(2)
Thevariablesi,j,andkinthedeclarationstatementallhavetypeint.Allvariables
declaredintheinitializationsectionarelocalvariablesinthefor(;;)blockandobey
thescoperulesforlocalblocks.Thefollowingcodewillnotcompile,however,asvariable
declarationsofdifferenttypes(inthiscase,intandString)requiredeclaration
statementsthatareterminatedbysemicolons:
Clickheretoviewcodeimage
for(inti=0,Stringstr=“@”;…;…)…;//(3)Compile-timeerror
Theinitializationsectioncanalsobeacomma-separatedlistofexpressionstatements
(§3.2,p.50).Anyvaluereturnedbyanexpressionstatementisdiscarded.Forexample,
theloopat(2)canberewrittenbyfactoringoutthevariabledeclaration:
Clickheretoviewcodeimage
inti,j,k;//Variabledeclaration
for(i=0,j=1,k=2;…;…)…;//(4)Onlyinitialization
Theinitializationsectionisnowacomma-separatedlistofthreeexpressions.The
expressionsinsuchalistarealwaysevaluatedfromlefttoright,andtheirvaluesare
discarded.Notethatthevariablesi,j,andkat(4)arenotlocaltotheloop.
Declarationstatementscannotbemixedwithexpressionstatementsintheinitialization
section,asisthecaseat(5)inthefollowingexample.Factoringoutthevariable
declaration,asat(6),leavesalegalcomma-separatedlistofexpressionstatements.
Clickheretoviewcodeimage
//(5)Notlegalandugly:
for(inti=0,System.out.println(“Thiswon’tdo!”);flag;i++){//Error!
//loopbody
}
//(6)Legal,butstillugly:
inti;//Declarationfactoredout.
for(i=0,System.out.println(“Thisislegal!”);flag;i++){//OK.
//loopbody
}
Theupdateexpressioncanalsobeacomma-separatedlistofexpressionstatements.The
followingcodespecifiesafor(;;)loopthathasacomma-separatedlistofthree
variablesintheinitializationsection,andacomma-separatedlistoftwoexpressionsinthe
updateexpressionsection:
Clickheretoviewcodeimage
//Legalusagebutnotrecommended.
int[][]sqMatrix={{3,4,6},{5,7,4},{5,8,9}};
for(inti=0,j=sqMatrix[0].length-1,asymDiagonal=0;//
initialization
i<sqMatrix.length;//loop
condition
i++,j—)//updateexpression
asymDiagonal+=sqMatrix[i][j];//loopbody
WOW! eBook
www.wowebook.org
Allsectionsinthefor(;;)headerareoptional.Anyorallofthemcanbeleftempty,
butthetwosemicolonsaremandatory.Inparticular,leavingouttheloopcondition
signifiesthattheloopconditionistrue.The“crab”,(;;),canbeusedtoconstructan
infiniteloop,whereterminationispresumablyachievedthroughcodeintheloopbody
(seethenextsectionontransferstatements):
Clickheretoviewcodeimage
for(;;)doProgramming();//Infiniteloop
The Statement
Theenhancedforloopisconvenientwhenweneedtoiterateoveranarrayora
collection,especiallywhensomeoperationneedstobeperformedoneachelementofthe
arrayorcollection.Inthissectionwediscussiteratingoverarrays;in§10.1,p.423,we
takealookatthefor(:)loopforiteratingoverArrayLists.
Earlierinthischapterweusedafor(;;)looptosumthevaluesofelementsinanint
array:
Clickheretoviewcodeimage
intsum=0;
int[]intArray={12,23,5,7,19};
for(intindex=0;index<intArray.length;index++){//(1)usingfor(;;)
loop
sum+=intArray[index];
}
Thefor(;;)loopat(1)isrewrittenusingthefor(:)loopinFigure6.6.
Figure6.6EnhancedforStatement
Thebodyoftheloopisexecutedforeachelementinthearray,wherethevariable
elementsuccessivelydenotesthecurrentelementinthearrayintArray.Whenthe
loopterminates,thevariablesumwillcontainthesumofallelementsinthearray.Wedo
notcareaboutthepositionoftheelementsinthearray,justthattheloopiteratesoverall
elementsofthearray.
FromFigure6.6weseethatthefor(:)loopheaderhastwoparts.Theexpressionmust
evaluatetoareferencevaluethatreferstoanarray—thatis,thearraywewanttoiterate
over.Thearraycanbeanarrayofprimitivevaluesorobjects,orevenanarrayofarrays.
Theexpressionisevaluatedonlyonce.Theelementdeclarationspecifiesalocalvariable
thatcanbeassignedavalueoftheelementtypeofthearray.Thetypeofthearray
intArrayinFigure6.6isint[],andtheelementtypeisint.Theelementvariableof
typeintcanbeassignedintvaluesfromthearrayofint.However,thisassignment
mightrequireeitheraboxingoranunboxingconversion,withoptionalwidening
WOW! eBook
www.wowebook.org
conversion.
Theelementvariableislocaltotheloopblockandisnotaccessibleaftertheloop
terminates.Also,changingthevalueofthecurrentvariabledoesnotchangeanyvaluein
thearray.Theloopbody,whichcanbeasimplestatementorastatementblock,is
executedforeachelementinthearrayandthereisnodangerofanyout-of-boundserrors.
Thefor(:)loophasitslimitations.Specifically,wecannotchangeelementvalues,and
thiskindofloopdoesnotprovideanyprovisionforpositionalaccessusinganindex.The
for(:)looponlyincrementsbyoneandalwaysinaforwarddirection.Itdoesnotallow
iterationsoverseveralarrayssimultaneously.Undersuchcircumstances,thefor(;;)
loopcanbemoreconvenient.
Herearesomecodeexamplesoflegalfor(:)loops:
Clickheretoviewcodeimage
//Some1-dimarrays:
int[]intArray={10,20,30};
Integer[]intObjArray={10,20,30};
String[]strArray={“one”,“two”};
//Some2-dimarrays:
Object[][]objArrayOfArrays={intObjArray,strArray};
Number[][]numArrayOfArrays={{1.5,2.5},intObjArray,{100L,200L}};
int[][]intArrayOfArrays={{20},intArray,{40}};
//IterateoveranarrayofStrings.
//ExpressiontypeisString[],andelementtypeisString.
//StringisassignabletoObject(wideningconversion).
for(Objectobj:strArray){}
//Iterateoveranarrayofints.
//Expressiontypeisint[],andelementtypeisint.
//intisassignabletoInteger(boxingconversion)
for(IntegeriRef:intArrayOfArrays[0]){}
//IterateoveranarrayofIntegers.
//ExpressiontypeisInteger[],andelementtypeisInteger.
//Integerisassignabletoint(unboxingconversion)
for(inti:intObjArray){}
//Iterateovera2-dimarrayofints.
//Outerloop:expressiontypeisint[][],andelementtypeisint[].
//Innerloop:expressiontypeisint[],andelementtypeisint.
for(int[]row:intArrayOfArrays)
for(intval:row){}
//Iterateovera2-dimarrayofNumbers.
//Outerloop:expressiontypeisNumber[][],andelementtypeisNumber[].
//Outerloop:Number[]isassignabletoObject[](wideningconversion).
//Innerloop:expressiontypeisObject[],andelementtypeisObject.
for(Object[]row:numArrayOfArrays)
for(Objectobj:row){}
//Outerloop:expressiontypeisInteger[][],andelementtypeisInteger[].
//Outerloop:Integer[]isassignabletoNumber[].
//Innerloop:expressiontypeisint[],andelementtypeisint.
//Innerloop:intisassignabletodouble.
for(Number[]row:newInteger[][]{intObjArray,intObjArray,intObjArray})
WOW! eBook
www.wowebook.org
for(doublenum:newint[]{}){}
Herearesomecodeexamplesoffor(:)loopsthatarenotlegal:
Clickheretoviewcodeimage
//ExpressiontypeisNumber[][],andelementtypeisNumber[].
//Number[]isnotassignabletoNumber.
for(Numbernum:numArrayOfArrays){}//Compile-timeerror.
//ExpressiontypeisNumber[],andelementtypeisNumber.
//Numberisnotassignabletoint.
for(introw:numArrayOfArrays[0]){}//Compile-timeerror.
//Outerloop:expressiontypeisint[][],andelementtypeisint[].
//int[]isnotassignabletoInteger[].
for(Integer[]row:intArrayOfArrays)//Compile-timeerror.
for(intval:row){}
//ExpressiontypeisObject[][],andelementtypeisObject[].
//Object[]isnotassignabletoInteger[].
for(Integer[]row:objArrayOfArrays){}//Compile-timeerror.
//Outerloop:expressiontypeisString[],andelementtypeisString.
//Innerloop:expressiontypeisString,whichisnotlegalhere.Notan
array.
for(Stringstr:strArray)
for(charval:str){}//Compile-timeerror.
Whenusingthefor(:)looptoiterateoveranarray,thetwomaincausesoferrorsarean
expressionintheloopheaderthatdoesnotrepresentanarrayand/oranelementtypeof
thearraythatisnotassignabletothelocalvariabledeclaredintheloopheader.
6.4TransferStatements
Javaprovidessixlanguageconstructsfortransferringcontrolinaprogram:
•break
•continue
•return
•try-catch-finally
•throw
•assert
Thissectiondiscussesthefirstthreestatements.Exceptfortheassertstatement(noton
theOCAJP8exam),theremainingstatementsarediscussedinsubsequentsections.
NotethatJavadoesnothaveagotostatement,althoughgotoisareservedword.
LabeledStatements
Astatementmayhavealabel:
label:statement
WOW! eBook
www.wowebook.org
Alabelisanyvalididentifier;italwaysimmediatelyprecedesthestatement.Labelnames
existintheirownnamespace,sothattheydonotconflictwithnamesofpackages,classes,
interfaces,methods,fields,andlocalvariables.Thescopeofalabelisthestatement
prefixedbythelabel,meaningthatitcannotberedeclaredasalabelinsidethelabeled
statement—analogoustothescopeoflocalvariables.
Clickheretoviewcodeimage
L1:if(i>0){
L1:System.out.println(i);//(1)NotOK.Labelredeclared.
}
L1:while(i<0){//(2)OK.
L2:System.out.println(i);
}
L1:{//(3)OK.Labeledblock.
intj=10;
System.out.println(j);
}
L1:try{//(4)OK.Labeledtry-catch-finallyblock.
intj=10,k=0;
L2:System.out.println(j/k);
}catch(ArithmeticExceptionae){
L3:ae.printStackTrace();
}finally{
L4:System.out.println(“Finallydone.”);
}
Astatementcanhavemultiplelabels:
Clickheretoviewcodeimage
LabelA:LabelB:System.out.println(“Mutliplelabels.Usejudiciously.”);
Adeclarationstatementcannothavealabel:
Clickheretoviewcodeimage
L0:inti=0;//Compile-timeerror!
Alabeledstatementisexecutedasifitwasunlabeled,unlessitisthebreakor
continuestatement.Thisbehaviorisdiscussedinthenexttwosubsections.
The Statement
Thebreakstatementcomesintwoforms:unlabeledandlabeled.
Clickheretoviewcodeimage
break;//theunlabeledform
breaklabel;//thelabeledform
Theunlabeledbreakstatementterminatesloops(for(;;),for(:),while,do-
while)andswitchstatements,andtransferscontroloutofthecurrentcontext(i.e.,the
closestenclosingblock).Therestofthestatementbodyisskipped,andexecution
continuesaftertheenclosingstatement.
InExample6.6,thebreakstatementat(1)isusedtoterminateafor(;;)loop.Control
istransferredto(2)whenthevalueofiisequalto4at(1),skippingtherestoftheloop
WOW! eBook
www.wowebook.org
bodyandterminatingtheloop.
Example6.6alsoshowsthattheunlabeledbreakstatementterminatesonlythe
innermostlooporswitchstatementthatcontainsthebreakstatement.Thebreak
statementat(3)terminatestheinnerfor(;;)loopwhenjisequalto2,andexecution
continuesintheouterswitchstatementat(4)afterthefor(;;)loop.
Example6.6ThebreakStatement
Clickheretoviewcodeimage
classBreakOut{
publicstaticvoidmain(String[]args){
System.out.println(“isqrt(i)”);
for(inti=1;i<=5;++i){
if(i==4)
break;//(1)Terminateloop.Controlto
(2).
//Restofloopbodyskippedwhenigetsthevalue4.
System.out.printf(“%d%.2f%n”,i,Math.sqrt(i));
}//endfor
//(2)Continuehere.
intn=2;
switch(n){
case1:
System.out.println(n);
break;
case2:
System.out.println(“Innerfor(;;)loop:“);
for(intj=0;j<=n;j++){
if(j==2)
break;//(3)Terminateloop.Controlto
(4).
System.out.println(“j=”+j);
}
default:
System.out.println(“default:n=”+n);//(4)Continuehere.
}
}
}
Outputfromtheprogram:
isqrt(i)
11.00
21.41
31.73
Innerfor(;;)loop:
j=0
j=1
default:n=2
Alabeledbreakstatementcanbeusedtoterminateanylabeledstatementthatcontains
thebreakstatement.Controlisthentransferredtothestatementfollowingtheenclosing
labeledstatement.Inthecaseofalabeledblock,therestoftheblockisskippedand
executioncontinueswiththestatementfollowingtheblock:
Clickheretoviewcodeimage
WOW! eBook
www.wowebook.org
out://Label.
{//(1)Labeledblock.
//…
if(j==10)breakout;//(2)Terminateblock.Controlto(3).
System.out.println(j);//Restoftheblocknotexecutedifj==10.
//…
}
//(3)Continuehere.
InExample6.7,theprogramcontinuestoaddtheelementsbelowthediagonalofasquare
matrixuntilthesumisgreaterthan10.Twonestedforloopsaredefinedat(1)and(2).
Theouterloopislabeledouterat(1).Theunlabeledbreakstatementat(3)transfers
controlto(5)whenitisexecuted;thatis,itterminatestheinnerloopandcontrolis
transferredtothestatementaftertheinnerloop.Thelabeledbreakstatementat(4)
transferscontrolto(6)whenitisexecuted;thatis,itterminatesboththeinnerandthe
outerloop,transferringcontroltothestatementafterthelooplabeledouter.
Example6.7LabeledbreakStatement
Clickheretoviewcodeimage
classLabeledBreakOut{
publicstaticvoidmain(String[]args){
int[][]squareMatrix={{4,3,5},{2,1,6},{9,7,8}};
intsum=0;
outer:for(inti=0;i<squareMatrix.length;++i){//(1)label
for(intj=0;j<squareMatrix[i].length;++j){//(2)
if(j==i)break;//(3)Terminateinnerloop.Controlto
(5).
System.out.println(“Element[”+i+“,”+j+“]:”+
squareMatrix[i][j]);
sum+=squareMatrix[i][j];
if(sum>10)breakouter;//(4)Terminatebothloops.Controlto
(6).
}//endinnerloop
//(5)Continuewithupdateexpressionintheouterloopheader.
}//endouterloop
//(6)Continuehere.
System.out.println(“sum:”+sum);
}
}
Outputfromtheprogram:
Element[1,0]:2
Element[2,0]:9
sum:11
The Statement
Likethebreakstatement,thecontinuestatementcomesintwoforms:unlabeledand
labeled.
Clickheretoviewcodeimage
continue;//theunlabeledform
continuelabel;//thelabeledform
Thecontinuestatementcanbeusedonlyinafor(;;),for(:),while,ordo-
WOW! eBook
www.wowebook.org
whilelooptoprematurelystopthecurrentiterationoftheloopbodyandproceedwith
thenextiteration,ifpossible.Inthecaseofthewhileanddo-whileloops,therestof
theloopbodyisskipped—thatis,thecurrentiterationisstopped,withexecution
continuingwiththeloopcondition.Inthecaseofthefor(;;)loop,therestoftheloop
bodyisskipped,withexecutioncontinuingwiththeupdateexpression.
InExample6.8,anunlabeledcontinuestatementisusedtoskipaniterationina
for(;;)loop.Controlistransferredto(2)whenthevalueofiisequalto4at(1),
skippingtherestoftheloopbodyandcontinuingwiththeupdateexpressioninthe
for(;;)statement.
Example6.8continueStatement
Clickheretoviewcodeimage
classSkip{
publicstaticvoidmain(String[]args){
System.out.println(“isqrt(i)”);
for(inti=1;i<=5;++i){
if(i==4)continue;//(1)Controlto(2).
//Restofloopbodyskippedwhenihasthevalue4.
System.out.printf(“%d%.2f%n”,i,Math.sqrt(i));
//(2)Continuewithupdateexpressionintheloopheader.
}//endfor
}
}
Outputfromtheprogram:
isqrt(i)
11.00
21.41
31.73
52.24
Alabeledcontinuestatementmustoccurwithinalabeledloopthathasthesamelabel.
Executionofthelabeledcontinuestatementthentransferscontroltotheendofthat
enclosinglabeledloop.InExample6.9,theunlabeledcontinuestatementat(3)
transferscontrolto(5)whenitisexecuted;thatis,therestoftheloopbodyisskippedand
executioncontinueswiththeupdateexpressionintheinnerloop.Thelabeledcontinue
statementat(4)transferscontrolto(6)whenitisexecuted;thatis,itterminatestheinner
loopbutexecutioncontinueswiththeupdateexpressioninthelooplabeledouter.Itis
instructivetocomparetheoutputfromExample6.7(labeledbreak)andthatfrom
Example6.9(labeledcontinue).
WOW! eBook
www.wowebook.org
Example6.9LabeledcontinueStatement
Clickheretoviewcodeimage
classLabeledSkip{
publicstaticvoidmain(String[]args){
int[][]squareMatrix={{4,3,5},{2,1,6},{9,7,8}};
intsum=0;
outer:for(inti=0;i<squareMatrix.length;++i){//(1)label
for(intj=0;j<squareMatrix[i].length;++j){//(2)
if(j==i)continue;//(3)Controlto
(5).
System.out.println(“Element[”+i+“,”+j+“]:”+
squareMatrix[i][j]);
sum+=squareMatrix[i][j];
if(sum>10)continueouter;//(4)Controlto
(6).
//(5)Continuewithupdateexpressionintheinnerloopheader.
}//endinnerloop
//(6)Continuewithupdateexpressionintheouterloopheader.
}//endouterloop
System.out.println(“sum:”+sum);
}
}
Outputfromtheprogram:
Element[0,1]:3
Element[0,2]:5
Element[1,0]:2
Element[1,2]:6
Element[2,0]:9
sum:25
The Statement
Thereturnstatementisusedtostopexecutionofamethod(oraconstructor)and
transfercontrolbacktothecallingcode(alsocalledthecallerorinvoker).Theusageof
thetwoformsofthereturnstatementisdictatedbywhetherthatstatementisusedina
voidoranon-voidmethod(Table6.1).Thefirstformdoesnotreturnanyvaluetothe
callingcode,butthesecondformdoes.Notethatthekeywordvoiddoesnotrepresent
anytype.
Table6.1ThereturnStatement
InTable6.1,theexpressionmustevaluatetoaprimitivevalueorareferencevalue,andits
typemustbeassignabletothereturntypespecifiedinthemethodheader(§5.6,p.158,
and§7.9,p.312).Seealsothediscussiononcovariantreturninconnectionwithmethod
overridingin§7.2,p.268.
WOW! eBook
www.wowebook.org
AscanbeseenfromTable6.1,avoidmethodneednothaveareturnstatement—in
whichcasethecontroltypicallyreturnstothecallerafterthelaststatementinthe
method’sbodyhasbeenexecuted.However,avoidmethodcanspecifyonlythefirst
formofthereturnstatement.Thisformofthereturnstatementcanalsobeusedin
constructors,astheylikewisedonotreturnavalue.
Table6.1alsoshowsthatthefirstformofthereturnstatementisnotallowedinanon-
voidmethod.Thesecondformofthereturnstatementismandatoryinanon-void
method,ifthemethodexecutionisnotterminatedprogrammatically—forexample,by
throwinganexception.Example6.10illustratestheuseofthereturnstatement
summarizedinTable6.1.Arecommendedbestpracticeistodocumentthevaluereturned
byamethodinaJavadoccommentusingthe@returntag.
Example6.10ThereturnStatement
Clickheretoviewcodeimage
publicclassReturnDemo{
publicstaticvoidmain(String[]args){//(1)voidmethodcanuse
return.
if(args.length==0)return;
output(checkValue(args.length));
}
staticvoidoutput(intvalue){//(2)voidmethodneednotusereturn.
System.out.println(value);
return‘a’;//NotOK.Cannotreturnavalue.
}
staticintcheckValue(inti){//(3)Non-voidmethod:Anyreturn
statement
//mustreturnavalue.
if(i>3)
returni;//OK.
else
return2.0;//NotOK.doublenotassignabletoint.
}
staticintabsentMinded(){//(4)Non-voidmethod.
thrownewRuntimeException();//OK:Noreturnstatementprovided,but
//methodterminatesbythrowingan
exception.
}
}
ReviewQuestions
6.7Whatwillbetheresultofattemptingtocompileandrunthefollowingcode?
Clickheretoviewcodeimage
classMyClass{
publicstaticvoidmain(String[]args){
booleanb=false;
inti=1;
do{
WOW! eBook
www.wowebook.org
i++;
b=!b;
}while(b);
System.out.println(i);
}
}
Selecttheonecorrectanswer.
(a)Thecodewillfailtocompilebecausebisaninvalidconditionforthedo-
whilestatement.
(b)Thecodewillfailtocompilebecausetheassignmentb=!bisnotallowed.
(c)Thecodewillcompilewithouterror,andwillprint1atruntime.
(d)Thecodewillcompilewithouterror,andwillprint2atruntime.
(e)Thecodewillcompilewithouterror,andwillprint3atruntime.
6.8Whatwillbetheoutputwhenrunningthefollowingprogram?
Clickheretoviewcodeimage
publicclassStillMyClass{
publicstaticvoidmain(String[]args){
inti=0;
intj;
for(j=0;j<10;++j){i++;}
System.out.println(i+””+j);
}
}
Selectthetwocorrectanswers.
(a)Thefirstnumberprintedwillbe9.
(b)Thefirstnumberprintedwillbe10.
(c)Thefirstnumberprintedwillbe11.
(d)Thesecondnumberprintedwillbe9.
(e)Thesecondnumberprintedwillbe10.
(f)Thesecondnumberprintedwillbe11.
6.9Whichofthefollowingforstatementsisvalid?
Selecttheonecorrectanswer.
(a)intj=10;for(inti=0,j+=90;i<j;i++){j-
-;}
(b)for(inti=10;i=0;i--){}
(c)for(inti=0,j=100;i<j;i++,--j){;}
(d)inti,j;for(j=100;i<j;j--){i+=2;}
(e)inti=100;for((i>0);i--){}
WOW! eBook
www.wowebook.org
6.10Whatwillbetheresultofattemptingtocompileandrunthefollowingprogram?
Clickheretoviewcodeimage
classAnotherClass{
publicstaticvoidmain(String[]args){
inti=0;
for(;i<10;i++);//(1)
for(i=0;;i++)break;//(2)
for(i=0;i<10;)i++;//(3)
for(;;);//(4)
}
}
Selecttheonecorrectanswer.
(a)Thecodewillfailtocompilebecauseoferrorsintheforloopat(1).
(b)Thecodewillfailtocompilebecauseoferrorsintheforloopat(2).
(c)Thecodewillfailtocompilebecauseoferrorsintheforloopat(3).
(d)Thecodewillfailtocompilebecauseoferrorsintheforloopat(4).
(e)Thecodewillcompilewithouterror,andtheprogramwillrunandterminate
withoutanyoutput.
(f)Thecodewillcompilewithouterror,butwillneverterminatewhenrun.
6.11Whichofthefollowingstatementsarevalidwhenoccurringontheirown?
Selectthethreecorrectanswers.
(a)while()break;
(b)do{break;}while(true);
(c)if(true){break;}
(d)switch(1){default:break;}
(e)for(;true;)break;
6.12Giventhefollowingcodefragment,whichofthefollowinglineswillbeapartof
theoutput?
Clickheretoviewcodeimage
outer:
for(inti=0;i<3;i++){
for(intj=0;j<2;j++){
if(i==j){
continueouter;
}
System.out.println(“i=”+i+“,j=”+j);
}
}
Selectthetwocorrectanswers.
(a)i=1,j=0
(b)i=0,j=1
WOW! eBook
www.wowebook.org
(c)i=1,j=2
(d)i=2,j=1
(e)i=2,j=2
(f)i=3,j=3
(g)i=3,j=2
6.13Whatwillbetheresultofattemptingtocompileandrunthefollowingcode?
Clickheretoviewcodeimage
classMyClass{
publicstaticvoidmain(String[]args){
for(inti=0;i<10;i++){
switch(i){
case0:
System.out.println(i);
}
if(i){
System.out.println(i);
}
}
}
}
Selecttheonecorrectanswer.
(a)Thecodewillfailtocompilebecauseofanillegalswitchexpressioninthe
switchstatement.
(b)Thecodewillfailtocompilebecauseofanillegalconditionintheif
statement.
(c)Thecodewillcompilewithouterror,andwillprintthenumbers0through10
atruntime.
(d)Thecodewillcompilewithouterror,andwillprintthenumber0atruntime.
(e)Thecodewillcompilewithouterror,andwillprintthenumber0twiceat
runtime.
(f)Thecodewillcompilewithouterror,andwillprintthenumbers1through10at
runtime.
6.14Whichdeclarations,wheninsertedat(1),willresultintheprogramcompilingand
printing90atruntime?
Clickheretoviewcodeimage
publicclassRQ400A10{
publicstaticvoidmain(String[]args){
//(1)INSERTDECLARATIONHERE
intsum=0;
for(inti:nums)
sum+=i;
System.out.println(sum);
}
}
WOW! eBook
www.wowebook.org
Selectthetwocorrectanswers.
(a)Object[]nums={20,30,40};
(b)Number[]nums={20,30,40};
(c)Integer[]nums={20,30,40};
(d)int[]nums={20,30,40};
(e)Noneoftheabove
6.15Whichmethoddeclarations,wheninsertedat(1),willresultintheprogram
compilingandprinting90whenrun?
Clickheretoviewcodeimage
publicclassRQ400A30{
publicstaticvoidmain(String[]args){
doIt();
}
//(1)INSERTMETHODDECLARATIONHERE.
}
Selectthetwocorrectanswers.
(a)
publicstaticvoiddoIt(){
int[]nums={20,30,40};
for(intsum=0,i:nums)
sum+=i;
System.out.println(sum);
}
(b)
Clickheretoviewcodeimage
publicstaticvoiddoIt(){
for(intsum=0,i:{20,30,40})
sum+=i;
System.out.println(sum);
}
(c)
publicstaticvoiddoIt(){
intsum=0;
for(inti:{20,30,40})
sum+=i;
System.out.println(sum);
}
(d)
Clickheretoviewcodeimage
publicstaticvoiddoIt(){
intsum=0;
for(inti:newint[]{20,30,40})
sum+=i;
System.out.println(sum);
}
WOW! eBook
www.wowebook.org
(e)
publicstaticvoiddoIt(){
int[]nums={20,30,40};
intsum=0;
for(inti:nums)
sum+=i;
System.out.println(sum);
}
6.5Stack-BasedExecutionandExceptionPropagation
AnexceptioninJavasignalstheoccurrenceofanerrorsituationduetotheviolationof
somesemanticconstraintoftheJavaprogramminglanguageduringexecution—for
example,arequestedfilecannotbefound,anarrayindexisoutofbounds,oranetwork
linkfailed.Explicitchecksinthecodeforsuchsituationscaneasilyresultin
incomprehensiblecode.Javaprovidesanexceptionhandlingmechanismfor
systematicallydealingwithsucherrorsituations.
Theexceptionmechanismisbuiltaroundthethrow-and-catchparadigm.Tothrowan
exceptionistosignalthatanunexpectedconditionhasoccurred.Tocatchanexceptionis
totakeappropriateactiontodealwiththeexception.Anexceptioniscaughtbyan
exceptionhandler,andtheexceptionneednotbecaughtinthesamecontextinwhichit
wasthrown.Theruntimebehavioroftheprogramdetermineswhichexceptionsare
thrownandhowtheyarecaught.Thethrow-and-catchprincipleisembeddedinthetry-
catch-finallyconstruct.
SeveralthreadscanbeexecutingatthesametimeintheJVM.Eachthreadhasitsown
JVMstack(alsocalledaruntimestack,callstack,andinvocationstackintheliterature)
thatisusedtohandleexecutionofmethods.Eachelementonthestack(calledan
activationframeorastackframe)correspondstoamethodcall.Eachnewcallresultsina
newactivationframebeingpushedonthestack,whichstoresallthepertinentinformation
suchasthelocalvariables.Themethodwiththeactivationframeonthetopofthestackis
theonecurrentlyexecuting.Whenthismethodfinishesexecuting,itsactivationframeis
poppedfromthetopofthestack.Executionthencontinuesinthemethodcorrespondingto
theactivationframethatisnowuncoveredonthetopofthestack.Themethodsonthe
stackaresaidtobeactive,astheirexecutionhasnotcompleted.Atanygiventime,the
activemethodsonaJVMstackmakeupwhatiscalledthestacktraceofathread’s
execution.
Example6.11isasimpleprogramtoillustratemethodexecution.Itcalculatestheaverage
foralistofintegers,giventhesumofalltheintegersandthenumberofintegers.Ituses
threemethods:
•Themethodmain()callsthemethodprintAverage()withparametersgiving
thetotalsumoftheintegersandthetotalnumberofintegers,(1).
•ThemethodprintAverage()inturncallsthemethodcomputeAverage(),
(3).
•ThemethodcomputeAverage()usesintegerdivisiontocalculatetheaverage
andreturnstheresult,(7).
WOW! eBook
www.wowebook.org
Example6.11MethodExecution
Clickheretoviewcodeimage
publicclassAverage1{
publicstaticvoidmain(String[]args){
printAverage(100,20);//(1)
System.out.println(“Exitmain().”);//(2)
}
publicstaticvoidprintAverage(inttotalSum,inttotalNumber){
intaverage=computeAverage(totalSum,totalNumber);//(3)
System.out.println(“Average=”+//(4)
totalSum+”/”+totalNumber+”=”+average);
System.out.println(“ExitprintAverage().”);//(5)
}
publicstaticintcomputeAverage(intsum,intnumber){
System.out.println(“Computingaverage.”);//(6)
returnsum/number;//(7)
}
}
Outputofprogramexecution:
Computingaverage.
Average=100/20=5
ExitprintAverage().
Exitmain().
ExecutionofExample6.11isillustratedinFigure6.7.Eachmethodexecutionisshownas
aboxwiththelocalvariablesdeclaredinthemethod.Theheightoftheboxindicateshow
longamethodisactive.BeforethecalltothemethodSystem.out.println()at(6)
inFigure6.7,thestacktracecomprisesthethreeactivemethods:main(),
printAverage(),andcomputeAverage().Theresult5fromthemethod
computeAverage()isreturnedat(7)inFigure6.7.Theoutputfromtheprogram
correspondswiththesequenceofmethodcallsinFigure6.7.Astheprogramterminates
normally,thisprogrambehavioriscallednormalexecution.
WOW! eBook
www.wowebook.org
Figure6.7MethodExecution
Ifthemethodcallat(1)inExample6.11
Clickheretoviewcodeimage
printAverage(100,20);//(1)
isreplacedwith
Clickheretoviewcodeimage
printAverage(100,0);//(1)
andtheprogramisrunagain,theoutputisasfollows:
Clickheretoviewcodeimage
Computingaverage.
Exceptioninthread“main”java.lang.ArithmeticException:/byzero
atAverage1.computeAverage(Average1.java:18)
atAverage1.printAverage(Average1.java:10)
atAverage1.main(Average1.java:5)
Figure6.8illustratestheprogramexecutionwhenthemethodprintAverage()is
calledwiththearguments100and0at(1).Allgoeswelluntilthereturnstatementat
(7)inthemethodcomputeAverage()isexecuted.Anerrorconditionoccursin
calculatingtheexpressionsum/number,becauseintegerdivisionby0isanillegal
WOW! eBook
www.wowebook.org
operation.ThiserrorconditionissignaledbytheJVMbythrowinganArithmetic-
Exception(§6.6,p.233).ThisexceptionispropagatedbytheJVMthroughtheJVM
stackasexplainednext.
Figure6.8ExceptionPropagation
Figure6.8illustratesthecasewhereanexceptionisthrownandtheprogramdoesnottake
anyexplicitactiontodealwiththeexception.InFigure6.8,executionofthe
computeAverage()methodissuspendedatthepointwheretheexceptionisthrown.
Theexecutionofthereturnstatementat(7)nevergetscompleted.Sincethismethod
doesnothaveanycodetodealwiththeexception,itsexecutionislikewiseterminated
abruptlyanditsactivationframepopped.Wesaythatthemethodcompletesabruptly.The
exceptionisthenofferedtothemethodwhoseactivationisnowonthetopofthestack
(methodprintAverage()).Thismethoddoesnothaveanycodetodealwiththe
exceptioneither,soitsexecutioncompletesabruptly.Thestatementsat(4)and(5)inthe
methodprintAverage()nevergetexecuted.Theexceptionnowpropagatestothelast
activemethod(methodmain()).Thisdoesnotdealwiththeexceptioneither.The
main()methodalsocompletesabruptly.Thestatementat(2)inthemain()method
nevergetsexecuted.Sincetheexceptionisnotcaughtbyanyoftheactivemethods,itis
dealtwithbythemainthread’sdefaultexceptionhandler.Thedefaultexceptionhandler
WOW! eBook
www.wowebook.org
usuallyprintsthenameoftheexception,withanexplanatorymessage,followedbya
printoutofthestacktraceatthetimetheexceptionwasthrown.Anuncaughtexception,as
inthiscase,resultsinthedeathofthethreadinwhichtheexceptionoccurred.
Ifanexceptionisthrownduringtheevaluationoftheleft-handoperandofabinary
expression,thentheright-handoperandisnotevaluated.Similarly,ifanexceptionis
thrownduringtheevaluationofalistofexpressions(e.g.,alistofactualparametersina
methodcall),evaluationoftherestofthelistisskipped.
Ifthelinenumbersinthestacktracearenotprintedintheoutputasshownpreviously,use
thefollowingcommandtoruntheprogram:
Clickheretoviewcodeimage
>java-Djava.compiler=NONEAverage1
6.6ExceptionTypes
ExceptionsinJavaareobjects.Allexceptionsarederivedfromthe
java.lang.Throwableclass.Figure6.9showsapartialhierarchyofclassesderived
fromtheThrowableclass.ThetwomainsubclassesExceptionandError
constitutethemaincategoriesofthrowables,thetermusedtorefertobothexceptionsand
errors.Figure6.9alsoshowsthatnotallexceptionclassesarefoundinthejava.lang
package.
WOW! eBook
www.wowebook.org
Figure6.9PartialExceptionInheritanceHierarchy
TheThrowableclassprovidesaStringvariablethatcanbesettoprovideadetail
messagewhenanexceptionisconstructed.Thepurposeofthedetailmessageistoprovide
moreinformationabouttheactualexception.Allclassesofthrowablesdefineaone-
parameterconstructorthattakesastringasthedetailmessage.
TheclassThrowableprovidesthefollowingcommonmethodstoqueryanexception:
WOW! eBook
www.wowebook.org
StringgetMessage()
Returnsthedetailmessage.
voidprintStackTrace()
Printsthestacktraceonthestandarderrorstream.Thestacktracecomprisesthe
methodinvocationsequenceontheJVMstackwhentheexceptionwasthrown.The
stacktracecanalsobewrittentoaPrintStreamoraPrintWriterby
supplyingsuchadestinationasanargumenttooneofthetwooverloaded
printStackTrace()methods.Anysuppressedexceptionsassociatedwithan
exceptiononthestacktracearealsoprinted.Itwillalsoprintthecauseofan
exception(whichisalsoanexception)ifoneisavailable.
StringtoString()
Returnsashortdescriptionoftheexception,whichtypicallycomprisestheclass
nameoftheexceptiontogetherwiththestringreturnedbythegetMessage()
method.
Indealingwiththrowables,itisimportanttorecognizesituationsinwhichparticular
throwablescanoccur,andthesourcethatisresponsibleforthrowingthem.Bysourcewe
mean:
•TheJVMthatisresponsibleforthrowingthethrowable,or
•Thethrowablethatisexplicitlythrownprogrammaticallybythecodeinthe
applicationorbyanyAPIusedbytheapplication.
Infurtherdiscussionofexceptiontypes,weprovideanoverviewofsituationsinwhich
selectedthrowablescanoccurandthesourceresponsibleforthrowingthem.
The Class
TheclassExceptionrepresentsexceptionsthataprogramwouldnormallywantto
catch.ItssubclassRuntimeExceptionrepresentsmanycommonprogrammingerrors
thatcanmanifestatruntime(seethenextsubsection).Othersubclassesofthe
Exceptionclassdefineothercategoriesofexceptions,suchasI/O-relatedexceptionsin
thejava.iopackage(IOException,FileNotFoundException,
EOFException)anddatabase-relatedexceptionsinthejava.sqlpackage
(SQLException).
ClassNotFoundException
ThesubclassClassNotFoundExceptionsignalsthattheJVMtriedtoloadaclassby
itsstringname,buttheclasscouldnotbefound.Atypicalexampleofthissituationis
whentheclassnameismisspelledwhilestartingprogramexecutionwiththejava
command.ThesourceinthiscaseistheJVMthrowingtheexceptiontosignalthatthe
classcannotbefoundandthereforeexecutioncannotbestarted.
WOW! eBook
www.wowebook.org
The Class
Runtimeexceptionsareallsubclassesofthejava.lang.RuntimeExceptionclass,
whichisasubclassoftheExceptionclass.Astheseruntimeexceptionsareusually
causedbyprogrambugsthatshouldnotoccurinthefirstplace,itisusuallymore
appropriatetotreatthemasfaultsintheprogramdesignandletthembehandledbythe
defaultexceptionhandler.
ArithmeticException
Thisexceptionrepresentssituationswhereanillegalarithmeticoperationisattempted,
suchasintegerdivisionby0.ItistypicallythrownbytheJVM.SeeChapter5fordetails
onillegalarithmeticoperations.
ArrayIndexOutOfBoundsException
Javaprovidesruntimecheckingofthearrayindexvalue,meaningout-of-boundsarray
indices.ThesubclassArrayIndexOutOfBoundsExceptionrepresentsexceptions
thrownbytheJVMthatsignalout-of-bounderrorsspecificallyforarrays—thatis,anerror
inwhichaninvalidindexisusedtoaccessanelementinthearray.Theindexvaluemust
satisfytherelation0≤indexvalue<lengthofthearray.See§3.4,p.58,coveringarrays.
ClassCastException
ThisexceptionisthrownbytheJVMtosignalthatanattemptwasmadetocasta
referencevaluetoatypethatwasnotlegal,suchascastingthereferencevalueofan
IntegerobjecttotheLongtype.Castingreferencevaluesisdiscussedin§7.11,p.320.
IllegalArgumentExceptionandNumberFormatException
TheIllegalArgumentExceptionisthrownprogrammaticallytoindicatethata
methodwascalledwithanillegalorinappropriateargument.Forexample,the
ofPattern(Stringpattern)methodinthe
java.time.format.DateTimeFormatterclassthrowsan
IllegalArgumentExceptionwhentheletterpatternpassedasanargumentis
invalid(§11.4,p.495).
TheclassNumberFormatExceptionisasubclassofthe
IllegalArgumentExceptionclass,andisspecializedtosignalproblemswhen
convertingastringtoanumericvalueiftheformatofthecharactersinthestringisnot
appropriatefortheconversion.Thisexceptionisalsothrownprogrammatically.The
numericwrapperclassesallhavemethodsthatthrowthisexceptionwhenconversionfrom
astringtoanumericvalueisnotpossible(§8.3,p.346).
WOW! eBook
www.wowebook.org
NullPointerException
ThisexceptionistypicallythrownbytheJVMwhenanattemptismadetousethenull
valueasareferencevaluetorefertoanobject.Thismightinvolvecallinganinstance
methodusingareferencethathasthenullvalue,oraccessingafieldusingareference
thathasthenullvalue.Thisprogrammingerrorhasmadethisexceptiononeofthe
exceptionsmostoftenthrownbytheJVM.
The Class
TheclassErroranditssubclassesdefineerrorsthatareinvariablyneverexplicitly
caughtandareusuallyirrecoverable.Notsurprisingly,mostsucherrorsaresignaledbythe
JVM.Apartfromthesubclassesmentionedinthefollowingsubsections,othersubclasses
ofthejava.lang.Errorclassdefineerrorsthatindicateclasslinkage
(LinkageError),thread(ThreadDeath),andvirtualmachine
(VirtualMachineError)problems.
AssertionError
ThesubclassAssertionErrorofthejava.lang.ErrorclassisusedbytheJava
assertionfacility.ThiserroristhrownbytheJVMinresponsetotheconditioninthe
assertstatementevaluatingtofalse.Theassertionfacilityisnotdiscussedinthis
book.
StackOverflowError
ThiserroroccurswhentheJVMstackhasnomoreroomfornewmethodactivation
frames.Insuchacase,wesaythatthestackhasoverflowed.Thissituationcanoccurwhen
methodexecutioninanapplicationrecursestoodeeply.Hereisarecursivemethodto
illustratestackoverflow:
Clickheretoviewcodeimage
publicvoidcallMe(){
System.out.println(“Don’tdothisathome!”);
callMe();
}
Oncethismethodiscalled,itwillkeeponcallingitselfuntiltheJVMstackisfull,
resultingintheStackOverflowErrorbeingthrownbytheJVM.
CheckedandUncheckedExceptions
ExceptforRuntimeException,Error,andtheirsubclasses,allexceptionsare
checkedexceptions.Thatis,thecompilerensuresthatifamethodcanthrowachecked
exception,directlyorindirectly,themethodmustexplicitlydealwithit.Themethodmust
eithercatchtheexceptionandtaketheappropriateaction,orpassontheexceptiontoits
caller(§6.9,p.251).
ExceptionsdefinedbytheErrorandRuntimeExceptionclassesandtheir
subclassesareknownasuncheckedexceptions,meaningthatamethodisnotobligedto
dealwiththesekindsofexceptions(shownwithgraycolorinFigure6.9).Theyareeither
WOW! eBook
www.wowebook.org
irrecoverable(exemplifiedbytheErrorclass),inwhichcasetheprogramshouldnot
attempttodealwiththem,ortheyareprogrammingerrors(exemplifiedbythe
RuntimeExceptionclass)andshouldusuallybedealtwithassuch,andnotas
exceptions.
DefiningCustomizedExceptions
Customizedexceptionsareusuallydefinedtoprovidefine-grainedcategorizationoferror
situations,insteadofusingexistingexceptionclasseswithdescriptivedetailmessagesto
differentiateamongthevarioussituations.Newcustomizedexceptionsareusuallydefined
byeitherextendingtheExceptionclassoroneofitscheckedsubclasses,thereby
makingthenewexceptionschecked,orextendingtheRuntimeExceptionsubclassto
createnewuncheckedexceptions.
Asexceptionsaredefinedbyclasses,theycandeclarefieldsandmethods,thereby
providingmoreinformationastotheircauseandremedywhentheyarethrownand
caught.Thesuper()callcanbeusedtosetthedetailmessagefortheexception.Note
thattheexceptionclassmustbeinstantiatedtocreateanexceptionobjectthatcanbe
thrownandsubsequentlycaughtanddealtwith.Thefollowingcodesketchesaclass
declarationforanexceptionthatcanincludeallpertinentinformationabouttheexception.
Ataminimum,thenewexceptionclassshouldprovideaconstructortosetthedetail
message.
Clickheretoviewcodeimage
publicclassEvacuateExceptionextendsException{
//Data
Datedate;
Zonezone;
TransportModetransport;
//Constructor
publicEvacuateException(Dated,Zonez,TransportModet){
//Calltheconstructorofthesuperclass
super(“Evacuationofzone”+z);
//…
}
//Methods
//…
}
Severalexamplesinsubsequentsectionsillustrateexceptionhandling.
6.7ExceptionHandling: , ,and
Themechanismforhandlingexceptionsisembeddedinthetry-catch-finally
construct,whichhasthefollowingbasicform:
Clickheretoviewcodeimage
try{//tryblock
statements
}catch(exception_type1parameter1){//uni-catchclause
statements
}
…
WOW! eBook
www.wowebook.org
catch(exception_typenparametern){//uni-catchclause
statements
}finally{//finallyclause
statements
}
Afewaspectsaboutthesyntaxofthisconstructshouldbenoted.Foreachtryblock,
therecanbezeroormorecatchclauses(i.e.,itcanhavemultiplecatchclauses),but
onlyonefinallyclause.Thecatchclausesandthefinallyclausemustalways
appearinconjunctionwithatryblock,andintherightorder.Atryblockmustbe
followedbyatleastonecatchclause,orafinallyclausemustbespecified.In
additiontothetryblock,eachcatchclauseandthefinallyclausespecifyablock,
{}.Theblocknotationismandatory.
Exceptionsthrownduringexecutionofthetryblockcanbecaughtandhandledina
catchclause.Eachcatchclausedefinesanexceptionhandler.Theheaderofthe
catchclausespecifiesexactlyoneexceptionparameter.Theexceptiontypemustbeof
theThrowableclassoroneofitssubclasses.Thetypeoftheexceptionparameterofa
catchclauseisspecifiedbyasingleexceptiontypeinthesyntaxgivenearlier,andsuch
acatchclauseiscalledauni-catchclause.
Afinallyclauseisguaranteedtobeexecuted,regardlessofthecauseofexitfromthe
tryblock,orwhetheranycatchclausewasexecuted.Figure6.10showsthreetypical
scenariosofcontrolflowthroughthetry-catch-finallyconstruct.
Figure6.10Thetry-catch-finallyConstruct
Thetryblock,thecatchclause,andthefinallyclauseofatry-catch-
finallyconstructcancontainarbitrarycode,whichmeansthatatry-catch-
WOW! eBook
www.wowebook.org
finallyconstructcanbenestedinanyblockofthetry-catch-finallyconstruct.
However,suchnestingcaneasilymakethecodedifficulttoreadandisbestavoided,if
possible.
The Block
Thetryblockestablishesacontextforexceptionhandling.Terminationofatryblock
occursasaresultofencounteringanexception,orfromsuccessfulexecutionofthecode
inthetryblock.
Thecatchclausesareskippedforallnormalexitsfromthetryblockwhenno
exceptionsarethrown,andcontrolistransferredtothefinallyclauseifoneis
specified((1)inFigure6.10).
Forallexitsfromthetryblockresultingfromexceptions,controlistransferredtothe
catchclauses—ifanysuchclausesarespecified—tofindamatchingcatchclause((2)
inFigure6.10).Ifnocatchclausematchesthethrownexception,controlistransferred
tothefinallyclauseifoneisspecified((3)inFigure6.10).
The Clause
Onlyanexitfromatryblockresultingfromanexceptioncantransfercontroltoa
catchclause.Acatchclausecancatchthethrownexceptiononlyiftheexceptionis
assignabletotheparameterinthecatchclause(§7.8,p.311).Thecodeofthefirstsuch
catchclauseisexecuted,andallothercatchclausesareignored.
Onexitfromacatchclause,normalexecutioncontinuesunlessthereisanyuncaught
exceptionthathasbeenthrownandnothandled.Ifthisisthecase,themethodisaborted
andtheexceptionispropagateduptheJVMstackasexplainedin§6.5,p.230.
Afteracatchclausehasbeenexecuted,controlisalwaystransferredtothefinally
clauseifoneisspecified.Thisisalwaystrueaslongasthereisafinallyclause,
regardlessofwhetherthecatchclauseitselfthrowsanexception.
InExample6.12,themethodprintAverage()callsthemethod
computeAverage()inatry-catchconstructat(4).Thecatchclauseisdeclared
tocatchexceptionsoftypeArithmeticException.Thecatchclausehandlesthe
exceptionbyprintingthestacktraceandsomeadditionalinformationat(7)and(8),
respectively.NormalexecutionoftheprogramisillustratedinFigure6.11,whichshows
thatthetryblockisexecutedbutnoexceptionsarethrown,withnormalexecution
continuingafterthetry-catchconstruct.ThiscorrespondstoScenario1inFigure6.10.
WOW! eBook
www.wowebook.org
Figure6.11ExceptionHandling(Scenario1)
WOW! eBook
www.wowebook.org
Example6.12Thetry-catchConstruct
Clickheretoviewcodeimage
publicclassAverage2{
publicstaticvoidmain(String[]args){
printAverage(100,20);//(1)
System.out.println(“Exitmain().”);//(2)
}
publicstaticvoidprintAverage(inttotalSum,inttotalNumber){
try{//(3)
intaverage=computeAverage(totalSum,totalNumber);//(4)
System.out.println(“Average=”+//(5)
totalSum+”/”+totalNumber+”=”+average);
}catch(ArithmeticExceptionae){//(6)
ae.printStackTrace();//(7)
System.out.println(“ExceptionhandledinprintAverage().”);//(8)
}
System.out.println(“ExitprintAverage().”);//(9)
}
publicstaticintcomputeAverage(intsum,intnumber){
System.out.println(“Computingaverage.”);//(10)
returnsum/number;//(11)
}
}
Outputfromtheprogram,withcallprintAverage(100,20)at(1):
Computingaverage.
Average=100/20=5
ExitprintAverage().
Exitmain().
Outputfromtheprogram,withcallprintAverage(100,0)at(1):
Clickheretoviewcodeimage
Computingaverage.
java.lang.ArithmeticException:/byzero
atAverage2.computeAverage(Average2.java:23)
atAverage2.printAverage(Average2.java:11)
atAverage2.main(Average2.java:5)
ExceptionhandledinprintAverage().
ExitprintAverage().
Exitmain().
However,ifweruntheprograminExample6.12withthefollowingcallin(1):
printAverage(100,0)
anArithmeticExceptionisthrownbytheintegerdivisionoperatorinthemethod
computeAverage().InFigure6.12weseethattheexecutionofthemethod
compute-Average()isstoppedandtheexceptionpropagatedtomethod
printAverage(),whereitishandledbythecatchclauseat(6).Normalexecution
ofthemethodcontinuesat(9)afterthetry-catchconstruct,aswitnessedbytheoutput
fromthestatementsat(9)and(2).ThiscorrespondstoScenario2inFigure6.10.
WOW! eBook
www.wowebook.org
Figure6.12ExceptionHandling(Scenario2)
InExample6.13,themain()methodcallstheprintAverage()methodinatry-
catchconstructat(1).Thecatchclauseat(3)isdeclaredtocatchexceptionsoftype
ArithmeticException.TheprintAverage()methodcallsthe
computeAverage()methodinatry-catchconstructat(7),butherethecatch
clauseisdeclaredtocatchexceptionsoftypeIllegalArgumentException.
ExecutionoftheprogramisillustratedinFigure6.13,whichshowsthatthe
ArithmeticExceptionisfirstpropagatedtothecatchclauseinthe
printAverage()method.Becausethiscatchclausecannothandlethisexception,it
ispropagatedfurthertothecatchclauseinthemain()method,whereitiscaughtand
handled.Normalexecutioncontinuesat(6)aftertheexceptionishandled.
WOW! eBook
www.wowebook.org
Figure6.13ExceptionHandling(Scenario3)
Notethattheexecutionofthetryblockat(7)intheprintAverage()methodis
nevercompleted:Thestatementat(9)isneverexecuted.Thecatchclauseat(10)is
skipped.TheexecutionoftheprintAverage()methodisaborted:Thestatementat
(13)isneverexecuted,andtheexceptionispropagated.ThiscorrespondstoScenario3in
Figure6.10.
WOW! eBook
www.wowebook.org
Example6.13ExceptionPropagation
Clickheretoviewcodeimage
publicclassAverage3{
publicstaticvoidmain(String[]args){
try{//(1)
printAverage(100,0);//(2)
}catch(ArithmeticExceptionae){//(3)
ae.printStackTrace();//(4)
System.out.println(“Exceptionhandledinmain().”);//(5)
}
System.out.println(“Exitmain().”);//(6)
}
publicstaticvoidprintAverage(inttotalSum,inttotalNumber){
try{//(7)
intaverage=computeAverage(totalSum,totalNumber);//(8)
System.out.println(“Average=”+//(9)
totalSum+”/”+totalNumber+”=”+average);
}catch(IllegalArgumentExceptioniae){//(10)
iae.printStackTrace();//(11)
System.out.println(“ExceptionhandledinprintAverage().”);//(12)
}
System.out.println(“ExitprintAverage().”);//(13)
}
publicstaticintcomputeAverage(intsum,intnumber){
System.out.println(“Computingaverage.”);//(14)
returnsum/number;//(15)
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
Computingaverage.
java.lang.ArithmeticException:/byzero
atAverage3.computeAverage(Average3.java:28)
atAverage3.printAverage(Average3.java:16)
atAverage3.main(Average3.java:6)
Exceptionhandledinmain().
Exitmain().
Thescopeoftheparameternameinthecatchclauseistheclauseitself.Asmentioned
earlier,thetypeoftheexceptionobjectmustbeassignabletothetypeoftheargumentin
thecatchclause(§7.8,p.311).Inthebodyofthecatchclause,theexceptionobject
canbequeriedlikeanyotherobjectbyusingtheparametername.Thejavaccompiler
alsocomplainsifacatchclauseforasuperclassexceptionshadowsthecatchclause
forasubclassexception,asthecatchclauseofthesubclassexceptionwillneverbe
executed(asituationknownasunreachablecode).Thefollowingexampleshows
incorrectorderofthecatchclausesat(1)and(2),whichwillresultinacompile-time
error:ThesuperclassExceptionwillshadowthesubclassArithmeticException.
Clickheretoviewcodeimage
…
//Compiler-timeerrorat(1).
WOW! eBook
www.wowebook.org
catch(Exceptione){//(1)superclass
System.out.println(e);
}catch(ArithmeticExceptione){//(2)subclass
System.out.println(e);
}
…
The Clause
Ifthetryblockisexecuted,thenthefinallyclauseisguaranteedtobeexecuted,
regardlessofwhetheranycatchclausewasexecuted.Sincethefinallyclauseis
alwaysexecutedbeforecontroltransferstoitsfinaldestination,thefinallyclausecan
beusedtospecifyanyclean-upcode(e.g.,tofreeresourcessuchasfilesandnet
connections).However,thetry-with-resourcesstatementprovidesabettersolutionfor
handlingresources,andeliminatesuseofthefinallyclauseinmanycases.Butthatisa
storyforanotherday,asthistopicisnotontheOCAJP8exam.
Atry-finallyconstructcanbeusedtocontroltheinterplaybetweentwoactionsthat
mustbeexecutedinthecorrectorder,possiblywithotherinterveningactions.Inthe
followingcode,theoperationinthecalculateAverage()methodisdependenton
thesuccessofthesumNumbers()method,whichischeckedbythevalueofthesum
variablebeforecallingthecalculateAverage()method:
Clickheretoviewcodeimage
intsum=0;
try{
sum=sumNumbers();
//otheractions
}finally{
if(sum>0)calculateAverage();
}
Thiscodeguaranteesthatifthetryblockisentered,thesumNumbers()methodwill
beexecutedfirst,andlaterthecalculateAverage()methodwillbeexecutedinthe
finallyclause,regardlessofhowexecutionproceedsinthetryblock.Wecan,if
desired,includeanycatchclausestohandleanyexceptions.
Ifthefinallyclauseneitherthrowsanexceptionnorexecutesacontroltransfer
statementlikeareturnoralabeledbreak,theexecutionofthetryblockorany
catchclausedetermineshowexecutionproceedsafterthefinallyclause(Figure
6.10,p.239).
•Ifnoexceptionisthrownduringexecutionofthetryblockortheexceptionhas
beenhandledinacatchclause,normalexecutioncontinuesafterthefinally
clause.
•Ifthereisanyuncaughtexception(eitherbecausenocatchclausewasfoundor
becausethecatchclausethrewanexception),themethodisabortedandthe
exceptionispropagatedaftertheexecutionofthefinallyclause.
TheoutputofExample6.14showsthatthefinallyclauseat(9)isexecuted,regardless
ofwhetheranexceptionisthrowninthetryblockat(3).Ifanexceptionisthrown,itis
WOW! eBook
www.wowebook.org
caughtandhandledbythecatchclauseat(6).Aftertheexecutionofthefinally
clauseat(9),normalexecutioncontinuesat(10).
Example6.14Thetry-catch-finallyConstruct
Clickheretoviewcodeimage
publicclassAverage4{
publicstaticvoidmain(String[]args){
printAverage(100,20);//(1)
System.out.println(“Exitmain().”);//(2)
}
publicstaticvoidprintAverage(inttotalSum,inttotalNumber){
try{//(3)
intaverage=computeAverage(totalSum,totalNumber);//(4)
System.out.println(“Average=”+//(5)
totalSum+”/”+totalNumber+”=”+average);
}catch(ArithmeticExceptionae){//(6)
ae.printStackTrace();//(7)
System.out.println(“ExceptionhandledinprintAverage().”);//(8)
}finally{//(9)
System.out.println(“Finallydone.”);
}
System.out.println(“ExitprintAverage().”);//(10)
}
publicstaticintcomputeAverage(intsum,intnumber){
System.out.println(“Computingaverage.”);//(11)
returnsum/number;//(12)
}
}
Outputfromtheprogram,withthecallprintAverage(100,20)at(1):
Computingaverage.
Average=100/20=5
Finallydone.
ExitprintAverage().
Exitmain().
Outputfromtheprogram,withthecallprintAverage(100,0)at(1):
Clickheretoviewcodeimage
Computingaverage.
java.lang.ArithmeticException:/byzero
atAverage4.computeAverage(Average4.java:25)
atAverage4.printAverage(Average4.java:11)
atAverage4.main(Average4.java:5)
ExceptionhandledinprintAverage().
Finallydone.
ExitprintAverage().
Exitmain().
Onexitingfromthefinallyclause,ifthereisanyuncaughtexception,themethodis
abortedandtheexceptionpropagatedasexplainedearlier.ThisisillustratedinExample
6.15.ThemethodprintAverage()isabortedafterthefinallyclauseat(6)has
beenexecuted,astheArithmeticExceptionthrownat(9)isnothandledby
WOW! eBook
www.wowebook.org
anymethod.Inthiscase,theexceptionishandledbythedefaultexceptionhandler.
NoticethedifferenceintheoutputfromExample6.14andExample6.15.
Example6.15Thetry-finallyConstruct
Clickheretoviewcodeimage
publicclassAverage5{
publicstaticvoidmain(String[]args){
printAverage(100,0);//(1)
System.out.println(“Exitmain().”);//(2)
}
publicstaticvoidprintAverage(inttotalSum,inttotalNumber){
try{//(3)
intaverage=computeAverage(totalSum,totalNumber);//(4)
System.out.println(“Average=”+//(5)
totalSum+”/”+totalNumber+”=”+average);
}finally{//(6)
System.out.println(“Finallydone.”);
}
System.out.println(“ExitprintAverage().”);//(7)
}
publicstaticintcomputeAverage(intsum,intnumber){
System.out.println(“Computingaverage.”);//(8)
returnsum/number;//(9)
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
Computingaverage.
Finallydone.
Exceptioninthread“main”java.lang.ArithmeticException:/byzero
atAverage5.computeAverage(Average5.java:22)
atAverage5.printAverage(Average5.java:11)
atAverage5.main(Average5.java:4)
Ifthefinallyclauseexecutesacontroltransferstatement,suchasareturnora
labeledbreak,thiscontroltransferstatementdetermineshowtheexecutionwillproceed
—regardlessofhowthetryblockoranycatchclausewasexecuted.Inparticular,a
valuereturnedbyareturnstatementinthefinallyclausewillsupercedeanyvalue
returnedbyareturnstatementinthetryblockoracatchclause.
Example6.16showshowtheexecutionofacontroltransferstatementsuchasareturn
inthefinallyclauseaffectstheprogramexecution.Thefirstoutputfromtheprogram
showsthattheaverageiscomputedbutthevaluereturnedisfromthereturnstatement
at(8)inthefinallyclause,notfromthereturnstatementat(6)inthetryblock.
ThesecondoutputshowsthattheArithmeticExceptionthrowninthe
computeAverage()methodandpropagatedtotheprintAverage()methodis
nullifiedbythereturnstatementinthefinallyclause.Normalexecutioncontinues
afterthereturnstatementat(8),withthevalue0beingreturnedfromthe
WOW! eBook
www.wowebook.org
printAverage()method.
Ifthefinallyclausethrowsanexception,thisexceptionispropagatedwithallits
ramifications—regardlessofhowthetryblockoranycatchclausewasexecuted.In
particular,thenewexceptionoverrulesanypreviouslyuncaughtexception.
Example6.16ThefinallyClauseandthereturnStatement
Clickheretoviewcodeimage
publicclassAverage6{
publicstaticvoidmain(String[]args){
System.out.println(“Average:”+printAverage(100,20));//(1)
System.out.println(“Exitmain().”);//(2)
}
publicstaticintprintAverage(inttotalSum,inttotalNumber){
intaverage=0;
try{//(3)
average=computeAverage(totalSum,totalNumber);//(4)
System.out.println(“Average=”+//(5)
totalSum+”/”+totalNumber+”=”+average);
returnaverage;//(6)
}finally{//(7)
System.out.println(“Finallydone.”);
returnaverage*2;//(8)
}
}
publicstaticintcomputeAverage(intsum,intnumber){
System.out.println(“Computingaverage.”);//(9)
returnsum/number;//(10)
}
}
Outputfromtheprogram,withcallprintAverage(100,20)in(1):
Computingaverage.
Average=100/20=5
Finallydone.
Average:10
Exitmain().
Outputfromtheprogram,withcallprintAverage(100,0)in(1):
Computingaverage.
Finallydone.
Average:0
Exitmain().
6.8The Statement
Earlierexamplesinthischapterhaveshownhowanexceptioncanbethrownimplicitlyby
theJVMduringexecution.Nowwelookathowanapplicationcanprogrammatically
throwanexceptionusingthethrowstatement.Thegeneralformatofthethrow
statementisasfollows:
Clickheretoviewcodeimage
WOW! eBook
www.wowebook.org
throwobject_reference_expression;
ThecompilerensuresthattheobjectreferenceexpressionisofthetypeThrowableclass
oroneofitssubclasses.AtruntimeaNullPointerExceptionisthrownbytheJVM
iftheobjectreferenceexpressionisnull.ThisensuresthataThrowablewillalways
bepropagated.Adetailmessageisoftenpassedtotheconstructorwhentheexception
objectiscreated.
Clickheretoviewcodeimage
thrownewArithmeticException(“Integerdivisionby0”);
Whenanexceptionisthrown,normalexecutionissuspended.Theruntimesystem
proceedstofindacatchclausethatcanhandletheexception.Thesearchstartsinthe
contextofthecurrenttryblock,propagatingtoanyenclosingtryblocksandthrough
theJVMstacktofindahandlerfortheexception.Anyassociatedfinallyclauseofa
tryblockencounteredalongthesearchpathisexecuted.Ifnohandlerisfound,thenthe
exceptionisdealtwithbythedefaultexceptionhandleratthetoplevel.Ifahandleris
found,normalexecutionresumesafterthecodeinitscatchclausehasbeenexecuted,
barringanyrethrowingofanexception.
InExample6.17,anexceptionisthrownusingathrowstatementat(17).Thisexception
ispropagatedtothemain()method,whereitiscaughtandhandledbythecatch
clauseat(3).Notethatthefinallyclausesat(6)and(14)areexecuted.Execution
continuesnormallyat(7).
WOW! eBook
www.wowebook.org
Example6.17ThrowingExceptions
Clickheretoviewcodeimage
publicclassAverage7{
publicstaticvoidmain(String[]args){
try{//(1)
printAverage(100,0);//(2)
}catch(ArithmeticExceptionae){//(3)
ae.printStackTrace();//(4)
System.out.println(“Exceptionhandledinmain().”);//(5)
}finally{
System.out.println(“Finallyinmain().”);//(6)
}
System.out.println(“Exitmain().”);//(7)
}
publicstaticvoidprintAverage(inttotalSum,inttotalNumber){
try{//(8)
intaverage=computeAverage(totalSum,totalNumber);//(9)
System.out.println(“Average=”+//(10)
totalSum+”/”+totalNumber+”=”+average);
}catch(IllegalArgumentExceptioniae){//(11)
iae.printStackTrace();//(12)
System.out.println(“ExceptionhandledinprintAverage().”);//(13)
}finally{
System.out.println(“FinallyinprintAverage().”);//(14)
}
System.out.println(“ExitprintAverage().”);//(15)
}
publicstaticintcomputeAverage(intsum,intnumber){
System.out.println(“Computingaverage.”);
if(number==0)//(16)
thrownewArithmeticException(“Integerdivisionby0”);//(17)
returnsum/number;//(18)
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
Computingaverage.
FinallyinprintAverage().
java.lang.ArithmeticException:Integerdivisionby0
atAverage7.computeAverage(Average7.java:33)
atAverage7.printAverage(Average7.java:18)
atAverage7.main(Average7.java:6)
Exceptionhandledinmain().
Finallyinmain().
Exitmain().
6.9The Clause
Athrowsclausecanbespecifiedinamethodoraconstructorheadertodeclareany
checkedexceptionsthatcanbethrownbyastatementinthebodyofamethodora
constructor.Itisdeclaredimmediatelyprecedingthebodyofthemethodorthe
constructor.
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
…throwsExceptionType1,ExceptionType2,…,ExceptionTypen{…}
EachExceptionTypeiisanexceptiontype,althoughusuallyonlycheckedexceptionsare
specified.Thecompilerenforcesthatifacheckedexceptioncanbetheresultofexecuting
amethodoraconstructor,theneithertheexceptiontypeofthisexceptionorasupertype
ofitsexceptiontypeisspecifiedinthethrowsclauseofthemethodortheconstructor.
Thethrowsclausecanspecifyuncheckedexceptions,butthisisseldomdoneandthe
compilerdoesnotenforceanyrestrictionsontheirusage.
Thethrowsclauseispartofthecontractthatamethodoraconstructorofferstoits
clients.Thethrowsclausecanspecifyanynumberofexceptiontypes,eventhosethat
arenotthrownbythemethodortheconstructor.Thecompilersimplyensuresthatany
checkedexceptionthatcanactuallybethrowninthemethodorconstructorbodyis
coveredbythethrowsclause.Ofcourse,theclientscannotignorethechecked
exceptionsinthethrowsclause.
Inamethodoraconstructor,acheckedexceptioncanbethrowndirectlybyathrow
statement,orindirectlybycallingothermethodsorconstructorsthatcanthrowachecked
exception.Ifacheckedexceptionisthrown,itmustbehandledinoneofthreeways:
•Byusingatryblockandcatchingtheexceptioninahandleranddealingwithit
•Byusingatryblockandcatchingtheexceptioninahandler,butthrowinganother
exceptionthatiseitheruncheckedordeclaredinitsthrowsclause
•Byexplicitlyallowingpropagationoftheexceptiontoitscallerbydeclaringitinthe
throwsclauseofitsheader
Thismechanism(alsoknownascatch-or-declare)ensuresthatacheckedexceptionwill
bedealtwith,regardlessofthepathofexecution.Thisaidsdevelopmentofrobust
programs,asallowancecanbemadeformanycontingencies.Nativemethodscanalso
declarecheckedexceptionsintheirthrowsclause,butthecompilerisnotabletocheck
themforconsistency.
InExample6.18,anewcheckedexceptionisdefined,wherethecheckedexceptionclass
IntegerDivisionByZeroextendstheExceptionclass.Themethodmain()
callsthemethodprintAverage()inatryblockat(1).Intheifstatementat(9),the
methodcomputeAverage()throwsthecheckedexception
IntegerDivisionByZero.NeitherthecomputeAverage()methodnorthe
printAverage()methodcatchestheexception,butinsteadthrowsittothecaller,as
declaredinthethrowsclausesintheirheadersat(6)and(8).Theexceptionpropagates
tothemain()method.SincetheprintAverage()methodwascalledfromthe
contextofthetryblockat(1)inthemain()method,theexceptionissuccessfully
caughtbyitscatchclauseat(3).Theexceptionishandledandthefinallyclauseat
(4)executed,withnormalexecutionresumingfrom(5).Ifthemethodmain()didnot
catchtheexception,itwouldhavetodeclarethisexceptioninathrowsclause.Inthat
case,theexceptionwouldendupbeinghandledbythedefaultexceptionhandler.
WOW! eBook
www.wowebook.org
Example6.18ThethrowsClause
Clickheretoviewcodeimage
//File:IntegerDivisionByZero.java
publicclassIntegerDivisionByZeroextendsException{
IntegerDivisionByZero(Stringstr){super(str);}
}
//File:Average8.java
publicclassAverage8{
publicstaticvoidmain(String[]args){
try{//(1)
printAverage(100,0);//(2)
}catch(IntegerDivisionByZeroidbz){//(3)
idbz.printStackTrace();
System.out.println(“Exceptionhandledinmain().”);
}finally{//(4)
System.out.println(“Finallydoneinmain().”);
}
System.out.println(“Exitmain().”);//(5)
}
publicstaticvoidprintAverage(inttotalSum,inttotalNumber)
throwsIntegerDivisionByZero{//(6)
intaverage=computeAverage(totalSum,totalNumber);
System.out.println(“Average=”+
totalSum+”/”+totalNumber+”=”+average);
System.out.println(“ExitprintAverage().”);//(7)
}
publicstaticintcomputeAverage(intsum,intnumber)
throwsIntegerDivisionByZero{//(8)
System.out.println(“Computingaverage.”);
if(number==0)//(9)
thrownewIntegerDivisionByZero(“IntegerDivisionByZero”);
returnsum/number;//(10)
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
Computingaverage.
IntegerDivisionByZero:IntegerDivisionByZero
atAverage8.computeAverage(Average8.java:27)
atAverage8.printAverage(Average8.java:17)
atAverage8.main(Average8.java:5)
Exceptionhandledinmain().
Finallydoneinmain().
Exitmain().
Asmentionedearlier,theexceptiontypespecifiedinthethrowsclausecanbea
superclassoftheactualexceptionsthrown;thatis,theexceptionsthrownmustbe
assignabletothetypeoftheexceptionsspecifiedinthethrowsclause.Ifamethodora
constructorcanthrowacheckedexception,thenthethrowsclausemustdeclareits
exceptiontypeorasupertypeofitsexceptiontype;otherwise,acompile-timeerrorwill
occur.IntheprintAverage()method,themethodheadercouldspecifythesuperclass
WOW! eBook
www.wowebook.org
ExceptionofthesubclassIntegerDivisionByZerointhethrowsclause.This
wouldalsoentailthatthemain()methodeithercatchanExceptionordeclareitina
throwsclause.
Clickheretoviewcodeimage
publicstaticvoidmain(String[]args)throwsException{
/*…*/
}
publicstaticvoidprintAverage(inttotalSum,inttotalNumber)throws
Exception{
/*…*/
}
Itisgenerallyconsideredbadprogrammingstyletospecifyexceptionsuperclassesinthe
throwsclauseoftheheaderwhentheactualexceptionsthrownareinstancesoftheir
subclasses.Itisalsorecommendedtousethe@throwstaginaJavadoccommentto
documentthecheckedexceptionsthatamethodoraconstructorcanthrow,togetherwith
anyuncheckedexceptionsthatmightalsoberelevanttocatch.
Overridingthe Clause
Asubclasscanoverrideamethoddefinedinitssuperclassbyprovidinganew
implementation(§7.2,p.268).Whathappenswhenasuperclassmethodwithalistof
exceptionsinitsthrowsclauseisoverriddeninasubclass?Themethoddeclarationin
thesubclassneednotspecifyathrowsclauseifitdoesnotthrowanychecked
exceptions,andifitdoes,itcanspecifyonlycheckedexceptionclassesthatarealreadyin
thethrowsclauseofthesuperclassmethod,orthataresubclassesofthechecked
exceptionsinthethrowsclauseofthesuperclassmethod.Asaconsequence,an
overridingmethodcannotallowmorecheckedexceptionsinitsthrowsclausethanthe
superclassmethoddoes.Allowingmorecheckedexceptionsintheoverridingmethod
wouldcreateproblemsforclientswhoalreadydealwiththeexceptionsspecifiedinthe
superclassmethod.Suchclientswouldbeillpreparedifanobjectofthesubclassthrewa
checkedexceptiontheywerenotpreparedfor.However,therearenorestrictionson
specifyinguncheckedexceptionsinthethrowsclauseoftheoverridingmethod.The
precedingdiscussionalsoappliestomethodsfromaninterfacethataclassimplements,as
thesemethodsareoverriddenbyanyclassimplementingtheinterface.
Inthefollowingcode,themethodsuperclassMethodXinsuperclassAisoverridden
insubclassB.ThethrowsclauseofthemethodinsubclassBat(2)specifiesasubsetof
thecheckedexceptionsspecifiedinthethrowsclauseat(1)andaddsthemorespecific
subclassexception,SubFirstException,ofthesuperclassexception,First-
Exception,specifiedinthethrowsclauseat(1).
Clickheretoviewcodeimage
//Newexceptionclasses:
classFirstExceptionextendsException{}
classSecondExceptionextendsException{}
classThirdExceptionextendsException{}
classSubFirstExceptionextendsFirstException{}
WOW! eBook
www.wowebook.org
//Superclass
classA{
//…
protectedvoidsuperclassMethodX()
throwsFirstException,SecondException,ThirdException{/*…*/}//
(1)
//…
}
//Subclass
classBextendsA{
//…
@OverrideprotectedvoidsuperclassMethodX()
throwsFirstException,ThirdException,SubFirstException{/*…*/}//
(2)
//…
}
6.10AdvantagesofExceptionHandling
Robustnessreferstotheabilityofasoftwaresystemtorespondtoerrorsduringexecution.
Asystemshouldrespondtounexpectedsituationsatruntimeinaresponsibleway.
Applicationsthatprovidetheuserwithfrequentcrypticmessageswitherrorcodesorthat
repeatedlygivetheuserthesilenttreatmentwhensomethinggoeswrongcanhardlybe
consideredrobust.
TheexceptionhandlingmechanisminJavaoffersthefollowingadvantagesthatfacilitate
developingrobustapplicationsinJava:
•SeparationofExceptionHandlingCode
Thecodeforhandlingerrorsituationscanbeseparatedfromthecodeforthe
programlogicbyusingtheexceptionhandlingconstructsprovidedbythelanguage.
Codethatcanresultinerrorsituationsisconfinedinthetryblock,andtheir
handlinginthecatchclause.
•TransparentExceptionPropagation
PropagationofacheckedexceptionintheJVMstackcannotbeignoredbyanactive
method.Themethodmustcomplywiththecatch-or-declarerequirement:either
catchandhandletheexception,orpropagateitbydeclaringitinthemethod’s
throwsclause.Errorsituationscausingexceptionpropagationarethusalways
detected,andcanbecaughtandremedied.
•ExceptionCategorizationandSpecialization
TheexceptionanderrorclassesintheJavaSEplatformAPIareorganizedinan
inheritancehierarchy(Figure6.9,p.234).Classeshigherupinthishierarchy
representcategoriesofexceptionsanderrors(Exception,
RuntimeException,IO-Exception,Error),whereasclasseslowerinthis
hierarchyrepresentmorespecificexceptionsanderrors
(NullPointerException,FileNotFoundException,
AssertionError).Thetry-catchconstructallowsflexibilityincatchingand
handlingexceptions.Acatchclausecanspecifyanexceptioncategoryforcoarse-
grainedexceptionhandling,astheexceptioncategoryclasswillsubsumeitsmore
WOW! eBook
www.wowebook.org
specificexceptionsubclasses,oritcanspecifyamorespecificexceptionclassfor
fine-grainedexceptionhandling.Bestpracticedictatesthatfine-grainedexception
handlingbeused.
ReviewQuestions
6.16Whichdigits,andinwhichorder,willbeprintedwhenthefollowingprogramis
run?
Clickheretoviewcodeimage
publicclassDemoClass{
publicstaticvoidmain(String[]args){
intk=0;
try{
inti=5/k;
}catch(ArithmeticExceptione){
System.out.println(“1”);
}catch(RuntimeExceptione){
System.out.println(“2”);
return;
}catch(Exceptione){
System.out.println(“3”);
}finally{
System.out.println(“4”);
}
System.out.println(“5”);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillonlyprint5.
(b)Theprogramwillonlyprint1and4,inthatorder.
(c)Theprogramwillonlyprint1,2,and4,inthatorder.
(d)Theprogramwillonlyprint1,4,and5,inthatorder.
(e)Theprogramwillonlyprint1,2,4,and5,inthatorder.
(f)Theprogramwillonlyprint3and5,inthatorder.
6.17Giventhefollowingprogram,whichstatementsaretrue?
Clickheretoviewcodeimage
publicclassExceptions{
publicstaticvoidmain(String[]args){
try{
if(args.length==0)return;
System.out.println(args[0]);
}finally{
System.out.println(“Theend”);
}
}
}
Selectthetwocorrectanswers.
WOW! eBook
www.wowebook.org
(a)Ifrunwithnoarguments,theprogramwillproducenooutput.
(b)Ifrunwithnoarguments,theprogramwillprintTheend.
(c)TheprogramwillthrowanArrayIndexOutOfBoundsException.
(d)Ifrunwithoneargument,theprogramwillsimplyprintthegivenargument.
(e)Ifrunwithoneargument,theprogramwillprintthegivenargumentfollowed
by"Theend".
6.18Whichofthefollowingstatementsaretrue?
Selectthetwocorrectanswers.
(a)Ifanexceptionisnotcaughtinamethod,themethodwillterminateandnormal
executionwillresume.
(b)Anoverridingmethodmustdeclarethatitthrowsthesameexceptionclassesas
themethoditoverrides.
(c)Themain()methodofaprogramcandeclarethatitthrowschecked
exceptions.
(d)Amethoddeclaringthatitthrowsanexceptionofacertainclassmaythrow
instancesofanysubclassofthatexceptionclass.
(e)finallyclausesareexecutedif,andonlyif,anexceptiongetsthrownwhile
insidethecorrespondingtryblock.
6.19Whichdigits,andinwhichorder,willbeprintedwhenthefollowingprogramis
run?
Clickheretoviewcodeimage
publicclassRQ6A19{
publicstaticvoidmain(String[]args)throwsInterruptedException{
try{
throwIt();
System.out.println(“1”);
}finally{
System.out.println(“2”);
}
System.out.println(“3”);
}
//InterruptedExceptionisadirectsubclassofException.
staticvoidthrowIt()throwsInterruptedException{
thrownewInterruptedException(“Timetogohome.”);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillprint2andthrowInterruptedException.
(b)Theprogramwillprint1and2,inthatorder.
(c)Theprogramwillprint1,2,and3,inthatorder.
WOW! eBook
www.wowebook.org
(d)Theprogramwillprint2and3,inthatorder.
(e)Theprogramwillprint3and2,inthatorder.
(f)Theprogramwillprint1and3,inthatorder.
6.20Whatiswrongwiththefollowingcode?
Clickheretoviewcodeimage
publicclassRQ6A20{
publicstaticvoidmain(String[]args)throwsA{
try{
action();
}finally{
System.out.println(“Done.”);
}catch(Ae){
throwe;
}
}
publicstaticvoidaction()throwsB{
thrownewB();
}
}
classAextendsThrowable{}
classBextendsA{}
Selecttheonecorrectanswer.
(a)Themain()methodmustdeclarethatitthrowsB.
(b)Thefinallyclausemustfollowthecatchclauseinthemain()method.
(c)Thecatchclauseinthemain()methodmustdeclarethatitcatchesBrather
thanA.
(d)Asingletryblockcannotbefollowedbybothcatchandfinallyclauses.
(e)ThedeclarationofclassAisillegal.
6.21Whichthrowsclauseshouldbeinsertedat(1)fortheoverridingmethod
compute()inthefollowingcodesothatthecodewillcompilewithouterrors?
Clickheretoviewcodeimage
classA{
//InterruptedExceptionisadirectsubclassofException.
voidcompute()throwsArithmeticException,InterruptedException{
div(5,5);
}
intdiv(inti,intj)throwsArithmeticException{
returni/j;
}
}
publicclassClientextendsA{
voidcompute()/*(1)INSERTthrowsCLAUSEHERE.*/{
try{
div(5,0);
WOW! eBook
www.wowebook.org
}catch(ArithmeticExceptione){
return;
}
thrownewRuntimeException(“ArithmeticExceptionwasexpected.”);
}
}
Selecttheonecorrectanswer.
(a)Nothrowsclauseisnecessary.
(b)throwsArithmeticException
(c)throwsInterruptedException
(d)throwsRuntimeException
(e)throwsArithmeticException,InterruptedException
ChapterSummary
Thefollowinginformationwascoveredinthischapter:
•Theselectionstatements:if,if-else,switch
•Theiterationstatements:for(;;),for(:),while,do-while
•Thetransferstatements:break,continue,return
•ExceptionhandlingandexceptionclassesinthecoreAPI
•Definingcustomizedexceptiontypes
•Thetry-catch-finallyconstructandcontrolflowpathsthroughtheconstruct
•Usingmultiplecatchclauseswiththetrystatement
•Throwingexceptionsprogrammaticallywiththethrowstatement
•Usingthethrowsclausetospecifycheckedexceptions
ProgrammingExercises
6.1Createdifferentversionsofaprogramthatfindsalltheprimessmallerthan100.
Createoneversionthatusesonlythefor(;;)loop(i.e.,nowhileordo-
while).Createanotherversionthatusesonlythewhileloop.
6.2Hereisaskeletonofasystemforsimulatinganuclearpowerplant.Implementthe
methodsintheclassnamedControl.Modifythemethoddeclarationsif
necessary.TheJavadoccommentsforeachmethodgiveadescriptionofwhatthe
implementationshoulddo.Someofthemethodsintheotherclasseshave
unspecifiedimplementations.Assumethatthesemethodshavebeenproperly
implementedandprovidehookstotherestofthesystem.
Clickheretoviewcodeimage
packageenergy;
WOW! eBook
www.wowebook.org
/**APowerPlantwithareactorcore.*/
publicclassPowerPlant{
/**Eachpowerplanthasareactorcore.
ThisfieldhaspackageaccessibilitysothattheControlclass,
definedinthesamepackage,canaccessit.*/
finalReactorcore;
/**Initializesthepowerplant,createsareactorcore.*/
publicPowerPlant(){
core=newReactor();
}
/**Soundsthealarmtoevacuatethepowerplant.*/
publicvoidsoundEvacuateAlarm(){
//…implementationunspecified…
}
/**@returnthelevelofreactoroutputthatismostdesirableatthis
time.
(Unitsareunspecified.)*/
publicintgetOptimalThroughput(){
//…implementationunspecified…
return0;
}
/**Themainentrypointoftheprogram:setsupaPowerPlantobject
andaControlobjectandletstheControlobjectrunthepowerplant.
*/
publicstaticvoidmain(String[]args){
PowerPlantplant=newPowerPlant();
Controlctrl=newControl(plant);
ctrl.runSystem();
}
}
//______________________________________________________________________________
/**Areactorcorethathasathroughputthatcanbeeitherdecreasedor
increased.*/
classReactor{
/**@returnthecurrentthroughputofthereactor.(Unitsareunspecified.)
*/
publicintgetThroughput(){
//…implementationunspecified…
return0;
}
/**@returntrueifthereactorstatusiscritical,falseotherwise.*/
publicbooleanisCritical(){
//…implementationunspecified…
returnfalse;
}
/**Asksthereactortoincreasethroughput.*/
voidincreaseThroughput()throwsReactorCritical{
//…implementationunspecified…
}
/**Asksthereactortodecreasethroughput.*/
voiddecreaseThroughput(){
//…implementationunspecified…
}
WOW! eBook
www.wowebook.org
}
//______________________________________________________________________________
/**Thisexceptionclassshouldbeusedtoreportthatthereactorstatusis
critical.*/
classReactorCriticalextendsException{}
//______________________________________________________________________________
/**Acontrollerthatwillmanagethepowerplanttomakesurethatthe
reactorrunswithoptimalthroughput.*/
classControl{
privatefinalPowerPlantthePlant;
staticfinalintTOLERANCE=10;
/**@parampthepowerplanttocontrol*/
publicControl(PowerPlantp){
thePlant=p;
}
/**Runsthepowerplantbycontinuouslymonitoringthe
optimalthroughputandtheactualthroughputofthereactor.
Ifthethroughputsdifferbymorethan10units(i.e.tolerance),
adjustthereactorthroughput.
Ifthereactorgoescritical,theevacuatealarmis
soundedandthereactorisshutdown.
TherunSystem()methodcallsthemethodsneedAdjustment(),
adjustThroughput(),andshutdown().*/
publicvoidrunSystem(){
//…provideimplementationhere…
}
/**Reportswhetherthethroughputofthereactorneedsadjusting.
Thismethodshouldalsomonitorandreportifthereactorgoes
critical.
@paramtargetthedesiredthroughput.
@returntrueiftheoptimalandactualthroughputvaluesdifferby
morethan10units.*/
publicbooleanneedAdjustment(inttarget){
//…provideimplementationhere…
returntrue;
}
/**AdjuststhethroughputofthereactorbycallingincreaseThroughput()
anddecreaseThroughput()methodsuntiltheactualthroughputiswithin
10unitsofthetargetthroughput.
@paramtargetthedesiredthroughput.*/
publicvoidadjustThroughput(inttarget){
//…provideimplementationhere…
}
/**Shutsdownthereactorbyloweringthethroughputto0.*/
publicvoidshutdown(){
//…provideimplementationhere…
}
}
WOW! eBook
www.wowebook.org
7.Object-OrientedProgramming
7.1SingleImplementationInheritance
Inheritanceisoneofthefundamentalmechanismsforcodereuseinobject-oriented
programming(OOP).Itallowsnewclassestobederivedfromexistingones.Thenew
class(alsocalledasubclass,subtype,derivedclass,orchildclass)caninheritmembers
fromtheoldclass(alsocalledasuperclass,supertype,baseclass,orparentclass).The
subclasscanaddnewbehaviorandpropertiesand,undercertaincircumstances,modifyits
inheritedbehavior.
InJava,implementationinheritance(alsoknownasclassinheritance)isachievedby
extendingclasses(i.e.,addingnewfieldsandmethods)andmodifyinginheritedmembers
(§7.2,p.268).Inheritanceofmembersiscloselytiedtotheirdeclaredaccessibility.Ifa
superclassmemberisaccessiblebyitssimplenameinthesubclass(withouttheuseofany
extrasyntaxlikesuper),thatmemberisconsideredinherited.Conversely,private,
overridden,andhiddenmembersofthesuperclassarenotinherited.Inheritanceshouldnot
WOW! eBook
www.wowebook.org
beconfusedwiththeexistenceofsuchmembersinthestateofasubclassobject(Example
7.1).
Asubclassspecifiesthenameofitssuperclassinthesubclassheaderusingtheextends
clause.
Clickheretoviewcodeimage
classTubeLightextendsLight{…}//TubeLightisasubclassofLight.
Thesubclassspecifiesonlytheadditionalnewandmodifiedmembersinitsclassbody.
Therestofitsdeclarationismadeupofitsinheritedmembers.Ifnoextendsclauseis
specifiedintheheaderofaclassdeclaration,theclassimplicitlyinheritsfromthe
java.lang.Objectclass(§8.2,p.342).Thisimplicitinheritanceisassumedinthe
declarationoftheLightclassat(1)inExample7.1.AlsoinExample7.1,thesubclass
TubeLightat(2)explicitlyusestheextendsclauseandspecifiesonlymembersother
thanthosethatitalreadyinheritsfromthesuperclassLight(which,inturn,inheritsfrom
theObjectclass).MembersofthesuperclassLight,whichareaccessiblebytheir
simplenamesinthesubclassTubeLight,areinheritedbythesubclass,asevidentfrom
theoutputinExample7.1.
Privatemembersofthesuperclassarenotinheritedbythesubclassandcanbeaccessed
onlyindirectly.TheprivatefieldindicatorofthesuperclassLightisnotinherited,
butexistsinthesubclassobjectandisindirectlyaccessiblethroughpublicmethods.
Usingappropriateaccessibilitymodifiers,thesuperclasscanlimitwhichmemberscanbe
accesseddirectlyand,therefore,inheritedbyitssubclasses(§4.7,p.123).Asshownin
Example7.1,thesubclasscanusetheinheritedmembersasiftheyweredeclaredinits
ownclassbody.Thisisnotthecaseformembersthataredeclaredasprivateinthe
superclass.Membersthathavepackageaccessibilityinthesuperclassarealsonot
inheritedbysubclassesinotherpackages,asthesemembersareaccessiblebytheirsimple
namesonlyinsubclasseswithinthesamepackageasthesuperclass.
Sinceconstructors(§7.5,p.282)arenotmembersofaclass,theyarenotinheritedbya
subclass.
Example7.1ExtendingClasses:InheritanceandAccessibility
Clickheretoviewcodeimage
//File:Utility.java
classLight{//(1)
//Instancefields:
intnoOfWatts;//Wattage
privatebooleanindicator;//Onoroff
protectedStringlocation;//Placement
//Staticfield:
privatestaticintcounter;//NumberofLightobjectscreated
//No-argumentconstructor:
Light(){
noOfWatts=50;
indicator=true;
location=“X”;
WOW! eBook
www.wowebook.org
counter++;
}
//Instancemethods:
publicvoidswitchOn(){indicator=true;}
publicvoidswitchOff(){indicator=false;}
publicbooleanisOn(){returnindicator;}
privatevoidprintLocation(){
System.out.println(“Location:”+location);
}
//Staticmethods:
publicstaticvoidwriteCount(){
System.out.println(“Numberoflights:”+counter);
}
//…
}
//______________________________________________________________________________
classTubeLightextendsLight{//(2)Subclassusestheextends
clause.
//Instancefields:
privateinttubeLength=54;
privateintcolorNo=10;
//Instancemethods:
publicintgetTubeLength(){returntubeLength;}
publicvoidprintInfo(){
System.out.println(“Fromthesubclass:”);
System.out.println(“Tubelength:“+tubeLength);
System.out.println(“Colornumber:”+colorNo);
System.out.println(“Tubelength:“+getTubeLength());
System.out.println();
System.out.println(“Fromthesuperclass:”);
System.out.println(“Wattage:“+noOfWatts);//Inherited.
//System.out.println(“Indicator:“+indicator);//Notinherited.
System.out.println(“Location:“+location);//Inherited.
//System.out.println(“Counter:“+counter);//Notinherited.
switchOn();//Inherited
switchOff();//Inherited
System.out.println(“Indicator:“+isOn());//Inherited.
//printLocation();//Notinherited.
writeCount();//Inherited.
}
//…
}
//______________________________________________________________________________
publicclassUtility{//(3)
publicstaticvoidmain(String[]args){
newTubeLight().printInfo();
}
}
Outputfromtheprogram:
Fromthesubclass:
Tubelength:54
Colornumber:10
Tubelength:54
Fromthesuperclass:
Wattage:50
Location:X
WOW! eBook
www.wowebook.org
Indicator:false
Numberoflights:1
InJava,aclasscanextendonlyoneclass;thatis,itcanhaveonlyoneimmediate
superclass.Thiskindofinheritanceissometimescalledsingleorlinearimplementation
inheritance.Thenameisappropriate,asthesubclassinheritstheimplementationsofits
superclassmembers.Theinheritancerelationshipcanbedepictedasaninheritance
hierarchy(alsocalledaclasshierarchy).Classeshigherupinthehierarchyaremore
generalized(oftencalledbroader),astheyabstracttheclassbehavior.Classeslowerdown
inthehierarchyaremorespecialized(oftencallednarrower),astheycustomizethe
inheritedbehaviorbyadditionalpropertiesandbehavior.Figure7.1illustratesthe
inheritancerelationshipbetweentheclassLight,whichrepresentsthemoregeneral
abstraction,anditsmorespecializedsubclasses.Thejava.lang.Objectclassis
alwaysatthetop(theroot)ofanyJavainheritancehierarchy,asallclasses,withthe
exceptionoftheObjectclassitself,inherit(eitherdirectlyorindirectly)fromthisclass.
Figure7.1InheritanceHierarchy
WOW! eBook
www.wowebook.org
Relationships:is-aandhas-a
Inheritancedefinestherelationshipis-a(alsocalledthesuperclass–subclassrelationship)
betweenasuperclassanditssubclasses.Thus,anobjectofasubclassis-asuperclass
object,andcanbeusedwhereveranobjectofthesuperclasscanbeused.Thiscriterionis
oftenemployedasalitmustestforchoosinginheritanceinobject-orienteddesign.Ithas
particularconsequencesforhowobjectscanbeused.AnobjectoftheTubeLightclass
is-anobjectofthesuperclassLight.ReferringtoFigure7.1,anobjectofthe
TubeLightclasscanbeusedwhereveranobjectofthesuperclassLightcanbeused.
Theinheritancerelationshipistransitive:IfclassBextendsclassAandclassCextends
classB,thenclassCwillalsoinheritfromclassAviaclassB.Anobjectofthe
SpotLightBulbclassis-anobjectoftheclassLight.Theis-arelationshipdoesnot
holdbetweenpeerclasses:AnobjectoftheLightBulbclassisnotanobjectoftheclass
TubeLight,andviceversa.
Whereasinheritancedefinestherelationshipis-abetweenasuperclassanditssubclasses,
aggregationdefinestherelationshiphas-a(alsocalledthewhole–partrelationship)
betweenaninstanceofaclassanditsconstituents(alsocalledparts).Aggregation
comprisestheusageofobjects.AninstanceofclassLighthas(oruses)thefollowing
parts:afieldtostoreitswattage(noOfWatts),afieldtostorewhetheritisonoroff
(indicator),andaStringobjecttostoreitslocation(denotedbythefieldreference
location).InJava,acompositeobjectcannotcontainotherobjects.Itcanstoreonly
referencevaluesofitsconstituentobjectsinitsfields.Thisrelationshipdefinesan
aggregationhierarchy(alsocalledobjecthierarchy)thatembodiesthehasarelationship.
Asexplainedin§1.7,p.12,constituentobjectscanbesharedbetweenobjects.Iftheir
lifetimesaredependentonthelifetimeofthecompositeobject,thenthisrelationshipis
calledcomposition,andimpliesstrongownershipofthepartsbythecompositeobject.
Inheritanceandaggregationarecomparedin§7.13,p.331.
TheSupertype–SubtypeRelationship
Aclassdefinesareferencetype,adatatypewhoseobjectscanbeaccessedonlyby
references.Thereforetheinheritancehierarchycanberegardedasatypehierarchy,
embodyingthesupertype–subtyperelationshipbetweenreferencetypes.Inthecontextof
Java,thesupertype–subtyperelationshipimpliesthatthereferencevalueofasubtype
objectcanbeassignedtoasupertypereference,becauseasubtypeobjectcanbe
substitutedforasupertypeobject.Thisassignmentinvolvesawideningreference
conversion(§5.1,p.145),asreferencesareassigneduptheinheritancehierarchy.Using
thereferencetypesinExample7.1,thefollowingcodeassignsthereferencevalueofan
objectofthesubtypeTubeLighttothereferencelightofthesupertypeLight:
Clickheretoviewcodeimage
Lightlight=newTubeLight();//(1)wideningreference
conversion
Animplicitwideningconversiontakesplaceunderassignment,asthereferencevalueofa
narrowertype(subtypeTubeLight)objectisbeingassignedtoareferenceofbroader
type(supertypeLight).Wecannowusethereferencelighttoinvokethosemethods
WOW! eBook
www.wowebook.org
onthesubtypeobjectthatareinheritedfromthesupertypeLight:
Clickheretoviewcodeimage
light.switchOn();//(2)
Notethatthecompilerknowsaboutonlythedeclaredtype(statictype)ofthereference
light,whichisLight,andensuresthatonlymethodsfromthistypecanbecalled
usingthereferencelight.However,atruntime,thereferencelightwillrefertoan
objectofthesubtypeTubeLightwhenthecalltothemethodswitchOn()is
executed.Itisthetypeoftheobjectthatthereferencereferstoatruntimethatdetermines
whichmethodisexecuted.ThesubtypeobjectinheritstheswitchOn()methodfromits
supertypeLight,sothismethodisexecuted.Thetypeoftheobjectthatthereference
referstoatruntimeisoftencalledthedynamictypeofthereference.
OnemightbetemptedtoinvokemethodsexclusivetotheTubeLightsubtypeviathe
supertypereferencelight:
Clickheretoviewcodeimage
light.getTubeLength();//(3)NotOK.
Thiscodewillnotwork,asthecompilerdoesnotknowwhichobjectthereferencelight
willdenoteatruntime;itmerelyknowsthedeclaredtypeofthereference.Asthe
declarationoftheclassLightdoesnothaveamethodcalledgetTubeLength(),this
methodcallat(3)resultsinacompile-timeerror.Asweshallseelaterinthischapter,
elicitingsubtype-specificbehaviorusingasupertypereferencerequiresanarrowing
referenceconversionwithanexplicitcast(§7.11,p.320).
TherestofthischapterelaboratesonvariousaspectsofOOP.Understandingthemis
fundamentalinunderstandingtheconsequencesofthesubtype–supertyperelationship.
7.2OverridingMethods
InstanceMethodOverriding
Undercertaincircumstances,asubclasscanoverrideinstancemethodsthatitinheritsfrom
itssuperclass.Overridingsuchamethodallowsthesubclasstoprovideitsown
implementationofthemethod.Theoverriddenmethodinthesuperclassisnotinheritedby
thesubclass.Whenthemethodisinvokedonanobjectofthesubclass,itisthemethod
implementationinthesubclassthatisexecuted.Thenewmethodinthesubclassmust
abidebythefollowingrulesofmethodoverriding:
•Thenewmethoddefinitioninthesubclassmusthavethesamemethodsignature.In
otherwords,themethodname,andthetypesandthenumberofparameters,
includingtheirorder,mustbethesameasintheoverriddenmethodofthe
superclass.
Whetherparametersintheoverridingmethodshouldbefinalisatthediscretion
ofthesubclass(§3.7,p.86).Amethod’ssignaturedoesnotcomprisethefinal
modifierofparameters,onlytheirtypesandorder.
•Thereturntypeoftheoverridingmethodcanbeasubtypeofthereturntypeofthe
WOW! eBook
www.wowebook.org
overriddenmethod(calledcovariantreturn,p.273).
•Thenewmethoddefinitioncannotnarrowtheaccessibilityofthemethod,butitcan
widenit(§4.7,p.123).
•Thenewmethoddefinitioncanthroweitherallornone,orasubsetofthechecked
exceptions(includingtheirsubclasses)thatarespecifiedinthethrowsclauseof
theoverriddenmethodinthesuperclass(§6.9,p.253).
Theserequirementsalsoapplytointerfaces,whereasubinterfacecanoverrideabstract
anddefaultmethoddeclarationsfromitssuperinterfaces(§7.6,p.290).
Example7.2illustratesoverriding,overloading,andhidingofmembersinaclass.Figure
7.2givesanoverviewofthetwomainclassesinExample7.2.Thenewdefinitionofthe
energyCost()methodat(7)inthesubclassTubeLighthasthesamesignatureand
thesamereturntypeasthemethodat(2)inthesuperclassLight.Thenewdefinition
specifiesasubsetoftheexceptions(ZeroHoursException)thrownbytheoverridden
method(theexceptionclassInvalidHoursExceptionisasuperclassof
NegativeHoursExceptionandZeroHoursException).Thenewdefinitionalso
widenstheaccessibility(public)fromwhatitwasintheoverriddendefinition
(protected).Theoverridingmethoddeclarestheparametertobefinal,butthishas
nobearinginoverridingthemethod.
Figure7.2InheritanceHierarchyforExample7.2andExample7.3
Theastutereaderwillhavenoticedthe@Overrideannotationprecedingthemethod
definitionat(7).Thecompilerwillnowreportanerrorifthemethoddefinitionat(7)does
notoverrideaninheritedmethod.Theannotationhelpstoensurethatthemethod
definitionoverridestheinheritedmethod,ratherthanoverloadinganothermethodsilently.
WOW! eBook
www.wowebook.org
InvocationofthemethodenergyCost()onanobjectofsubclassTubeLightusing
referencesofthesubclassandthesuperclassat(15)and(16)resultsinthenewdefinition
at(7)beingexecuted,sincebothreferencesarealiasesoftheTubeLightobjectcreated
at(12).
Clickheretoviewcodeimage
tubeLight.energyCost(50);//(15)Invokesmethodat(7).
light1.energyCost(50);//(16)Invokesmethodat(7).
Notsurprisingly,theinvocationofthemethodenergyCost()onanobjectof
superclassLight,usingareferenceofthesuperclassat(17),resultsintheoverridden
definitionat(2)beingexecuted:
Clickheretoviewcodeimage
light2.energyCost(50);//(17)Invokesmethodat(2).
Example7.2Overriding,Overloading,andHiding
Clickheretoviewcodeimage
//File:Client2.java
//Exceptions
classInvalidHoursExceptionextendsException{}
classNegativeHoursExceptionextendsInvalidHoursException{}
classZeroHoursExceptionextendsInvalidHoursException{}
classLight{
protectedStringlightType=“GenericLight”;//(1)Instancefield
protecteddoubleenergyCost(intnoOfHours)//(2)Instancemethod
throwsInvalidHoursException{
System.out.print(“>>Light.energyCost(int):“);
if(noOfHours<0)
thrownewNegativeHoursException();
doublecost=00.20*noOfHours;
System.out.println(“Energycostfor”+lightType+“:”+cost);
returncost;
}
publicLightmakeInstance(){//(3)Instancemethod
System.out.print(“>>Light.makeInstance():“);
returnnewLight();
}
publicvoidshowSign(){//(4)Instancemethod
System.out.print(“>>Light.showSign():“);
System.out.println(“Lettherebelight!”);
}
publicstaticvoidprintLightType(){//(5)Staticmethod
System.out.print(“>>StaticLight.printLightType():“);
System.out.println(“GenericLight”);
}
}
//______________________________________________________________________________
classTubeLightextendsLight{
publicstaticStringlightType=“TubeLight”;//(6)Hidingfieldat(1).
WOW! eBook
www.wowebook.org
@Override
publicdoubleenergyCost(finalintnoOfHours)//(7)Overridinginstance
throwsZeroHoursException{//methodat(2).
System.out.print(“>>TubeLight.energyCost(int):“);
if(noOfHours==0)
thrownewZeroHoursException();
doublecost=00.10*noOfHours;
System.out.println(“Energycostfor”+lightType+“:”+cost);
returncost;
}
publicdoubleenergyCost(){//(8)Overloadingmethodat(7).
System.out.print(“>>TubeLight.energyCost():“);
doubleflatrate=20.00;
System.out.println(“Energycostfor”+lightType+“:”+flatrate);
returnflatrate;
}
@Override
publicTubeLightmakeInstance(){//(9)Overridinginstancemethodat
(3).
System.out.print(“>>TubeLight.makeInstance():“);
returnnewTubeLight();
}
publicstaticvoidprintLightType(){//(10)Hidingstaticmethodat(5).
System.out.print(“>>StaticTubeLight.printLightType():“);
System.out.println(lightType);
}
}
//______________________________________________________________________________
publicclassClient2{
publicstaticvoidmain(String[]args)//(11)
throwsInvalidHoursException{
TubeLighttubeLight=newTubeLight();//(12)
Lightlight1=tubeLight;//(13)Aliases.
Lightlight2=newLight();//(14)
System.out.println(“Invokeoverriddeninstancemethod:”);
tubeLight.energyCost(50);//(15)Invokesmethodat(7).
light1.energyCost(50);//(16)Invokesmethodat(7).
light2.energyCost(50);//(17)Invokesmethodat(2).
System.out.println(
”\nInvokeoverriddeninstancemethodwithcovariantreturn:”);
System.out.println(
light2.makeInstance().getClass());//(18)Invokesmethodat(3).
System.out.println(
tubeLight.makeInstance().getClass());//(19)Invokesmethodat(9).
System.out.println(“\nAccesshiddenfield:”);
System.out.println(tubeLight.lightType);//(20)Accessesfieldat(6).
System.out.println(light1.lightType);//(21)Accessesfieldat(1).
System.out.println(light2.lightType);//(22)Accessesfieldat(1).
System.out.println(“\nInvokehiddenstaticmethod:”);
tubeLight.printLightType();//(23)Invokesmethodat
(10).
light1.printLightType();//(24)Invokesmethodat(5).
light2.printLightType();//(25)Invokesmethodat(5).
WOW! eBook
www.wowebook.org
System.out.println(“\nInvokeoverloadedmethod:”);
tubeLight.energyCost();//(26)Invokesmethodat(8).
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
Invokeoverriddeninstancemethod:
>>TubeLight.energyCost(int):EnergycostforTubeLight:5.0
>>TubeLight.energyCost(int):EnergycostforTubeLight:5.0
>>Light.energyCost(int):EnergycostforGenericLight:10.0
Invokeoverriddeninstancemethodwithcovariantreturn:
>>Light.makeInstance():classLight
>>TubeLight.makeInstance():classTubeLight
Accesshiddenfield:
TubeLight
GenericLight
GenericLight
Invokehiddenstaticmethod:
>>StaticTubeLight.printLightType():TubeLight
>>StaticLight.printLightType():GenericLight
>>StaticLight.printLightType():GenericLight
Invokeoverloadedmethod:
>>TubeLight.energyCost():EnergycostforTubeLight:20.0
Hereareafewmorefactstonoteaboutoverriding.First,asubclassmustusethekeyword
supertoinvokeanoverriddenmethodinthesuperclass(p.276).
Second,afinalmethodcannotbeoverridden,becausethemodifierfinalprevents
methodoverriding.Anattempttooverrideafinalmethodwillresultinacompile-time
error.Anabstractmethod,incontrast,requiresthenon-abstractsubclassestooverride
themethod,soastoprovideanimplementation.
Third,theaccessibilitymodifierprivateforamethodmeansthatthemethodisnot
accessibleoutsidetheclassinwhichitisdefined;therefore,asubclasscannotoverrideit.
However,asubclasscangiveitsowndefinitionofsuchamethod,whichmayhavethe
samesignatureasthemethodinitssuperclass.
Fourth,asubclasswithinthesamepackageasthesuperclasscanoverrideanynon-final
andnon-privatemethodsdeclaredinthesuperclass.However,asubclassinadifferent
packagecanoverrideonlythenon-finalmethodsthataredeclaredaseitherpublicor
protectedinthesuperclass.
Fifth,aninstancemethodinasubclasscannotoverrideastaticmethodinthe
superclass.Thecompilerwillflagsuchanattemptasanerror.Astaticmethodisclass-
specificandnotpartofanyobject,whileoverridingmethodsareinvokedonbehalfof
objectsofthesubclass.However,astaticmethodinasubclasscanhideastaticmethod
inthesuperclass,asweshallsee(p.275).Constructors,sincetheyarenotmethods,
cannotbeoverridden.
WOW! eBook
www.wowebook.org
Covariant inOverridingMethods
InExample7.2,thedefinitionofthemethodmakeInstance()at(9)overridesthe
methoddefinitionat(3).Notethatthemethodsignaturesarethesame,butthereturntype
at(9)isasubtypeofthereturntypeat(3).Themethodat(9)returnsanobjectofthe
subtypeTubeLight,whereasthemethodat(3)returnsanobjectofthesupertype
Light.Thisisanexampleofcovariantreturn.
DependingonwhetherwecallthemethodmakeInstance()onanobjectofthe
subtypeTubeLightoranobjectofthesupertypeLight,therespectivemethod
definitionwillbeexecuted.Thecodeat(18)and(19)illustrateswhichobjectisreturned
bythemethod,dependingonwhichmethoddefinitionisexecuted.
Notethatcovariantreturnappliesonlytoreferencetypes,nottoprimitivetypes.For
example,changingthereturntypeoftheenergyCost()methodat(7)tofloatwill
resultinacompile-timeerror.Thereisnosupertype–subtyperelationshipbetween
primitivetypes.
OverridingversusOverloading
Methodoverridingshouldnotbeconfusedwithmethodoverloading(§3.2,p.52).
Methodoverridingalwaysrequiresthesamemethodsignature(nameandparametertypes)
andthesameorcovariantreturntypes.Overloadingoccurswhenthemethodnamesare
thesame,buttheparameterlistsdiffer.Therefore,tooverloadmethods,theparameters
mustdifferineithertype,order,ornumber.Asthereturntypeisnotapartofthemethod
signature,justhavingdifferentreturntypesisnotenoughtooverloadmethods.
Onlynon-finalinstancemethodsinthesuperclassthataredirectlyaccessiblefromthe
subclassusingtheirsimplenamecanbeoverridden.Bothinstanceandstaticmethodscan
beoverloadedintheclasstheyaredefinedinorinasubclassoftheirclass.
Invokinganoverriddenmethodinthesuperclassfromasubclassrequiresaspecialsyntax
(e.g.,thekeywordsuper).Thisisnotnecessaryforinvokinganoverloadedmethodin
thesuperclassfromasubclass.Iftherightkindsofargumentsarepassedinthemethod
calloccurringinthesubclass,theoverloadedmethodinthesuperclasswillbeinvoked.In
Example7.2,themethodenergyCost()at(2)inclassLightisoverriddeninclass
TubeLightat(7)andoverloadedat(8).Wheninvokedat(26),theoverloaded
definitionat(8)isexecuted.
Foroverloadedmethods,whichmethodimplementationwillbeexecutedatruntimeis
determinedatcompiletime(§7.10,p.316).Incontrast,foroverriddenmethods,the
methodimplementationtobeexecutedisdeterminedatruntime(§7.12,p.329).Table7.1
providesacomparisonbetweenoverridingandoverloading.
WOW! eBook
www.wowebook.org
Table7.1OverridingversusOverloading
7.3HidingMembers
FieldHiding
Asubclasscannotoverrideinheritedfieldsofthesuperclass,butitcanhidethem.The
subclasscandefinefieldswiththesamenameasinthesuperclass.Ifthisisthecase,the
fieldsinthesuperclasscannotbeaccessedinthesubclassbytheirsimplenames;
therefore,theyarenotinheritedbythesubclass.Ahiddenstaticfieldcanalwaysbe
invokedbyusingthesuperclassnameinthesubclassdeclaration.Additionally,the
keywordsupercanbeusedinnon-staticcodeinthesubclassdeclarationtoaccess
hiddenstaticfields(§7.4,p.276).
Thefollowingdistinctionbetweeninvokinginstancemethodsonanobjectandaccessing
fieldsofanobjectmustbenoted.Whenaninstancemethodisinvokedonanobjectusing
areference,itisthedynamictypeofthereference(i.e.,thetypeofthecurrentobject
denotedbythereferenceatruntime),notthedeclaredtypeofthereference,that
determineswhichmethodimplementationwillbeexecuted.InExample7.2at(15),(16),
WOW! eBook
www.wowebook.org
and(17),thisisevidentfrominvokingtheoverriddenmethodenergyCost():The
methodfromtheclasscorrespondingtothecurrentobjectisexecuted,regardlessofthe
declaredreferencetype.Whenafieldofanobjectisaccessedusingareference,itisthe
declaredtypeofthereference,notthetypeofthecurrentobjectdenotedbythereference,
thatdetermineswhichfieldwillactuallybeaccessed.InExample7.2at(20),(21),and
(22),thisisevidentfromaccessingthehiddenfieldlightType:Thefieldaccessedis
theonedeclaredintheclasscorrespondingtothedeclaredreferencetype,regardlessof
theobjectdenotedbythereferenceatruntime.
Incontrasttomethodoverriding,whereaninstancemethodcannotoverrideastatic
method,therearenosuchrestrictionsonthehidingoffields.ThefieldlightTypeis
staticinthesubclass,butnotinthesuperclass.Thedeclaredtypeofthefieldsneednot
bethesameeither—onlythefieldnamemattersinthehidingoffields.
StaticMethodHiding
Astaticmethodinasubclasscannotoverrideaninstancemethodfromthesuperclass,but
itcanhideastaticmethodfromthesuperclassiftheexactrequirementsforoverriding
instancemethodsarefulfilled(§7.2,p.268).Ahiddensuperclassstaticmethodisnot
inherited.Thecompilerwillflagthecodeascontaininganerrorifthesignaturesarethe
same,buttheotherrequirementsregardingreturntype,throwsclause,andaccessibility
arenotmet.Ifthesignaturesaredifferent,themethodnameisoverloaded,nothidden.
Acalltoastaticorfinalmethodisboundtoamethodimplementationatcompile
time(privatemethodsareimplicitlyfinal).Example7.2illustratesinvocationof
staticmethods.Analogoustoaccessingfields,thestaticmethodinvokedin(23),(24),and
(25)isdeterminedbythedeclaredtypeofthereference.In(23),thedeclaredreference
typeisTubeLight;therefore,thestaticmethodprintLightType()at(10)inthis
classisinvoked.In(24)and(25),thedeclaredreferencetypeisLight,andthehidden
staticmethodprintLightType()at(5)inthatclassisinvoked.Thisisborneoutby
theoutputfromtheprogram.
Analogoustohiddenfields,ahiddenstaticmethodcanalwaysbeinvokedbyusingthe
superclassnameorbyusingthekeywordsuperinnon-staticcodeinthesubclass
declaration(§7.4,p.276).
Table7.2summarizestheconsequenceswhenasubclassmethodhasthesamesignatureas
amethodinthesuperclass.
Table7.2SameSignatureforSubclassandSuperclassMethod
WOW! eBook
www.wowebook.org
7.4TheObjectReference
Thethisreferencecanbeusedinnon-staticcodetorefertothecurrentobject(§3.2,p.
50).Thekeywordsuper,incontrast,canbeusedinnon-staticcodetoaccessfieldsand
invokemethodsfromthesuperclass(Table4.1,p.115).Thekeywordsuperprovidesa
referencetothecurrentobjectasaninstanceofitssuperclass.Inmethodinvocationswith
super,themethodfromthesuperclassisinvokedregardlessofwhattheactualtypeof
thecurrentobjectisorwhetherthecurrentclassoverridesthemethod.Thisapproachis
typicallyusedtoinvokemethodsthatareoverridden,andtoaccessmembersthatare
hiddeninthesubclass.Unlikethethiskeyword,thesuperkeywordcannotbeusedas
anordinaryreference.Forexample,itcannotbeassignedtootherreferencesorcastto
otherreferencetypes.
Example7.3usestheclassesLightandTubeLightfromExample7.2,whicharealso
showninFigure7.2.InExample7.3,theclassNeonLightextendstheclass
TubeLight.Thedeclarationofthemethoddemonstrate()at(11)intheclass
NeonLightmakesuseofthesuperkeywordtoaccessmembershigherupinits
inheritancehierarchy.ThisisthecasewhentheshowSign()methodisinvokedat(12).
Thismethodisdefinedat(4)intheclassLight,ratherthanintheimmediatesuperclass
TubeLightofthesubclassNeonLight.TheoverriddenmethodenergyCost()at
(7)anditsoverloadedversionat(8)intheclassTubeLightareinvoked,usingthe
objectreferencesuperat(13)and(14),respectively.
ThesuperclassLighthasafieldnamedlightTypeandamethodnamed
energyCostdefinedat(1)and(2),respectively.Onemightbetemptedtousethe
syntaxsuper.super.energyCost(20)inthesubclassNeonLighttoinvokethis
method,butthisisnotavalidconstruct.Onemightalsobetemptedtocastthethis
referencetotheclassLightandtryagain,asshownat(15).Theoutputshowsthatthe
methodenergyCost()at(7)intheclassTubeLightwasexecuted,nottheonefrom
theclassLight.Thereasonisthatacastsimplychangesthetypeofthereference(inthis
casetoLight),nottheclassoftheobject(whichisstillNeonLight).Method
invocationisdeterminedbytheclassofthecurrentobject,resultingintheinherited
methodenergyCost()intheclassTubeLightbeingexecuted.Thereisnowayto
invokethemethodenergyCost()intheclassLightfromthesubclassNeonLight,
withoutdeclaringareferenceofthetypeLight.
At(16),thekeywordsuperisusedtoaccessthefieldlightTypeat(6)intheclass
TubeLight,butisredundantinthiscase.At(17),thefieldlightTypefromtheclass
Lightisaccessedsuccessfullybycastingthethisreference,becauseitisthetypeof
thereferencethatdetermineswhichfieldisaccessed.Fromnon-staticcodeinasubclass,
itispossibletodirectlyaccessfieldsinaclasshigherupintheinheritancehierarchyby
castingthethisreference.However,itisfutiletocastthethisreferencetoinvoke
instancemethodsinaclasshigherupintheinheritancehierarchy,asillustratedearlierfor
theoverriddenmethodenergyCost().
Finally,thecallstothestaticmethodsat(18)and(19)usingthesuperandthis
WOW! eBook
www.wowebook.org
references,respectively,exhibitruntimebehavioranalogoustoaccessingfields,as
discussedpreviously.
Example7.3UsingthesuperKeyword
Clickheretoviewcodeimage
//File:Client3.java
//Exceptions
classInvalidHoursExceptionextendsException{}
classNegativeHoursExceptionextendsInvalidHoursException{}
classZeroHoursExceptionextendsInvalidHoursException{}
classLight{
protectedStringlightType=“GenericLight”;//(1)Instancefield
protecteddoubleenergyCost(intnoOfHours)//(2)Instancemethod
throwsInvalidHoursException{
System.out.print(“>>Light.energyCost(int):“);
if(noOfHours<0)
thrownewNegativeHoursException();
doublecost=00.20*noOfHours;
System.out.println(“Energycostfor”+lightType+“:”+cost);
returncost;
}
publicLightmakeInstance(){//(3)Instancemethod
System.out.print(“>>Light.makeInstance():“);
returnnewLight();
}
publicvoidshowSign(){//(4)Instancemethod
System.out.print(“>>Light.showSign():“);
System.out.println(“Lettherebelight!”);
}
publicstaticvoidprintLightType(){//(5)Staticmethod
System.out.print(“>>StaticLight.printLightType():“);
System.out.println(“GenericLight”);
}
}
//______________________________________________________________________________
classTubeLightextendsLight{
publicstaticStringlightType=“TubeLight”;//(6)Hidingfieldat(1).
@Override
publicdoubleenergyCost(finalintnoOfHours)//(7)Overridinginstance
throwsZeroHoursException{//methodat(2).
System.out.print(“>>TubeLight.energyCost(int):“);
if(noOfHours==0)
thrownewZeroHoursException();
doublecost=00.10*noOfHours;
System.out.println(“Energycostfor”+lightType+“:”+cost);
returncost;
}
publicdoubleenergyCost(){//(8)Overloadingmethodat(7).
System.out.print(“>>TubeLight.energyCost():“);
doubleflatrate=20.00;
System.out.println(“Energycostfor”+lightType+“:”+flatrate);
WOW! eBook
www.wowebook.org
returnflatrate;
}
@Override
publicTubeLightmakeInstance(){//(9)Overridinginstancemethodat
(3).
System.out.print(“>>TubeLight.makeInstance():“);
returnnewTubeLight();
}
publicstaticvoidprintLightType(){//(10)Hidingstaticmethodat(5).
System.out.print(“>>StaticTubeLight.printLightType():“);
System.out.println(lightType);
}
}
//______________________________________________________________________________
classNeonLightextendsTubeLight{
//…
publicvoiddemonstrate()//(11)
throwsInvalidHoursException{
super.showSign();//(12)Invokesmethodat
(4)
super.energyCost(50);//(13)Invokesmethodat
(7)
super.energyCost();//(14)Invokesmethodat
(8)
((Light)this).energyCost(50);//(15)Invokesmethodat
(7)
System.out.println(super.lightType);//(16)Accessesfieldat
(6)
System.out.println(((Light)this).lightType);//(17)Accessesfieldat
(1)
super.printLightType();//(18)Invokesmethodat
(10)
((Light)this).printLightType();//(19)Invokesmethodat
(5)
}
}
//______________________________________________________________________________
publicclassClient3{
publicstaticvoidmain(String[]args)
throwsInvalidHoursException{
NeonLightneonRef=newNeonLight();
neonRef.demonstrate();
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
>>Light.showSign():Lettherebelight!
>>TubeLight.energyCost(int):EnergycostforTubeLight:5.0
>>TubeLight.energyCost():EnergycostforTubeLight:20.0
>>TubeLight.energyCost(int):EnergycostforTubeLight:5.0
TubeLight
GenericLight
>>StaticTubeLight.printLightType():TubeLight
>>StaticLight.printLightType():GenericLight
WOW! eBook
www.wowebook.org
ReviewQuestions
7.1Whichofthefollowingstatementsaretrue?
Selectthetwocorrectanswers.
(a)InJava,theextendsclauseisusedtospecifytheinheritancerelationship.
(b)Thesubclassofanon-abstractclasscanbedeclaredasabstract.
(c)Allmembersofthesuperclassareinheritedbythesubclass.
(d)Afinalclasscanbeabstract.
(e)Aclassinwhichallthemembersaredeclaredprivatecannotbedeclaredas
public.
7.2Whichofthefollowingstatementsaretrue?
Selectthetwocorrectanswers.
(a)Aclasscanbeextendedbyonlyoneclass.
(b)EveryJavaobjecthasapublicmethodnamedequals.
(c)EveryJavaobjecthasapublicmethodnamedlength.
(d)Aclasscanextendanynumberofclasses.
(e)Anon-finalclasscanbeextendedbyanynumberofclasses.
7.3Giventhefollowingclassesanddeclarations,whichstatementsaretrue?
Clickheretoviewcodeimage
//Classes
classFoo{
privateinti;
publicvoidf(){/*…*/}
publicvoidg(){/*…*/}
}
classBarextendsFoo{
publicintj;
publicvoidg(){/*…*/}
}
//Declarations:
Fooa=newBar();
Barb=newBar();
Selectthethreecorrectanswers.
(a)TheBarclassisasubclassofFoo.
(b)Thestatementb.f();islegal.
(c)Thestatementa.j=5;islegal.
(d)Thestatementa.g();islegal.
WOW! eBook
www.wowebook.org
(e)Thestatementb.i=3;islegal.
7.4GivenclassesA,B,andC,whereBextendsA,andCextendsB,andwhereall
classesimplementtheinstancemethodvoiddoIt(),howcanthedoIt()
methodinAbecalledfromaninstancemethodinC?
Selecttheonecorrectanswer.
(a)doIt();
(b)super.doIt();
(c)super.super.doIt();
(d)this.super.doIt();
(e)A.this.doIt();
(f)((A)this).doIt();
(g)Itisnotpossible.
7.5Whatwouldbetheresultofcompilingandrunningthefollowingprogram?
Clickheretoviewcodeimage
publicclassUserClass{
publicstaticvoidmain(String[]args){
Bb=newC();
System.out.println(b.max(13,29));
}
}
classA{
intmax(intx,inty){if(x>y)returnx;elsereturny;}
}
classBextendsA{
intmax(intx,inty){returnsuper.max(y,x)-10;}
}
classCextendsB{
intmax(intx,inty){returnsuper.max(x+10,y+10);}
}
Selecttheonecorrectanswer.
(a)Thecodewillfailtocompile.
(b)Thecodewillcompile,butthrowanexceptionatruntime.
(c)Thecodewillcompile,andprint13atruntime.
(d)Thecodewillcompile,andprint23atruntime.
(e)Thecodewillcompile,andprint29atruntime.
(f)Thecodewillcompile,andprint39atruntime.
7.6Whichisthesimplestexpressionthatcanbeinsertedat(1),sothattheprogram
printsthevalueofthetextfieldfromtheMessageclass?
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
//File:MyClass.java
classMessage{
//Themessagethatshouldbeprinted:
Stringtext=“Hello,world!”;
}
classMySuperclass{
Messagemsg=newMessage();
}
publicclassMyClassextendsMySuperclass{
publicstaticvoidmain(String[]args){
MyClassobject=newMyClass();
object.print();
}
publicvoidprint(){
System.out.println(/*(1)INSERTTHESIMPLESTEXPRESSIONHERE*/);
}
}
Selecttheonecorrectanswer.
(a)text
(b)Message.text
(c)msg.text
(d)this.msg.text
(e)super.msg.text
(f)this.super.msg.text
7.7Whatwouldbetheresultofcompilingandrunningthefollowingprogram?
Clickheretoviewcodeimage
classVehicle{
staticpublicStringgetModelName(){return“Volvo”;}
publiclonggetRegNo(){return12345;}
}
classCarextendsVehicle{
staticpublicStringgetModelName(){return“Toyota”;}
publiclonggetRegNo(){return54321;}
}
publicclassTakeARide{
publicstaticvoidmain(String[]args){
Carc=newCar();
Vehiclev=c;
System.out.println(“|”+v.getModelName()+“|”+c.getModelName()+
”|”+v.getRegNo()+“|”+c.getRegNo()+
“|”);
}
}
Selecttheonecorrectanswer.
WOW! eBook
www.wowebook.org
(a)Thecodewillfailtocompile.
(b)Thecodewillcompile,andprint|Toyota|Volvo|12345|54321|at
runtime.
(c)Thecodewillcompile,andprint|Volvo|Toyota|12345|54321|at
runtime.
(d)Thecodewillcompile,andprint|Toyota|Toyota|12345|12345|at
runtime.
(e)Thecodewillcompile,andprint|Volvo|Volvo|12345|54321|at
runtime.
(f)Thecodewillcompile,andprint|Toyota|Toyota|12345|12345|at
runtime.
(g)Thecodewillcompile,andprint|Volvo|Toyota|54321|54321|at
runtime.
7.5ChainingConstructorsUsing and
Constructorsarediscussedin§3.3,p.53.Otherusesofthekeywordsthisandsuper
canbefoundin§7.2,p.268.
The ConstructorCall
Constructorscannotbeinheritedoroverridden.Theycanbeoverloaded,butonlyinthe
sameclass.Sinceaconstructoralwayshasthesamenameastheclass,eachparameterlist
mustbedifferentwhendefiningmorethanoneconstructorforaclass.InExample7.4,the
classLighthasthreeoverloadedconstructors.Intheconstructorat(3),thethis
referenceisusedtoaccessthefieldsshadowedbytheparameters.Inthemain()method
at(4),theappropriateconstructorisinvokeddependingontheargumentsinthe
constructorcall,asillustratedbytheprogramoutput.
WOW! eBook
www.wowebook.org
Example7.4ConstructorOverloading
Clickheretoviewcodeimage
//File:DemoConstructorCall.java
classLight{
//Fields:
privateintnoOfWatts;//wattage
privatebooleanindicator;//onoroff
privateStringlocation;//placement
//Constructors:
Light(){//(1)No-argumentconstructor
noOfWatts=0;
indicator=false;
location=“X”;
System.out.println(“Returningfromno-argumentconstructorno.1.”);
}
Light(intwatts,booleanonOffState){//(2)
noOfWatts=watts;
indicator=onOffState;
location=“X”;
System.out.println(“Returningfromconstructorno.2.”);
}
Light(intnoOfWatts,booleanindicator,Stringlocation){//(3)
this.noOfWatts=noOfWatts;
this.indicator=indicator;
this.location=location;
System.out.println(“Returningfromconstructorno.3.”);
}
}
//______________________________________________________________________________
publicclassDemoConstructorCall{
publicstaticvoidmain(String[]args){//(4)
System.out.println(“CreatingLightobjectno.1.”);
Lightlight1=newLight();
System.out.println(“CreatingLightobjectno.2.”);
Lightlight2=newLight(250,true);
System.out.println(“CreatingLightobjectno.3.”);
Lightlight3=newLight(250,true,“attic”);
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
CreatingLightobjectno.1.
Returningfromno-argumentconstructorno.1.
CreatingLightobjectno.2.
Returningfromconstructorno.2.
CreatingLightobjectno.3.
Returningfromconstructorno.3.
Example7.5illustratestheuseofthethis()construct,whichisusedtoimplementlocal
chainingofconstructorsintheclasswhenaninstanceoftheclassiscreated.Thefirsttwo
constructorsat(1)and(2)fromExample7.4havebeenrewrittenusingthethis()
constructinExample7.5at(1)and(2),respectively.Thethis()constructcanbe
regardedasbeinglocallyoverloaded,sinceitsparameters(andhenceitssignature)can
vary,asshowninthebodyoftheconstructorsat(1)and(2).Thethis()callinvokesthe
WOW! eBook
www.wowebook.org
localconstructorwiththecorrespondingparameterlist.Inthemain()methodat(4),the
appropriateconstructorisinvokeddependingontheargumentsintheconstructorcall
wheneachofthethreeLightobjectsarecreated.Callingtheno-argumentconstructorat
(1)tocreateaLightobjectresultsintheconstructorsat(2)and(3)beingexecutedas
well.Thisisconfirmedbytheoutputfromtheprogram.Inthiscase,theoutputshowsthat
theconstructorat(3)completedfirst,followedbytheconstructorat(2),andfinallybythe
no-argumentconstructorat(1)thatwascalledfirst.Bearinginmindthedefinitionofthe
constructors,theconstructorsareinvokedinthereverseorder;thatis,invocationofthe
no-argumentconstructorimmediatelyleadstoinvocationoftheconstructorat(2)bythe
callthis(0,false),anditsinvocationleadstotheconstructorat(3)beingcalled
immediatelybythecallthis(watt,ind,"X"),withthecompletionofthe
executioninthereverseorderoftheirinvocation.Similarly,callingtheconstructorat(2)
tocreateaninstanceoftheLightclassresultsintheconstructorat(3)beingexecutedas
well.
Javarequiresthatanythis()callmustoccurasthefirststatementinaconstructor.The
this()callcanbefollowedbyanyotherrelevantcode.ThisrestrictionisduetoJava’s
handlingofconstructorinvocationinthesuperclasswhenanobjectofthesubclassis
created.Thismechanismisexplainedinthenextsubsection.
WOW! eBook
www.wowebook.org
Example7.5Thethis()ConstructorCall
Clickheretoviewcodeimage
//File:DemoThisCall.java
classLight{
//Fields:
privateintnoOfWatts;
privatebooleanindicator;
privateStringlocation;
//Constructors:
Light(){//(1)No-argumentconstructor
this(0,false);
System.out.println(“Returningfromno-argumentconstructorno.1.”);
}
Light(intwatt,booleanind){//(2)
this(watt,ind,“X”);
System.out.println(“Returningfromconstructorno.2.”);
}
Light(intnoOfWatts,booleanindicator,Stringlocation){//(3)
this.noOfWatts=noOfWatts;
this.indicator=indicator;
this.location=location;
System.out.println(“Returningfromconstructorno.3.”);
}
}
//______________________________________________________________________________
publicclassDemoThisCall{
publicstaticvoidmain(String[]args){//(4)
System.out.println(“CreatingLightobjectno.1.”);
Lightlight1=newLight();//(5)
System.out.println(“CreatingLightobjectno.2.”);
Lightlight2=newLight(250,true);//(6)
System.out.println(“CreatingLightobjectno.3.”);
Lightlight3=newLight(250,true,“attic”);//(7)
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
CreatingLightobjectno.1.
Returningfromconstructorno.3.
Returningfromconstructorno.2.
Returningfromno-argumentconstructorno.1.
CreatingLightobjectno.2.
Returningfromconstructorno.3.
Returningfromconstructorno.2.
CreatingLightobjectno.3.
Returningfromconstructorno.3.
WOW! eBook
www.wowebook.org
The ConstructorCall
Thesuper()constructisusedinasubclassconstructortoinvokeaconstructorinthe
immediatesuperclass.Thisallowsthesubclasstoinfluencetheinitializationofits
inheritedstatewhenanobjectofthesubclassiscreated.Asuper()callinthe
constructorofasubclasswillresultintheexecutionoftherelevantconstructorfromthe
superclass,basedonthesignatureofthecall.Sincethesuperclassnameisknowninthe
subclassdeclaration,thecompilercandeterminethesuperclassconstructorinvokedfrom
thesignatureoftheparameterlist.
Aconstructorinasubclasscanaccesstheclass’sinheritedmembersbytheirsimple
names.Thekeywordsupercanalsobeusedinasubclassconstructortoaccessinherited
membersviaitssuperclass.Onemightbetemptedtousethesuperkeywordina
constructortospecifyinitialvaluesforinheritedfields.However,thesuper()construct
providesabettersolutiontoinitializetheinheritedstate.
InExample7.6,theconstructorat(3)oftheclassLighthasasuper()call(withno
arguments)at(4).Althoughtheconstructorisnotstrictlynecessary,asthecompilerwill
insertone—asexplainedlater—itisincludedhereforexpositionalpurposes.The
constructorat(6)oftheclassTubeLighthasasuper()call(withthreearguments)at
(7).Thissuper()callwillmatchtheconstructorat(3)ofthesuperclassLight.Thisis
evidentfromtheprogramoutput.
Example7.6Thesuper()ConstructorCall
Clickheretoviewcodeimage
//File:Chaining.java
classLight{
//Fields:
privateintnoOfWatts;
privatebooleanindicator;
privateStringlocation;
//Constructors:
Light(){//(1)No-argumentconstructor
this(0,false);
System.out.println(
“Returningfromno-argumentconstructorno.1inclassLight”);
}
Light(intwatt,booleanind){//(2)
this(watt,ind,“X”);
System.out.println(
“Returningfromconstructorno.2inclassLight”);
}
Light(intnoOfWatts,booleanindicator,Stringlocation){//(3)
super();//(4)
this.noOfWatts=noOfWatts;
this.indicator=indicator;
this.location=location;
System.out.println(
“Returningfromconstructorno.3inclassLight”);
}
}
//______________________________________________________________________________
classTubeLightextendsLight{
WOW! eBook
www.wowebook.org
//Instancevariables:
privateinttubeLength;
privateintcolorNo;
//Constructors:
TubeLight(inttubeLength,intcolorNo){//(5)
this(tubeLength,colorNo,100,true,“Unknown”);
System.out.println(
“Returningfromconstructorno.1inclassTubeLight”);
}
TubeLight(inttubeLength,intcolorNo,intnoOfWatts,
booleanindicator,Stringlocation){//(6)
super(noOfWatts,indicator,location);//(7)
this.tubeLength=tubeLength;
this.colorNo=colorNo;
System.out.println(
“Returningfromconstructorno.2inclassTubeLight”);
}
}
//______________________________________________________________________________
publicclassChaining{
publicstaticvoidmain(String[]args){
System.out.println(“CreatingaTubeLightobject.”);
TubeLighttubeLightRef=newTubeLight(20,5);//(8)
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
CreatingaTubeLightobject.
Returningfromconstructorno.3inclassLight
Returningfromconstructorno.2inclassTubeLight
Returningfromconstructorno.1inclassTubeLight
Thesuper()constructhasthesamerestrictionsasthethis()construct:Ifused,the
super()callmustoccurasthefirststatementinaconstructor,anditcanonlybeusedin
aconstructordeclaration.Thisimpliesthatthis()andsuper()callscannotboth
occurinthesameconstructor.Thethis()constructisusedtochainconstructorsinthe
sameclass.Theconstructorattheendofsuchachaincaninvokeasuperclassconstructor
usingthesuper()construct.Justasthethis()constructleadstochainingof
constructorsinthesameclass,sothesuper()constructleadstochainingofsubclass
constructorstosuperclassconstructors.Thischainingbehaviorguaranteesthatall
superclassconstructorsarecalled,startingwiththeconstructoroftheclassbeing
instantiated,allthewaytothetopoftheinheritancehierarchy,whichisalwaysthe
Objectclass.Notethatthebodyoftheconstructorisexecutedinthereverseordertothe
callorder,asthesuper()callcanoccuronlyasthefirststatementinaconstructor.This
orderofexecutionensuresthattheconstructorfromtheObjectclassiscompletedfirst,
followedbytheconstructorsintheotherclassesdowntotheclassbeinginstantiatedinthe
inheritancehierarchy.Itiscalled(subclass–superclass)constructorchaining.Theoutput
fromExample7.6clearlyillustratesthischainofeventswhenanobjectoftheclass
TubeLightiscreated.
Ifaconstructorattheendofathis()chain(whichmaynotbeachainatallifno
WOW! eBook
www.wowebook.org
this()callisinvoked)doesnothaveanexplicitcalltosuper(),thecallsuper()
(withouttheparameters)isimplicitlyinsertedbythecompilertoinvoketheno-argument
constructorofthesuperclass.Inotherwords,ifaconstructorhasneitherathis()call
norasuper()callasitsfirststatement,thecompilerinsertsasuper()calltotheno-
argumentconstructorinthesuperclass.Thecode
Clickheretoviewcodeimage
classA{
A(){}//No-argumentconstructor.
//…
}
classBextendsA{//Noconstructors.
//…
}
isequivalentto
Clickheretoviewcodeimage
classA{
A(){super();}//(1)Calltono-argumentsuperclassconstructor
inserted.
//…
}
classBextendsA{
B(){super();}//(2)Defaultconstructorinserted.
//…
}
wherethecompilerinsertsasuper()callintheno-argumentconstructorforclassAat
(1)andinsertsthedefaultconstructorforclassBat(2).Thesuper()callat(2)will
resultinacalltotheno-argumentconstructorinBat(1),andthesuper()callat(1)will
resultinacalltotheno-argumentconstructorinthesuperclassofA—thatis,theObject
class.
Ifasuperclassdefinesjustnon-zeroargumentconstructors(i.e.,onlyconstructorswith
parameters),itssubclassescannotrelyontheimplicitsuper()callbeinginserted.This
willbeflaggedasacompile-timeerror.Thesubclassesmustthenexplicitlycalla
superclassconstructor,usingthesuper()constructwiththerightarguments.
Clickheretoviewcodeimage
classNeonLightextendsTubeLight{
//Field
Stringsign;
NeonLight(){//(1)
super(10,2,100,true,“Roof-top”);//(2)Cannotbecommentedout.
sign=“Allwillberevealed!”;
}
//…
}
TheprecedingdeclarationofthesubclassNeonLightprovidesano-argument
constructorat(1).Thecalloftheconstructorat(2)inthesuperclassTubeLightcannot
beomitted.Ifitisomitted,anyinsertionofasuper()call(withnoarguments)inthis
constructorwilltrytomatchano-argumentconstructorinthesuperclassTubeLight,
WOW! eBook
www.wowebook.org
whichprovidesonlynon-zeroargumentconstructors.TheclassNeonLightwillnot
compileunlessanexplicitvalidsuper()callisinsertedat(2).
Ifthesuperclassprovidesjustnon-zeroargumentconstructors(i.e.,itdoesnothaveano-
argumentconstructor),thishasimplicationsforitssubclasses.Asubclassthatreliesonits
defaultconstructorwillfailtocompile,becausethedefaultconstructorofthesubclasswill
attempttocallthe(nonexistent)no-argumentconstructorinthesuperclass.Aconstructor
inasubclassmustexplicitlyusethesuper()call,withtheappropriatearguments,to
invokeanon-zeroargumentconstructorinthesuperclass.Thiscallisnecessarybecause
theconstructorinthesubclasscannotrelyonanimplicitsuper()calltotheno-
argumentconstructorinthesuperclass.
ReviewQuestions
7.8Whichconstructorscanbeinsertedat(1)inMySubwithoutcausingacompile-
timeerror?
Clickheretoviewcodeimage
classMySuper{
intnumber;
MySuper(inti){number=i;}
}
classMySubextendsMySuper{
intcount;
MySub(intcount,intnum){
super(num);
this.count=count;
}
//(1)INSERTCONSTRUCTORHERE
}
Selecttheonecorrectanswer.
(a)MySub(){}
(b)MySub(intcount){this.count=count;}
(c)MySub(intcount){super();this.count=count;}
(d)MySub(intcount){this.count=count;super(count);
}
(e)MySub(intcount){this(count,count);}
(f)MySub(intcount){super(count);this(count,0);}
7.9Whichofthefollowingstatementsistrue?
Selecttheonecorrectanswer.
(a)Asuper()orthis()callmustalwaysbeprovidedexplicitlyasthefirst
statementinthebodyofaconstructor.
(b)Ifbothasubclassanditssuperclassdonothaveanydeclaredconstructors,the
WOW! eBook
www.wowebook.org
implicitdefaultconstructorofthesubclasswillcallsuper()whenrun.
(c)Ifneithersuper()northis()isspecifiedasthefirststatementinthebody
ofaconstructor,this()willimplicitlybeinsertedasthefirststatement.
(d)Ifsuper()isthefirststatementinthebodyofaconstructor,this()canbe
declaredasthesecondstatement.
(e)Callingsuper()asthefirststatementinthebodyofaconstructorofa
subclasswillalwayswork,sinceallsuperclasseshaveadefaultconstructor.
7.10Whatwillthefollowingprogramprintwhenrun?
Clickheretoviewcodeimage
publicclassMyClass{
publicstaticvoidmain(String[]args){
Bb=newB(“Test”);
}
}
classA{
A(){this(“1”,“2”);}
A(Strings,Stringt){this(s+t);}
A(Strings){System.out.println(s);}
}
classBextendsA{
B(Strings){System.out.println(s);}
B(Strings,Stringt){this(t+s+“3”);}
B(){super(“4”);};
}
Selecttheonecorrectanswer.
(a)ItwilljustprintTest.
(b)ItwillprintTestfollowedbyTest.
(c)Itwillprint123followedbyTest.
(d)Itwillprint12followedbyTest.
(e)Itwillprint4followedbyTest.
7.6Interfaces
Extendingclassesusingsingleimplementationinheritancecreatesnewclasstypes.A
superclassreferencecanrefertoobjectsofitsowntypeanditssubclassesstrictly
accordingtotheinheritancehierarchy.Becausethisrelationshipislinear,itrulesout
multipleimplementationinheritance,inwhichasubclassinheritsfrommorethanone
superclass.InsteadJavaprovidesinterfaces,whichnotonlyallownewnamedreference
typestobeintroduced,butalsopermitmultipleinterfaceinheritance.
WOW! eBook
www.wowebook.org
DefiningInterfaces
Atop-levelinterfacehasthefollowingsimplifiedsyntax,whichwillsufficeforthe
purposesofthisbook:
Clickheretoviewcodeimage
accessibility_modifierinterfaceinterface_name
extends_interface_clause//Interface
header
{//Interfacebody
abstract_method_declarations
default_method_declarations
static_method_declarations
constant_declarations
}
Intheinterfaceheader,thenameoftheinterfaceisprecededbythekeyword
interface.Theinterfacenamecanalsoincludealistofformaltypeparametersfor
declaringagenericinterface.Inaddition,theinterfaceheadercanspecifythefollowing
information:
•Theaccessibilitymodifiermustbepublic,andthelackofanaccessibility
modifierimpliespackageaccessibility,asonewouldexpect(§4.5,p.118).
•Theextendsinterfaceclausespecifiesacomma-separatedlistofanysuperinterfaces
thattheinterfaceextends(p.294).
Theinterfacebodycancontainmemberdeclarationsthatincludeanyofthefollowing:
•Abstractmethoddeclarations(p.291)
•Defaultmethoddeclarations(p.297)
•Staticmethoddeclarations(p.300)
•Constantdeclarations(p.302)
Aninterfaceisabstractbydefinition,whichmeansthatitcannotbeinstantiated.
Declaringaninterfaceasabstractissuperfluousandseldomdoneinpractice.Itisthe
onlynon-accessibilitymodifierthatcanbespecifiedforatop-levelinterface(apartfrom
thekeywordstrictfp).
Thememberdeclarationscanappearinanyorderintheinterfacebody,whichcanbe
empty.Sinceinterfacesaremeanttobeimplementedbyclasses,interfacemembers
implicitlyhavepublicaccessibilityandthepublicmodifiercanbeomitted.The
followingdeclarationisanexampleofabare-bonesinterfacethathasanemptybody:
interfacePlayable{}
Interfaceswithemptybodiescanbeusedasmarkerstotagclassesashavingacertain
propertyorbehavior.Suchinterfacesarealsocalledabilityinterfaces.TheJavaSE
platformAPIprovidesseveralexamplesofsuchmarkerinterfaces—namely,
java.lang.Cloneable,java.io.Serializable,and
WOW! eBook
www.wowebook.org
java.util.EventListener.
AbstractMethodsinInterfaces
Aninterfacedefinesacontractbyspecifyingasetofabstractanddefaultmethod
declarations,butprovidesimplementationsonlyforthedefaultmethods—notforthe
abstractmethods.Theabstractmethodsinaninterfaceareallimplicitlyabstractand
publicbyvirtueoftheirdefinitions.Onlythemodifiersabstractandpublicare
allowed,buttheseareinvariablyomitted.Anabstractmethoddeclarationhasthe
followingsimpleforminatop-levelinterface:
Clickheretoviewcodeimage
return_typemethod_name(formal_parameter_list)throws_clause;
Anabstractmethoddeclarationisessentiallyamethodheaderterminatedbyasemicolon
(;).Notethatanabstractmethodisaninstancemethodwhoseimplementationwillbe
providedbyaclassthatimplementstheinterfaceinwhichtheabstractmethodisdeclared.
Thethrowsclauseisdiscussedin§6.9,p.251.
TheinterfacePlayableshownnextdeclaresanabstractmethodstartPlaying().
Thatitispublicandabstractisimplicitlyimplied.
Clickheretoviewcodeimage
interfacePlayable{
voidstartPlaying();//Abstractmethod:noimplementation
}
Aninterfacethathasnodirectsuperinterfacesimplicitlydeclaresapublicabstractmethod
foreachpublicinstancemethodinthejava.lang.Objectclass.
Incontrasttothesyntaxofabstractmethodsintop-levelinterfaces,abstractmethodsin
top-levelclassesmustbeexplicitlyspecifiedwiththekeywordabstract,andcanhave
public,protected,andpackageaccessibility(§4.8,p.136).
Functionalinterfaces,meaninginterfaceswithasingleabstractmethod,arediscussed
togetherwithlambdaexpressionsin§10.2,p.442.
Therestofthischapterprovidesnumerousexamplesofusinginterfaces.
ImplementingInterfaces
Aclasscanimplement,whollyorpartially,zeroormoreinterfaces.Aclassspecifiesthe
interfacesitimplementsasacomma-separatedlistofuniqueinterfacenamesinan
implementsclauseintheclassheader.Theinterfacemethodsmustallhavepublic
accessibilitywhenimplementedintheclass(oritssubclasses).Aclasscanneithernarrow
theaccessibilityofaninterfacemethodnorspecifynewexceptionsinthemethod’s
throwsclause,asattemptingtodosowouldamounttoalteringtheinterface’scontract,
whichisillegal.Thecriteriaforoverridingmethodsalsoapplywhenimplementing
abstractmethods(§7.2,p.268).
Aclasscanprovideimplementationsofmethodsdeclaredinaninterface.Toreapthe
benefitsofinterfaces,however,theclassmustalsospecifytheinterfacenameinits
WOW! eBook
www.wowebook.org
implementsclause.
InExample7.7,theclassStackImplimplementstheinterfaceIStack.Itboth
specifiestheinterfacenameusingtheimplementsclauseinitsclassheaderat(2)and
providestheimplementationfortheabstractmethodsintheinterfaceat(3)and(4).
Changingthepublicaccessibilityofthesemethodsintheclasswillresultinacompile-
timeerror,asthiswouldnarrowtheiraccessibility.
Example7.7ImplementingInterfaces
Clickheretoviewcodeimage
//File:RetailSeller.java
interfaceIStack{//(1)
voidpush(Objectitem);
Objectpop();
}
//______________________________________________________________________________
classStackImplimplementsIStack{//(2)
protectedObject[]stackArray;
protectedinttos;//topofstack
publicStackImpl(intcapacity){
stackArray=newObject[capacity];
tos=-1;
}
@Override
publicvoidpush(Objectitem){stackArray[++tos]=item;}//(3)
@Override
publicObjectpop(){//(4)
ObjectobjRef=stackArray[tos];
stackArray[tos]=null;
tos—;
returnobjRef;
}
publicObjectpeek(){returnstackArray[tos];}
}
//______________________________________________________________________________
interfaceISafeStackextendsIStack{//(5)
booleanisEmpty();
booleanisFull();
}
//______________________________________________________________________________
classSafeStackImplextendsStackImplimplementsISafeStack{//(6)
publicSafeStackImpl(intcapacity){super(capacity);}
@OverridepublicbooleanisEmpty(){returntos<0;}//
(7)
@OverridepublicbooleanisFull(){returntos>=stackArray.length-1;}//
(8)
}
//______________________________________________________________________________
publicclassStackUser{
publicstaticvoidmain(String[]args){//(9)
SafeStackImplsafeStackRef=newSafeStackImpl(10);
StackImplstackRef=safeStackRef;
WOW! eBook
www.wowebook.org
ISafeStackisafeStackRef=safeStackRef;
IStackistackRef=safeStackRef;
ObjectobjRef=safeStackRef;
safeStackRef.push(“Dollars”);//(10)
stackRef.push(“Kroner”);
System.out.println(isafeStackRef.pop());
System.out.println(istackRef.pop());
System.out.println(objRef.getClass());
}
}
Outputfromtheprogram:
Kroner
Dollars
classSafeStackImpl
Aclasscanchoosetoimplementonlysomeoftheabstractmethodsofitsinterfaces(i.e.,
giveapartialimplementationofitsinterfaces).Theclassmustthenbedeclaredas
abstract(§4.6,p.120).Notethatabstractmethodscannotbedeclaredasstatic,
becausetheycomprisethecontractfulfilledbytheobjectsoftheclassimplementingthe
interface.Abstractmethodsarealwaysimplementedasinstancemethods.
Theinterfacesthataclassimplementsandtheclassesthatitextends(directlyor
indirectly)arecalledsupertypesoftheclass.Conversely,theclassisasubtypeofits
supertypes.Classesimplementinginterfacesintroducemultipleinterfaceinheritanceinto
theirimplementationinheritancehierarchy.Evenso,regardlessofhowmanyinterfacesa
classimplementsdirectlyorindirectly,itprovidesjustasingleimplementationofany
abstractmethoddeclaredinmultipleinterfaces.
Singleimplementationofanabstractmethodisillustratedbythefollowingcode,where
theWorkerclassat(5)providesonlyoneimplementationofthedoIt()methodthatis
declaredinbothinterfaces,at(1)and(2).TheclassWorkerfulfillsthecontractforboth
interfaces,asthedoIt()methoddeclarationsat(1)and(2)havethesamemethod
signatureandreturntype.However,theclassCombinedat(3)declaresthatit
implementsthetwointerfaces,butdoesnotprovideanyimplementationofthedoIt()
method;consequently,itmustbedeclaredasabstract.
Clickheretoviewcodeimage
interfaceIA{intdoIt();}//(1)
interfaceIB{intdoIt();}//(2)
abstractclassCombinedimplementsIA,IB{}//(3)
publicclassWorkerimplementsIA,IB{//(4)
@Override
publicintdoIt(){return0;}//(5)
}
IfthedoIt()methodsinthetwointerfacesat(1)and(2)hadthesamesignaturesbut
differentreturntypes,theWorkerclasswouldnotbeabletoimplementbothinterfaces.
Thisisillustratedbythenextcodesnippet.ThedoIt()methodsat(1)and(2)havethe
samesignature,butdifferentreturntypes.TheWorkerclassprovidestwo
WOW! eBook
www.wowebook.org
implementationsofthedoIt()methodat(5)and(6),whichresultsincompile-time
errors,becauseaclasscannothavetwomethodswiththesamesignaturebutdifferent
returntypes.RemovingeitherimplementationfromtheWorkerclasswillbeflaggedasa
compile-timeerror,becausetheWorkerclasswillnotbeimplementingbothinterfaces.
ThereisnowaytheWorkerclasscanimplementbothinterfaces,giventhedeclarations
showninthecode.Inaddition,theabstractclassCombinedat(3)willnotcompile,
becauseitwillbeinheritingtwomethodswithconflictingabstractmethoddeclarations.In
fact,thecompilercomplainsofduplicatemethods.
Clickheretoviewcodeimage
interfaceIA{intdoIt();}//(1)
interfaceIB{doubledoIt();}//(2)
abstractclassCombinedimplementsIA,IB{}//(3)Compile-time
error.
publicclassLameWorkerimplementsIA,IB{//(4)
@Override
publicintdoIt(){return0;}//(5)Compile-time
error.
@Override
publicdoubledoIt(){//(6)Compile-time
error.
System.out.println(“Sorry!”);
return=0.0;
}
}
ExtendingInterfaces
Aninterfacecanextendotherinterfaces,usingtheextendsclause.Unlikewhen
extendingclasses,aninterfacecanextendseveralinterfaces.Theinterfacesextendedby
aninterface(directlyorindirectly)arecalledsuperinterfaces.Conversely,theinterfaceis
asubinterfaceofitssuperinterfaces.Sinceinterfacesdefinenewreferencetypes,
superinterfacesandsubinterfacesarealsosupertypesandsubtypes,respectively.
Asubinterfaceinheritsfromitssuperinterfaces,allmembersofthosesuperinterfaces,
exceptforthefollowing:
•Abstractordefaultmethodsthatitoverrides(p.297)
•Anystaticmethodsdeclaredinitssuperinterfaces(p.300)
•Anyconstantsthatithides(p.302)
Barringanyconflicts,asubinterfaceinheritsabstractanddefaultmethoddeclarationsthat
arenotoverridden,aswellasconstantsthatitdoesnothideinitssuperinterfaces.
Abstract,static,anddefaultmethoddeclarationscanalsobeoverloaded,analogousto
methodoverloadinginclasses.
Example7.7illustratestherelationshipsbetweenclassesandinterfaces.InExample7.7,
theinterfaceISafeStackextendstheinterfaceIStackat(5).Theclass
SafeStackImplbothextendstheStackImplclassandimplementsthe
WOW! eBook
www.wowebook.org
ISafeStackinterfaceat(6).Boththeimplementationandtheinterfaceinheritance
hierarchiesforclassesandinterfacesdefinedinExample7.7areshowninFigure7.3.
Figure7.3InheritanceHierarchies
InUML,aninterfaceresemblesaclass.Onewaytodifferentiatebetweenthemistouse
an«interface»stereotype,asinFigure7.3.Interfaceinheritanceisdepictedinasimilar
mannertoimplementationinheritance,butisindicatedbyanunbrokeninheritancearrow.
Thinkingintermsoftypes,everyreferencetypeinJavaisasubtypeoftheObjectclass.
Inturn,anyinterfacetypeisalsoasubtypeoftheObjectclass,butitdoesnotinherit
fromtheObjectclass.Aninterfacethathasnodirectsuperinterfacesimplicitlydeclares
apublicabstractmethodforeachpublicinstancemethodintheObjectclass.
Theseabstractmethoddeclarationsareinheritedbyallsubinterfacesofsuchaninterface.
Notethatthisdoesnotmeantheimplementationisinherited.Theimplicitpublic
abstractmethoddeclarationsinaninterfaceallowpublicinstancemethodsinthe
Objectclasstobeinvokedonobjectsreferredtobyaninterfacereference.Allclasses
implementthesemethods,whethertheyareinheritedoroverriddenfromtheObject
class.Anyinterfacecanalsoprovideexplicitpublicabstractmethoddeclarations
fornon-finalpublicinstancemethodsintheObjectclass.
Clickheretoviewcodeimage
interfaceIStack{//(1)
voidpush(Objectitem);
WOW! eBook
www.wowebook.org
Objectpop();
@Overridebooleanequals(Objectother);//publicmethodinObject
class.
@OverrideStringtoString();//publicmethodinObject
class.
//@OverrideClassgetClass();//Compile-timeerror!finalmethodinObject
class.
}
ItisinstructivetoconsiderhowtheclassSafeStackImplimplementstheIStack
interface:Itinheritstheimplementationsofthepush()andpop()methodsfromits
superclassStackImpl,whichitselfimplementstheIStackinterfaceinwhichthese
twomethodsaredeclared.TheclassSafeStackImplalsoimplementstheIStack
interfaceviatheISafeStackinterface.TheclassSafeStackImplprovidesitsown
implementationoftheisFull()andisEmpty()methodsdeclaredinthe
ISafeStackinterface,andhasinheritedimplementationsofthepush()andpop()
methodswhosedeclarationstheISafeStackinterfaceinheritsfromitssuperinterface
IStack.Thisisreadilyevidentfromthediamondshapeoftheinheritancehierarchyin
Figure7.3.Notethatthereisonlyonesingleimplementationinheritanceintotheclass
SafeStackImpl—fromitssuperclassStackImpl.Javadoesnotsupportmultiple
implementationinheritance.
Theassociationbetweenaclassandanyinterfaceitimplementsiscalledarealizationin
UML.InFigure7.3,therearethreerealizations:TheclassSafeStackImplimplements
theISafeStackinterfaceandalsoimplicitlyimplementstheIStackinterface,andthe
classStackImplimplementstheIStackinterface.
Thus,threedifferentinheritancerelationsareatworkwhendefininginheritanceamong
classesandinterfaces:
1.Singleimplementationinheritancehierarchybetweenclasses:aclassextends
anotherclass(subclasses–superclasses).
2.Multipleinheritancehierarchybetweeninterfaces:aninterfaceextendsother
interfaces(subinterfaces–superinterfaces).
3.Multipleinterfaceinheritancehierarchybetweenclassesandinterfaces:aclass
implementsinterfaces(realization).
InterfaceReferences
Althoughinterfacescannotbeinstantiated,referencesofaninterfacetypecanbedeclared.
Thereferencevalueofanobjectcanbeassignedtoreferencesoftheobject’ssupertypes.
InExample7.7,anobjectoftheclassSafeStackImpliscreatedinthemain()
methodoftheclassStackUserat(9).Thereferencevalueoftheobjectisassignedto
referencesofalltheobject’ssupertypes,whichareusedtomanipulatetheobject.The
referencesarealiasestothesameSafeStackImplobject,buttheycanonlybeusedto
manipulatethisobjectasanobjectofthereferencetype.Forexample,callingthemethod
isFull()onthisobjectusingthestackRefreferencewillbeflaggedasacompile-
timeerror,astheclassStackImpldoesnotprovidesuchamethod.Polymorphic
behaviorofsupertypereferencesisdiscussedin§7.12,p.329.
WOW! eBook
www.wowebook.org
DefaultMethodsinInterfaces
Onlyinterfacescandefinedefaultmethods.Adefaultmethodisaninstancemethod
declaredwiththekeyworddefaultandwhoseimplementationisprovidedbythe
interface.However,adefaultmethodinatop-levelinterfacealwayshaspublic
accessibility,whetherthekeywordpublicisspecifiedornot.
Clickheretoviewcodeimage
defaultreturn_typemethod_name(formal_parameter_list)throws_clause
{implementaion_of_method_body}
Aclassimplementinganinterfacecanoptionallydecidetooverrideanydefaultmethodin
theinterface.Iftheclassdoesnotoverrideadefaultmethodtoprovideanew
implementation,thedefaultimplementationprovidedbytheinterfaceisinheritedbythe
class.
Noothernon-accessibilitymodifiers,suchasabstract,final,orstatic,are
allowedinadefaultmethoddeclaration,exceptthekeywordstrictfp.Adefault
methodisnotabstractbecauseitprovidesanimplementation;isnotfinalbecauseit
canbeoverridden;andisnotstaticbecauseitcanbeinvokedonlyoninstancesofa
classthatimplementstheinterfaceinwhichthedefaultmethodisdeclared.
Example7.8illustratestheuseofdefaultmethods.Thedefaultmethod
printSlogan()at(1)intheinterfaceISloganisoverriddenat(2)intheclass
JavaGuru,andinheritedbytheclassJavaGeekat(3).Theoutputfromtheprogram
showsthatthisisthecase.
WOW! eBook
www.wowebook.org
Example7.8DefaultMethodsinInterfaces
Clickheretoviewcodeimage
//File:JavaParty.java
interfaceISlogan{
defaultvoidprintSlogan(){//(1)
System.out.println(“Happinessisgettingcertified!”);
}
}
//_______________________________________________________________________________
classJavaGuruimplementsISlogan{
@Override
publicvoidprintSlogan(){//(2)overrides(1)
System.out.println(“Happinessiscatchingalltheexceptions!”);
}
}
//_______________________________________________________________________________
classJavaGeekimplementsISlogan{}//(3)inherits(1)
//_______________________________________________________________________________
publicclassJavaParty{
publicstaticvoidmain(String[]args){
JavaGuruguru=newJavaGuru();
guru.printSlogan();//(4)
JavaGeekgeek=newJavaGeek();
geek.printSlogan();//(5)
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
Happinessiscatchingalltheexceptions!
Happinessisgettingcertified!
Thekeyworddefaultinthecontextofadefaultmethodshouldnotbeconfusedwith
defaultorpackageaccessibilityofamethodinaclass,whichisimpliedintheabsenceof
anyaccessibilitymodifier.Thekeyworddefaultisalsousedonlyfordefaultmethod
declarationsininterfacesthatprovideanimplementationforsuchmethods,andnotby
classesthatoverridethem.
Overridingadefaultmethodfromaninterfacedoesnotnecessarilyimplythatanew
implementationisbeingprovided.Thedefaultmethodcanalsobeoverriddenby
providinganabstractmethoddeclaration,asillustratedbythenextcodesnippet.The
defaultmethodprintSlogan()at(1)intheinterfaceISloganisoverriddenbyan
abstractmethoddeclarationat(2)and(3)intheinterfaceINewSloganandtheabstract
classJavaMaster,respectively.Thisstrategyeffectivelyforcesthesubtypesofthe
interfaceINewSloganandoftheabstractclassJavaMastertoprovideanew
concreteimplementationforthemethod,asonewouldexpectforanabstractmethod.
Clickheretoviewcodeimage
interfaceISlogan{
defaultvoidprintSlogan(){//(1)Defaultmethod.
System.out.println(“Happinessisgettingcertified!”);
}
}
WOW! eBook
www.wowebook.org
interfaceINewSloganextendsISlogan{
@Override
abstractvoidprintSlogan();//(2)overrides(1)withabstract
method.
}
abstractclassJavaMasterimplementsISlogan{
@Override
publicabstractvoidprintSlogan();//(3)overrides(1)withabstract
method.
}
Problemswithmultipleinheritancecanarisewhendefaultmethodsareinheritedfrom
multipleinterfaces.Example7.9illustratesonesuchcase.Thedefaultmethod
printSlogan()isdeclaredat(1)and(2)intheinterfacesICheapSloganand
IFunny-Slogan,respectively.Thetwomethoddeclarationshavethesamesignature.
TheinterfaceIAvailableSloganat(3)triestoextendthetwointerfaces
ICheapSloganandIFunnySlogan.Ifthiswasallowed,theinterface
IAvailableSloganwouldinherittwoimplementationsofmethodsthathavethesame
signature,whichofcourseisnotallowed—sothecompilerflagsitasanerror.Bythe
sametoken,thecompilerflagsanerrorat(4),indicatingthattheabstractclass
Wholesalercannotinherittwomethodswiththesamesignature.
Thewayoutofthisdilemmaistooverridetheconflictingmethods.Theabstractclass
RetailSellerthatimplementstheinterfacesICheapSloganandIFunnySlogan
overridestheconflictingmethodsbyprovidinganabstractmethoddeclarationofthe
defaultmethodprintSlogan()at(5).Similarly,theclassNetSellerthat
implementstheinterfacesICheapSloganandIFunnySloganoverridesthe
conflictingmethodsbyprovidinganimplementationofthedefaultmethod
printSlogan()at(6).
TheupshotofthissolutionisthatclientsoftheclassesRetailSellerand
NetSellernowhavetodealwiththenewdeclarationsoftheprintSlogan()
methodprovidedbytheseclasses.OnesuchclientistheclassMutlipleInheritance
at(10),whichcallsthemethodprintSlogan()onaninstanceofclassNetSellerat
(11).Notsurprisingly,theprogramoutputshowsthatthemethodintheNetSellerclass
wasexecuted.
WhatiftheclassNetSellerwantedtoinvokethedefaultmethodprintSlogan()in
theinterfacesitimplements?Theoverriddendefaultmethodcanbecalledbythe
overridingsubtype(inthiscase,NetSeller)usingthekeywordsuperinconjunction
withthefullyqualifiednameoftheinterfaceandthenameofthemethod,asshownat(8)
and(9).Thissyntaxworksforcallingoverriddendefaultmethodsinthedirect
superinterface,butnotatanyhigherlevelintheinheritancehierarchy.Theclass
NetSellercancallonlydefaultmethodsinitsdirectsuperinterfacesICheapSlogan
andIFunnySlogan.ItwouldnotbepossiblefortheclassNetSellertocallany
defaultmethodsinheritedbythesesuperinterfaces,eveniftheyhadany.
WOW! eBook
www.wowebook.org
Example7.9DefaultMethodsandMultipleInheritance
Clickheretoviewcodeimage
//File:MultipleInheritance.java
interfaceICheapSlogan{
defaultvoidprintSlogan(){//(1)
System.out.println(“Override,don’toverload.”);
}
}
//_______________________________________________________________________________
interfaceIFunnySlogan{
defaultvoidprintSlogan(){//(2)
System.out.println(“Catchexceptions,notbugs.”);
}
}
//_______________________________________________________________________________
interfaceIAvailableSlogan//(3)Compile-timeerror.
extendsICheapSlogan,IFunnySlogan{}
//_______________________________________________________________________________
abstractclassWholesaler//(4)Compile-timeerror.
implementsICheapSlogan,IFunnySlogan{}
//_______________________________________________________________________________
abstractclassRetailSellerimplementsICheapSlogan,IFunnySlogan{
@Override//Abstractmethod.
publicabstractvoidprintSlogan();//(5)overrides(1)and(2).
}
//_______________________________________________________________________________
classNetSellerimplementsICheapSlogan,IFunnySlogan{
@Override//Concretemethod.
publicvoidprintSlogan(){//(6)overrides(1)and(2).
System.out.println(“Thinkoutsideoftheclass.”);
}
publicvoidinvokeDirect(){//(7)
ICheapSlogan.super.printSlogan();//(8)calls
ICheapSlogan.printSlogan()
IFunnySlogan.super.printSlogan();//(9)calls
IFunnySlogan.printSlogan()
}
}
//_______________________________________________________________________________
publicclassMultipleInheritance{//(10)
publicstaticvoidmain(String[]args){
NetSellerseller=newNetSeller();
seller.printSlogan();//(11)
seller.invokeDirect();
}
}
Outputfromtheprogram:
Thinkoutsideoftheclass.
Override,don’toverload.
Catchexceptions,notbugs.
WOW! eBook
www.wowebook.org
StaticMethodsinInterfaces
Aninterfacecanalsodeclarestaticmethods.Staticmethoddeclarationsinatop-level
interfaceareanalogoustostaticmethoddeclarationsinaclass(§4.8,p.132).However,a
staticmethodinatop-levelinterfacealwayshaspublicaccessibility,whetherthe
keywordpublicisspecifiedornot.Aswithstaticmethodsinaclass,thekeyword
staticismandatory;otherwise,thecodewillnotcompile.Withoutthekeyword
static,themethoddeclarationisidenticaltothatofaninstancemethod,butsuch
instancemethodscannotbedeclaredinaninterface.
Clickheretoviewcodeimage
staticreturn_typemethod_name(formal_parameter_list)throws_clause
{implementaion_of_method_body}
Staticmethodsinaninterfacedifferfromthoseinaclassinoneimportantrespect:Static
methodsinaninterfacecannotbeinherited,unlikestaticmethodsinclasses.This
essentiallymeansthatsuchmethodscannotbeinvokeddirectlybycallingthemethodin
subinterfacesorinclassesthatextendorimplementinterfacescontainingsuchmethods,
respectively.Astaticmethodcanbeinvokedonlybyusingitsqualifiedname—thatis,the
nameoftheinterfaceinwhichitisdeclared—togetherwithitssimplename,usingthedot
notation(.).
Example7.10illustratestheuseofstaticmethodsininterfaces.Thestaticmethod
getNumOfCylinders()at(1)isdeclaredintheIMaxEngineSizeinterface.There
aretwoimplementationsofthemethodgetEngineSize(),at(2)and(3),inthe
interfaceIMaxEngineSizeanditssubinterfaceINewEngineSize,respectively.The
classCarRaceimplementsthesubinterfaceINewEngineSize.
ItisnotpossibletoinvokethemethodgetNumOfCylinders()directly,asshownat
(4).ItisalsonotpossibletoinvokedirectlythemethodgetEngineSize()fromeither
interface,asshownat(6).Therespectiveimplementationsofthestaticmethodscanbe
invokedonlybyusingtheirqualifiednames,asshownat(5),(7)and(8).Itdoesnot
matterthatastaticmethodisredeclaredinasubinterface;thestaticmethodisnot
inherited.EachstaticmethoddeclarationinExample7.10isanewmethod.
WOW! eBook
www.wowebook.org
Example7.10StaticMethodsinInterfaces
Clickheretoviewcodeimage
//File:CarRace.java
importstaticjava.lang.System.out;
interfaceIMaxEngineSize{
staticintgetNumOfCylinders(){return6;}//(1)Staticmethod
staticdoublegetEngineSize(){return1.6;}//(2)Staticmethod
}
//_______________________________________________________________________________
interfaceINewEngineSizeextendsIMaxEngineSize{
staticdoublegetEngineSize(){return2.4;}//(3)Staticmethod
}
//_______________________________________________________________________________
publicclassCarRaceimplementsINewEngineSize{
publicstaticvoidmain(String[]args){
//out.println(“No.ofcylinders:”+
//getNumOfCylinders());//(4)Compile-time
error.
out.println(“No.ofcylinders:”+
IMaxEngineSize.getNumOfCylinders());//(5)
//out.println(“Enginesize:”+getEngineSize());//(6)Compile-time
error.
out.println(“Maxenginesize:”+IMaxEngineSize.getEngineSize());//(7)
out.println(“Newenginesize:”+INewEngineSize.getEngineSize());//(8)
}
}
Outputfromtheprogram:
No.ofcylinders:6
Maxenginesize:1.6
Newenginesize:2.4
ConstantsinInterfaces
Aninterfacecanalsodefinenamedconstants.Namingconventionsrecommendusing
uppercaselettersfortheirnames,withmultiplewordsinthenamebeingseparatedby
underscores.Suchconstantsaredefinedbyfielddeclarationsandareconsideredtobe
public,static,andfinal.Thesemodifierscanbeomittedfromthedeclaration.
Suchaconstantmustbeinitializedwithaninitializerexpression.
Aninterfaceconstantcanbeaccessedbyanyclient(aclassorinterface)usingitsqualified
name,regardlessofwhethertheclientextendsorimplementsitsinterface.However,ifthe
clientisaclassthatimplementsthisinterfaceorisaninterfacethatextendsthisinterface,
thentheclientcanalsoaccesssuchconstantsdirectlybytheirsimplenames.Suchaclient
inheritstheinterfaceconstants.Typicalusageofconstantsininterfacesisillustratedin
Example7.11,showingaccessbothbytheconstant’ssimplenameanditsqualifiedname
intheprintstatementsat(1)and(2),respectively.
WOW! eBook
www.wowebook.org
Example7.11ConstantsinInterfaces
Clickheretoviewcodeimage
//File:Client.java
interfaceConstants{
doublePI_APPROXIMATION=3.14;
StringAREA_UNITS=“sq.cm.”;
StringLENGTH_UNITS=“cm.”;
}
//______________________________________________________________________________
publicclassClientimplementsConstants{
publicstaticvoidmain(String[]args){
doubleradius=1.5;
//(1)Usingsimplename:
System.out.printf(“Areaofcircleis%.2f%s%n”,
PI_APPROXIMATION*radius*radius,AREA_UNITS);
//(2)Usingqualifiedname:
System.out.printf(“Circumferenceofcircleis%.2f%s%n”,
2.0*Constants.PI_APPROXIMATION*radius,
Constants.LENGTH_UNITS);
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
Areaofcircleis7.06sq.cm.
Circumferenceofcircleis9.42cm.
Extendinganinterfacethathasconstantsisanalogoustoextendingaclasshavingstatic
variables.ThisisillustratedbyFigure7.4andExample7.12.Notethediamondshapeof
theinheritancehierarchy,indicatingthepresenceofmultipleinheritancepathsthrough
whichconstantscanbeinherited.TheconstantsIDLEandBUSYat(1)and(2)inthe
interfaceIBaseStatesareinheritedbythesubinterfaceIAllStatesviaboththe
interfaceIExtStatesAandtheinterfaceIExtStatesB.Insuchcases,theconstantis
consideredtobeinheritedonlyonce,andcanbeaccessedbyitssimplename,asshownat
(12)inExample7.12.
WOW! eBook
www.wowebook.org
Figure7.4InheritanceRelationshipsforInterfaceConstants
Constantscanbehiddenbythesubinterfaces.ThedeclarationoftheconstantBLOCKEDat
(6)intheinterfaceIAllStateshidesthedeclarationoftheconstantat(2)inthe
interfaceIBaseStates.Thenewdeclarationcanbeaccessedbyitssimplenameina
classimplementingtheinterfaceIAllStates,asshownat(10)inExample7.12.The
hiddenconstantdeclarationcanalwaysbeaccessedbyusingitsqualifiednameasshown
at(11)inExample7.12.
Inthecaseofmultipleinheritanceofinterfaceconstants,anynameconflictscanbe
resolvedbyusingthequalifiednametoaccesstheconstants.Thisisillustratedbythe
constantDISMANTLED,whichisdeclaredinboththeIExtStatesAand
IExtStatesBinterfaces.Bothdeclarationsareinheritedbythesubinterface
IAllStates.Suchdeclarationsaresaidtobeambiguous.Thecompilerwillreportan
erroronlyifsuchconstantsareaccessedbytheirsimplenames,asshownat(7)and(8)for
theconstantDISMANTLE.Onlythequalifiednamecanbeusedtodisambiguatesuch
constantsandresolvetheconflict,asshownat(7a)and(8a)fortheconstant
DISMANTLE.
Whendefiningasetofrelatedconstants,therecommendedpracticeistousean
enumeratedtype,ratherthannamedconstantsinaninterface.
WOW! eBook
www.wowebook.org
Example7.12InheritingConstantsinInterfaces
Clickheretoviewcodeimage
//File:Factory.java
interfaceIBaseStates{
StringIDLE=“idle”;//(1)
StringBUSY=“busy”;//(2)
StringBLOCKED=“blocked”;//(3)
}
//_______________________________________________________________________________
interfaceIExtStatesAextendsIBaseStates{
StringDISMANTLED=“dismantled”;//(4)
}
//_______________________________________________________________________________
interfaceIExtStatesBextendsIBaseStates{
StringDISMANTLED=“kaput”;//(5)
}
//_______________________________________________________________________________
interfaceIAllStatesextendsIExtStatesB,IExtStatesA{
StringBLOCKED=“outoforder”;//(6)hides(3)
//StringABSOLETE=BLOCKED+“,”+
//DISMANTLED+”andscrapped.”;//(7)Ambiguous
StringABSOLETE=BLOCKED+“,”+
IExtStatesB.DISMANTLED+”andscrapped”;//(7a)
}
//_______________________________________________________________________________
publicclassFactoryimplementsIAllStates{
publicstaticvoidmain(String[]args){
//System.out.println(“MachineAis”+DISMANTLED);//(8)
Ambiguous.
System.out.println(“MachineAis”+IExtStatesB.DISMANTLED);//(8a)
System.out.println(“MachineBis”+ABSOLETE);//
(9)IAllStates.ABSOLETE
System.out.println(“MachineCis”+BLOCKED);//(10)
IAllStates.BLOCKED
System.out.println(“MachineDis”+IBaseStates.BLOCKED);//(11)
System.out.println(“MachineEis”+BUSY);//(12)Simplename
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
MachineAiskaput
MachineBisoutoforder,kaputandscrapped
MachineCisoutoforder
MachineDisblocked
MachineEisbusy
ReviewQuestions
7.11Whichofthefollowingstatementsaboutinterfacesaretrue?
Selectthetwocorrectanswers.
(a)Interfacesallowmultipleimplementationinheritance.
(b)Interfacescanbeextendedbyanynumberofinterfaces.
WOW! eBook
www.wowebook.org
(c)Interfacescanextendanynumberofinterfaces.
(d)Membersofaninterfaceareneverstatic.
(e)Membersofaninterfacecanalwaysbedeclaredstatic.
7.12Whichmodifierscanmethodsdeclaredinatop-levelinterfacespecify?
Selectthefourcorrectanswers.
(a)public
(b)protected
(c)private
(d)default
(e)abstract
(f)static
(g)final
7.13Whichmodifiersareimplicitlyimpliedforinterfacevariables?
Selectthethreecorrectanswers.
(a)public
(b)protected
(c)private
(d)default
(e)abstract
(f)static
(g)final
7.14Howmanyerrorswillthecompilerreportforthefollowingcode?
Clickheretoviewcodeimage
publicinterfaceVehicle{
finalstaticintNUMBER_OF_HEADLIGHTS;//(1)
voidincreaseSpeed(intincrement){//(2)
System.out.println(“Increasingspeedby”+increment);
}
staticvoidreduceSpeed(intdecrement);//(3)
finaldefaultvoidstop(){//(4)
System.out.println(“Slammingthebrakes!”);
}
}
Selecttheonecorrectanswer.
(a)Noerrors
(b)1error
WOW! eBook
www.wowebook.org
(c)2errors
(d)3errors
(e)Morethan3errors
7.15Whichmethodcallscanbeinsertedatboth(1)and(2),sothatthefollowingcode
willstillcompile?
Clickheretoviewcodeimage
//File:Company.java
interfaceISlogan{
StringSLOGAN=“Happinesssharedishappinessdoubled!”;
defaultvoidprintSlogan(){System.out.println(SLOGAN);}
}
//______________________________________________________________________________
publicclassCompanyimplementsISlogan{
publicstaticvoidmain(String[]args){
Companyco=newCompany();
ISlogansl=co;
//(1)INSERTTHEMETHODCALLHERE.
}
publicvoidtestSlogan(){
Companyco=newCompany();
ISlogansl=co;
//(2)INSERTTHEMETHODCALLHERE.
}
}
Selectthetwocorrectanswers.
(a)printSlogan();
(b)co.printSlogan();
(c)sl.printSlogan();
(d)Company.printSlogan();
(e)ISlogan.printSlogan();
7.16Whichmethodcallcanbeinsertedatboth(1)and(2),sothatthefollowingcode
willstillcompile?
Clickheretoviewcodeimage
//File:Firm.java
interfaceINewSlogan{
StringSLOGAN=“Troublesharedistroublehalved!”;
staticvoidprintSlogan(){System.out.println(SLOGAN);}
}
//______________________________________________________________________________
publicclassFirmimplementsINewSlogan{
publicstaticvoidmain(String[]args){
Firmco=newFirm();
INewSlogansl=co;
//(1)INSERTTHESTATEMENTEXPRESSIONHERE.
}
voidtestSlogan(){
Firmco=newFirm();
WOW! eBook
www.wowebook.org
INewSlogansl=co;
//(2)INSERTTHESTATEMENTEXPRESSIONHERE.
}
}
Selecttheonecorrectanswer.
(a)printSlogan();
(b)co.printSlogan();
(c)sl.printSlogan();
(d)Firm.printSlogan();
(e)INewSlogan.printSlogan();
7.17Whatwillthefollowingprogramprintwhencompiledandrun?
Clickheretoviewcodeimage
//File:RaceA.java
interfaceIJogger{
defaultbooleanjustDoIt(Stringmsg){returnfalse;}//(1)
staticbooleanjustDoIt(inti){returntrue;}//(2)
}
classAthleteimplementsIJogger{
publicbooleanjustDoIt(Stringmsg){returntrue;}//(3)
publicbooleanjustDoIt(inti){returnfalse;}//(4)
}
publicclassRaceA{
publicstaticvoidmain(String[]args){
Athleteathlete=newAthlete();
IJoggerjogger=athlete;
System.out.print(jogger.justDoIt(“Run”));//(5)
System.out.println(“|”+athlete.justDoIt(10));//(6)
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile.
(b)true|true
(c)true|false
(d)false|true
(e)false|false
7.18Whatwillthefollowingprogramprintwhencompiledandrun?
Clickheretoviewcodeimage
//File:HouseC
interfaceISwitch{
defaultbooleanisOn(){returnfalse;}//(1)
}
classLightimplementsISwitch{
booleanisOn(){returntrue;}//(2)
WOW! eBook
www.wowebook.org
}
publicclassHouseC{
publicstaticvoidmain(String[]args){
ISwitchlightswitch=newLight();
System.out.println(lightswitch.isOn());
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile.
(b)Theprogramwillcompile,andprinttruewhenrun.
(c)Theprogramwillcompile,andprintfalsewhenrun.
(d)Theprogramwillcompile,andthrowanexceptionwhenrun.
7.19Whichofthesefielddeclarationsarelegalwithinthebodyofaninterface?
Selectthethreecorrectanswers.
(a)publicstaticintANSWER=42;
(b)intANSWER;
(c)staticfinalintANSWER=42;
(d)publicintANSWER=42;
(e)privatestaticfinalintANSWER=42;
7.20Whichstatementsaboutthekeywordsextendsandimplementsaretrue?
Selectthetwocorrectanswers.
(a)Thekeywordextendsisusedtospecifythataninterfaceinheritsfrom
anotherinterface.
(b)Thekeywordextendsisusedtospecifythataclassimplementsaninterface.
(c)Thekeywordimplementsisusedtospecifythataninterfaceinheritsfrom
anotherinterface.
(d)Thekeywordimplementsisusedtospecifythataclassinheritsfroman
interface.
(e)Thekeywordimplementsisusedtospecifythataclassinheritsfromanother
class.
7.21Whichstatementistrueaboutthefollowingcode?
Clickheretoviewcodeimage
//File:MyClass.java
abstractclassMyClassimplementsInterface1,Interface2{
publicvoidf(){}
publicvoidg(){}
}
interfaceInterface1{
WOW! eBook
www.wowebook.org
intVAL_A=1;
intVAL_B=2;
voidf();
voidg();
}
interfaceInterface2{
intVAL_B=3;
intVAL_C=4;
voidg();
voidh();
}
Selecttheonecorrectanswer.
(a)MyClassimplementsonlyInterface1;theimplementationforvoid
h()fromInterface2ismissing.
(b)Thedeclarationsofvoidg()inthetwointerfacesareinconflict,sothecode
willnotcompile.
(c)ThedeclarationsofintVAL_Binthetwointerfacesareinconflict,sothe
codewillnotcompile.
(d)Nothingiswrongwiththecode;itwillcompilewithouterrors.
7.22Whichdeclarationcanbeinsertedat(1)withoutresultinginacompile-timeerror?
interfaceMyConstants{
intR=42;
intS=69;
//(1)INSERTCODEHERE
}
Selectthetwocorrectanswers.
(a)finaldoubleCIRCUMFERENCE=2*Math.PI*R;
(b)intTOTAL=TOTAL+R+S;
(c)intAREA=R*S;
(d)publicstaticMAIN=15;
(e)protectedintCODE=13082009;
7.7ArraysandSubtyping
Table7.3summarizesthetypesfoundinJava.Onlyprimitivedataandreferencevalues
canbestoredinvariables.Onlyclassandarraytypescanbeexplicitlyinstantiatedto
createobjects.
WOW! eBook
www.wowebook.org
Table7.3TypesandValues
ArraysandSubtypeCovariance
ArraysareobjectsinJava.Arraytypes(boolean[],Object[],StackImpl[])
implicitlyaugmenttheinheritancehierarchy.TheinheritancehierarchydepictedinFigure
7.3,forexample,canbeaugmentedbythecorrespondingarraytypestoproducethetype
hierarchyshowninFigure7.5.Anarraytypeisshownasa“class”withthe[]notation
appendedtothenameoftheelementtype.TheclassSafeStackImplisasubclassof
theclassStackImpl.Thecorrespondingarraytypes,SafeStackImpl[]and
StackImpl[],areshownasthesubtypeandthesupertype,respectively,inthetype
hierarchy.Figure7.5alsoshowsarraytypescorrespondingtosomeoftheprimitivedata
types.
Figure7.5ReferenceTypeHierarchy:ArraysandSubtypeCovariance
FromthetypehierarchyinFigure7.5,thefollowingfactsareapparent:
•AllreferencetypesaresubtypesoftheObjecttype.Thisappliestoclasses,
interfaces,enums,andarraytypes,astheseareallreferencetypes.
•AllarraysofreferencetypesarealsosubtypesofthearraytypeObject[],but
arraysofprimitivedatatypesarenot.NotethatthearraytypeObject[]isalsoa
subtypeoftheObjecttype.
•Ifanon-genericreferencetypeisasubtypeofanothernon-genericreferencetype,
WOW! eBook
www.wowebook.org
thecorrespondingarraytypesalsohaveananalogoussubtype–supertype
relationship.Thisiscalledthesubtypecovariancerelationship.
•Thereisnosubtype–supertyperelationshipbetweenatypeanditscorresponding
arraytype.
Wecancreateanarrayofaninterfacetype,butwecannotinstantiateaninterface(asisthe
casewithabstractclasses).Inthefollowingdeclarationstatement,thereference
iSafeStackArrayhastypeISafeStack[](i.e.,anarrayoftheinterfacetype
ISafeStack):
Clickheretoviewcodeimage
ISafeStack[]iSafeStackArray=newISafeStack[5];
ThearraycreationexpressioncreatesanarraywhoseelementtypeisISafeStack.The
arrayobjectcanaccommodatefivereferencesofthetypeISafeStack.Thedeclaration
statementdoesnotinitializethesereferencestorefertoanyobjects;instead,theyare
initializedtothedefaultvaluenull.
ArrayStoreCheck
Anarrayreferenceexhibitspolymorphicbehaviorlikeanyotherreference,subjecttoits
locationinthetypehierarchy(§7.12,p.329).However,aruntimecheckisnecessary
whenobjectsareinsertedinanarray,asthenextexampleillustrates.
Thefollowingassignmentisvalid,asasupertypereference(StackImpl[])canreferto
objectsofitssubtype(SafeStackImpl[]):
Clickheretoviewcodeimage
StackImpl[]stackImplArray=newSafeStackImpl[2];//(1)
SinceStackImplisasupertypeofSafeStackImpl,thefollowingassignmentisalso
valid:
Clickheretoviewcodeimage
stackImplArray[0]=newSafeStackImpl(10);//(2)
Theassignmentat(2)assignsthereferencevalueofanewSafeStackImplobjectto
thereferenceatindex0intheSafeStackImpl[]object(i.e.,thearrayof
SafeStackImpl)createdat(1).
SincethetypeofstackImplArray[i],(0≤i<2),isStackImpl,itshouldbe
possibletomakethefollowingassignmentaswell:
Clickheretoviewcodeimage
stackImplArray[1]=newStackImpl(20);//(3)
ArrayStoreException
Atcompiletimetherearenoproblems,asthecompilercannotdeducethatthearray
variablestackImplArraywillactuallydenoteaSafeStackImpl[]objectat
runtime.However,theassignmentat(3)resultsinanArrayStoreExceptionbeing
thrownatruntime,becauseanarrayofSafeStackImplobjectscannotpossiblycontain
objectsofitssupertypeStackImpl.
WOW! eBook
www.wowebook.org
Thearraystorecheckatruntimeensuresthatanobjectbeingstoredinthearrayis
assignmentcompatible(p.314)withtheelementtypeofthearray.Tomakethearraystore
checkfeasibleatruntime,thearrayretainsinformationaboutitsdeclaredelementtypeat
runtime.
7.8ReferenceValuesandConversions
Areviewofconversions(§5.1,p.144)isrecommendedbeforeproceedingwiththis
section.
Referencevalues,likeprimitivevalues,canbeassigned,cast,andpassedasarguments.
Conversionscanoccurinthefollowingcontexts:
•Assignment
•Methodinvocation
•Casting
Theruleofthumbfortheprimitivedatatypesisthatwideningconversionsarepermitted,
butnarrowingconversionsrequireanexplicitcast.Theruleofthumbforreferencevalues
isthatwideningconversionsupthetypehierarchyarepermitted,butnarrowing
conversionsdownthehierarchyrequireanexplicitcast.Inotherwords,conversionsthat
arefromasubtypetoitssupertypesareallowed,butotherconversionsrequireanexplicit
castorareotherwiseillegal.Thereisnonotionofpromotionforreferencevalues.
7.9ReferenceValueAssignmentConversions
Inthecontextofassignments,thefollowingconversionsarepermitted(Table5.1,p.147):
•Wideningprimitiveandreferenceconversions(long←int,Object←
String)
•Boxingconversionofprimitivevalues,followedbyoptionalwideningreference
conversion(Integer←int,Number←Integer←int)
•Unboxingconversionofaprimitivevaluewrapperobject,followedbyoptional
wideningprimitiveconversion(long←int←Integer)
Forassignmentconversionsonly,thefollowingconversionsarealsopossible:
•Narrowingconversionforconstantexpressionsofnon-longintegertypes,with
optionalboxing(Byte←byte←int)
Notethattheserulesimplythatawideningconversioncannotbefollowedbyanyboxing
conversion,buttheconverseispermitted.
Wideningreferenceconversionstypicallyoccurduringassignmentupthetypehierarchy,
withimplicitconversionofthesourcereferencevaluetothatofthedestinationreference
type:
Clickheretoviewcodeimage
Objectobj=“Upthetree”;//Wideningreferenceconversion:Object<—
String
Stringstr1=obj;//NotOK.Narrowingreferenceconversionrequiresa
WOW! eBook
www.wowebook.org
cast.
Stringstr2=newInteger(10);//Illegal.NorelationbetweenStringand
Integer.
Thesourcevaluecanbeaprimitivevalue,inwhichcasethevalueisboxedinawrapper
objectcorrespondingtotheprimitivetype.Ifthedestinationreferencetypeisasupertype
ofthewrappertype,awideningreferenceconversioncanoccur:
Clickheretoviewcodeimage
IntegeriRef=10;//Onlyboxing
Numbernum=10L;//Boxing,followedbywidening:Number<–Long<–long
Objectobj=100;//Boxing,followedbywidening:Object<–Integer<–int
Moreexamplesofboxingduringassignmentcanbefoundin§5.1,p.145.
Example7.13AssigningandPassingReferenceValues
Clickheretoviewcodeimage
interfaceIStack{/*FromExample7.7*/}
interfaceISafeStackextendsIStack{/*FromExample7.7*/}
classStackImplimplementsIStack{/*FromExample7.7*/}
classSafeStackImplextendsStackImpl
implementsISafeStack{/*FromExample7.7*/}
publicclassReferenceConversion{
publicstaticvoidmain(String[]args){
//Referencedeclarations:
ObjectobjRef;
StackImplstackRef;
SafeStackImplsafeStackRef;
IStackiStackRef;
ISafeStackiSafeStackRef;
//SourceTypeisaclasstype:
safeStackRef=newSafeStackImpl(10);
objRef=safeStackRef;//(1)Alwayspossible
stackRef=safeStackRef;//(2)Subclasstosuperclassassignment
iStackRef=stackRef;//(3)StackImplimplementsIStack
iSafeStackRef=safeStackRef;//(4)SafeStackImplimplements
ISafeStack
//SourceTypeisaninterfacetype:
objRef=iStackRef;//(5)Alwayspossible
iStackRef=iSafeStackRef;//(6)Sub-tosuper-interface
assignment
//SourceTypeisanarraytype:
Object[]objArray=newObject[3];
StackImpl[]stackArray=newStackImpl[3];
SafeStackImpl[]safeStackArray=newSafeStackImpl[5];
ISafeStack[]iSafeStackArray=newISafeStack[5];
int[]intArray=newint[10];
//Referencevalueassignments:
objRef=objArray;//(7)Alwayspossible
objRef=stackArray;//(8)Alwayspossible
objArray=stackArray;//(9)Alwayspossible
objArray=iSafeStackArray;//(10)Alwayspossible
objRef=intArray;//(11)Alwayspossible
//objArray=intArray;//(12)Compile-timeerror:
WOW! eBook
www.wowebook.org
//int[]notsubtypeofObject[]
stackArray=safeStackArray;//(13)Subclassarraytosuperclass
array
iSafeStackArray=safeStackArray;//(14)SafeStackImplimplements
ISafeStack
//Methodinvocationconversions:
System.out.println(“Firstcall:”);
sendParams(stackRef,safeStackRef,iStackRef,
safeStackArray,iSafeStackArray);//(15)
//CallSignature:sendParams(StackImpl,SafeStackImpl,IStack,
//SafeStackImpl[],ISafeStack[]);
System.out.println(“Secondcall:”);
sendParams(iSafeStackArray,stackRef,iSafeStackRef,
stackArray,safeStackArray);//(16)
//CallSignature:sendParams(ISafeStack[],StackImpl,ISafeStack,
//StackImpl[],SafeStackImpl[]);
}
publicstaticvoidsendParams(ObjectobjRefParam,StackImplstackRefParam,
IStackiStackRefParam,StackImpl[]stackArrayParam,
IStack[]iStackArrayParam){//(17)
//Signature:sendParams(Object,StackImpl,IStack,StackImpl[],
IStack[])
//Printclassnameofobjectdenotedbythereferenceatruntime.
System.out.println(objRefParam.getClass());
System.out.println(stackRefParam.getClass());
System.out.println(iStackRefParam.getClass());
System.out.println(stackArrayParam.getClass());
System.out.println(iStackArrayParam.getClass());
}
}
Outputfromtheprogram:
Firstcall:
classSafeStackImpl
classSafeStackImpl
classSafeStackImpl
class[LSafeStackImpl;
class[LSafeStackImpl;
Secondcall:
class[LSafeStackImpl;
classSafeStackImpl
classSafeStackImpl
class[LSafeStackImpl;
class[LSafeStackImpl;
Therulesforreferencevalueassignmentarestatedinthissection,basedonthefollowing
code:
Clickheretoviewcodeimage
SourceTypesrcRef;
//srcRefisappropriatelyinitialized.
DestinationTypedestRef=srcRef;
Ifanassignmentislegal,thereferencevalueofsrcRefissaidtobeassignable(or
assignmentcompatible)tothereferenceofDestinationType.Therulesareillustrated
byconcretecasesfromExample7.13.NotethatthecodeinExample7.13usesreference
typesfromExample7.7,p.292.
WOW! eBook
www.wowebook.org
•IftheSourceTypeisaclasstype,thereferencevalueinsrcRefmaybeassigned
tothedestRefreference,providedtheDestinationTypeisoneofthe
following:
DestinationTypeisasuperclassofthesubclassSourceType.
DestinationTypeisaninterfacetypethatisimplementedbytheclass
SourceType.
Clickheretoviewcodeimage
objRef=safeStackRef;//(1)Alwayspossible
stackRef=safeStackRef;//(2)Subclasstosuperclassassignment
iStackRef=stackRef;//(3)StackImplimplementsIStack
iSafeStackRef=safeStackRef;//(4)SafeStackImplimplements
ISafeStack
•IftheSourceTypeisaninterfacetype,thereferencevalueinsrcRefmaybe
assignedtothedestRefreference,providedtheDestinationTypeisoneof
thefollowing:
DestinationTypeistheObjectclass.
DestinationTypeisasuperinterfaceofthesubinterfaceSourceType.
Clickheretoviewcodeimage
objRef=iStackRef;//(5)Alwayspossible
iStackRef=iSafeStackRef;//(6)Subinterfacetosuperinterface
assignment
•IftheSourceTypeisanarraytype,thereferencevalueinsrcRefmaybe
assignedtothedestRefreference,providedtheDestinationTypeisoneof
thefollowing:
DestinationTypeistheObjectclass.
DestinationTypeisanarraytype,wheretheelementtypeofthe
SourceTypeisassignabletotheelementtypeoftheDestinationType.
Clickheretoviewcodeimage
objRef=objArray;//(7)Alwayspossible
objRef=stackArray;//(8)Alwayspossible
objArray=stackArray;//(9)Alwayspossible
objArray=iSafeStackArray;//(10)Alwayspossible
objRef=intArray;//(11)Alwayspossible
//objArray=intArray;//(12)Compile-timeerror:
//int[]notsubtypeofObject[]
stackArray=safeStackArray;//(13)Subclassarraytosuperclass
array
iSafeStackArray=safeStackArray;//(14)SafeStackImplimplements
ISafeStack
Therulesforassignmentareenforcedatcompiletime,guaranteeingthatnotype
conversionerrorwilloccurduringassignmentatruntime.Suchconversionsaretype-safe.
Thereasontherulescanbeenforcedatcompiletimeisthattheyconcernthedeclaredtype
ofthereference(whichisalwaysknownatcompiletime)ratherthantheactualtypeofthe
objectbeingreferenced(whichisknownatruntime).
WOW! eBook
www.wowebook.org
7.10MethodInvocationConversionsInvolvingReferences
Theconversionsforreferencevalueassignmentarealsoapplicabletomethodinvocation
conversions,exceptforthenarrowingconversionforconstantexpressionsofnon-long
integertype(Table5.1,p.147).Thisisreasonable,asparametersinJavaarepassedby
value(§3.5,p.72),requiringthatvaluesoftheactualparametersmustbeassignableto
formalparametersofthecompatibletypes.
InExample7.13,themethodsendParams()at(17)hasthefollowingsignature,
showingthetypesoftheformalparameters:
Clickheretoviewcodeimage
sendParams(Object,StackImpl,IStack,StackImpl[],IStack[])
Themethodcallat(15)hasthefollowingsignature,showingthetypesoftheactual
parameters:
Clickheretoviewcodeimage
sendParams(StackImpl,SafeStackImpl,IStack,SafeStackImpl[],ISafeStack[]);
Notethattheassignmentofthevaluesoftheactualparameterstothecorresponding
formalparametersislegal,accordingtotherulesforassignmentdiscussedearlier.The
methodcallat(16)providesanotherexampleoftheparameterpassingconversion.Ithas
thefollowingsignature:
Clickheretoviewcodeimage
sendParams(ISafeStack[],StackImpl,ISafeStack,StackImpl[],
SafeStackImpl[]);
Analogoustoassignment,therulesforparameterpassingconversionsarebasedonthe
referencetypeoftheparametersandareenforcedatcompiletime.TheoutputinExample
7.13showstheclassoftheactualobjectsreferencedbytheformalparametersatruntime,
whichinthiscaseturnsouttobeeitherSafeStackImplorSafeStackImpl[].The
characters[Lintheoutputindicateaone-dimensionalarrayofaclassorinterfacetype
(seetheClass.getName()methodintheJavaSEplatformAPIdocumentation).
OverloadedMethodResolution
Inthissubsection,wetakealookatsomeaspectsregardingoverloadedmethodresolution
—namely,howthecompilerdetermineswhichoverloadedmethodwillbeinvokedbya
givenmethodcallatruntime.
Resolutionofoverloadedmethodsselectsthemostspecificmethodforexecution.One
methodisconsideredmorespecificthananothermethodifallactualparametersthatcan
beacceptedbytheonemethodcanbeacceptedbytheothermethod.Ifmorethanone
suchmethodispresent,thecallisdescribedasambiguous.Thefollowingoverloaded
methodsillustratethissituation:
Clickheretoviewcodeimage
privatestaticvoidflipFlop(Stringstr,inti,IntegeriRef){//(1)
out.println(str+”==>(String,int,Integer)”);
}
privatestaticvoidflipFlop(Stringstr,inti,intj){//(2)
out.println(str+”==>(String,int,int)”);
WOW! eBook
www.wowebook.org
}
Theirmethodsignaturesfollow:
Clickheretoviewcodeimage
flipFlop(String,int,Integer)//See(1)
flipFlop(String,int,int)//See(2)
Thefollowingmethodcallisambiguous:
Clickheretoviewcodeimage
flipFlop(“(String,Integer,int)”,newInteger(4),2004);//(3)Ambiguous
call
Ithasthecallsignature:
Clickheretoviewcodeimage
flipFlop(String,Integer,int)//See(3)
Themethodat(1)canbecalledwiththesecondargumentunboxedandthethirdargument
boxed,ascanthemethodat(2)withonlythesecondargumentunboxed.Inotherwords,
forthecallat(3),noneofthemethodsismorespecificthantheothers.
Example7.14illustratesasimplecaseofhowmethodresolutionisdonetochoosethe
mostspecificoverloadedmethod.ThemethodtestIfOn()isoverloadedat(1)and(2)
intheclassOverload.Thecallclient.testIfOn(tubeLight)at(3)satisfies
theparameterlistsinbothimplementationsgivenat(1)and(2),asthereference
tubeLightcanalsobeassignedtoareferenceofitssuperclassLight.Themost
specificmethod,(2),ischosen,resultinginfalsebeingwrittenontheterminal.Thecall
client.testIfOn(light)at(4)satisfiesonlytheparameterlistinthe
implementationgivenat(1),resultingintruebeingwrittenontheterminal.Thisisalso
thecaseat(5).Theobjectreferredtobytheargumentinthecallisirrelevant;rather,itis
thetypeoftheargumentthatisimportantforoverloadedmethodresolution.
WOW! eBook
www.wowebook.org
Example7.14ChoosingtheMostSpecificMethod(SimpleCase)
Clickheretoviewcodeimage
classLight{/*…*/}
classTubeLightextendsLight{/*…*/}
publicclassOverload{
booleantestIfOn(LightaLight){returntrue;}//(1)
booleantestIfOn(TubeLightaTubeLight){returnfalse;}//(2)
publicstaticvoidmain(String[]args){
TubeLighttubeLight=newTubeLight();
Lightlight=newLight();
Lightlight2=newTubeLight();
Overloadclient=newOverload();
System.out.println(client.testIfOn(tubeLight));//(3)==>methodat(2)
System.out.println(client.testIfOn(light));//(4)==>methodat(1)
System.out.println(client.testIfOn(light2));//(5)==>methodat(2)
}
}
Outputfromtheprogram:
false
true
true
Thealgorithmusedbythecompilerfortheresolutionofoverloadedmethodsincorporates
thefollowingphases:
1.Thecompilerperformsoverloadresolutionwithoutpermittingboxing,unboxing,or
theuseofavariablearitycall.
2.Ifphase(1)fails,thecompilerperformsoverloadresolutionallowingboxingand
unboxing,butexcludingtheuseofavariablearitycall.
3.Ifphase(2)fails,thecompilerperformsoverloadresolutioncombiningavariable
aritycall,boxing,andunboxing.
Example7.15providessomeinsightintohowthecompilerdeterminesthemostspecific
overloadedmethodusingthesethreephases.Theexamplehassixoverloadeddeclarations
ofthemethodaction().Thesignatureofeachmethodisgivenbythelocalvariable
signatureineachmethod.Thefirstformalparameterofeachmethodisthesignature
ofthecallthatinvokedthemethod.Theprintoutfromeachmethodallowsustoseewhich
methodcallresolvedtowhichmethod.Themain()methodcontains10calls,(8)to(17),
oftheaction()method.Ineachcall,thefirstargumentisthesignatureofthatmethod
call.
Animportantpointtonoteisthatthecompilerchoosesafixedaritycalloveravariable
aritycall,asseeninthecallsfrom(8)to(12):
WOW! eBook
www.wowebook.org
Anunboxingconversion(Integertoint)takesplaceforthecallat(10).Awidening
primitiveconversion(bytetoint)takesplaceforthecallat(11).
Variablearitycallsarechosenfrom(13)to(17):
Whenavariablearitycallischosen,themethoddeterminedhasthemostspecificvariable
arityparameterthatisapplicablefortheactualargument.Forexample,inthemethodcall
at(14),thetypeInteger[]ismorespecificthaneitherNumber[]orObject[].
Notealsotheboxingoftheelementsoftheimplicitlycreatedarrayinthecallsfrom(13)
to(17).
Example7.15OverloadedMethodResolution
Clickheretoviewcodeimage
importstaticjava.lang.System.out;
classOverloadResolution{
publicvoidaction(Stringstr){//(1)
Stringsignature=“(String)”;
out.println(str+”=>”+signature);
}
publicvoidaction(Stringstr,intm){//(2)
Stringsignature=“(String,int)”;
out.println(str+”=>”+signature);
}
publicvoidaction(Stringstr,intm,intn){//(3)
Stringsignature=“(String,int,int)”;
out.println(str+”=>”+signature);
}
publicvoidaction(Stringstr,Integer…data){//(4)
Stringsignature=“(String,Integer[])”;
out.println(str+”=>”+signature);
}
publicvoidaction(Stringstr,Number…data){//(5)
Stringsignature=“(String,Number[])”;
out.println(str+”=>”+signature);
}
publicvoidaction(Stringstr,Object…data){//(6)
WOW! eBook
www.wowebook.org
Stringsignature=“(String,Object[])”;
out.println(str+”=>”+signature);
}
publicstaticvoidmain(String[]args){
OverloadResolutionref=newOverloadResolution();
ref.action(“(String)”);//(8)calls
(1)
ref.action(“(String,int)”,10);//(9)calls
(2)
ref.action(“(String,Integer)”,newInteger(10));//(10)calls
(2)
ref.action(“(String,int,byte)”,10,(byte)20);//(11)calls
(3)
ref.action(“(String,int,int)”,10,20);//(12)calls
(3)
ref.action(“(String,int,long)”,10,20L);//(13)calls
(5)
ref.action(“(String,int,int,int)”,10,20,30);//(14)calls
(4)
ref.action(“(String,int,double)”,10,20.0);//(15)calls
(5)
ref.action(“(String,int,String)”,10,“what?”);//(16)calls
(6)
ref.action(“(String,boolean)”,false);//(17)calls
(6)
}
}
Outputfromtheprogram(withremarkstotheoutputontheright):
Clickheretoviewcodeimage
(String)=>(String)(8)calls(1)
(String,int)=>(String,int)(9)calls(2)
(String,Integer)=>(String,int)(10)calls(2)
(String,int,byte)=>(String,int,int)(11)calls(3)
(String,int,int)=>(String,int,int)(12)calls(3)
(String,int,long)=>(String,Number[])(13)calls(5)
(String,int,int,int)=>(String,Integer[])(14)calls(4)
(String,int,double)=>(String,Number[])(15)calls(5)
(String,int,String)=>(String,Object[])(16)calls(6)
(String,boolean)=>(String,Object[])(17)calls(6)
7.11ReferenceCastingandthe Operator
TheCastOperator
Thetypecastexpressionforreferencetypeshasthefollowingsyntax:
Clickheretoviewcodeimage
(destination_type)reference_expression
wherethereferenceexpressionevaluatestoareferencevalueofanobjectofsome
referencetype.Atypecastexpressionchecksthatthereferencevaluereferstoanobject
whosetypeiscompatiblewiththedestinationtype,meaningthatitstypeisasubtypeof
thedestinationtype.Theconstruct(destination_type)isusuallycalledthecastoperator.
Theresultofatypecastexpressionforreferencesisalwaysareferencevalueofanobject.
WOW! eBook
www.wowebook.org
Theliteralnullcanbecasttoanyreferencetype.
Thenextcodesnippetillustratesthevariousscenariosthatarisewhenusingthecast
operator.Inthisdiscussion,itisthetypecastexpressionthatisimportant,notthe
evaluationoftheassignmentoperatorinthedeclarationstatements.In(1),thecastisfrom
thesuperclassObjecttothesubclassString;thecodecompilesandatruntimethis
castispermitted,asthereferenceobjwilldenoteanobjectofclassString.In(2),the
castisfromthesuperclassObjecttothesubclassInteger;thecodecompiles,butat
runtimethiscastresultsinaClassCastException,sincethereferenceobjwill
denoteanobjectofclassString,whichcannotbeconvertedtoanInteger.In(3),the
castisfromtheclassStringtotheclassInteger.Asthesetwoclassesareunrelated,
thecompilerflagsanerrorforthecast.
Clickheretoviewcodeimage
Objectobj=newString(“Castme!”);
Stringstr=(String)obj;//(1)CastfromObjecttoString.
IntegeriRef1=(Integer)obj;//(2)CastfromObjecttoInteger,but
//ClassCastExceptionatruntime.
IntegeriRef2=(Integer)str;//(3)Compile-timeerror!
//Castbetweenunrelatedtypes.
Thefollowingconversionscanbeappliedtotheoperandofacastoperator:
•Bothwideningandnarrowingreferenceconversions,followedoptionallybyan
uncheckedconversion
•Bothboxingandunboxingconversions
Boxingandunboxingconversionsthatcanoccurduringcastingareillustratedbythe
followingcode.Again,itisthetypecastexpressionthatisimportantinthisdiscussion,
ratherthanwhethertheassignmentoperatorrequiresoneinthedeclarationstatements.
Clickheretoviewcodeimage
//(1)Boxingandcasting:Number<—Integer<—int:
Numbernum=(Number)100;
//(2)Casting,boxing,casting:Object<—Integer<—int<—double:
Objectobj=(Object)(int)10.5;
//(3)Casting,unboxing,casting:double<–int<—Integer<—Object:
doubled=(double)(Integer)obj;
Notethattheresultingobjectin(1)and(2)isanInteger,buttheresultingvaluein(3)
isadouble.TheboxingconversionsfrominttoIntegerin(1)and(2)areimplicit,
andtheunboxingconversionfromIntegertointin(3)isalsoimplicit.
The Operator
Thebinaryinstanceofoperatorcanbeusedforcomparingtypes.Ithasthefollowing
syntax(notethatthekeywordiscomposedoflowercaselettersonly):
Clickheretoviewcodeimage
reference_expressioninstanceofdestination_type
Theinstanceofoperatorreturnstrueiftheleft-handoperand(i.e.,thereference
valuethatresultsfromtheevaluationofreferenceexpression)canbeasubtypeofthe
WOW! eBook
www.wowebook.org
right-handoperand(destination_type).Italwaysreturnsfalseiftheleft-handoperandis
null.Iftheinstanceofoperatorreturnstrue,thecorrespondingtypecast
expressionwillalwaysbevalid.Boththetypecastexpressionandtheinstanceof
operatorsrequireacompile-timecheckandaruntimecheck,asexplainedlaterinthis
section.
Thecompile-timecheckdetermineswhetherthereisasubtype–supertyperelationship
betweenthesourceanddestinationtypes.Giventhatthetypeofthereferenceexpression
issourcetype,thecompilerdetermineswhetherareferenceofsourcetypeandareference
ofdestinationtypecanrefertoobjectsofareferencetypethatareacommonsubtypeof
bothsourcetypeanddestinationtypeinthetypehierarchy.Ifthisisnotthecase,then
obviouslythereisnorelationshipbetweenthetypes,andneitherthecastnorthe
instanceofoperatorapplicationwouldbevalid.Atruntime,thereferenceexpression
evaluatestoareferencevalueofanobject.Itisthetypeoftheactualobjectthat
determinestheoutcomeoftheoperation,asexplainedearlier.
WiththeclassesLightandStringassourcetypeanddestinationtype,respectively,
thereisnosubtype–supertyperelationshipbetweensourcetypeanddestinationtype.The
compilerwouldrejectcastingareferenceoftypeLighttotypeStringorapplyingthe
instanceofoperator,asshownat(2)and(3)inExample7.16.Referencesofthe
classesLightandTubeLightcanrefertoobjectsoftheclassTubeLight(orits
subclasses)intheinheritancehierarchydepictedinFigure7.1.Therefore,itmakessense
toapplytheinstanceofoperatororcastareferenceofthetypeLighttothetype
TubeLightasshownat(4)and(5),respectively,inExample7.16.
Atruntime,theresultofapplyingtheinstanceofoperatorat(4)isfalse,because
thereferencelight1oftheclassLightwillactuallydenoteanobjectofthesubclass
LightBulb,andthisobjectcannotbedenotedbyareferenceofthepeerclass
TubeLight.Applyingthecastat(5)resultsinaClassCastExceptionforthesame
reason.Thisisthereasonwhycastconversionsaresaidtobeunsafe,astheymaythrowa
ClassCastExceptionatruntime.Notethatiftheresultoftheinstanceof
operatorisfalse,thecastinvolvingtheoperandswillthrowa
ClassCastException.
InExample7.16,theresultofapplyingtheinstanceofoperatorat(6)isalsofalse,
becausethereferencelight1willstilldenoteanobjectoftheclassLightBulb,whose
objectscannotbedenotedbyareferenceofitssubclassSpotLightBulb.Thus
applyingthecastat(7)causesaClassCastExceptiontobethrownatruntime.
Thesituationshownat(8),(9),and(10)illustratestypicalusageoftheinstanceof
operatortodeterminewhichobjectareferenceisdenoting,sothatitcanbecastforthe
purposeofcarryingoutsomespecificaction.Thereferencelight1oftheclassLight
isinitializedtoanobjectofthesubclassNeonLightat(8).Theresultofthe
instanceofoperatorat(9)istrue,becausethereferencelight1willdenotean
objectofthesubclassNeonLight,whoseobjectscanalsobedenotedbyareferenceof
itssuperclassTubeLight.Bythesametoken,thecastat(10)isvalid.Iftheresultofthe
WOW! eBook
www.wowebook.org
instanceofoperatoristrue,thecastinvolvingtheoperandswillbevalidaswell.
Example7.16TheinstanceofandCastOperators
Clickheretoviewcodeimage
//SeeFigure7.1,p.267,forinheritancehierarchy.
classLight{/*…*/}
classLightBulbextendsLight{/*…*/}
classSpotLightBulbextendsLightBulb{/*…*/}
classTubeLightextendsLight{/*…*/}
classNeonLightextendsTubeLight{/*…*/}
publicclassWhoAmI{
publicstaticvoidmain(String[]args){
booleanresult1,result2,result3;
Lightlight1=newLightBulb();//(1)
//Stringstr=(String)light1;//(2)Compile-time
error!
//result1=light1instanceofString;//(3)Compile-time
error!
result2=light1instanceofTubeLight;//(4)false:peer
class.
//TubeLighttubeLight1=(TubeLight)light1;//(5)
ClassCastException!
result3=light1instanceofSpotLightBulb;//(6)false:
superclass.
//SpotLightBulbspotRef=(SpotLightBulb)light1;//(7)
ClassCastException!
light1=newNeonLight();//(8)
if(light1instanceofTubeLight){//(9)true.
TubeLighttubeLight2=(TubeLight)light1;//(10)OK.
//CannowusetubeLight2toaccessanobjectoftheclassNeonLight,
//butonlythosemembersthattheobjectinheritsoroverrides
//fromtheclassTubeLight.
}
}
}
Aswehaveseen,theinstanceofoperatoreffectivelydetermineswhetherthereference
valueinthereferenceontheleft-handsidereferstoanobjectwhoseclassisasubtypeof
thetypeofthereferencespecifiedontheright-handside.Atruntime,itisthetypeofthe
actualobjectdenotedbythereferenceontheleft-handsidethatiscomparedwiththetype
specifiedontheright-handside.Inotherwords,whatmattersatruntimeisthetypeofthe
actualobjectdenotedbythereference,notthedeclaredtypeofthereference.
Example7.17providesmoreexamplesoftheinstanceofoperator.Itisinstructiveto
gothroughtheprintstatementsandunderstandwhythoseresultsprintedout.Theliteral
nullisnotaninstanceofanyreferencetype,asshownintheprintstatementsat(1),(2),
and(16).Aninstanceofasuperclassisnotaninstanceofitssubclass,asshowninthe
printstatementat(4).Aninstanceofaclassisnotaninstanceofatotallyunrelatedclass,
asshownintheprintstatementat(10).Aninstanceofaclassisnotaninstanceofan
interfacetypethattheclassdoesnotimplement,asshownintheprintstatementat(6).
Anyarrayofnon-primitivetypeisaninstanceofbothObjectandObject[]types,as
WOW! eBook
www.wowebook.org
shownintheprintstatementsat(14)and(15),respectively.
Example7.17UsingtheinstanceofOperator
Clickheretoviewcodeimage
//SeeFigure7.3,p.295,forinheritancehierarchy.
interfaceIStack{/*FromExample7.7*/}
interfaceISafeStackextendsIStack{/*FromExample7.7*/}
classStackImplimplementsIStack{/*FromExample7.7*/}
classSafeStackImplextendsStackImpl
implementsISafeStack{/*FromExample7.7*/}
publicclassIdentification{
publicstaticvoidmain(String[]args){
Objectobj=newObject();
StackImplstack=newStackImpl(10);
SafeStackImplsafeStack=newSafeStackImpl(5);
IStackiStack;
StringstrFormat=“(%d)%-25sinstanceof%-25s:%s%n”;
System.out.printf(strFormat,1,
null,Object.class,
nullinstanceofObject);//Alwaysfalse.
System.out.printf(strFormat,2,
null,IStack.class,
nullinstanceofIStack);//Alwaysfalse.
System.out.printf(strFormat,3,
stack.getClass(),Object.class,
stackinstanceofObject);//true:instanceofsubclassof
Object.
System.out.printf(strFormat,4,
obj.getClass(),StackImpl.class,
objinstanceofStackImpl);//false:Objectnotsubtypeof
StackImpl.
System.out.printf(strFormat,5,
stack.getClass(),StackImpl.class,
stackinstanceofStackImpl);//true:instanceofStackImpl.
System.out.printf(strFormat,6,
obj.getClass(),IStack.class,
objinstanceofIStack);//false:Objectdoesnotimplement
IStack.
System.out.printf(strFormat,7,
safeStack.getClass(),IStack.class,
safeStackinstanceofIStack);//true:SafeStackImplimplements
IStack.
obj=stack;//Nocastrequired:assigningsubclassto
superclass.
System.out.printf(strFormat,8,
obj.getClass(),StackImpl.class,
objinstanceofStackImpl);//true:instanceofStackImpl.
System.out.printf(strFormat,9,
obj.getClass(),IStack.class,
objinstanceofIStack);//true:StackImplimplementsIStack.
System.out.printf(strFormat,10,
obj.getClass(),String.class,
objinstanceofString);//false:norelationship.
iStack=(IStack)obj;//Castrequired:assigningsuperclassto
WOW! eBook
www.wowebook.org
subclass.
System.out.printf(strFormat,11,
iStack.getClass(),Object.class,
iStackinstanceofObject);//true:instanceofsubclassof
Object.
System.out.printf(strFormat,12,
iStack.getClass(),StackImpl.class,
iStackinstanceofStackImpl);//true:instanceofStackImpl.
String[]strArray=newString[10];
//System.out.printf(strFormat,13,
//strArray.getClass(),String.class,
//strArrayinstanceofString);//Compile-timeerror:no
relationship.
System.out.printf(strFormat,14,
strArray.getClass(),Object.class,
strArrayinstanceofObject);//true:arraysubclassofObject.
System.out.printf(strFormat,15,
strArray.getClass(),Object[].class,
strArrayinstanceofObject[]);//true:arraysubclassofObject[].
System.out.printf(strFormat,16,
strArray[0],Object.class,
strArray[0]instanceofObject);//false:strArray[0]isnull.
System.out.printf(strFormat,17,
strArray.getClass(),String[].class,
strArrayinstanceofString[]);//true:arrayofString.
strArray[0]=“Amoebastrip”;
System.out.printf(strFormat,18,
strArray[0].getClass(),String.class,
strArray[0]instanceofString);//true:strArray[0]instanceof
String.
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
(1)nullinstanceofclassjava.lang.Object:false
(2)nullinstanceofinterfaceIStack:false
(3)classStackImplinstanceofclassjava.lang.Object:true
(4)classjava.lang.ObjectinstanceofclassStackImpl:false
(5)classStackImplinstanceofclassStackImpl:true
(6)classjava.lang.ObjectinstanceofinterfaceIStack:false
(7)classSafeStackImplinstanceofinterfaceIStack:true
(8)classStackImplinstanceofclassStackImpl:true
(9)classStackImplinstanceofinterfaceIStack:true
(10)classStackImplinstanceofclassjava.lang.String:false
(11)classStackImplinstanceofclassjava.lang.Object:true
(12)classStackImplinstanceofclassStackImpl:true
(14)class[Ljava.lang.String;instanceofclassjava.lang.Object:true
(15)class[Ljava.lang.String;instanceofclass[Ljava.lang.Object;:true
(16)nullinstanceofclassjava.lang.Object:false
(17)class[Ljava.lang.String;instanceofclass[Ljava.lang.String;:true
(18)classjava.lang.Stringinstanceofclassjava.lang.String:true
ReviewQuestions
7.23Whichstatementaboutthefollowingprogramistrue?
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
publicclassMyClass{
publicstaticvoidmain(String[]args){
A[]arrA;
B[]arrB;
arrA=newA[10];
arrB=newB[20];
arrA=arrB;//(1)
arrB=(B[])arrA;//(2)
arrA=newA[10];
arrB=(B[])arrA;//(3)
}
}
classA{}
classBextendsA{}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompilebecauseoftheassignmentat(1).
(b)Whenrun,theprogramwillthrowajava.lang.ClassCastException
intheassignmentat(2).
(c)Whenrun,theprogramwillthrowajava.lang.ClassCastException
intheassignmentat(3).
(d)Theprogramwillcompileandrunwithouterrors,evenifthecastoperator
(B[])inthestatementsat(2)and(3)isremoved.
(e)Theprogramwillcompileandrunwithouterrors,butwillnotdosoifthecast
operator(B[])instatementsat(2)and(3)isremoved.
7.24Whichstatementswillcauseacompile-timeerrorinthefollowingcode?
Clickheretoviewcodeimage
publicclassMyClass{
publicstaticvoidmain(String[]args){
MyClassa;
MySubclassb;
a=newMyClass();//(1)
b=newMySubclass();//(2)
a=b;//(3)
b=a;//(4)
a=newMySubclass();//(5)
b=newMyClass();//(6)
}
}
classMySubclassextendsMyClass{}
Selectthetwocorrectanswers.
(a)(1)
(b)(2)
WOW! eBook
www.wowebook.org
(c)(3)
(d)(4)
(e)(5)
(f)(6)
7.25Giventhefollowingtypeandreferencedeclarations,whichassignmentislegal?
Clickheretoviewcodeimage
//Typedeclarations:
interfaceI1{}
interfaceI2{}
classC1implementsI1{}
classC2implementsI2{}
classC3extendsC1implementsI2{}
//Referencedeclarations:
C1obj1=null;
C2obj2=null;
C3obj3=null;
Selecttheonecorrectanswer.
(a)obj2=obj1;
(b)obj3=obj1;
(c)obj3=obj2;
(d)I1a=obj2;
(e)I1b=obj3;
(f)I2c=obj1;
7.26Giventhefollowingclassandreferencedeclarations,whatcanbesaidaboutthe
statementy=(Sub)x?
//Classdeclarations:
classSuper{}
classSubextendsSuper{}
//Referencedeclarations:
Superx=null;
Suby=null;
Selecttheonecorrectanswer.
(a)Itisillegalatcompiletime.
(b)Itislegalatcompiletime,butmightbeillegalatruntime.
(c)Itisdefinitelylegalatruntime,butthecastoperator(Sub)isnotstrictly
needed.
(d)Itisdefinitelylegalatruntime,andthecastoperator(Sub)isneeded.
7.27GiventhreeclassesA,B,andC,whereBisasubclassofA,andCisasubclassof
B,whichoneofthesebooleanexpressionsistrueonlywhenthereferenceo
WOW! eBook
www.wowebook.org
referstoanobjectofclassB,andnottoanobjectofclassAorclassC?
Selecttheonecorrectanswer.
(a)(oinstanceofB)&&(!(oinstanceofA))
(b)(oinstanceofB)&&(!(oinstanceofC))
(c)!((oinstanceofA)||(oinstanceofB))
(d)(oinstanceofB)
(e)(oinstanceofB)&&!((oinstanceofA)||(o
instanceofC))
7.28Whatwillthefollowingprogramprintwhenrun?
Clickheretoviewcodeimage
publicclassRQ07A100{
publicstaticvoidmain(String[]args){
Ix=newD();
if(xinstanceofI)System.out.print(“I”);
if(xinstanceofJ)System.out.print(“J”);
if(xinstanceofC)System.out.print(“C”);
if(xinstanceofD)System.out.print(“D”);
System.out.println();
}
}
interfaceI{}
interfaceJ{}
classCimplementsI{}
classDextendsCimplementsJ{}
Selecttheonecorrectanswer.
(a)Theprogramwillnotprintanyletters.
(b)ICD
(c)IJD
(d)IJCD
(e)ID
7.29Whatistheresultofcompilingandrunningthefollowingprogram?
Clickheretoviewcodeimage
classYingYang{
voidyingyang(Integeri){
System.out.println(“Integer:”+i);
}
voidyingyang(Integer[]ints){
System.out.println(“Integer[]:”+ints[0]);
}
voidyingyang(Integer…ints){
System.out.println(“Integer…:”+ints[0]);
}
}
WOW! eBook
www.wowebook.org
publicclassRQ800A50{
publicstaticvoidmain(String[]args){
YingYangyy=newYingYang();
yy.yingyang(10);
yy.yingyang(10,12);
yy.yingyang(newInteger[]{10,20});
yy.yingyang(newInteger(10),newInteger(20));
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompilebecauseoferrors.
(b)Theprogramwillcompile,butthrowanexceptionatruntime.
(c)Theprogramwillcompileandprint:
Integer:10
Integer…:10
Integer…:10
Integer…:10
(d)Theprogramwillcompileandprint:
Integer:10
Integer…:10
Integer[]:10
Integer…:10
7.30Whatwillbetheresultofcompilingandrunningthefollowingprogram?
Clickheretoviewcodeimage
publicclassRQ800A20{
staticvoidcompute(int…ia){//(1)
System.out.print(“|”);
for(inti:ia){
System.out.print(i+“|”);
}
System.out.println();
}
staticvoidcompute(int[]ia1,int…ia2){//(2)
compute(ia1);
compute(ia2);
}
staticvoidcompute(int[]ia1,int[]…ia2d){//(3)
for(int[]ia:ia2d){
compute(ia);
}
}
publicstaticvoidmain(String[]args){
compute(newint[]{10,11},newint[]{12,13,14});//(4)
compute(15,16);//(5)
compute(newint[]{17,18},newint[][]{{19},{20}});//(6)
compute(null,newint[][]{{21},{22}});//(7)
}
}
Selecttheonecorrectanswer.
(a)Theprogramdoesnotcompilebecauseoferrorsinoneormorecallstothe
compute()method.
WOW! eBook
www.wowebook.org
(b)Theprogramcompiles,butthrowsaNullPointerExceptionwhenrun.
(c)Theprogramcompilesandprints:
|10|11|
|12|13|14|
|15|16|
|19|
|20|
|21|
|22|
(d)Theprogramcompilesandprints:
|12|13|14|
|15|16|
|10|11|
|19|
|20|
|21|
|22|
7.12PolymorphismandDynamicMethodLookup
Whichobjectareferencewillactuallydenoteduringruntimecannotalwaysbedetermined
atcompiletime.Polymorphismallowsareferencetodenoteobjectsofdifferenttypesat
differenttimesduringexecution.Asupertypereferenceexhibitspolymorphicbehavior
sinceitcandenoteobjectsofitssubtypes.
Whenanon-privateinstancemethodisinvokedonanobject,themethoddefinition
actuallyexecutedisdeterminedbothbythetypeoftheobjectatruntimeandbythe
methodsignature.Dynamicmethodlookup(alsoknownaslatebinding,dynamicbinding,
andvirtualmethodinvocation)istheprocessofdeterminingwhichmethoddefinitiona
methodsignaturedenotesduringruntime,basedonthetypeoftheobject.However,acall
toaprivateinstancemethodisnotpolymorphic.Suchacallcanoccuronlywithinthe
classandgetsboundtotheprivatemethodimplementationatcompiletime.
TheinheritancehierarchydepictedinFigure7.6isimplementedinExample7.18.The
implementationofthemethoddraw()isoverriddeninallsubclassesoftheclass
Shape.Theinvocationofthedraw()methodinthetwoloopsat(3)and(4)inExample
7.18reliesonthepolymorphicbehaviorofreferencesanddynamicmethodlookup.The
arrayshapesholdsShapereferencesdenotingaCircle,aRectangle,anda
Square,asshownat(1).Atruntime,dynamiclookupdeterminesthedraw()
implementationthatwillexecute,basedonthetypeoftheobjectdenotedbyeachelement
inthearray.Thisisalsothecasefortheelementsofthearraydrawablesat(2),which
holdsIDrawablereferencesthatcanbeassignedthereferencevalueofanyobjectofa
classthatimplementstheIDrawableinterface.Thefirstloopwillstillworkwithoutany
changeifobjectsofnewsubclassesoftheclassShapeareaddedtothearrayshapes.If
theydidnotoverridethedraw()method,aninheritedversionofthemethodwouldbe
executed.Thispolymorphicbehaviorappliestothearraydrawables,wherethesubtype
objectsareguaranteedtohaveimplementedtheIDrawableinterface.
WOW! eBook
www.wowebook.org
Figure7.6TypeHierarchyThatIllustratesPolymorphism
Polymorphismanddynamicmethodlookupformapowerfulprogrammingparadigmthat
simplifiesclientdefinitions,encouragesobjectdecoupling,andsupportsdynamically
changingrelationshipsbetweenobjectsatruntime.
WOW! eBook
www.wowebook.org
Example7.18PolymorphismandDynamicMethodLookup
Clickheretoviewcodeimage
//File:PolymorphRefs.java
interfaceIDrawable{
voiddraw();
}
//_______________________________________________________________________________
classShapeimplementsIDrawable{
@Overridepublicvoiddraw(){System.out.println(“DrawingaShape.”);}
}
//_______________________________________________________________________________
classCircleextendsShape{
@Overridepublicvoiddraw(){System.out.println(“DrawingaCircle.”);}
}
//_______________________________________________________________________________
classRectangleextendsShape{
@Overridepublicvoiddraw(){System.out.println(“DrawingaRectangle.”);
}
}
//_______________________________________________________________________________
classSquareextendsRectangle{
@Overridepublicvoiddraw(){System.out.println(“DrawingaSquare.”);}
}
//_______________________________________________________________________________
classGraphimplementsIDrawable{
@Overridepublicvoiddraw(){System.out.println(“DrawingaGraph.”);}
}
//_______________________________________________________________________________
publicclassPolymorphRefs{
publicstaticvoidmain(String[]args){
Shape[]shapes={newCircle(),newRectangle(),newSquare()};//
(1)
IDrawable[]drawables={newShape(),newRectangle(),newGraph()};//
(2)
System.out.println(“Drawshapes:”);
for(Shapeshape:shapes)//
(3)
shape.draw();
System.out.println(“Drawdrawables:”);
for(IDrawabledrawable:drawables)//
(4)
drawable.draw();
}
}
Outputfromtheprogram:
Drawshapes:
DrawingaCircle.
DrawingaRectangle.
DrawingaSquare.
Drawdrawables:
DrawingaShape.
DrawingaRectangle.
DrawingaGraph.
WOW! eBook
www.wowebook.org
7.13InheritanceversusAggregation
Figure7.7isaUMLclassdiagramshowingseveralaggregationrelationshipsandone
inheritancerelationship.Thisclassdiagramshowsaqueuedefinedbyaggregationanda
stackdefinedbyinheritance,bothofwhicharebasedonlinkedlists.Alinkedlist,inturn,
isdefinedbyaggregation.Example7.19showsanon-genericimplementationofthese
datastructures.Thepurposeoftheexampleistoillustrateinheritanceandaggregation,not
industrial-strengthimplementationofqueuesandstacks.TheclassNodeat(1)is
straightforward,definingtwofields:onedenotingthedataandtheotherdenotingthenext
nodeinthelist.TheclassLinkedListat(2)keepstrackofthelistbymanaginghead
andtailreferences.Nodescanbeinsertedinthefrontorback,butdeletedonlyfromthe
frontofthelist.
Figure7.7ImplementingDataStructuresbyInheritanceandAggregation
Example7.19ImplementingDataStructuresbyInheritanceandAggregation
Clickheretoviewcodeimage
classNode{//(1)
privateObjectdata;//Data
privateNodenext;//Nextnode
//Constructorforinitializingdataandreferencetothenextnode.
Node(Objectdata,Nodenext){
this.data=data;
this.next=next;
}
//Methods:
publicvoidsetData(Objectobj){data=obj;}
publicObjectgetData(){returndata;}
publicvoidsetNext(Nodenode){next=node;}
publicNodegetNext(){returnnext;}
}
//______________________________________________________________________________
classLinkedList{//(2)
protectedNodehead=null;
protectedNodetail=null;
//Methods:
publicbooleanisEmpty(){returnhead==null;}
publicvoidinsertInFront(ObjectdataObj){
if(isEmpty())head=tail=newNode(dataObj,null);
WOW! eBook
www.wowebook.org
elsehead=newNode(dataObj,head);
}
publicvoidinsertAtBack(ObjectdataObj){
if(isEmpty())
head=tail=newNode(dataObj,null);
else{
tail.setNext(newNode(dataObj,null));
tail=tail.getNext();
}
}
publicObjectdeleteFromFront(){
if(isEmpty())returnnull;
Noderemoved=head;
if(head==tail)head=tail=null;
elsehead=head.getNext();
returnremoved.getData();
}
}
//______________________________________________________________________________
classQueueByAggregation{//(3)
privateLinkedListqList;
//Constructor
QueueByAggregation(){
qList=newLinkedList();
}
//Methods:
publicbooleanisEmpty(){returnqList.isEmpty();}
publicvoidenqueue(Objectitem){qList.insertAtBack(item);}
publicObjectdequeue(){
if(qList.isEmpty())returnnull;
returnqList.deleteFromFront();
}
publicObjectpeek(){
return(qList.isEmpty()?null:qList.head.getData());
}
}
//______________________________________________________________________________
classStackByInheritanceextendsLinkedList{//(4)
publicvoidpush(Objectitem){insertInFront(item);}
publicObjectpop(){
if(isEmpty())returnnull;
returndeleteFromFront();
}
publicObjectpeek(){
return(isEmpty()?null:head.getData());
}
}
//______________________________________________________________________________
publicclassClient{//(5)
publicstaticvoidmain(String[]args){
Stringstring1=“Queuesareboringtostandin!”;
intlength1=string1.length();
QueueByAggregationqueue=newQueueByAggregation();
for(inti=0;i<length1;i++)
queue.enqueue(newCharacter(string1.charAt(i)));
while(!queue.isEmpty())
System.out.print(queue.dequeue());
System.out.println();
Stringstring2=“!notisotnuferaskcatS”;
WOW! eBook
www.wowebook.org
intlength2=string2.length();
StackByInheritancestack=newStackByInheritance();
for(inti=0;i<length2;i++)
stack.push(newCharacter(string2.charAt(i)));
stack.insertAtBack(newCharacter(‘!’));//(6)
while(!stack.isEmpty())
System.out.print(stack.pop());
System.out.println();
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
Queuesareboringtostandin!
Stacksarefuntositon!!
Choosingbetweeninheritanceandaggregationtomodelrelationshipscanbeacrucial
designdecision.Agooddesignstrategyadvocatesthatinheritanceshouldbeusedonlyif
therelationshipis-aisunequivocallymaintainedthroughoutthelifetimeoftheobjects
involved;otherwise,aggregationisthebestchoice.Aroleisoftenconfusedwithanis-a
relationship.Forexample,giventheclassEmployee,itwouldnotbeagoodideato
modeltherolesthatanemployeecanplay(suchasmanagerorcashier)byinheritance,if
theseroleschangeintermittently.Changingroleswouldinvolveanewobjecttorepresent
thenewroleeverytimethishappens.
Codereuseisalsobestachievedbyaggregationwhenthereisnois-arelationship.
Enforcinganartificialis-arelationshipthatisnotnaturallypresentisusuallynotagood
idea.SincetheclassStackByInheritanceat(4)inExample7.19isasubclassofthe
classLinkedListat(2),anyinheritedmethodfromthesuperclasscanbeinvokedonan
instanceofthesubclass.Also,methodsthatcontradicttheabstractionrepresentedbythe
subclasscanbeinvoked,asshownat(6).Usingaggregationinsuchacaseresultsina
bettersolution,asdemonstratedbytheclassQueueByAggregationat(3).Theclass
definestheoperationsofaqueuebydelegatingsuchrequeststotheunderlyingclass
LinkedList.Clientsimplementingaqueueinthismannerdonothaveaccesstothe
underlyingclassand,therefore,cannotbreaktheabstraction.
Bothinheritanceandaggregationpromoteencapsulationofimplementation,aschangesto
theimplementationarelocalizedtotheclass.Changingthecontractofasuperclasscan
haveconsequencesforthesubclasses(calledtherippleeffect)aswellasforclientsthat
aredependentonaparticularbehaviorofthesubclasses.
Polymorphismisachievedthroughinheritanceandinterfaceimplementation.Coderelying
onpolymorphicbehaviorwillstillworkwithoutanychangeifnewsubclassesornew
classesimplementingtheinterfaceareadded.Ifnoobviousis-arelationshipispresent,
polymorphismisbestachievedbyusingaggregationwithinterfaceimplementation.
7.14BasicConceptsinObject-OrientedDesign
Inthissection,weprovideabriefexplanationofsomebasicconceptsinobject-oriented
(OO)design.Formoredetails,thereaderisencouragedtoconsultthevastbodyof
literaturethatisreadilyavailableonthissubject.
WOW! eBook
www.wowebook.org
Encapsulation
Anobjecthaspropertiesandbehaviorsthatareencapsulatedinsidetheobject.The
servicesthattheobjectofferstoitsclientsmakeupitscontract,orpublicinterface.Only
thecontractdefinedbytheobjectisavailabletotheclients.Theimplementationofits
propertiesandbehaviorisnotaconcernoftheclients.Encapsulationhelpstomakeclear
thedistinctionbetweenanobject’scontractandimplementation.Thisdemarcationhas
majorconsequencesforprogramdevelopment,astheimplementationofanobjectcan
changewithoutaffectingtheclients.Encapsulationalsoreducescomplexity,asthe
internalsofanobjectarehiddenfromtheclients,whichcannotalteritsimplementation.
Encapsulationisachievedthroughinformationhiding,bymakingjudicioususeof
languagefeaturesprovidedforthispurpose.InformationhidinginJavacanbeachievedat
differentlevelsofgranularity:
•Methodorblocklevel
Localizinginformationinamethodhidesitfromtheoutside.
•Classlevel
Theaccessibilityofmembersdeclaredinaclasscanbecontrolledthroughmember
accessibilitymodifiers.Onemuch-advocatedinformation-hidingtechniqueisto
preventdirectaccessbyclientstodatamaintainedbyanobject.Thefieldsofthe
objectareprivate,anditscontractdefinespublicmethodsfortheservicesprovided
bytheobject.Suchtightencapsulationhelpstoseparatetheusefromthe
implementationofaclass.
•Packagelevel
Classesthatbelongtogethercanbegroupedintorelevantpackagesbyusingthe
packagestatement.Interpackageaccessibilityofclassescanbecontrolledbyclass
accessibilitymodifiers.
Cohesion
Cohesionisaninterclassmeasureofhowwellstructuredandcloselyrelatedthe
functionalityisinaclass.Theobjectiveistodesignclasseswithhighcohesion,that
performwell-definedandrelatedtasks(alsocalledfunctionalcohesion).Thepublic
methodsofahighlycohesiveclasstypicallyimplementasinglespecifictaskthatis
relatedtothepurposeoftheclass.Forexample,inanMVC-basedapplication,the
respectiveclassesfortheModel,theView,andtheControllershouldfocusonproviding
functionalitythatrelatestotheirindividualpurpose.Inotherwords,amethodinoneclass
shouldnotperformataskthatshouldactuallybeimplementedbyoneoftheothertwo
classes.
Lackofcohesioninaclassmeansthatthepurposeoftheclassisnotfocused,and
unrelatedfunctionalityisendingupintheclass(alsocalledcoincidentalcohesion)—
whichwilleventuallyimpactthemaintainabilityoftheapplication.
WOW! eBook
www.wowebook.org
Coupling
Couplingisameasureofintraclassdependencies.Becauseobjectsneedtointeractwith
oneanother,dependenciesbetweenclassesareinherentinOOdesign.However,these
dependenciesshouldbeminimizedtoachieveloosecoupling,whichfacilitatesthe
creationofextensibleapplications.
Onemajorsourceofintraclassdependenciesistheexposureofimplementationdetailsof
anobject.Suchdetailscanbeutilizedbyotherobjects,andthisdependencycanimpede
changesintheimplementation,resultinginlessextensibleapplications.
HighcohesionandloosecouplinghelptoachievethemaingoalsofOOdesign:
maintainability,reusability,extensibility,andreliability.
ReviewQuestions
7.31Whatwillbetheresultofcompilingandrunningthefollowingprogram?
Clickheretoviewcodeimage
publicclassPolymorphism{
publicstaticvoidmain(String[]args){
Aref1=newC();
Bref2=(B)ref1;
System.out.println(ref2.f());
}
}
classA{intf(){return0;}}
classBextendsA{intf(){return1;}}
classCextendsB{intf(){return2;}}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompile.
(b)Theprogramwillcompile,butwillthrowaClassCastExceptionat
runtime.
(c)Theprogramwillcompile,andprint0whenrun.
(d)Theprogramwillcompile,andprint1whenrun.
(e)Theprogramwillcompile,andprint2whenrun.
7.32Whatwillbetheresultofcompilingandrunningthefollowingprogram?
Clickheretoviewcodeimage
publicclassPolymorphism2{
publicstaticvoidmain(String[]args){
Aref1=newC();
Bref2=(B)ref1;
System.out.println(ref2.g());
}
}
classA{
privateintf(){return0;}
publicintg(){return3;}
WOW! eBook
www.wowebook.org
}
classBextendsA{
privateintf(){return1;}
publicintg(){returnf();}
}
classCextendsB{
publicintf(){return2;}
}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompile.
(b)Theprogramwillcompile,andprint0whenrun.
(c)Theprogramwillcompile,andprint1whenrun.
(d)Theprogramwillcompile,andprint2whenrun.
(e)Theprogramwillcompile,andprint3whenrun.
7.33Whichstatementsaboutthefollowingprogramaretrue?
Clickheretoviewcodeimage
publicinterfaceHeavenlyBody{Stringdescribe();}
classStar{
StringstarName;
publicStringdescribe(){return“star”+starName;}
}
classPlanetextendsStar{
Stringname;
publicStringdescribe(){
return“planet”+name+”orbitingstar”+starName;
}
}
Selectthethreecorrectanswers:
(a)Thecodewillfailtocompile.
(b)ThecodedefinesaPlanetis-aStarrelationship.
(c)ThecodewillfailtocompileifthenamestarNameisreplacedwiththename
bodyNamethroughoutthedeclarationoftheStarclass.
(d)ThecodewillfailtocompileifthenamestarNameisreplacedwiththename
namethroughoutthedeclarationoftheStarclass.
(e)AninstanceofPlanetisavalidinstanceofHeavenlyBody.
(f)ThecodedefinesaPlanethas-aStarrelationship.
7.34Giventhefollowingcode,whichstatementistrue?
Clickheretoviewcodeimage
publicinterfaceHeavenlyBody{Stringdescribe();}
classStarimplementsHeavenlyBody{
StringstarName;
WOW! eBook
www.wowebook.org
publicStringdescribe(){return“star”+starName;}
}
classPlanet{
Stringname;
Starorbiting;
publicStringdescribe(){
return“planet”+name+”orbiting”+orbiting.describe();
}
}
Selecttheonecorrectanswer:
(a)Thecodewillfailtocompile.
(b)ThecodedefinesaPlanethas-aStarrelationship.
(c)ThecodewillfailtocompileifthenamestarNameisreplacedwiththename
bodyNamethroughoutthedeclarationoftheStarclass.
(d)ThecodewillfailtocompileifthenamestarNameisreplacedwiththename
namethroughoutthedeclarationoftheStarclass.
(e)AninstanceofPlanetisavalidinstanceofaHeavenlyBody.
(f)ThecodedefinesaPlanetis-aStarrelationship.
7.35Whichofthefollowingstatementsisnottrue?
Selecttheonecorrectanswer.
(a)Maximizingcohesionandminimizingcouplingarethehallmarksofawell-
designedapplication.
(b)CouplingisaninherentpropertyofanynontrivialOOdesign.
(c)Dependenciesbetweenclassescanbeminimizedbyhidingimplementation
details.
(d)Eachmethodimplementingasingletaskthatisrelatedtothepurposeofthe
classwillresultinaclassthathashighcohesion.
(e)Noneoftheabove.
ChapterSummary
Thefollowingtopicswerecoveredinthischapter:
•Inheritanceanditsimplicationsinobject-orientedprogramming
•Overridingandhidingofsuperclassmembers
•Methodoverridingversusmethodoverloading
•Useofthesuperreferencetoaccesssuperclassmembers
•Useofthis()andsuper()calls,includingconstructorchaining
•Interfacesandmultipleinterfaceinheritance
WOW! eBook
www.wowebook.org
•Subtype–supertyperelationships
•Conversionswhenassigning,casting,andpassingreferencevalues
•Resolutionofoverloadedmethods
•Identifyingthetypeofobjectsusingtheinstanceofoperator
•Polymorphismanddynamicmethodlookup
•Inheritance(is-a)versusaggregation(has-a)
•Bestpracticesforobject-orienteddesign:tightencapsulation,loosecoupling,and
highcohesioninclasses
ProgrammingExercises
7.1DeclareaninterfacecalledFunctionthathasamethodnamedevaluatethat
takesanintparameterandreturnsanintvalue.
CreateaclasscalledHalfthatimplementstheFunctioninterface.The
implementationofthemethodevaluate()shouldreturnthevalueobtainedby
dividingtheintargumentby2.
Inaclient,createamethodthattakesanarbitrarynumberofintvaluesasa
varargsparameter,andreturnsanarraythathaslengthequaltothenumberof
valuespassedinthevarargsparameter,butwiththevalueofanelementinthenew
arraybeinghalfthatofthecorrespondingvalueinthevarargsparameter.Letthe
implementationofthismethodcreateaninstanceofHalf,andusethisinstanceto
calculatevaluesforthearraythatisreturned.
7.2Rewritethemethodthatoperatedonintvaluesfromthepreviousexercise:The
methodshouldnowalsoacceptaFunctionreferenceasanargument,anduse
thisargumentinsteadofaninstanceoftheHalfclass.
CreateaclasscalledPrintthatimplementsthemethodevaluate()inthe
Functioninterface.Thismethodsimplyprintstheintvaluepassedasan
argument,andreturnsthisvalue.
Nowwriteaprogramthatdoesthefollowing:
PrintsanarbitrarynumberofintvaluesusinganinstanceofthePrintclassand
themethoddescribedearlier.
Halvesthevaluesinthearrayandprintsthevaluesagain,usingtheHalfand
Printclasses,andthemethoddescribedearlier.
WOW! eBook
www.wowebook.org
8.FundamentalClasses
8.1Overviewofthe Package
Thejava.langpackageisindispensablewhenprogramminginJava.Itisautomatically
importedintoeverysourcefileatcompiletime.ThepackagecontainstheObjectclass
thatisthesuperclassofallclasses,andthewrapperclasses(Boolean,Character,
Byte,Short,Integer,Long,Float,Double)thatareusedtohandleprimitive
valuesasobjects.ItprovidesclassesessentialforinteractingwiththeJVM(Runtime),
forsecurity(SecurityManager),forloadingclasses(ClassLoader),fordealing
withthreads(Thread),andforexceptions(Throwable,Error,Exception,
RuntimeException).Thejava.langpackagealsocontainsclassesthatprovidethe
standardinput,output,anderrorstreams(System),stringhandling(String,
StringBuilder,StringBuffer),andmathematicalfunctions(Math).
Figure8.1showstheimportantclassesthatarediscussedindetailinthischapter.
WOW! eBook
www.wowebook.org
Figure8.1PartialInheritanceHierarchyinthejava.langPackage
8.2The Class
AllclassesextendtheObjectclass,eitherdirectlyorindirectly.Aclassdeclaration,
withouttheextendsclause,implicitlyextendstheObjectclass(§7.1,p.264).Thus,
theObjectclassisalwaysattherootofanyinheritancehierarchy.TheObjectclass
definesthebasicfunctionalitythatallobjectsexhibitandallclassesinherit.This
relationshipalsoappliestoarrays,sincethesearegenuineobjectsinJava.
TheObjectclassprovidesthefollowinggeneralutilitymethods(seeExample8.1for
usageofsomeofthesemethods):
booleanequals(Objectobj)
Objectreferenceandvalueequalityarediscussedtogetherwiththe==and!=
operators(§5.12,p.181).Theequals()methodintheObjectclassreturns
trueonlyifthetworeferencescompareddenotethesameobject.Theequals()
methodisusuallyoverriddentoprovidethesemanticsofobjectvalueequality,asis
thecaseforthewrapperclasses(§8.3,p.350)andtheStringclass(§8.4,p.363).
inthashCode()
Whenstoringobjectsinhashtables,thismethodcanbeusedtogetahashvaluefor
anobject.Thisvalueisguaranteedtobeconsistentduringtheexecutionofthe
program,providedtheinformationusedintheequals()comparisonsonthe
objectdoesnotchange.Thismethodtriestoreturndistinctintegersfordistinct
objectsastheirdefaulthashvalue.ThehashCode()methodisusually
overriddenbyaclass,asisthecaseforthewrapperclassesandtheStringclass.
finalClass<?>getClass()
Returnstheruntimeclassoftheobject,whichisrepresentedbyanobjectofthe
classjava.lang.Classatruntime.
Clickheretoviewcodeimage
protectedObjectclone()throwsCloneNotSupportedException
Newobjectsthatareexactlythesame(i.e.,haveidenticalstates)asthecurrent
objectcanbecreatedbyusingtheclone()method;thatis,primitivevaluesand
referencevaluesarecopied.Thisiscalledshallowcopying.Aclasscanoverride
thismethodtoprovideitsownnotionofcloning.Forexample,cloningacomposite
objectbyrecursivelycloningtheconstituentobjectsiscalleddeepcopying.
WOW! eBook
www.wowebook.org
Whenoverridden,themethodinthesubclassisusuallydeclaredaspublicto
allowanyclienttocloneobjectsoftheclass.Iftheoverridingclone()methodin
thesubclassreliesontheclone()methodintheObjectclass(i.e.,ashallow
copy),thesubclassmustimplementtheCloneablemarkerinterfacetoindicate
thatitsobjectscanbesafelycloned.Otherwise,theclone()methodinthe
ObjectclasswillthrowacheckedCloneNotSupportedException.
StringtoString()
Ifasubclassdoesnotoverridethismethod,itreturnsatextualrepresentationofthe
object,whichhasthefollowingformat:
Clickheretoviewcodeimage
“<nameoftheclass>@<hashcodevalueofobject>”
Sincethedefaulthashvalueofanobjectisanintvalue,thisvalueisprintedasa
hexadecimalnumber(e.g.,3e25a5).Thismethodisusuallyoverridden.The
methodcallSystem.out.println(objRef)willimplicitlyconvertits
argumenttoatextualrepresentationbycallingthetoString()methodonthe
argument.Seealsothebinarystringconcatenationoperator+,discussedin§5.7on
page169.
Clickheretoviewcodeimage
protectedvoidfinalize()throwsThrowable
Thismethodisdiscussedinconnectionwithgarbagecollection(§9.4,p.390).Itis
calledonanobjectjustbeforeitisgarbagecollected,sothatanycleaningupcanbe
done.However,thedefaultfinalize()methodintheObjectclassdoesnot
doanythinguseful.
Inaddition,theObjectclassprovidessupportforthreadcommunicationinsynchronized
code,throughthefollowingmethods.Thisimportanttopicisbeyondthescopeofthis
book.
Clickheretoviewcodeimage
finalvoidwait(longtimeout)throwsInterruptedException
finalvoidwait(longtimeout,intnanos)throwsInterruptedException
finalvoidwait()throwsInterruptedException
finalvoidnotify()
finalvoidnotifyAll()
Athreadinvokesthesemethodsontheobjectwhoselockitholds.Athreadwaits
fornotificationbyanotherthread.
Example8.1MethodsintheObjectClass
Clickheretoviewcodeimage
//File:ObjectMethods.java
classMyClassimplementsCloneable{
@Override
publicMyClassclone(){
MyClassobj=null;
WOW! eBook
www.wowebook.org
try{obj=(MyClass)super.clone();}//Callsoverriddenmethod.
catch(CloneNotSupportedExceptione){System.out.println(e);}
returnobj;
}
}
//______________________________________________________________________________
publicclassObjectMethods{
publicstaticvoidmain(String[]args){
//TwoobjectsofMyClass.
MyClassobj1=newMyClass();
MyClassobj2=newMyClass();
//Twostrings.
Stringstr1=newString(“WhoAmI”);
Stringstr2=newString(“WhoAmI”);
//MethodhashCode()overriddeninStringclass.
//Stringsthatareequalhavethesamehashcode.
System.out.println(“hashcodeforstr1:”+str1.hashCode());
System.out.println(“hashcodeforstr2:”+str2.hashCode()+“\n”);
//HashcodesaredifferentfordifferentMyClassobjects.
System.out.println(“hashcodeforMyClassobj1:”+obj1.hashCode());
System.out.println(“hashcodeforMyClassobj2:”+
obj2.hashCode()+”\n”);
//Methodequals()overriddenintheStringclass.
System.out.println(“str1.equals(str2):”+str1.equals(str2));
System.out.println(“str1==str2:”+(str1==str2)+“\n”);
//Methodequals()fromtheObjectclasscalled.
System.out.println(“obj1.equals(obj2):”+obj1.equals(obj2));
System.out.println(“obj1==obj2:”+(obj1==obj2)+“\n”);
//Theruntimeobjectthatrepresentstheclassofanobject.
ClassrtStringClass=str1.getClass();
ClassrtMyClassClass=obj1.getClass();
//Thenameoftheclassrepresentedbytheruntimeobject.
System.out.println(“Classforstr1:”+rtStringClass);
System.out.println(“Classforobj1:”+rtMyClassClass+“\n”);
//ThetoString()methodisoverriddenintheStringclass.
StringtextRepStr=str1.toString();
StringtextRepObj=obj1.toString();
System.out.println(“Textrepresentationofstr1:”+textRepStr);
System.out.println(“Textrepresentationofobj1:”+textRepObj+“\n”);
//Shallowcopyingofarrays.
MyClass[]array1={newMyClass(),newMyClass(),newMyClass()};
MyClass[]array2=array1.clone();
//Arrayobjectsaredifferent,butsharetheelementobjects.
System.out.println(“array1==array2:”+(array1==array2));
for(inti=0;i<array1.length;i++){
System.out.println(“array1[”+i+“]==array2[”+i+“]:”+
(array1[i]==array2[i]));
}
System.out.println();
//CloneanobjectofMyClass.
MyClassobj3=obj1.clone();
System.out.println(“hashcodeforMyClassobj3:”+obj3.hashCode());
System.out.println(“obj1==obj3:”+(obj1==obj3));
WOW! eBook
www.wowebook.org
}
}
Probableoutputfromtheprogram:
Clickheretoviewcodeimage
hashcodeforstr1:-1704812257
hashcodeforstr2:-1704812257
hashcodeforMyClassobj1:25669322
hashcodeforMyClassobj2:14978587
str1.equals(str2):true
str1==str2:false
obj1.equals(obj2):false
obj1==obj2:false
Classforstr1:classjava.lang.String
Classforobj1:classMyClass
Textrepresentationofstr1:WhoAmI
Textrepresentationofobj1:MyClass@187aeca
array1==array2:false
array1[0]==array2[0]:true
array1[1]==array2[1]:true
array1[2]==array2[2]:true
hashcodeforMyClassobj3:19770577
obj1==obj3:false
ReviewQuestions
8.1WhatisthereturntypeofthehashCode()methodintheObjectclass?
Selecttheonecorrectanswer.
(a)String
(b)int
(c)long
(d)Object
(e)Class
8.2Whichofthefollowingstatementsistrue?
Selecttheonecorrectanswer.
(a)Ifthereferencesxandydenotetwodifferentobjects,theexpression
x.equals(y)isalwaysfalse.
(b)Ifthereferencesxandydenotetwodifferentobjects,theexpression
(x.hashCode()==y.hashCode())isalwaysfalse.
(c)ThehashCode()methodintheObjectclassisdeclaredasfinal.
WOW! eBook
www.wowebook.org
(d)Theequals()methodintheObjectclassisdeclaredasfinal.
(e)Allarrayshaveamethodnamedclone.
8.3Whichexceptioncantheclone()methodoftheObjectclassthrow?
Selecttheonecorrectanswer.
(a)CloneNotSupportedException
(b)NotCloneableException
(c)IllegalCloneException
(d)NoClonesAllowedException
8.3TheWrapperClasses
Wrapperclasseswereintroducedwiththediscussionoftheprimitivedatatypes(§2.2,p.
37),andalsoinconnectionwithboxingandunboxingofprimitivevalues(§5.1,p.145).
PrimitivevaluesinJavaarenotobjects.Tomanipulatethesevaluesasobjects,the
java.langpackageprovidesawrapperclassforeachoftheprimitivedatatypes
(showninthebottomleftofFigure8.2).Thenameofthewrapperclassisthenameofthe
primitivedatatypewithauppercaseletter,exceptforint(Integer)andchar
(Character).Allwrapperclassesarefinal.Theobjectsofallwrapperclassesthat
canbeinstantiatedareimmutable;inotherwords,thevalueinthewrapperobjectcannot
bechanged.
WOW! eBook
www.wowebook.org
Figure8.2ConvertingValuesamongPrimitive,Wrapper,andStringTypes
AlthoughtheVoidclassisconsideredawrapperclass,itdoesnotwrapanyprimitive
valueandisnotinstantiable(i.e.,hasnopublicconstructors).ItjustdenotestheClass
objectrepresentingthekeywordvoid.TheVoidclasswillnotbediscussedfurtherin
thissection.
Inadditiontothemethodsdefinedforconstructingandmanipulatingobjectsofprimitive
values,thewrapperclassesdefineusefulconstants,fields,andconversionmethods.
CommonWrapperClassConstructors
TheCharacterclasshasonlyonepublicconstructor,takingacharvalueasits
parameter.Theotherwrapperclassesallhavetwopublicone-argumentconstructors:
onetakesaprimitivevalueandtheothertakesastring.
WrapperType(typev)
WrapperType(Stringstr)
Thetypeisaprimitivedatatype.Thestringargumentisconvertedtoaprimitive
valuethatcorrespondstotheWrapperType.Anunchecked
NumberFormatExceptionisthrownifthestringcannotbeconvertedtoa
primitivevaluethatcorrespondstoanumericWrapperType.
WOW! eBook
www.wowebook.org
WrappingPrimitiveValuesinObjects
Boxingisaconvenientwaytowrapaprimitivevalueinanobject((1a)inFigure8.2and
§5.1,p.145).
CharactercharObj1=‘\n’;
BooleanboolObj1=true;
IntegerintObj1=2014;
DoubledoubleObj1=3.14;
Aconstructorthattakesaprimitivevaluecanbeusedtocreatewrapperobjects((1b)in
Figure8.2).
Clickheretoviewcodeimage
CharactercharObj1=newCharacter(‘\n’);
BooleanboolObj1=newBoolean(true);
IntegerintObj1=newInteger(2014);
DoubledoubleObj1=newDouble(3.14);
WecanalsousethevalueOf()methodthattakestheprimitivevaluetowrapasan
argument((1c)inFigure8.2).
Clickheretoviewcodeimage
CharactercharObj1=Character.valueOf(‘\n’);
BooleanboolObj1=Boolean.valueOf(true);
IntegerintObj1=Integer.valueOf(2014);
DoubledoubleObj1=Double.valueOf(3.14);
ConvertingStringstoWrapperObjects
AconstructorthattakesaStringobjectrepresentingtheprimitivevaluecanalsobe
usedtocreatewrapperobjects.Theconstructorsforthenumericwrappertypesthrowan
uncheckedNumberFormatExceptioniftheStringparameterdoesnotparsetoa
validnumber((2a)inFigure8.2).
Clickheretoviewcodeimage
BooleanboolObj2=newBoolean(“TrUe”);//caseignored:true
BooleanboolObj3=newBoolean(“XX”);//false
IntegerintObj2=newInteger(“2014”);
DoubledoubleObj2=newDouble(“3.14”);
LonglongObj1=newLong(“3.14”);//NumberFormatException
CommonWrapperClassUtilityMethods
ConvertingStringstoWrapperObjects
Eachwrapperclass(exceptCharacter)definesthestaticmethodvalueOf(String
str)thatreturnsthewrapperobjectcorrespondingtotheprimitivevaluerepresentedby
theStringobjectpassedasanargument((6b)inFigure8.2).Thismethodforthe
numericwrappertypesalsothrowsaNumberFormatExceptioniftheString
parameterisnotavalidnumber.
Clickheretoviewcodeimage
staticWrapperTypevalueOf(Stringstr)
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
BooleanboolObj4=Boolean.valueOf(“false”);
IntegerintObj3=Integer.valueOf(“1949”);
DoubledoubleObj3=Double.valueOf(“-3.0”);
Inadditiontotheone-argumentvalueOf()method,theintegerwrapperclassesdefine
anoverloadedstaticvalueOf()methodthatcantakeasecondargument.Thisargument
specifiesthebase(orradix)inwhichtointerpretthestringrepresentingthesignedinteger
inthefirstargument.
Clickheretoviewcodeimage
staticIntegerWrapperTypevalueOf(Stringstr,intbase)
throwsNumberFormatException
Clickheretoviewcodeimage
BytebyteObj1=Byte.valueOf(“1010”,2);//Decimalvalue10
ShortshortObj2=Short.valueOf(“12”,8);//Not“\012”.Decimalvalue
10.
IntegerintObj4=Integer.valueOf(“-a”,16);//Not“-0xa”.Decimalvalue
-10.
LonglongObj2=Long.valueOf(“-a”,16);//Not“-0xa”.Decimalvalue
-10L.
ConvertingWrapperObjectstoStrings
EachwrapperclassoverridesthetoString()methodfromtheObjectclass.The
overridingmethodreturnsaStringobjectcontainingthestringrepresentationofthe
primitivevalueinthewrapperobject((3)inFigure8.2).
StringtoString()
Clickheretoviewcodeimage
StringcharStr=charObj1.toString();//“\n”
StringboolStr=boolObj2.toString();//“true”
StringintStr=intObj1.toString();//“2014”
StringdoubleStr=doubleObj1.toString();//“3.14”
ConvertingPrimitiveValuestoStrings
EachwrapperclassdefinesastaticmethodtoString(typev)thatreturnsthestring
correspondingtotheprimitivevalueoftype,whichispassedasanargument((6a)in
Figure8.2).
Clickheretoviewcodeimage
staticStringtoString(typev)
Clickheretoviewcodeimage
StringcharStr2=Character.toString(‘\n’);//“\n”
StringboolStr2=Boolean.toString(true);//“true”
StringintStr2=Integer.toString(2014);//Base10.“2014”
StringdoubleStr2=Double.toString(3.14);//“3.14”
Forintegerprimitivetypes,thebaseisassumedtobe10.Forfloating-pointnumbers,the
WOW! eBook
www.wowebook.org
textualrepresentation(decimalformorscientificnotation)dependsonthesignandthe
magnitude(absolutevalue)ofthenumber.TheNaNvalue,positiveinfinity,andnegative
infinitywillresultinthestrings"NaN","Infinity",and"-Infinity",
respectively.
Inaddition,thewrapperclassesIntegerandLongdefinemethodsforconverting
integerstostringrepresentationsindecimal,binary,octal,andhexadecimalnotation(p.
353).
ConvertingWrapperObjectstoPrimitiveValues
Unboxingisaconvenientwaytounwraptheprimitivevalueinawrapperobject((4a)in
Figure8.2and§5.1,p.145).
Clickheretoviewcodeimage
charc=charObj1;//‘\n’
booleanb=boolObj2;//true
inti=intObj1;//2014
doubled=doubleObj1;//3.14
EachwrapperclassdefinesatypeValue()methodthatreturnstheprimitivevalueinthe
wrapperobject((4b)inFigure8.2).
typetypeValue()
Clickheretoviewcodeimage
charc=charObj1.charValue();//‘\n’
booleanb=boolObj2.booleanValue();//true
inti=intObj1.intValue();//2014
doubled=doubleObj1.doubleValue();//3.14
Inaddition,eachnumericwrapperclassdefinestypeValue()methodsforconvertingthe
primitivevalueinthewrapperobjecttoavalueofanynumericprimitivedatatype.These
methodsarediscussedlater.
WrapperComparison,Equality,andHashCode
EachwrapperclassimplementstheComparable<Type>interface,whichdefinesthe
followingmethod:
intcompareTo(Typeobj2)
Thismethodreturnsavaluethatislessthan,equalto,orgreaterthanzero,dependingon
whethertheprimitivevalueinthecurrentwrapperTypeobjectislessthan,equalto,or
greaterthantheprimitivevalueinthewrapperTypeobjectdenotedbyargumentobj2.
Clickheretoviewcodeimage
//Comparisonsbasedonobjectscreatedearlier
CharactercharObj2=‘a’;
intresult1=charObj1.compareTo(charObj2);//result1<0
intresult2=intObj1.compareTo(intObj3);//result2>0
intresult3=doubleObj1.compareTo(doubleObj2);//result==0
intresult4=doubleObj1.compareTo(intObj1);//Compile-timeerror!
WOW! eBook
www.wowebook.org
Eachwrapperclassoverridestheequals()methodfromtheObjectclass.The
overridingmethodcomparestwowrapperobjectsforobjectvalueequality.
booleanequals(Objectobj2)
Clickheretoviewcodeimage
//Comparisonsbasedonobjectscreatedearlier
booleancharTest=charObj1.equals(charObj2);//false
booleanboolTest=boolObj2.equals(Boolean.FALSE);//false
booleanintTest=intObj1.equals(intObj2);//true
booleandoubleTest=doubleObj1.equals(doubleObj2);//true
booleantest=intObj1.equals(newLong(2014));//false.Notsametype.
Thefollowingvaluesareinternedwhentheyarewrappedduringboxing.Thatis,onlyone
wrapperobjectexistsintheprogramfortheseprimitivevalueswhenboxingisapplied:
•Thebooleanvaluestrueorfalse
•Abyte
•AcharwithaUnicodevalueintheinterval[\u0000,\u007f](i.e.,decimal
interval[0,127])
•Anintorshortvalueintheinterval[-128,127]
Ifreferencesw1andw2refertotwowrapperobjectsthatboxthesamevalue,whichis
amongtheonesmentionedhere,thenw1==w2isalwaystrue.Inotherwords,forthe
valueslistedpreviously,objectequalityandreferenceequalitygivethesameresult.
Clickheretoviewcodeimage
//Referenceandobjectequality
BytebRef1=10;
BytebRef2=10;
System.out.println(bRef1==bRef2);//true
System.out.println(bRef1.equals(bRef2));//true
IntegeriRef1=1000;
IntegeriRef2=1000;
System.out.println(iRef1==iRef2);//false
System.out.println(iRef1.equals(iRef2));//true
EachwrapperclassalsooverridesthehashCode()methodintheObjectclass.The
overridingmethodreturnsahashvaluebasedontheprimitivevalueinthewrapperobject.
inthashCode()
Clickheretoviewcodeimage
intindex=charObj1.hashCode();//10(‘\n’)
NumericWrapperClasses
ThenumericwrapperclassesByte,Short,Integer,Long,Float,andDoubleare
allsubclassesoftheabstractclassNumber(Figure8.1).
Eachnumericwrapperclassdefinesanassortmentofconstants,includingtheminimum
WOW! eBook
www.wowebook.org
andmaximumvaluesofthecorrespondingprimitivedatatype:
NumericWrapperType.MIN_VALUE
NumericWrapperType.MAX_VALUE
Thefollowingcoderetrievestheminimumandmaximumvaluesofvariousnumeric
types:
Clickheretoviewcodeimage
byteminByte=Byte.MIN_VALUE;//-128
intmaxInt=Integer.MAX_VALUE;//2147483647
doublemaxDouble=Double.MAX_VALUE;//1.7976931348623157e+308
ConvertingNumericWrapperObjectstoNumericPrimitiveTypes
EachnumericwrapperclassdefinesthefollowingsetoftypeValue()methodsfor
convertingtheprimitivevalueinthewrapperobjecttoavalueofanynumericprimitive
type:
bytebyteValue()
shortshortValue()
intintValue()
longlongValue()
floatfloatValue()
doubledoubleValue()
Seealso(4b)inFigure8.2.
Thefollowingcodeshowsconversionofvaluesinnumericwrapperobjectstoany
numericprimitivetype:
Clickheretoviewcodeimage
BytebyteObj2=newByte((byte)16);//Castmandatory
IntegerintObj5=newInteger(42030);
DoubledoubleObj4=newDouble(Math.PI);
shortshortVal=intObj5.shortValue();//(1)
longlongVal=byteObj2.longValue();
intintVal=doubleObj4.intValue();//(2)Truncation
doubledoubleVal=intObj5.doubleValue();
Noticethepotentialforlossofinformationat(1)and(2),whentheprimitivevalueina
wrapperobjectisconvertedtoanarrowerprimitivedatatype.
ConvertingStringstoNumericValues
EachnumericwrapperclassdefinesastaticmethodparseType(Stringstr),which
returnstheprimitivenumericvaluerepresentedbytheStringobjectpassedasan
argument.TheTypeinthemethodnameparseTypestandsforthenameofanumeric
wrapperclass,exceptforthenameoftheIntegerclass,whichisabbreviatedtoInt.
ThesemethodsthrowaNumberFormatExceptioniftheStringparameterisnota
validargument((5)inFigure8.2.)
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
statictypeparseType(Stringstr)throwsNumberFormatException
Clickheretoviewcodeimage
bytevalue1=Byte.parseByte(“16”);
intvalue2=Integer.parseInt(“2010”);//parseInt,notparseInteger
intvalue3=Integer.parseInt(“7UP”);//NumberFormatException
doublevalue4=Double.parseDouble(“3.14”);
Fortheintegerwrappertypes,theoverloadedstaticmethodparseType()can
additionallytakeasecondargument,whichcanspecifythebaseinwhichtointerpretthe
stringrepresentingthesignedintegerinthefirstargument:
Clickheretoviewcodeimage
typeparseType(Stringstr,intbase)throwsNumberFormatException
Clickheretoviewcodeimage
bytevalue6=Byte.parseByte(“1010”,2);//Decimalvalue10.
shortvalue7=Short.parseShort(“12”,8);//“012”,not“\012”.Decimalvalue
10.
intvalue8=Integer.parseInt(“-a”,16);//Not“-0xa”.Decimalvalue-10.
longvalue9=Long.parseLong(“-a”,16);//Not“-0xa”.Decimalvalue-10L.
ConvertingIntegerValuestoStringsinDifferentNotations
ThewrapperclassesIntegerandLongprovidestaticmethodsforconvertingintegers
tostringrepresentationsindecimal,binary,octal,andhexadecimalnotation.Someof
thesemethodsfromtheIntegerclassarelistedhere,butanalogousmethodsarealso
definedintheLongclass.Example8.2demonstratestheuseofthesemethods.
Clickheretoviewcodeimage
staticStringtoBinaryString(inti)
staticStringtoHexString(inti)
staticStringtoOctalString(inti)
Thesethreemethodsreturnastringrepresentationoftheintegerargumentasan
unsignedintegerinbase2,16,and8,respectively,withnoextraleadingzeroes.
Clickheretoviewcodeimage
staticStringtoString(inti,intbase)
staticStringtoString(inti)
Thefirstmethodreturnstheminussign'-'asthefirstcharacteriftheintegeriis
negative.Inallcases,itreturnsthestringrepresentationofthemagnitudeofthe
integeriinthespecifiedbase.
ThelastmethodisequivalenttothemethodtoString(inti,intbase),
wherethebasehasthevalue10,andwhichreturnsthestringrepresentationasa
signeddecimal((6a)inFigure8.2).
WOW! eBook
www.wowebook.org
Example8.2StringRepresentationofIntegers
Clickheretoviewcodeimage
publicclassIntegerRepresentation{
publicstaticvoidmain(String[]args){
intpositiveInt=+41;//0b101001,051,0x29
intnegativeInt=-41;//0b11111111111111111111111111010111,
-0b101001,
//037777777727,-051,0xffffffd7,-0x29
System.out.println(“Stringrepresentationfordecimalvalue:”+
positiveInt);
integerStringRepresentation(positiveInt);
System.out.println(“Stringrepresentationfordecimalvalue:”+
negativeInt);
integerStringRepresentation(negativeInt);
}
publicstaticvoidintegerStringRepresentation(inti){
System.out.println(“Binary:”+Integer.toBinaryString(i));
System.out.println(“Octal:”+Integer.toOctalString(i));
System.out.println(“Hex:”+Integer.toHexString(i));
System.out.println(“Decimal:”+Integer.toString(i));
System.out.println(“UsingtoString(inti,intbase)method:”);
System.out.println(“Base2:”+Integer.toString(i,2));
System.out.println(“Base8:”+Integer.toString(i,8));
System.out.println(“Base16:”+Integer.toString(i,16));
System.out.println(“Base10:”+Integer.toString(i,10));
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
Stringrepresentationfordecimalvalue:41
Binary:101001
Octal:51
Hex:29
Decimal:41
UsingtoString(inti,intbase)method:
Base2:101001
Base8:51
Base16:29
Base10:41
Stringrepresentationfordecimalvalue:-41
Binary:11111111111111111111111111010111
Octal:37777777727
Hex:ffffffd7
Decimal:-41
UsingtoString(inti,intbase)method:
Base2:-101001
Base8:-51
Base16:-29
Base10:-41
The Class
TheCharacterclassdefinesamyriadofconstants,includingthefollowing,which
representtheminimumandthemaximumvaluesofthechartype(§2.2,p.38):
WOW! eBook
www.wowebook.org
Character.MIN_VALUE
Character.MAX_VALUE
TheCharacterclassalsodefinesaplethoraofstaticmethodsforhandlingvarious
attributesofacharacter,andcaseissuesrelatingtocharacters,asdefinedbytheUnicode
standard:
Clickheretoviewcodeimage
staticintgetNumericValue(charch)
staticbooleanisLowerCase(charch)
staticbooleanisUpperCase(charch)
staticbooleanisTitleCase(charch)
staticbooleanisDigit(charch)
staticbooleanisLetter(charch)
staticbooleanisLetterOrDigit(charch)
staticchartoUpperCase(charch)
staticchartoLowerCase(charch)
staticchartoTitleCase(charch)
Thefollowingcodeconvertsalowercasecharactertoanuppercasecharacter:
Clickheretoviewcodeimage
charch=‘a’;
if(Character.isLowerCase(ch))ch=Character.toUpperCase(ch);
The Class
Inadditiontothecommonutilitymethodsforwrapperclassesdiscussedearlierinthis
section,theBooleanclassdefinesthefollowingwrapperobjectstorepresentthe
primitivevaluestrueandfalse,respectively:
Boolean.TRUE
Boolean.FALSE
ConvertingStringstoBooleanValues
ThewrapperclassBooleandefinesthefollowingstaticmethod,whichreturnsthe
booleanvaluetrueonlyiftheStringargumentisequaltothestring"true",
ignoringthecase;otherwise,itreturnsthebooleanvaluefalse.Notethatthismethod
doesnotthrowanyexceptions,asitsnumericcounterpartsdo.
Clickheretoviewcodeimage
staticbooleanparseBoolean(Stringstr)
Clickheretoviewcodeimage
booleanb1=Boolean.parseBoolean(“TRUE”);//true.
booleanb2=Boolean.parseBoolean(“true”);//true.
booleanb3=Boolean.parseBoolean(“false”);//false.
booleanb4=Boolean.parseBoolean(“FALSE”);//false.
booleanb5=Boolean.parseBoolean(“nottrue”);//false.
WOW! eBook
www.wowebook.org
ReviewQuestions
8.4Whichofthefollowingarewrapperclasses?
Selectthethreecorrectanswers.
(a)java.lang.Void
(b)java.lang.Int
(c)java.lang.Boolean
(d)java.lang.Long
(e)java.lang.String
8.5Whichofthefollowingclassesdonotextendthejava.lang.Numberclass?
Selectthetwocorrectanswers.
(a)java.lang.Float
(b)java.lang.Byte
(c)java.lang.Character
(d)java.lang.Boolean
(e)java.lang.Short
8.6Whichoftheseclassesdefineimmutableobjects?
Selectthethreecorrectanswers.
(a)Character
(b)Byte
(c)Number
(d)Short
(e)Object
8.7Whichoftheseclasseshaveasingle-parameterconstructortakingastring?
Selectthetwocorrectanswers.
(a)Void
(b)Integer
(c)Boolean
(d)Character
(e)Object
8.8WhichofthewrapperclasseshaveabooleanValue()method?
WOW! eBook
www.wowebook.org
Selecttheonecorrectanswer
(a)Allwrapperclasses
(b)AllwrapperclassesexceptVoid
(c)AllwrapperclassesthatalsoimplementthecompareTo()method
(d)AllwrapperclassesextendingNumber
(e)OnlytheclassBoolean
8.9Whichstatementsaretrueaboutwrapperclasses?
Selectthetwocorrectanswers.
(a)Stringisawrapperclass.
(b)DoublehasacompareTo()method.
(c)CharacterhasaintValue()method.
(d)ByteextendsNumber.
8.10Whatwillthefollowingprogramprintwhencompiledandrun?
Clickheretoviewcodeimage
publicclassRQ200A70{
publicstaticvoidmain(String[]args){
Integeri=newInteger(-10);
Integerj=newInteger(-10);
Integerk=-10;
System.out.print((i==j)+“|”);
System.out.print(i.equals(j)+“|”);
System.out.print((i==k)+“|”);
System.out.print(i.equals(k));
}
}
Selecttheonecorrectanswer.
(a)false|true|false|true
(b)true|true|true|true
(c)false|true|true|true
(d)true|true|false|true
(e)Noneoftheabove.
WOW! eBook
www.wowebook.org
8.4The Class
Handlingcharactersequencesissupportedthroughthreefinalclasses:String,
StringBuilder,andStringBuffer.TheJavaplatformusesthevariable-length
UTF-16encodingtostorecharactersinchararraysandinthestringhandlingclasses.
TheUTF-16encodingallowscharacterswhoseUnicodevaluesareintherange0000to
10FFFF.ThechartyperepresentsUnicodevaluesintherange0000toFFFF—thatis,
charactersthatcanberepresentedinasingle16-bitword.Asaconsequence,the
supplementarycharactersarerepresentedbymultiplecharvalues,ormultiple16-bit
words,whenthesearestoredinastringorachararray.Thestringhandlingclasses
providemethodstohandlethefullrangeofcharactersintheUTF-16encoding,butwe
willnotdwellonthesubjectinthisbook.
Immutability
TheStringclassimplementsimmutablecharacterstrings,whichareread-onlyoncethe
stringhasbeencreatedandinitialized.OperationsonaStringobjectthatmodifythe
charactersreturnanewStringobject.TheStringBuilderclassimplements
dynamiccharacterstrings.TheStringBufferclassisathread-safeversionofthe
StringBuilderclass.
ThissectiondiscussestheclassStringthatprovidesfacilitiesforcreating,initializing,
andmanipulatingcharacterstrings.ThenextsectiondiscussestheStringBuilderand
StringBufferclasses.
CreatingandInitializingStrings
StringLiteralsRevisited
TheeasiestwaytocreateaStringobjectistouseastringliteral:
Clickheretoviewcodeimage
Stringstr1=“Youcannotchangeme!”;
AstringliteralisareferencetoaStringobject.ThevalueintheStringobjectisthe
charactersequenceenclosedinthedoublequotesofthestringliteral.Sinceastringliteral
isareference,itcanbemanipulatedlikeanyotherStringreference.Thereference
valueofastringliteralcanbeassignedtoanotherStringreference:Thereference
str1willdenotetheStringobjectwiththevalue"Youcannotchangeme!"
aftertheprecedingassignment.Astringliteralcanbeusedtoinvokemethodsonits
Stringobject:
Clickheretoviewcodeimage
intstrLength=“Youcannotchangeme!”.length();//21
Thecompileroptimizeshandlingofstringliterals(andcompile-timeconstantexpressions
thatevaluatetostrings):OnlyoneStringobjectissharedbyallstring-valuedconstant
expressionswiththesamecharactersequence.Suchstringsaresaidtobeinterned,
meaningthattheyshareauniqueStringobjectiftheyhavethesamecontent.The
WOW! eBook
www.wowebook.org
Stringclassmaintainsastringliteralpoolwheresuchstringsareinterned.
Clickheretoviewcodeimage
Stringstr2=“Youcannotchangeme!”;//Alreadyinterned.
BothStringreferencesstr1andstr2denotethesameinternedString
objectinitializedwiththecharacterstring:"Youcannotchangeme!"Sodoesthe
referencestr3inthefollowingcode.Thecompile-timeevaluationoftheconstant
expressioninvolvingthetwostringliteralsresultsinastringthatisalreadyinterned:
Clickheretoviewcodeimage
Stringstr3=“Youcannot”+”changeme!”;//Compile-timeconstant
expression
Inthefollowingcode,boththereferencescan1andcan2denotethesameinterned
Stringobject,whichcontainsthestring"7Up":
Clickheretoviewcodeimage
Stringcan1=7+“Up”;//Valueofcompile-timeconstantexpression:“7Up”
Stringcan2=“7Up”;//“7Up”
However,inthefollowingcode,thereferencecan4denotesanewStringobjectthat
willhavethevalue"7Up"atruntime:
Clickheretoviewcodeimage
Stringword=“Up”;
Stringcan4=7+word;//Notacompile-timeconstantexpression.
ThesharingofStringobjectsbetweenstring-valuedconstantexpressionsposesno
problem,sincetheStringobjectsareimmutable.Anyoperationperformedonone
Stringreferencewillneverhaveanyeffectontheusageofotherreferencesdenoting
thesameobject.TheStringclassisalsodeclaredasfinal,sothatnosubclasscan
overridethisbehavior.
StringConstructors
TheStringclasshasnumerousconstructorstocreateandinitializeStringobjects
basedonvarioustypesofarguments.Herewepresentafewselectedconstructors:
WOW! eBook
www.wowebook.org
String()
ThisconstructorcreatesanewStringobject,whosecontentistheemptystring,
"".
String(Stringstr)
ThisconstructorcreatesanewStringobject,whosecontentsarethesameas
thoseoftheStringobjectpassedasargument.
Clickheretoviewcodeimage
String(char[]value)
String(char[]value,intoffset,intcount)
TheseconstructorscreateanewStringobject,whosecontentsarecopiedfroma
chararray.Thesecondconstructorallowsextractionofacertainnumberof
characters(count)fromagivenoffsetinthearray.
String(StringBuilderbuilder)
String(StringBufferbuffer)
TheseconstructorsallowinteroperabilitywiththeStringBuilderand
StringBufferclasses,respectively.
Notethatusingaconstructorcreatesabrand-newStringobject;usingaconstructor
doesnotinternthestring.Areferencetoaninternedstringcanbeobtainedbycallingthe
intern()methodintheStringclass—althoughinpractice,thereisusuallynoreason
todoso.
Inthefollowingcode,theStringobjectdenotedbystr4isdifferentfromtheinterned
Stringobjectpassedasanargument:
Clickheretoviewcodeimage
Stringstr4=newString(“Youcannotchangeme!”);
ConstructingStringobjectscanalsobedonefromarraysofbytes,arraysofcharacters,
orstringbuilders:
Clickheretoviewcodeimage
byte[]bytes={97,98,98,97};
char[]characters={‘a’,‘b’,‘b’,‘a’};
StringBuilderstrBuilder=newStringBuilder(“abba”);
//…
StringbyteStr=newString(bytes);//Usingarrayofbytes:“abba”
StringcharStr=newString(characters);//Usingarrayofchars:“abba”
StringbuildStr=newString(strBuilder);//Usingstringbuilder:“abba”
InExample8.3,notethatthereferencestr1doesnotdenotethesameStringobjectas
thereferencesstr4andstr5.UsingthenewoperatorwithaStringconstructor
alwayscreatesanewStringobject.Theexpression"Youcannot"+wordsisnot
aconstantexpressionand,therefore,resultsinthecreationofanewStringobject.The
localreferencesstr2andstr3inthemain()methodandthestaticreferencestr1in
theAuxiliaryclassalldenotethesameinternedstring.Objectvalueequalityishardly
surprisingbetweenthesereferences.Indeed,itmightbetemptingtousetheoperator==
WOW! eBook
www.wowebook.org
forobjectvalueequalityofstringliterals,butthisisnotadvisable.
Example8.3StringConstructionandEquality
Clickheretoviewcodeimage
//File:StringConstruction.java
classAuxiliary{
staticStringstr1=“Youcannotchangeme!”;//Interned
}
//______________________________________________________________________________
publicclassStringConstruction{
staticStringstr1=“Youcannotchangeme!”;//Interned
publicstaticvoidmain(String[]args){
StringemptyStr=newString();//””
System.out.println(“emptyStr:"”+emptyStr+“"”);
Stringstr2=“Youcannotchangeme!”;//Interned
Stringstr3=“Youcannot”+”changeme!”;//Interned
Stringstr4=newString(“Youcannotchangeme!”);//NewStringobject
Stringwords=”changeme!”;
Stringstr5=“Youcannot”+words;//NewStringobject
System.out.println(“str1==str2:”+(str1==str2));//(1)
true
System.out.println(“str1.equals(str2):”+str1.equals(str2));//(2)
true
System.out.println(“str1==str3:”+(str1==str3));//(3)
true
System.out.println(“str1.equals(str3):”+str1.equals(str3));//(4)
true
System.out.println(“str1==str4:”+(str1==str4));//(5)
false
System.out.println(“str1.equals(str4):”+str1.equals(str4));//(6)
true
System.out.println(“str1==str5:”+(str1==str5));//(7)
false
System.out.println(“str1.equals(str5):”+str1.equals(str5));//(8)
true
System.out.println(“str1==Auxiliary.str1:”+
(str1==Auxiliary.str1));//(9)true
System.out.println(“str1.equals(Auxiliary.str1):”+
str1.equals(Auxiliary.str1));//(10)true
System.out.println(“"Youcannotchangeme!".length():”+
“Youcannotchangeme!”.length());//(11)21
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
emptyStr:””
str1==str2:true
str1.equals(str2):true
WOW! eBook
www.wowebook.org
str1==str3:true
str1.equals(str3):true
str1==str4:false
str1.equals(str4):true
str1==str5:false
str1.equals(str5):true
str1==Auxiliary.str1:true
str1.equals(Auxiliary.str1):true
“Youcannotchangeme!”.length():21
The Interface
Thisinterfacedefinesareadablesequenceofcharvalues.Itisimplementedbyallthree
classes:String,StringBuilder,andStringBuffer.Manymethodsinthese
classesacceptargumentsofthisinterfacetype,andspecifyitastheirreturntype.This
interfacefacilitatesinteroperabilitybetweentheseclasses.Itdefinesthefollowing
methods:
charcharAt(intindex)
AcharacterataparticularindexinasequencecanbereadusingthecharAt()
method.Thefirstcharacterisatindex0andthelastoneatindex1lessthanthe
numberofcharactersinthestring.Iftheindexvalueisnotvalid,an
IndexOutOfBoundsExceptionisthrown.
intlength()
Thismethodreturnsthenumberofcharvaluesinthissequence.
Clickheretoviewcodeimage
CharSequencesubSequence(intstart,intend)
ThismethodreturnsanewCharSequencethatisasubsequenceofthis
sequence.Charactersfromthecurrentsequencearereadfromindexstarttothe
indexend-1,inclusive.
StringtoString()
Thismethodreturnsastringcontainingthecharactersinthissequenceinthesame
orderasthissequence.
ReadingCharactersfromaString
Thefollowingmethodscanbeusedforcharacter-relatedoperationsonastring:
WOW! eBook
www.wowebook.org
charcharAt(intindex)
ThismethodisdefinedintheCharSequenceinterface,whichtheStringclass
implements(p.360).
char[]toCharArray()
Thismethodreturnsanewcharacterarray,withlengthequaltothelengthofthis
string,thatcontainsthecharactersinthisstring.
Clickheretoviewcodeimage
voidgetChars(intsrcBegin,intsrcEnd,char[]dst,intdstBegin)
Thismethodcopiescharactersfromthecurrentstringintothedestinationcharacter
array.CharactersfromthecurrentstringarereadfromindexsrcBegintothe
indexsrcEnd-1,inclusive.Theyarecopiedintothedestinationarray(dst),
startingatindexdstBeginandendingatindexdstbegin+(srcEnd-src-
Begin)-1.Thenumberofcharacterscopiedis(srcEnd-srcBegin).An
Index-OutOfBoundsExceptionisthrowniftheindicesdonotmeetthe
criteriafortheoperation.
intlength()
ThismethodisdefinedintheCharSequenceinterface,whichtheStringclass
implements(p.360).
booleanisEmpty()
Thismethodreturnstrueifthelengthofthestringis0,andfalse
otherwise.
Example8.4usessomeofthesemethodsat(3),(4),(5),and(6).Theprogramprintsthe
frequencyofacharacterinastringandillustratescopyingfromastringintoacharacter
array.
WOW! eBook
www.wowebook.org
Example8.4ReadingCharactersfromaString
Clickheretoviewcodeimage
publicclassReadingCharsFromString{
publicstaticvoidmain(String[]args){
int[]frequencyData=newint[Character.MAX_VALUE];//(1)
Stringstr=“Youcannotchangeme!”;//(2)
//Countthefrequencyofeachcharacterinthestring.
for(inti=0;i<str.length();i++){//(3)
try{
frequencyData[str.charAt(i)]++;//(4)
}catch(StringIndexOutOfBoundsExceptione){
System.out.println(“Indexerrordetected:“+i+”notinrange.”);
}
}
//Printthecharacterfrequency.
System.out.println(“Characterfrequencyforstring:"”+str+“"”);
for(inti=0;i<frequencyData.length;i++){
if(frequencyData[i]!=0)
System.out.println((char)i+”(code“+i+”):”+frequencyData[i]);
}
System.out.println(“Copyingintoachararray:”);
char[]destination=newchar[str.length()-3];//3characters
less.
str.getChars(0,7,destination,0);//(5)“Youcan”
str.getChars(10,str.length(),destination,7);//(6)”change
me!”
//“not”not
copied.
//Printthecharacterarray.
for(inti=0;i<destination.length;i++){
System.out.print(destination[i]);
}
System.out.println();
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
CharacterFrequencyforstring:“Youcannotchangeme!”
(code32):3
!(code33):1
Y(code89):1
a(code97):2
c(code99):2
e(code101):2
g(code103):1
h(code104):1
m(code109):1
n(code110):3
o(code111):2
t(code116):1
u(code117):1
Copyingintoachararray:
Youcanchangeme!
WOW! eBook
www.wowebook.org
InExample8.4,thefrequencyDataarrayat(1)storesthefrequencyofeachcharacter
thatcanoccurinastring.Thestringinquestionisdeclaredat(2).Sinceacharvalueis
promotedtoanintvalueinarithmeticexpressions,itcanbeusedasanindexinanarray.
EachelementinthefrequencyDataarrayfunctionsasafrequencycounterforthe
charactercorrespondingtotheindexvalueoftheelement:
Clickheretoviewcodeimage
frequencyData[str.charAt(i)]++;//(4)
ThecallstothegetChars()methodat(5)and(6)copyparticularsubstringsfromthe
stringintodesignatedplacesinthedestinationarray,beforeprintingthewhole
characterarray.
ComparingStrings
CharactersarecomparedbasedontheirUnicodevalues.
Clickheretoviewcodeimage
booleantest=‘a’<‘b’;//truesince0x61<0x62
Twostringsarecomparedlexicographically,asinadictionaryortelephonedirectory,by
successivelycomparingtheircorrespondingcharactersateachpositioninthetwostrings,
startingwiththecharactersinthefirstposition.Thestring"abba"islessthan"aha",
sincethesecondcharacter'b'inthestring"abba"islessthanthesecondcharacter
'h'inthestring"aha".Thecharactersinthefirstpositionineachofthesestringsare
equal.
Thefollowingpublicmethodscanbeusedforcomparingstrings:
Clickheretoviewcodeimage
booleanequals(Objectobj)
booleanequalsIgnoreCase(Stringstr2)
TheStringclassoverridestheequals()methodfromtheObjectclass.The
Stringclassequals()methodimplementsStringobjectvalueequalityas
twoStringobjectshavingthesamesequenceofcharacters.The
equalsIgnoreCase()methoddoesthesame,butignoresthecaseofthe
characters.
intcompareTo(Stringstr2)
TheStringclassimplementstheComparable<String>interface.The
compareTo()methodcomparesthetwostrings,andreturnsavaluebasedonthe
outcomeofthecomparison:
•Thevalue0,ifthisstringisequaltothestringargument
•Avaluelessthan0,ifthisstringislexicographicallylessthanthestring
argument
•Avaluegreaterthan0,ifthisstringislexicographicallygreaterthanthestring
argument
WOW! eBook
www.wowebook.org
Herearesomeexamplesofstringcomparisons:
Clickheretoviewcodeimage
StringstrA=newString(“TheCasewasthrownoutofCourt”);
StringstrB=newString(“thecasewasthrownoutofcourt”);
booleanb1=strA.equals(strB);//false
booleanb2=strA.equalsIgnoreCase(strB);//true
Stringstr1=newString(“abba”);
Stringstr2=newString(“aha”);
intcompVal1=str1.compareTo(str2);//negativevalue=>str1<str2
CharacterCaseinaString
Clickheretoviewcodeimage
StringtoUpperCase()
StringtoUpperCase(Localelocale)
StringtoLowerCase()
StringtoLowerCase(Localelocale)
Notethattheoriginalstringisreturnedifnoneofthecharactersneedsitscase
changed,butanewStringobjectisreturnedifanyofthecharactersneedsits
casechanged.Thesemethodsdelegatethecharacter-by-charactercaseconversion
tocorrespondingmethodsfromtheCharacterclass.
Thesemethodsusetherulesofthe(default)locale(returnedbythemethod
Locale.getDefault()),whichembodiestheidiosyncrasiesofaspecific
geographical,political,orculturalregionregardingnumber/date/currencyformats,
characterclassification,alphabet(includingcaseidiosyncrasies),andother
localizations.
Exampleofcaseinstrings:
Clickheretoviewcodeimage
StringstrA=newString(“TheCasewasthrownoutofCourt”);
StringstrB=newString(“thecasewasthrownoutofcourt”);
StringstrC=strA.toLowerCase();//Caseconversion=>NewStringobject:
//“thecasewasthrownoutofcourt”
StringstrD=strB.toLowerCase();//Nocaseconversion=>SameString
object
StringstrE=strA.toUpperCase();//Caseconversion=>NewStringobject:
//“THECASEWASTHROWNOUTOFCOURT”
booleantest1=strC==strA;//false
booleantest2=strD==strB;//true
booleantest3=strE==strA;//false
WOW! eBook
www.wowebook.org
ConcatenationofStrings
Concatenationoftwostringsresultsinanewstringthatconsistsofthecharactersofthe
firststringfollowedbythecharactersofthesecondstring.Theoverloadedoperator+for
stringconcatenationisdiscussedin§5.7,p.169.Inaddition,thefollowingmethodcanbe
usedtoconcatenatetwostrings:
Stringconcat(Stringstr)
Theconcat()methoddoesnotmodifytheStringobjectonwhichitisinvoked,as
Stringobjectsareimmutable.Instead,theconcat()methodreturnsareferencetoa
brand-newStringobject:
Clickheretoviewcodeimage
Stringbillboard=“Just”;
billboard.concat(”lostinspace.”);//(1)Returnedreferencevaluenot
stored.
System.out.println(billboard);//(2)“Just”
billboard=billboard.concat(”advertise”).concat(”here.”);//(3)
Chaining.
System.out.println(billboard);//(4)“Justadvertisehere.”
At(1),thereferencevalueoftheStringobjectreturnedbythemethodconcat()is
notstored.ThisStringobjectbecomesinaccessibleafter(1).Weseethatthereference
billboardstilldenotesthestringliteral"Just"at(2).
At(3),twomethodcallstotheconcat()methodarechained.Thefirstcallreturnsa
referencevaluetoanewStringobject,whosecontentis"Justadvertise".The
secondmethodcallisinvokedonthisStringobjectusingthereferencevaluethatwas
returnedinthefirstmethodcall.ThesecondcallresultsinyetanothernewString
object,whosecontentis"Justadvertisehere.".Thereferencevalueofthis
Stringobjectisassignedtothereferencebillboard.BecauseStringobjectsare
immutable,thecreationofthetemporaryStringobjectwiththecontent"Just
advertise"isinevitableat(3).
Somemoreexamplesofstringconcatenationfollow:
Clickheretoviewcodeimage
Stringmotto=newString(“Programonce”);//(1)
motto+=“,executeeverywhere.”;//(2)
motto=motto.concat(”Don’tbetonit!”);//(3)
NotethatanewStringobjectisassignedtothereferencemottoeachtimeinthe
assignmentsat(1),(2),and(3).TheStringobjectwiththecontents"Program
once"becomesinaccessibleaftertheassignmentat(2).TheStringobjectwiththe
contents"Programonce,executeeverywhere."becomesinaccessibleafter
(3).ThereferencemottodenotestheStringobjectwiththefollowingcontentsafter
executionoftheassignmentat(3):
Clickheretoviewcodeimage
“Programonce,executeeverywhere.Don’tbetonit!”
WOW! eBook
www.wowebook.org
Joiningof Objects
Oneoperationcommonlyperformedonasequenceofstringsistoformatthemsothat
eachstringisseparatedfromthenextonebyadelimiter.Forexample,giventhefollowing
sequenceofstrings:
“2014”
“January”
“11”
wewishtoformatthemsothatindividualstringsareseparatedbythedelimiter“/”:
“2014/January/11”
ThefollowingstaticmethodsintheStringclasscanbeusedforthispurpose:
Clickheretoviewcodeimage
staticStringjoin(CharSequencedelimiter,CharSequence…elements)
staticStringjoin(CharSequencedelimiter,
Iterable<?extendsCharSequence>elements)
BothstaticmethodsreturnanewStringcomposedofcopiesofthe
CharSequenceelementsjoinedtogetherwithacopyofthespecified
CharSequencedelimiter.Thus,theresultingstringiscomposedoftextual
representationsoftheelementsseparatedbythetextualrepresentationofthe
specifieddelimiter.
Ifanelementisnull,thestring"null"isaddedasitstextualrepresentation.If
thedelimiterisnull,aNullPointerExceptionisthrown.
NotethatboththeindividualstringsandthedelimiterstringareCharSequenceobjects.
TheexamplesinthissectionuseStringandStringBuilderobjectsthatimplement
theCharSequenceinterface(p.360).
AnIterableprovidesaniteratortotraverseoveritselements.Thefollowingexamples
useanArrayList(§10.1,p.423)thatimplementstheIterableinterface.The
secondjoin()methodisthenabletotraversetheIterableusingtheiterator.This
methodwillacceptonlyanIterablewhoseelementsareeitheroftype
CharSequenceorsubtypesofCharSequence.
ThefirstexampleshowsjoiningofStringobjects.Thefirstjoin()methodiscalled
inthiscase.
Clickheretoviewcodeimage
//(1)JoiningindividualStringobjects:
StringdateStr=String.join(“/”,“2014”,“January”,“11”);
System.out.println(dateStr);//2014/January/11
ThesecondexampleshowsjoiningofelementsinaStringBuilderarray.Againthe
firstjoin()methodiscalled,withthearraybeingpassedasthesecondparameter.
Clickheretoviewcodeimage
//(2)JoiningelementsinaStringBuilderarray:
StringBuilderleft=newStringBuilder(“Left”);
WOW! eBook
www.wowebook.org
StringBuilderright=newStringBuilder(“Right”);
StringBuilder[]strBuilders={left,right,left};
Stringmarch=String.join(“—>”,strBuilders);
System.out.println(march);//Left—>Right—>Left
ThethirdexampleshowsjoiningofelementsinanArrayListofStringBuilder.
Thesecondjoin()methodiscalled,withtheArrayListbeingpassedasthesecond
parameter.NotethatsomeoftheelementsoftheArrayListarenull.
Clickheretoviewcodeimage
//(3)JoiningelementsinaStringBuilderlist:
ArrayList<StringBuilder>sbList=newArrayList<>();
sbList.add(right);sbList.add(null);sbList.add(left);sbList.add(null);
StringresultStr=“[”+String.join(“,“,sbList)+“]”;
System.out.println(resultStr);//[Right,null,Left,null]
ThelastexampleshowsjoiningofelementsinanArrayListofCharSequence.
Againthesecondjoin()methodiscalled,withtheArrayListbeingpassedasthe
secondparameter.NotethatelementsoftheArrayListareStringand
StringBuilderobjectsthatarealsooftypeCharSequence.
Clickheretoviewcodeimage
//(4)JoiningelementsinaCharSequencelist:
ArrayList<CharSequence>charSeqList=newArrayList<>();
charSeqList.add(right);charSeqList.add(left);//AddStringBuilder
objects.
charSeqList.add(“Right”);charSeqList.add(“Left”);//AddStringobjects.
StringresultStr2=“<”+String.join(“;“,charSeqList)+“>”;
System.out.println(resultStr2);//<Right;Left;Right;Left>
SearchingforCharactersandSubstrings
Thefollowingoverloadedmethodscanbeusedtofindtheindexofacharacterorthestart
indexofasubstringinastring.Thesemethodssearchforwardtowardtheendofthe
string.Inotherwords,theindexofthefirstoccurrenceofthecharacterorsubstringis
found.Ifthesearchisunsuccessful,thevalue–1isreturned.
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
intindexOf(intch)
intindexOf(intch,intfromIndex)
Thefirstmethodfindstheindexofthefirstoccurrenceoftheargumentcharacterin
astring.Thesecondmethodfindstheindexofthefirstoccurrenceoftheargument
characterinastring,startingattheindexspecifiedinthesecondargument.Ifthe
indexargumentisnegative,theindexisassumedtobe0.Iftheindexargumentis
greaterthanthelengthofthestring,itiseffectivelyconsideredtobeequaltothe
lengthofthestring,resultinginthevalue-1beingreturned.
Clickheretoviewcodeimage
intindexOf(Stringstr)
intindexOf(Stringstr,intfromIndex)
Thefirstmethodfindsthestartindexofthefirstoccurrenceofthesubstring
argumentinastring.Thesecondmethodfindsthestartindexofthefirstoccurrence
ofthesubstringargumentinastring,startingattheindexspecifiedinthesecond
argument.
TheStringclassalsodefinesasetofmethodsthatsearchforacharacterorasubstring,
butthesearchisbackwardtowardthestartofthestring.Inotherwords,theindexofthe
lastoccurrenceofthecharacterorsubstringisfound.
Clickheretoviewcodeimage
intlastIndexOf(intch)
intlastIndexOf(intch,intfromIndex)
intlastIndexOf(Stringstr)
intlastIndexOf(Stringstr,intfromIndex)
Thefollowingmethodscanbeusedtocreateastringinwhichalloccurrencesofa
characterorasubsequenceinastringhavebeenreplacedwithanothercharacteror
subsequence:
Clickheretoviewcodeimage
Stringreplace(charoldChar,charnewChar)
Stringreplace(CharSequencetarget,CharSequencereplacement)
ThefirstmethodreturnsanewStringobjectthatistheresultofreplacingall
occurrencesoftheoldCharinthecurrentstringwiththenewChar.Thecurrent
stringisreturnedifnooccurrencesoftheoldCharcanbefound.
ThesecondmethodreturnsanewStringobjectthatistheresultofreplacingall
occurrencesofthecharactersequencetargetinthecurrentstringwiththe
charactersequencereplacement.Thecurrentstringisreturnedifno
occurrencesofthetargetcanbefound.
Thefollowingmethodscanbeusedtotestwhetherastringsatisfiesagivencriterion:
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
booleancontains(CharSequencecs)
Thismethodreturnstrueifthecurrentstringcontainsthespecifiedcharacter
sequence,andfalseotherwise.
Clickheretoviewcodeimage
booleanstartsWith(Stringprefix)
Thismethodreturnstrueifthecurrentstringstartswiththecharactersequence
specifiedbyparameterprefix,andfalseotherwise.
Clickheretoviewcodeimage
booleanstartsWith(Stringprefix,intindex)
Thismethodreturnstrueifthesubstringofthecurrentstringatthespecified
indexstartswiththecharactersequencespecifiedbyparameterprefix,and
falseotherwise.
Clickheretoviewcodeimage
booleanendsWith(Stringsuffix)
Thismethodreturnstrueifthecurrentstringendswiththecharactersequence
specifiedbyparametersuffix,andfalseotherwise.
Examplesofsearchandreplacemethods:
Clickheretoviewcodeimage
StringfunStr=“JavaJives”;
//0123456789
intjInd1a=funStr.indexOf(‘J’);//0
intjInd1b=funStr.indexOf(‘J’,1);//5
intjInd2a=funStr.lastIndexOf(‘J’);//5
intjInd2b=funStr.lastIndexOf(‘J’,4);//0
Stringbanner=“Oneman,Onevote”;
//01234567890123456
intsubInd1a=banner.indexOf(“One”);//0
intsubInd1b=banner.indexOf(“One”,3);//9
intsubInd2a=banner.lastIndexOf(“One”);//9
intsubInd2b=banner.lastIndexOf(“One”,10);//9
intsubInd2c=banner.lastIndexOf(“One”,8);//0
intsubInd2d=banner.lastIndexOf(“One”,2);//0
StringnewStr=funStr.replace(‘J’,‘W’);//“WavaWives”
StringnewBanner=banner.replace(“One”,“No”);//“Noman,Novote”
booleanfound1=banner.contains(“One”);//true
booleanfound2=newBanner.contains(“One”);//false
Stringsong=“Startmeup!”;
//012345677890
booleanfound3=song.startsWith(“Start”);//true
booleannotFound1=song.startsWith(“start”);//false
booleanfound4=song.startsWith(“me”,6);//true
booleanfound5=song.endsWith(“up!”);//true
WOW! eBook
www.wowebook.org
booleannotFound2=song.endsWith(“up”);//false
ExtractingSubstrings
Stringtrim()
Thismethodcanbeusedtocreateastringwherewhitespace(infact,allcharacters
withvalueslessthanorequaltothespacecharacter'\u0020')hasbeenremoved
fromthefront(leading)andtheend(trailing)ofastring.
Clickheretoviewcodeimage
Stringsubstring(intstartIndex)
Stringsubstring(intstartIndex,intendIndex)
TheStringclassprovidestheseoverloadedmethodstoextractsubstringsfroma
string.AnewStringobjectcontainingthesubstringiscreatedandreturned.The
firstmethodextractsthestringthatstartsatthegivenindexstartIndexand
extendstotheendofthestring.Theendofthesubstringcanbespecifiedbyusinga
secondargumentendIndexthatistheindexofthefirstcharacterafterthe
substring—thatis,thelastcharacterinthesubstringisatindexendIndex-1.If
theindexvalueisnotvalid,anIndexOutOfBoundsExceptionisthrown.
Examplesofextractingsubstrings:
Clickheretoviewcodeimage
Stringutopia=“\t\nJavaNation\n\t”;
utopia=utopia.trim();//“JavaNation”
utopia=utopia.substring(5);//“Nation”
Stringradioactive=utopia.substring(3,6);//“ion”
ConvertingPrimitiveValuesandObjectstoStrings
TheStringclassoverridesthetoString()methodintheObjectclassandreturns
theStringobjectitself:
StringtoString()
ThismethodisdefinedintheCharSequenceinterface,whichtheStringclass
implements(p.360).
TheStringclassalsodefinesasetofstaticoverloadedvalueOf()methodstoconvert
objectsandprimitivevaluesintostrings:
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
staticStringvalueOf(Objectobj)
staticStringvalueOf(char[]charArray)
staticStringvalueOf(booleanb)
staticStringvalueOf(charc)
Allofthesemethodsreturnastringrepresentingthegivenparametervalue.Acall
tothemethodwiththeparameterobjisequivalenttoobj.toString()when
objisnotnull;otherwise,the"null"stringisreturned.Thebooleanvalues
trueandfalseareconvertedintothestrings"true"and"false".The
charparameterisconvertedtoastringconsistingofasinglecharacter.
Clickheretoviewcodeimage
staticStringvalueOf(inti)
staticStringvalueOf(longl)
staticStringvalueOf(floatf)
staticStringvalueOf(doubled)
ThestaticvalueOf()method,whichacceptsaprimitivevalueasanargument,is
equivalenttothestatictoString()methodinthecorrespondingwrapperclass
foreachoftheprimitivedatatypes((6a)and(6b)in§8.3,p.347).Notethatthere
arenovalueOf()methodsthatacceptabyteorashort.
Examplesofstringconversions:
Clickheretoviewcodeimage
StringanonStr=String.valueOf(“Makemeastring.”);//“Makemea
string.”
StringcharStr=String.valueOf(newchar[]{‘a’,‘h’,‘a’});//“aha”
StringboolTrue=String.valueOf(true);//“true”
StringdoubleStr=String.valueOf(Math.PI);//
“3.141592653589793”
FormattedStrings
WehaveusedtheSystem.out.printf()methodtoformatvaluesandprintthemto
theterminalwindow(§1.9,p.15).Tojustcreatethestringwiththeformattedvalues,but
notprinttheformattedresult,wecanusethefollowingstaticmethodfromtheString
class.Itacceptsthesameargumentsastheprintf()method,andusesthesameformat
specifications(Table1.2,p.20).
Clickheretoviewcodeimage
staticStringformat(Stringformat,Object…args)
Themethodreturnsastringwiththeresultofformattingthevaluesinthevarargs
parameterargsaccordingtotheStringparameterformat.Theformatstring
containsformatspecificationsthatdeterminehoweachsubsequentvalueinthe
varargsparameterargswillbeformatted.
Anyerrorintheformatstringwillresultinaruntimeexception.
Thefollowingcalltotheformat()methodcreatesaformattedstringwiththethree
WOW! eBook
www.wowebook.org
valuesformattedaccordingtothespecifiedformatstring:
Clickheretoviewcodeimage
StringformattedStr=String.format(“Formattedvalues|%5d|%8.3f|%5s|”,
2016,Math.PI,“Hi”);
System.out.println(formattedStr);//Formattedvalues|2016|3.142|Hi|
formattedStr=formattedStr.toUpperCase();
System.out.println(formattedStr);//FORMATTEDVALUES|2016|3.142|HI|
OthermiscellaneousmethodsexistintheStringclassforpatternmatching
(matches()),splittingstrings(split()),andconvertingastringtoanarrayofbytes
(getBytes()).ThemethodhashCode()canbeusedtocomputeahashvaluebased
onthecharactersinthestring.ConsulttheJavaSEplatformAPIdocumentationformore
details.
ReviewQuestions
8.11WhichofthefollowingoperatorscannothaveanoperandoftypeString?
Selectthetwocorrectanswers.
(a)+
(b)-
(c)+=
(d).
(e)&
8.12Whichexpressionwillextractthesubstring"kap",giventhefollowing
declaration:
Stringstr=“kakapo”;
Selecttheonecorrectanswer.
(a)str.substring(2,2)
(b)str.substring(2,3)
(c)str.substring(2,4)
(d)str.substring(2,5)
(e)str.substring(3,3)
8.13Whatwillbetheresultofattemptingtocompileandrunthefollowingcode?
Clickheretoviewcodeimage
classMyClass{
publicstaticvoidmain(String[]args){
Stringstr1=“str1”;
Stringstr2=“str2”;
Stringstr3=“str3”;
str1.concat(str2);
WOW! eBook
www.wowebook.org
System.out.println(str3.concat(str1));
}
}
Selecttheonecorrectanswer.
(a)Thecodewillfailtocompilebecausetheexpressionstr3.concat(str1)
willnotresultinavalidargumentfortheprintln()method.
(b)Theprogramwillprintstr3str1str2atruntime.
(c)Theprogramwillprintstr3atruntime.
(d)Theprogramwillprintstr3str1atruntime.
(e)Theprogramwillprintstr3str2atruntime.
8.14Whichstatementaboutthetrim()methodoftheStringclassistrue?
Selecttheonecorrectanswer.
(a)Itreturnsastringwheretheleadingwhitespaceoftheoriginalstringhasbeen
removed.
(b)Itreturnsastringwherethetrailingwhitespaceoftheoriginalstringhasbeen
removed.
(c)Itreturnsastringwhereboththeleadingandtrailingwhitespaceoftheoriginal
stringhasbeenremoved.
(d)Itreturnsastringwhereallthewhitespaceoftheoriginalstringhasbeen
removed.
(e)Noneoftheabove.
8.15Whichofthefollowingstatementsaretrue?
Selectthetwocorrectanswers.
(a)Stringobjectsareimmutable.
(b)SubclassesoftheStringclasscanbemutable.
(c)Allwrapperclassesaredeclaredasfinal.
(d)Allobjectshaveapublicmethodnamedclone.
(e)Theexpression((newchar[]{'o','k'})instanceof
String)isalwaystrue.
8.16Whatwillbetheresultofattemptingtocompileandrunthefollowingprogram?
Clickheretoviewcodeimage
publicclassRefEq{
publicstaticvoidmain(String[]args){
Strings=“ab”+“12”;
Stringt=“ab”+12;
Stringu=newString(“ab12”);
System.out.println((s==t)+””+(s==u));
}
WOW! eBook
www.wowebook.org
}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompile.
(b)Theprogramwillprintfalsefalseatruntime.
(c)Theprogramwillprintfalsetrueatruntime.
(d)Theprogramwillprinttruefalseatruntime.
(e)Theprogramwillprinttruetrueatruntime.
8.17WhichoftheseparameterlistscanbefoundinaconstructoroftheStringclass?
Selectthefivecorrectanswers.
(a)()
(b)(intcapacity)
(c)(char[]data)
(d)(Stringstr)
(e)(CharSequencecs)
(f)(StringBuildersb)
(g)(charc)
(h)(Objecto)
(i)(Stringstr,intbeginIndex,intendIndex)
(j)(char[]data,intoffset,intcount)
8.18WhichofthefollowingmethodsisnotdefinedintheStringclass?
Selecttheonecorrectanswer.
(a)trim()
(b)length()
(c)concat(String)
(d)hashCode()
(e)reverse()
8.19Whatwillthefollowingprogramprintwhenrun?
Clickheretoviewcodeimage
publicclassUppity{
publicstaticvoidmain(String[]args){
Stringstr1=“lower”,str2=“LOWER”,str3=“UPPER”;
str1.toUpperCase();
str1.replace(“LOWER”,“UPPER”);
System.out.println((str1.equals(str2))+””+(str1.equals(str3)));
WOW! eBook
www.wowebook.org
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillprintfalsetrue.
(b)Theprogramwillprintfalsefalse.
(c)Theprogramwillprinttruefalse.
(d)Theprogramwillprinttruetrue.
(e)Theprogramwillfailtocompile.
(f)Theprogramwillcompile,butthrowanexceptionatruntime.
8.20Whatwillthefollowingprogramprintwhenrun?
Clickheretoviewcodeimage
publicclassFunCharSeq{
privatestaticvoidputO(Strings1){
s1=s1.trim();
s1+=“O”;
}
publicstaticvoidmain(String[]args){
Strings1=”W“;
putO(s1);
s1.concat(“W”);
System.out.println(“|”+s1+“|”);
}
}
Selecttheonecorrectanswer.
(a)|WOW|
(b)|WW|
(c)|WO|
(d)|W|
(e)Theprogramwillfailtocompile.
(f)Theprogramwillcompile,butthrowanexceptionatruntime.
WOW! eBook
www.wowebook.org
8.5The and Classes
Thread-Safety
TheclassesStringBuilderandStringBufferimplementmutablesequencesof
characters.Bothclassessupportthesameoperations,buttheStringBufferclassisthe
thread-safeanalogoftheStringBuilderclass.Certainoperationsonastringbuffer
aresynchronized,sothatwhenusedbymultiplethreads,theseoperationsareperformedin
anorderlymanner.NotethataStringobjectisalsothread-safe—becauseitis
immutable,athreadcannotchangeitsstate.Stringbuildersarepreferredwhenheavy
modificationofcharactersequencesisinvolvedandsynchronizationofoperationsisnot
important.
Althoughtherestofthissectionfocusesonstringbuilders,itisequallyapplicableto
stringbuffers.
Mutability
IncontrasttotheStringclass,whichimplementsimmutablecharactersequences,the
StringBuilderclassimplementsmutablecharactersequences.Notonlycanthe
charactersequencesinastringbuilderbechanged,butthecapacityofthestringbuilder
canalsochangedynamically.Thecapacityofastringbuilderisthemaximumnumberof
charactersthatastringbuildercanaccommodatebeforeitssizeisautomatically
augmented.
AlthoughthereisacloserelationshipbetweenobjectsoftheStringand
StringBuilderclasses,thesearetwoindependentfinalclasses,bothdirectly
extendingtheObjectclass.Hence,Stringreferencescannotbestored(orcast)to
StringBuilderreferences,andviceversa.However,bothclassesimplementthe
CharSequenceinterface(p.360).
TheStringBuilderclassprovidesvariousfacilitiesformanipulatingstringbuilders:
•Constructingstringbuilders
•Changing,deleting,andreadingcharactersinstringbuilders
•Constructingstringsfromstringbuilders
•Appending,inserting,anddeletinginstringbuilders
•Controllingstringbuildercapacity
ConstructingStringBuilders
ThefinalclassStringBuilderprovidesfourconstructorsthatcreateandinitialize
StringBuilderobjectsandsettheirinitialcapacity.
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
StringBuilder(Stringstr)
StringBuilder(CharSequencecharSeq)
ThecontentsofthenewStringBuilderobjectarethesameasthecontentsof
theStringobjectorthecharactersequencepassedasanargument.Theinitial
capacityofthestringbuilderissettothelengthoftheargumentsequence,plus
roomfor16morecharacters.
Clickheretoviewcodeimage
StringBuilder(intinitialCapacity)
ThenewStringBuilderobjecthasnocontent.Theinitialcapacityofthestring
builderissettothevalueoftheargument,whichcannotbelessthan0.
StringBuilder()
ThisconstructoralsocreatesanewStringBuilderobjectwithnocontent.The
initialcapacityofthestringbuilderissetto16characters.
ExamplesofStringBuilderobjectcreationandinitialization:
Clickheretoviewcodeimage
StringBuilderstrBuilder1=newStringBuilder(“Phew!”);//“Phew!”,capacity
21
StringBuilderstrBuilder2=newStringBuilder(10);//””,capacity10
StringBuilderstrBuilder3=newStringBuilder();//””,capacity16
ReadingandChangingCharactersinStringBuilders
Returnsthenumberofcharactersinthestringbuilder.
Thesemethodsreadandchangethecharacterataspecifiedindexinthestring
builder,respectively.Thefirstcharacterisatindex0,andthelastoneisatindex1
lessthanthenumberofcharactersinthestringbuilder.AIndexOutOfBounds–
Exceptionisthrowniftheindexisnotvalid.
Clickheretoviewcodeimage
CharSequencesubSequence(intstart,intend)
ThismethodisimplementedaspartoftheCharSequenceinterface(p.360).
Thefollowingisanexampleofreadingandchangingstringbuildercontents:
Clickheretoviewcodeimage
StringBuilderstrBuilder=newStringBuilder(“Javv”);//“Javv”,
capacity20
strBuilder.setCharAt(strBuilder.length()-1,strBuilder.charAt(1));//“Java”
WOW! eBook
www.wowebook.org
ConstructingStringsfromStringBuilders
TheStringBuilderclassoverridesthetoString()methodfromtheObject
class(seealsotheCharSequenceinterface,p.360).Itreturnsthecontentsofastring
builderinaStringobject.
Clickheretoviewcodeimage
StringfromBuilder=strBuilder.toString();//“Java”
DifferencesbetweentheStringandStringBuilderClasses
SincetheStringBuilderclassdoesnotoverridetheequals()methodfromthe
Objectclass,nordoesitimplementtheComparableinterface,thecontentsofstring
buildersshouldbeconvertedtoStringobjectsforstringcomparison.
TheStringBuilderclassalsodoesnotoverridethehashCode()methodfromthe
Objectclass.Again,astringbuildercanbeconvertedtoaStringobjecttoobtaina
hashvalue.
Appending,Inserting,andDeletingCharactersinStringBuilders
Appending,inserting,anddeletingcharactersautomaticallyresultsinadjustmentofthe
stringbuilder’sstructureandcapacity,ifnecessary.Theindicespassedasargumentsinthe
methodsmustbeequaltoorgreaterthan0.AnIndexOutOfBounds–Exceptionis
thrownifanindexisnotvalid.
Notethatthemethodsinthissubsectionreturnthereferencevalueofthemodifiedstring
builder,makingitconvenienttochaincallstothesemethods.
AppendingCharacterstoaStringBuilder
Theoverloadedmethodappend()canbeusedtoappendcharactersattheendofa
stringbuilder.
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
StringBuilderappend(Objectobj)
Theobjargumentisconvertedtoastringasifbythestaticmethodcall
String.valueOf(obj),andthisstringisappendedtothecurrentstring
builder.
Clickheretoviewcodeimage
StringBuilderappend(Stringstr)
StringBuilderappend(CharSequencecharSeq)
StringBuilderappend(CharSequencecharSeq,intstart,intend)
StringBuilderappend(char[]charArray)
StringBuilderappend(char[]charArray,intoffset,intlength)
StringBuilderappend(charc)
Thesemethodsallowcharactersfromvarioussourcestobeappendedtotheendof
thecurrentstringbuilder.
Clickheretoviewcodeimage
StringBuilderappend(booleanb)
StringBuilderappend(inti)
StringBuilderappend(longl)
StringBuilderappend(floatf)
StringBuilderappend(doubled)
Thesemethodsconverttheprimitivevalueoftheargumenttoastringbyapplying
thestaticmethodString.valueOf()totheargument,beforeappendingthe
resulttothestringbuilder.
InsertingCharactersinaStringBuilder
Theoverloadedmethodinsert()canbeusedtoinsertcharactersatagivenpositionin
astringbuilder.
Clickheretoviewcodeimage
StringBuilderinsert(intoffset,Objectobj)
StringBuilderinsert(intdstOffset,CharSequenceseq)
StringBuilderinsert(intdstOffset,CharSequenceseq,intstart,intend)
StringBuilderinsert(intoffset,Stringstr)
StringBuilderinsert(intoffset,char[]charArray)
StringBuilderinsert(intoffset,charc)
StringBuilderinsert(intoffset,booleanb)
StringBuilderinsert(intoffset,inti)
StringBuilderinsert(intoffset,longl)
StringBuilderinsert(intoffset,floatf)
StringBuilderinsert(intoffset,doubled)
Theargumentisconverted,ifnecessary,byapplyingthestaticmethod
String.valueOf().Theoffsetargumentspecifieswherethecharactersare
tobeinsertedinthestringbuilder,andmustbegreaterthanorequalto0.
WOW! eBook
www.wowebook.org
DeletingCharactersinaStringBuilder
Thefollowingmethodscanbeusedtodeletecharactersfromspecificpositionsinastring
builder:
Clickheretoviewcodeimage
StringBuilderdeleteCharAt(intindex)
StringBuilderdelete(intstart,intend)
Thefirstmethoddeletesacharacterataspecifiedindexinthestringbuilder,
contractingthestringbuilderbyonecharacter.Thesecondmethoddeletesa
substring,whichisspecifiedbythestartindex(inclusive)andtheendindex
(exclusive),contractingthestringbuilderaccordingly.
AmongothermiscellaneousmethodsincludedintheclassStringBuilderisthe
followingmethod,whichreversesthecontentsofastringbuilder:
StringBuilderreverse()
Examplesofappending,inserting,anddeletinginstringbuilders:
Clickheretoviewcodeimage
StringBuilderbuilder=newStringBuilder(“bananasplit”);//“banana
split”
builder.delete(4,12);//“bana”
builder.append(42);//“bana42”
builder.insert(4,“na”);//“banana42”
builder.reverse();//“24ananab”
builder.deleteCharAt(builder.length()-1);//“24anana”
builder.append(‘s’);//“24ananas”
Allofthepreviouslymentionedmethodsmodifythecontentsofthestringbuilderand
returnareferencevaluedenotingthecurrentstringbuilder.Thisallowschainingof
methodcalls.Themethodcallsinvokedonthestringbuilderdenotedbythereference
buildercanbechainedasfollows,givingthesameresult:
Clickheretoviewcodeimage
builder.delete(4,12).append(42).insert(4,“na”).reverse().
deleteCharAt(builder.length()-1).append(‘s’);//“24ananas”
Themethodcallsinthechainareevaluatedfromlefttoright,sothatthepreviouschainof
callsisinterpretedasfollows:
Clickheretoviewcodeimage
(((((builder.delete(4,12)).append(42)).insert(4,“na”)).reverse()).
deleteCharAt(builder.length()-1)).append(‘s’);//“24ananas”
Eachmethodcallreturnsthereferencevalueofthemodifiedstringbuilder,whichisthen
usedtoinvokethenextmethod.Thestringbuilderremainsdenotedbythereference
builder.
Thecompilerusesstringbuilderstoimplementstringconcatenationwiththe+operatorin
String-valuednon-constantexpressions.Thefollowingcodeillustratesthis
optimization:
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
StringtheChosen=“U”;
Stringstr1=4+theChosen+“Only”;//(1)Non-constant
expression.
Theassignmentstatementat(1)isequivalenttothefollowingcodeusingonestring
builder:
Clickheretoviewcodeimage
Stringstr2=newStringBuilder().
append(4).append(theChosen).append(“Only”).toString();//
(2)
Thecodeat(2)doesnotcreateanytemporaryStringobjectswhenconcatenating
severalstrings,sinceasingleStringBuilderobjectismodifiedandfinallyconverted
toaStringobjecthavingthestringcontent"4UOnly".
ControllingStringBuilderCapacity
Thefollowingmethodscanbeusedtocontrolvariouscapacity-relatedaspectsofastring
builder:
intcapacity()
Returnsthecurrentcapacityofthestringbuilder,meaningthenumberofcharacters
thecurrentbuildercanaccommodatewithoutallocatinganew,largerarraytohold
characters.
Clickheretoviewcodeimage
voidensureCapacity(intminCapacity)
EnsuresthatthereisroomforatleastaminCapacitynumberofcharacters.It
expandsthestringbuilder,dependingonthecurrentcapacityofthebuilder.
voidtrimToSize()
Attemptstoreducethestorageusedforthecharactersequence.Itmayaffectthe
capacityofthestringbuilder.
voidsetLength(intnewLength)
Ensuresthattheactualnumberofcharacters—thatis,thelengthofthestring
builder—isexactlyequaltothevalueofthenewLengthargument,whichmustbe
greaterthanorequalto0.Thisoperationcanresultinthestringbeingtruncatedor
paddedwithnullcharacters('\u0000').
Thismethodaffectsthecapacityofthestringbuilderonlyifthevalueofthe
parameternewLengthisgreaterthanthecurrentcapacity.
Oneuseofthismethodistoclearthestringbuilder:
Clickheretoviewcodeimage
builder.setLength(0);//Emptythebuilder.
WOW! eBook
www.wowebook.org
ReviewQuestions
8.21Whatwillbetheresultofattemptingtocompileandrunthefollowingprogram?
Clickheretoviewcodeimage
publicclassMyClass{
publicstaticvoidmain(String[]args){
Strings=“hello”;
StringBuildersb=newStringBuilder(s);
sb.reverse();
if(s==sb)System.out.println(“a”);
if(s.equals(sb))System.out.println(“b”);
if(sb.equals(s))System.out.println(“c”);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompile.
(b)Theprogramwillcompile,butthrowanexceptionatruntime.
(c)Theprogramwillcompile,butwillnotprintanything.
(d)Theprogramwillcompile,andwillprintabc.
(e)Theprogramwillcompile,andwillprintbc.
(f)Theprogramwillcompile,andwillprinta.
(g)Theprogramwillcompile,andwillprintb.
(h)Theprogramwillcompile,andwillprintc.
8.22Whatwillbetheresultofattemptingtocompileandrunthefollowingprogram?
Clickheretoviewcodeimage
publicclassMyClass{
publicstaticvoidmain(String[]args){
StringBuildersb=newStringBuilder(“haveaniceday”);
sb.setLength(6);
System.out.println(sb);
}
}
Selecttheonecorrectanswer.
(a)Thecodewillfailtocompile,becausethereisnomethodnamedsetLength
intheStringBuilderclass.
(b)Thecodewillfailtocompile,becausetheStringBuilderreferencesbis
notalegalargumenttotheprintln()method.
(c)TheprogramwillthrowaStringIndexOutOfBoundsExceptionat
runtime.
(d)Theprogramwillprinthaveanicedayatruntime.
(e)Theprogramwillprinthaveaatruntime.
WOW! eBook
www.wowebook.org
(f)Theprogramwillprintcedayatruntime.
8.23Whichoftheseparameterlistscanbefoundinaconstructorofthe
StringBuilderclass?
Selectthefourcorrectanswers.
(a)()
(b)(intcapacity)
(c)(char[]data)
(d)(Stringstr)
(e)(CharSequencecs)
(f)(StringBuildersb)
(g)(charc)
(h)(Objecto)
(i)(Stringstr,intbeginIndex,intendIndex)
(j)(char[]data,intoffset,intcount)
8.24WhichofthefollowingmethodsisnotdefinedintheStringBuilderclass?
Selecttheonecorrectanswer.
(a)trim()
(b)length()
(c)append(String)
(d)reverse()
(e)setLength(int)
8.25Whatwillthefollowingprogramprintwhenrun?
Clickheretoviewcodeimage
publicclassPeskyCharSeq{
publicstaticvoidmain(String[]args){
StringBuildersb1=newStringBuilder(“WOW”);
StringBuildersb2=newStringBuilder(sb1);
System.out.println((sb1==sb2)+””+sb1.equals(sb2));
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillprintfalsetrue.
(b)Theprogramwillprintfalsefalse.
(c)Theprogramwillprinttruefalse.
(d)Theprogramwillprinttruetrue.
WOW! eBook
www.wowebook.org
(e)Theprogramwillfailtocompile.
(f)Theprogramwillcompile,butthrowsanexceptionatruntime.
8.26Whatwillthefollowingprogramprintwhenrun?
Clickheretoviewcodeimage
publicclassMoreCharSeq{
publicstaticvoidmain(String[]args){
Strings1=“WOW”;
StringBuilders2=newStringBuilder(s1);
Strings3=newString(s2);
System.out.println((s1.hashCode()==s2.hashCode())+””+
(s1.hashCode()==s3.hashCode()));
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillprintfalsetrue.
(b)Theprogramwillprintfalsefalse.
(c)Theprogramwillprinttruefalse.
(d)Theprogramwillprinttruetrue.
(e)Theprogramwillfailtocompile.
(f)Theprogramwillcompile,butthrowanexceptionatruntime.
8.27Whatwillthefollowingprogramprintwhenrun?
Clickheretoviewcodeimage
publicclassAppendage{
privatestaticvoidputO(StringBuilders1){
s1.append(“O”);
}
publicstaticvoidmain(String[]args){
StringBuilders1=newStringBuilder(“W”);
putO(s1);
s1.append(“W!”);
System.out.println(s1);
}
}
Selecttheonecorrectanswer.
(a)TheprogramwillprintWW!.
(b)TheprogramwillprintWOW!.
(c)TheprogramwillprintW.
(d)TheprogramwillprintWO.
(e)Theprogramwillfailtocompile.
(f)Theprogramwillcompile,butthrowanexceptionatruntime.
WOW! eBook
www.wowebook.org
ChapterSummary
Thefollowingtopicswerecoveredinthischapter:
•TheObjectclass,whichisthemostfundamentalclassinJava
•Wrapperclasses,whichnotonlyallowprimitivevaluestobetreatedasobjects,but
alsocontainusefulmethodsforconvertingvalues
•TheStringclass,includinghowimmutablestringsarecreatedandused
•TheStringBuilderclass,includinghowdynamicstringsarecreatedand
manipulated
•ComparisonoftheString,StringBuilder,andStringBufferclasses
ProgrammingExercises
8.1CreateaclassnamedPair,whichaggregatestwoarbitraryobjects.Implementthe
equals()andhashCode()methodsinsuchawaythataPairobjectis
identicaltoanotherPairobjectif,andonlyif,thepairofconstituentobjectsare
identical.MakethetoString()implementationreturnthetextualrepresentation
ofboththeconstituentobjectsinaPairobject.ObjectsofthePairclassshould
beimmutable.
8.2Apalindromeisatextphrasethatisspelledthesamewaybackwardandforward.
Thewordredividerisapalindrome,sincethewordwouldbespelledthesameeven
ifthecharactersequencewerereversed.Writeaprogramthattakesastringasan
argumentandreportswhetherthestringisacase-sensitivepalindrome.For
example,thewordRedividerwouldnotbeapalindromeinthiscase,sincewe
distinguishbetweenuppercaseandlowercaseletters.
WOW! eBook
www.wowebook.org
9.ObjectLifetime
9.1GarbageCollection
Efficientmemorymanagementisessentialinaruntimesystem.Storageforobjectsis
allocatedinadesignatedpartofthememorycalledtheheap,whichhasafinitesize.
Garbagecollectionisaprocessofmanagingtheheapefficiently,byreclaimingmemory
occupiedbyobjectsthatarenolongerneededandmakingitavailablefornewobjects.
Javaprovidesautomaticgarbagecollection,meaningthattheruntimeenvironmentcan
takecareofmemorymanagementwithouttheprogramhavingtotakeanyspecialaction.
Objectsallocatedontheheap(throughthenewoperator)areadministeredbythe
automaticgarbagecollector.Theautomaticgarbagecollectionschemeguaranteesthata
referencetoanobjectisalwaysvalidwhiletheobjectisneededbytheprogram.
Specifically,theobjectwillnotbereclaimed,leavingthereferencedangling.
Havinganautomaticgarbagecollectorfreestheprogrammerfromtheresponsibilityof
writingcodefordeletingobjects.Byrelyingontheautomaticgarbagecollector,aJava
programalsoforfeitsanysignificantinfluenceonthegarbagecollectionofitsobjects(p.
393).However,thispriceisinsignificantwhencomparedtothecostofputtingthecode
forobjectmanagementinplaceandpluggingallthememoryleaks.Time-critical
applicationsshouldrecognizethattheautomaticgarbagecollectorrunsasabackground
taskandmayhaveanegativeimpactontheirperformance.
WOW! eBook
www.wowebook.org
9.2ReachableObjects
Anautomaticgarbagecollectoressentiallyperformstwotasks:
•Decidesifandwhenmemoryneedstobereclaimed
•Findsobjectsthatarenolongerneededbytheprogramandreclaimstheirstorage
Aprogramhasnoguaranteesthattheautomaticgarbagecollectorwillberunduringits
execution.Consequently,aprogramshouldnotrelyontheschedulingoftheautomatic
garbagecollectorforitsbehavior(p.393).
Tounderstandhowtheautomaticgarbagecollectorfindsobjectswhosestorageshouldbe
reclaimed,weneedtolookattheactivityhappeningintheJVM.Javaprovidesthread-
basedmultitasking,meaningthatseveralthreadscanbeexecutingconcurrentlyinthe
JVM,eachdoingitsowntask.Athreadisanindependentpathofexecutionthroughthe
programcode.Athreadisaliveifithasnotcompleteditsexecution.Eachlivethreadhas
itsownJVMstack,asexplainedin§6.5,p.230.TheJVMstackcontainsactivationframes
ofmethodsthatarecurrentlyactive.Localreferencesdeclaredinamethodcanalwaysbe
foundinthemethod’sactivationframe,storedontheJVMstackassociatedwiththethread
inwhichthemethodiscalled.Objects,incontrast,arealwayscreatedontheheap.Ifan
objecthasafieldreference,thefieldwillbefoundinsidetheobjectintheheap,andthe
objectdenotedbythefieldreferencewillalsobefoundintheheap.
AnexampleofhowmemoryisorganizedduringexecutionisdepictedinFigure9.1,
whichshowstwolivethreads(t1andt2)andtheirrespectiveJVMstackswiththe
activationframes.Thediagramindicateswhichobjectsintheheaparereferencedbylocal
referencesinthemethodactivationframes.Italsoidentifiesfieldreferencesinobjects,
whichrefertootherobjectsintheheap.Someobjectshaveseveralaliases.
WOW! eBook
www.wowebook.org
Figure9.1MemoryOrganizationatRuntime
Anobjectintheheapissaidtobereachableifitisreferencedbyanylocalreferenceina
JVMstack.Likewise,anyobjectthatisdenotedbyareferenceinareachableobjectis
saidtobereachable.Reachabilityisatransitiverelationship.Thus,areachableobjecthas
atleastonechainofreachablereferencesfromtheJVMstack.Anyreferencethatmakes
anobjectreachableiscalledareachablereference.Anobjectthatisnotreachableissaid
tobeunreachable.
WOW! eBook
www.wowebook.org
Areachableobjectisalive,andisaccessiblebyalivethread.Notethatanobjectcanbe
accessiblebymorethanonethread.Anyobjectthatisnotaccessiblebyalivethreadisa
candidateforgarbagecollection.Whenanobjectbecomesunreachableandiswaitingfor
itsmemorytobereclaimed,itissaidtobeeligibleforgarbagecollection.Anobjectis
eligibleforgarbagecollectionifallreferencesdenotingitareineligibleobjects.Eligible
objectsdonotaffectthefuturecourseofprogramexecution.Whenthegarbagecollector
runs,itfindsandreclaimsthestorageofeligibleobjects,althoughgarbagecollectiondoes
notnecessarilyoccurassoonasanobjectbecomesunreachable.
InFigure9.1,theobjectso4,o5,o11,o12,o14,ando15allhavereachablereferences.
Objectso13ando16havenoreachablereferencesand,therefore,areeligibleforgarbage
collection.
Fromtheprecedingdiscussionwecanconcludethatifacompositeobjectbecomes
unreachable,itsconstituentobjectsalsobecomeunreachable,barringanyreachable
referencestotheconstituentobjects.Althoughtheobjectso1,o2,ando3inFigure9.1
formacircularlist,theydonothaveanyreachablereferences.Thus,theseobjectsareall
eligibleforgarbagecollection.Conversely,theobjectso5,o6,ando7formalinearlist,
buttheyareallreachable,asthefirstobjectinthelist,o5,isreachable.Theobjectso8,
o10,o11,ando9alsoformalinearlist(inthatorder),butnotallobjectsinthelistare
reachable.Onlytheobjectso9ando11arereachable,asobjecto11hasareachable
reference.Theobjectso8ando10areeligibleforgarbagecollection.
Thelifetimeofanobjectisthetimefromitscreationtothetimeitisgarbagecollected.
Undernormalcircumstances,anobjectisaccessiblefromthetimewhenitiscreatedtothe
timewhenitbecomesunreachable.Thelifetimeofanobjectcanalsoincludeaperiod
whenitiseligibleforgarbagecollection,waitingforitsstoragetobereclaimed.The
finalizationmechanism(p.390)inJavadoesprovideameansforresurrectinganobject
afteritiseligibleforgarbagecollection,butthefinalizationmechanismisrarelyusedfor
thispurpose.
9.3FacilitatingGarbageCollection
Theautomaticgarbagecollectordetermineswhichobjectsarenotreachableand,
therefore,eligibleforgarbagecollection.Itwillcertainlygotoworkifthereisan
imminentmemoryshortage.Evenso,automaticgarbagecollectionshouldnotbe
perceivedasalicenseforcreatingaplethoraofobjectsandthenforgettingaboutthem.
Nevertheless,certainprogrammingpracticescanhelpinminimizingtheoverhead
associatedwithgarbagecollectionduringprogramexecution.
Certainobjects,suchasfilesandnetworkconnections,cantieupresourcesandshouldbe
disposedofproperlywhentheyarenolongerneeded.Inmostcases,thetry-with-
resourcesstatement(notinthescopeofthisbook)providesaconvenientfacilityforsuch
purposes,asitwillalwaysensureproperclosingoftheAuto-Closeableresources.
Tooptimizeitsmemoryfootprint,alivethreadshouldretainaccesstoanobjectaslong
foronlyastheobjectisneededforitsexecution.Theprogramcanallowobjectsto
becomeeligibleforgarbagecollectionasearlyaspossiblebyremovingallreferencesto
anobjectwhenitisnolongerneeded.
WOW! eBook
www.wowebook.org
Objectsthatarecreatedandaccessedbylocalreferencesinamethodareeligiblefor
garbagecollectionwhenthemethodterminates,unlessreferencevaluestotheseobjects
areexportedoutofthemethod.Thiscanoccurifareferencevalueisreturnedfromthe
method,passedasargumenttoanothermethodthatrecordsthereferencevalue,orthrown
asanexception.However,amethodneednotalwaysleaveobjectstobegarbagecollected
afteritstermination.Itcanfacilitategarbagecollectionbytakingsuitableaction—for
example,bynullingreferences.
Clickheretoviewcodeimage
importjava.io.*;
classWellBehavedClass{
//…
voidwellBehavedMethod(){
FileaFile;
long[]bigArray=newlong[20000];
//…useslocalvariables…
//Doesclean-up(beforestartingsomethingextensive)
aFile=null;//(1)
bigArray=null;//(2)
//Startsomeotherextensiveactivity
//…
}
//…
}
Inthiscode,thelocalvariablesaresettonullafteruseat(1)and(2),beforestarting
someotherextensiveactivity.Thismakestheobjectsdenotedbythelocalvariables
eligibleforgarbagecollectionfromthispointonward,ratherthanafterthemethod
terminates.Thisoptimizationtechniqueofnullingreferencesshouldbeusedonlyasalast
resortwhenresourcesarescarce.
Herearesomeothertechniquestofacilitategarbagecollection:
•Whenamethodreturnsareferencevalueandtheobjectdenotedbythevalueisnot
needed,notassigningthisvaluetoareferencefacilitatesgarbagecollection.
•Ifareferenceisassignedanewvalue,theobjectthatwaspreviouslydenotedbythe
referencecanbecomeeligibleforgarbagecollection.
•Removingreachablereferencestoacompositeobjectcanmaketheconstituent
objectsbecomeeligibleforgarbagecollection,asexplainedearlier.
Example9.1illustrateshowaprogramcaninfluencegarbagecollectioneligibility.The
classHeavyItemrepresentsobjectswithalargememoryfootprint,forwhichwewantto
monitorgarbagecollection.EachcompositeHeavyItemobjecthasareferencetoalarge
array.Theclassoverridesthefinalize()methodfromtheObjectclasstoprintout
anIDwhentheobjectisfinalized.Thismethodisalwayscalledonaneligibleobject
beforeitisdestroyed(p.390).Weuseittoindicateintheoutputifandwhena
HeavyItemisreclaimed.Toillustratetheeffectofgarbagecollectiononobject
hierarchies,eachHeavyItemobjectmayalsohaveareferencetoanotherHeavyItem.
InExample9.1,theclassRecyclingBindefinesamethodcreateHeavyItem()at
WOW! eBook
www.wowebook.org
(4).Inthismethod,theHeavyItemcreatedat(5)iseligibleforgarbagecollectionafter
thereassignmentofreferenceitemAat(6),asthisobjectwillthenhavenoreferences.
TheHeavyItemcreatedat(6)isaccessibleonreturnfromthemethod.Itsfatedepends
onthecodethatcallsthismethod.
InExample9.1,theclassRecyclingBinalsodefinesamethodcreateList()at
(8).Itreturnsthereferencevalueinthereferenceitem1,whichdenotesthefirstitemina
listofthreeHeavyItemobjects.Becauseoftheliststructure,noneoftheHeavyItem
objectsinthelistiseligibleforgarbagecollectiononreturnfromthemethod.Again,the
fateoftheobjectsinthelistisdecidedbythecodethatcallsthismethod.Itisenoughfor
thefirstiteminthelisttobecomeunreachable,sothatallobjectsinthelistbecome
eligibleforgarbagecollection(barringanyreachablereferences).
Example9.1GarbageCollectionEligibility
Clickheretoviewcodeimage
//File:RecyclingBin.java
classHeavyItem{//(1)
int[]itemBody;
StringitemID;
HeavyItemnextItem;
HeavyItem(StringID,HeavyItemitemRef){//(2)
itemBody=newint[1_000_000];
itemID=ID;
nextItem=itemRef;
}
@Override
protectedvoidfinalize()throwsThrowable{//(3)
System.out.println(itemID+“:recycled.”);
super.finalize();
}
}
//______________________________________________________________________________
publicclassRecyclingBin{
publicstaticHeavyItemcreateHeavyItem(StringitemID){//(4)
HeavyItemitemA=newHeavyItem(itemID+“:localitem”,null);//(5)
itemA=newHeavyItem(itemID,null);//(6)
System.out.println(“ReturnfromcreatingHeavyItem”+itemID);
returnitemA;//(7)
}
publicstaticHeavyItemcreateList(StringlistID){//(8)
HeavyItemitem3=newHeavyItem(listID+“:item3”,null);//(9)
HeavyItemitem2=newHeavyItem(listID+“:item2”,item3);//(10)
HeavyItemitem1=newHeavyItem(listID+“:item1”,item2);//(11)
System.out.println(“Returnfromcreatinglist”+listID);
returnitem1;//(12)
}
publicstaticvoidmain(String[]args){//(13)
HeavyItemlist=createList(“X”);//(14)
list=createList(“Y”);//(15)
HeavyItemitemOne=createHeavyItem(“One”);//(16)
WOW! eBook
www.wowebook.org
HeavyItemitemTwo=createHeavyItem(“Two”);//(17)
itemOne=null;//(18)
createHeavyItem(“Three”);//(19)
createHeavyItem(“Four”);//(20)
System.out.println(“Returnfrommain().”);
}
}
Probableoutputfromtheprogram:
Clickheretoviewcodeimage
ReturnfromcreatinglistX
ReturnfromcreatinglistY
X:item3:recycled.
X:item2:recycled.
X:item1:recycled.
ReturnfromcreatingHeavyItemOne
ReturnfromcreatingHeavyItemTwo
ReturnfromcreatingHeavyItemThree
Three:localitem:recycled.
Three:recycled.
Two:localitem:recycled.
ReturnfromcreatingHeavyItemFour
One:localitem:recycled.
One:recycled.
Returnfrommain().
InExample9.1,themain()methodat(13)intheclassRecyclingBinusesthe
methodscreateHeavyItem()andcreateList().ItcreatesalistXat(14),butthe
referencetoitsfirstitemisreassignedat(15),makingobjectsinlistXeligibleforgarbage
collectionafter(15).ThefirstitemoflistYisstoredinthereferencelist,makingthis
listnon-eligibleforgarbagecollectionduringtheexecutionofthemain()method.
Themain()methodcreatestwoitemsat(16)and(17),storingtheirreferencevaluesin
thereferencesitemOneanditemTwo,respectively.ThereferenceitemOneisnulled
at(18),makingtheHeavyItemobjectwithidentityOneeligibleforgarbagecollection.
ThetwocallstothecreateHeavyItem()methodat(19)and(20)returnreference
valuestoHeavyItemobjects,whicharenotstored,makingeachobjecteligiblefor
garbagecollectionimmediatelyaftertheirrespectivemethodcallsreturn.
Theoutputfromtheprogrambearsouttheobservationsmadeearlier.ObjectsinlistY
(accessiblethroughthereferencelist)andtheHeavyItemobjectwithidentityTwo
(accessiblethroughthereferenceitemTwo)remainnon-eligiblewhilethemain()
methodexecutes.AlthoughtheoutputshowsthattheHeavyItemobjectwithidentity
Fourwasnevergarbagecollected,itisnotaccessibleonceitbecomeseligiblefor
garbagecollectionat(20).Anyobjectsintheheapaftertheprogramterminatesare
reclaimedbytheoperatingsystem.
WOW! eBook
www.wowebook.org
9.4ObjectFinalization
Objectfinalizationprovidesanobjectwithalastresorttoundertakeanyactionbeforeits
storageisreclaimed.Theautomaticgarbagecollectorcallsthefinalize()methodin
anobjectthatiseligibleforgarbagecollectionbeforeactuallydestroyingtheobject.The
finalize()methodisdefinedintheObjectclass:
Clickheretoviewcodeimage
protectedvoidfinalize()throwsThrowable
Animplementationofthefinalize()methodiscalledafinalizer.Asubclasscan
overridethefinalizerfromtheObjectclasssoastotakemorespecificandappropriate
actionbeforeanobjectofthesubclassisdestroyed.Notethattheoverridingmethod
cannotnarrowthevisibilityoftheoverriddenmethodandmustbedeclaredaseither
protectedorpublic.
Afinalizer,likeanyothermethod,cancatchandthrowexceptions(§6.7,p.238).Whena
finalizeriscalledexplicitlybytheprogramcode,exceptionhandlingisnodifferentduring
executionofafinalizerthanduringexecutionofanyothermethod.However,any
exceptionthrownbutnotcaughtbyafinalizerthatiscalledbythegarbagecollectoris
ignored,andthefinalizationofthisobjectisterminated.Thefinalizeriscalledonlyonce
onanobject,regardlessofwhetheranyexceptionisthrownduringitsexecution.Incase
offinalizationfailure,theobjectremainseligiblefordisposalatthediscretionofthe
garbagecollector(unlessithasbeenresurrected,asexplainedlaterinthissection).Since
thereisnoguaranteethatthegarbagecollectorwilleverrun,thereisalsonoguarantee
thatthefinalizerwilleverbecalled.
Inthefollowingcode,thefinalizerat(1)willtakeappropriateactionifandwhencalledon
objectsoftheclassbeforetheyaregarbagecollected,ensuringthattheresourceisfreed.
Sinceitisnotguaranteedthatthefinalizerwilleverbecalledatall,aprogramshouldnot
relyonthefinalizationtodoanycriticaloperations.
Clickheretoviewcodeimage
publicclassAnotherWellBehavedClass{
SomeResourceobjRef;
//…
@Override
protectedvoidfinalize()throwsThrowable{//(1)
try{//(2)
if(objRef!=null)objRef.close();
}finally{//(3)
super.finalize();//(4)
}
}
}
Thefinalizerinasubclassshouldexplicitlycallthefinalizerinitssuperclassasitslast
action,asshownat(4).Thecalltothefinalizerofthesuperclassisinafinallyblockat
(3),whichisguaranteedtoexecuteregardlessofanyexceptionsthrownbythecodeinthe
tryblockat(2).(AnotherexampleoffinalizerchainingisprovidedinExample9.2inthe
nextsection.)
WOW! eBook
www.wowebook.org
Thefinalizerofanobjectcanmaketheobjectnon-eligibleagain(i.e.,resurrectit),thereby
avoidinggarbagecollectionoftheobject.Onesimpletechniqueistoassigntheobject’s
thisreferencetoastaticfield,whichthenbecomesareachablereferencefortheobject.
Sinceafinalizeriscalledonlyonceonanobjectbeforeitisgarbagecollected,anobject
canberesurrectedonlyonce.Inotherwords,iftheobjectagainbecomeseligiblefor
garbagecollectionandthegarbagecollectorruns,thefinalizerwillnotbecalled.Such
objectresurrectionsarenotrecommended,astheyunderminethepurposeofthe
finalizationmechanism.
Notethatanenumtypecannotdeclareafinalizer.Therefore,anenumconstantmaynever
befinalized.
9.5FinalizerChaining
Unlikesubclassconstructors,overriddenfinalizersarenotimplicitlychained(§7.5,p.
282).Chainingoffinalizersrequiresanexplicitcalltotheoverriddenfinalizer.Example
9.2illustratestheprocessofprogrammaticallychainingfinalizers.Itcreatesauser-
specifiednumberoflargeobjectsofauser-specifiedsize;thenumberandsizeare
providedthroughcommand-lineprogramarguments.Theloopat(7)inthemain()
methodcreatesBlobobjects,butdoesnotstoreanyreferencestothem.Objectscreated
areinstancesoftheclassBlobdefinedat(3).TheBlobconstructorat(4)initializesthe
fieldsizebyconstructingalargearrayofintegers.TheBlobclassextendsthe
BasicBlobclass,whichassignseachblobauniquenumber(blobId)andkeepstrack
ofthenumberofblobs(population)notyetgarbagecollected.
CreationofeachBlobobjectbytheconstructorat(4)printstheIDnumberoftheobject
andthemessage"Hello".Thefinalize()methodat(5)iscalledbeforeaBlob
objectisgarbagecollected.ItprintstheinheritedfieldblobIdoftheBlobobjectand
themessage"Bye",beforecallingthefinalize()methodinthesuperclass
BasicBlobat(2),whichdecrementsthepopulationcount.Theprogramoutputshows
thattwoblobswerenotgarbagecollectedatthetimetheprintstatementat(8)was
executed.Itisevidentfromthenumberof"Bye"messagesthatthreeblobsweregarbage
collectedbeforeallfiveblobswerecreatedintheloopat(7).
Example9.2UsingFinalizers
Clickheretoviewcodeimage
//File:Finalizers.java
classBasicBlob{//(1)
privatestaticintidCounter;
privatestaticintpopulation;
protectedintblobId;
BasicBlob(){
blobId=idCounter++;
++population;
}
@Override
protectedvoidfinalize()throwsThrowable{//(2)
WOW! eBook
www.wowebook.org
—population;
super.finalize();
}
publicstaticintgetPopulation(){
returnpopulation;
}
}
//______________________________________________________________________________
classBlobextendsBasicBlob{//(3)
privateint[]size;
Blob(intbloatedness){//(4)
size=newint[bloatedness];
System.out.println(blobId+“:Hello”);
}
@Override
protectedvoidfinalize()throwsThrowable{//(5)
System.out.println(blobId+“:Bye”);
super.finalize();
}
}
//______________________________________________________________________________
publicclassFinalizers{
publicstaticvoidmain(String[]args){//(6)
intblobsRequired,blobSize;
try{
blobsRequired=Integer.parseInt(args[0]);
blobSize=Integer.parseInt(args[1]);
}catch(IndexOutOfBoundsExceptione){
System.out.println(“Toofewprogramarguments.”);
System.out.println(“Usage:Finalizers<numberofblobs><blobsize>”);
return;
}catch(NumberFormatExceptione){
System.out.println(“Illegalprogramargument.”);
System.out.println(“Usage:Finalizers<numberofblobs><blobsize>”);
return;
}
for(inti=0;i<blobsRequired;++i){//(7)
newBlob(blobSize);
}
System.out.println(BasicBlob.getPopulation()+”blobsalive”);//(8)
}
}
Probableoutputfromrunningtheprogramwiththefollowingcommand:
>javaFinalizers5500000
0:Hello
1:Hello
2:Hello
0:Bye
1:Bye
2:Bye
3:Hello
4:Hello
2blobsalive
WOW! eBook
www.wowebook.org
9.6InvokingGarbageCollectionProgrammatically
AlthoughJavaprovidesfacilitiestoinvokethegarbagecollectionexplicitly,thereareno
guaranteesthatitwillberun.Theprogramcanrequestthatgarbagecollectionbe
performed,butthereisnowaytoforcegarbagecollectiontobeactivated.
TheSystem.gc()methodcanbeusedtorequestgarbagecollection,andthe
System.runFinalization()methodcanbecalledtosuggestthatanypending
finalizersberunforobjectseligibleforgarbagecollection.
staticvoidgc()
Requeststhatgarbagecollectionberun.
staticvoidrunFinalization()
Requeststhatanypendingfinalizersberunforobjectseligibleforgarbage
collection.
Alternatively,correspondingmethodsintheRuntimeclasscanbeused.AJava
applicationhasauniqueRuntimeobjectthatcanbeusedbytheapplicationtointeract
withtheJVM.Anapplicationcanobtainthisobjectbycallingthemethod
Runtime.getRuntime().TheRuntimeclassprovidesseveralmethodsrelatedto
memoryissues:
staticRuntimegetRuntime()
ReturnstheRuntimeobjectassociatedwiththecurrentapplication.
voidgc()
Requeststhatgarbagecollectionberun.However,itisrecommendedtousethe
moreconvenientstaticmethodSystem.gc().
voidrunFinalization()
Requeststhatanypendingfinalizersberunforobjectseligibleforgarbage
collection.Again,itismoreconvenienttousethestaticmethod
System.runFinalization().
longfreeMemory()
Returnstheamountoffreememory(bytes)intheJVMthatisavailablefornew
objects.
longtotalMemory()
Returnsthetotalamountofmemory(bytes)availableintheJVM,includingboth
memoryoccupiedbycurrentobjectsandmemoryavailablefornewobjects.
Example9.3illustratestheprocessofinvokinggarbagecollection.TheclassMemory-
CheckisanadaptationoftheclassFinalizersfromExample9.2.TheRunTime
objectfortheapplicationisobtainedat(7).Thisobjectisusedtogetinformation
regardingtotalmemoryandfreememoryintheJVMat(8)and(9),respectively.Blobsare
createdintheloopat(10).Theamountoffreememoryafterblobcreationisprintedat
WOW! eBook
www.wowebook.org
(11).Fromtheprogramoutput,itisapparentthatsomeblobswerealreadygarbage
collectedbeforetheexecutionreached(11).Arequestforgarbagecollectionismadeat
(12).Checkingfreememoryafterthisrequestshowsthatmorememoryhasbecome
available,indicatingthattherequestwashonored.Itisinstructivetoruntheprogram
withoutthemethodcallSystem.gc()at(12)tocomparetheresultswithandwithout
thiscall.
WOW! eBook
www.wowebook.org
Example9.3InvokingGarbageCollection
Clickheretoviewcodeimage
classBasicBlob{/*SeeExample9.2.*/}
classBlobextendsBasicBlob{/*SeeExample9.2.*/}
//______________________________________________________________________________
publicclassMemoryCheck{
publicstaticvoidmain(String[]args){//(6)
intblobsRequired,blobSize;
try{
blobsRequired=Integer.parseInt(args[0]);
blobSize=Integer.parseInt(args[1]);
}catch(IndexOutOfBoundsExceptione){
System.out.println(“Toofewprogramarguments.”);
System.out.println(“Usage:MemoryCheck<numberofblobs><blobsize>”);
return;
}catch(NumberFormatExceptione){
System.out.println(“Illegalprogramargument.”);
System.out.println(“Usage:MemoryCheck<numberofblobs><blobsize>”);
return;
}
Runtimeenvironment=Runtime.getRuntime();//(7)
System.out.println(“Totalmemory:”+environment.totalMemory());//(8)
System.out.println(“Freememorybeforeblobcreation:”+
environment.freeMemory());//(9)
for(inti=0;i<blobsRequired;++i){//(10)
newBlob(blobSize);
}
System.out.println(“Freememoryafterblobcreation:”+
environment.freeMemory());//(11)
System.gc();//(12)
System.out.println(“FreememoryafterrequestingGC:”+
environment.freeMemory());//(13)
System.out.println(BasicBlob.getPopulation()+”blobsalive”);//(14)
}
}
Probableoutputfromrunningtheprogramwiththefollowingcommand:
Clickheretoviewcodeimage
>javaMemoryCheck5100000
Totalmemory:2031616
Freememorybeforeblobcreation:1773192
0:Hello
1:Hello
2:Hello
1:Bye
2:Bye
3:Hello
0:Bye
3:Bye
4:Hello
Freememoryafterblobcreation:818760
4:Bye
FreememoryafterrequestingGC:1619656
0blobsalive
Thefollowingpointsregardingautomaticgarbagecollectionshouldbenoted:
•Therearenoguaranteesthatthefinalizersofobjectseligibleforgarbagecollection
WOW! eBook
www.wowebook.org
willbeexecuted.Garbagecollectionmightnotevenberuniftheprogramexecution
doesnotwarrantit.Thus,anymemoryallocatedduringprogramexecutionmight
remainallocatedafterprogramtermination,butwilleventuallybereclaimedbythe
operatingsystem.
•Therearealsonoguaranteesabouttheorderinwhichtheobjectswillbegarbage
collected,ortheorderinwhichtheirfinalizerswillbeexecuted.Therefore,the
programshouldnotmakeanyassumptionsbasedonthesecriteria.
•Garbagecollectiondoesnotguaranteethattherewillbeenoughmemoryforthe
programtorun.Aprogramcanrelyonthegarbagecollectortorunwhenmemory
getsverylow,anditcanexpectanOutOfMemoryExceptiontobethrownifits
memorydemandscannotbemet.
ReviewQuestions
9.1Whichofthefollowingstatementsistrue?
Selecttheonecorrectanswer.
(a)Objectscanbeexplicitlydestroyedusingthekeyworddelete.
(b)Anobjectwillbegarbagecollectedimmediatelyafteritbecomesunreachable.
(c)Ifobjectobj1isaccessiblefromobjectobj2,andobjectobj2isaccessible
fromobj1,thenobj1andobj2arenoteligibleforgarbagecollection.
(d)Onceanobjecthasbecomeeligibleforgarbagecollection,itwillremain
eligibleuntilitisdestroyed.
(e)Ifobjectobj1canaccessobjectobj2thatiseligibleforgarbagecollection,
thenobj1isalsoeligibleforgarbagecollection.
9.2Identifythelocationinthefollowingprogramwheretheobject,initiallyreferenced
byarg1,iseligibleforgarbagecollection.
Clickheretoviewcodeimage
publicclassMyClass{
publicstaticvoidmain(String[]args){
Stringmsg;
Stringpre=“Thisprogramwascalledwith“;
Stringpost=”asfirstargument.”;
Stringarg1=newString((args.length>0)?”’”+args[0]+”’”:
”<noargument>”);
msg=arg1;
arg1=null;//(1)
msg=pre+msg+post;//(2)
pre=null;//(3)
System.out.println(msg);
msg=null;//(4)
post=null;//(5)
args=null;//(6)
}
}
Selecttheonecorrectanswer.
WOW! eBook
www.wowebook.org
(a)Afterthelinelabeled(1)
(b)Afterthelinelabeled(2)
(c)Afterthelinelabeled(3)
(d)Afterthelinelabeled(4)
(e)Afterthelinelabeled(5)
(f)Afterthelinelabeled(6)
9.3Howmanyobjectsareeligibleforgarbagecollectionwhencontrolreaches(1)?
Clickheretoviewcodeimage
publicclassEligible{
publicstaticvoidmain(String[]args){
for(inti=0;i<5;i++){
Eligibleobj=newEligible();
newEligible();
}
System.gc();//(1)
}
}
Selecttheonecorrectanswer.
(a)0
(b)5
(c)10
(d)Hardtosay
9.4Howmanyobjectsareeligibleforgarbagecollectionwhencontrolreaches(1)?
Clickheretoviewcodeimage
publicclassLink{
privateLinknext;
Link(Linknext){this.next=next;}
publicvoidfinialize(){System.out.print(“X”);}
publicstaticvoidmain(String[]args){
Linkp=null;
for(inti=0;i<5;i++){
p=newLink(p);
}
System.gc();//(1);
}
}
Selecttheonecorrectanswer.
(a)0
(b)5
(c)10
(d)Hardtosay
9.5Whichofthefollowingstatementsistrue?
WOW! eBook
www.wowebook.org
Selecttheonecorrectanswer.
(a)Ifanexceptionisthrownduringexecutionofthefinalize()methodofan
eligibleobject,theexceptionisignoredandtheobjectisdestroyed.
(b)Allobjectshaveafinalize()method.
(c)Objectscanbedestroyedbyexplicitlycallingthefinalize()method.
(d)Thefinalize()methodcanbedeclaredwithanyaccessibility.
(e)Thecompilerwillfailtocompilecodethatdefinesanoverriding
finalize()methodthatdoesnotexplicitlycalltheoverridden
finalize()methodfromthesuperclass.
9.6Whichofthefollowingstatementsistrue?
Selecttheonecorrectanswer.
(a)Thecompilerwillfailtocompilecodethatexplicitlytriestocallthe
finalize()method.
(b)Thefinalize()methodcanbeoverridden,butitmustbedeclaredwith
protectedaccessibility.
(c)Anoverridingfinalize()methodinanyclasscanalwaysthrowchecked
exceptions.
(d)Thefinalize()methodcanbeoverloaded.
(e)Thebodyofthefinalize()methodcanaccessonlyotherobjectsthatare
eligibleforgarbagecollection.
9.7Whichmethodheaderswillresultinacorrectimplementationofafinalizerforthe
followingclass?
Clickheretoviewcodeimage
publicclassCurtain{
//(1)INSERTMETHODHEADERHERE…
{
System.out.println(“Finalcurtain”);
super.finalize();
}
}
Selectthetwocorrectanswers.
(a)voidfinalize()throwsThrowable
(b)voidfinalize()throwsException
(c)voidfinalize()
(d)protectedvoidfinalize()throwsThrowable
(e)protectedvoidfinalize()throwsException
(f)protectedvoidfinalize()
WOW! eBook
www.wowebook.org
(g)publicvoidfinalize()throwsThrowable
(h)publicvoidfinalize()throwsException
(i)publicvoidfinalize()
(j)privatevoidfinalize()throwsThrowable
(k)privatevoidfinalize()throwsException
(l)privatevoidfinalize()
9.8Whichscenariocandefinitelynotbetheresultofcompilingandrunningthe
followingprogram?
Clickheretoviewcodeimage
publicclassGrade{
privatechargrade;
Grade(chargrade){this.grade=grade;}
publicvoidfinalize()throwsThrowable{
System.out.print(grade);
super.finalize();
}
publicstaticvoidmain(String[]args){
newGrade(‘A’);newGrade(‘F’);
System.gc();
}
}
Selecttheonecorrectanswer.
(a)TheprogrammayprintAF.
(b)TheprogrammayprintFA.
(c)TheprogrammayprintA.
(d)TheprogrammayprintF.
(e)TheprogrammayprintAFA.
(f)Theprogrammaynotprintanything.
9.9Whichscenarioscanbetheresultofcompilingandrunningthefollowing
program?
Clickheretoviewcodeimage
publicclassMyString{
privateStringstr;
MyString(Stringstr){this.str=str;}
publicvoidfinalize()throwsThrowable{
System.out.print(str);
super.finalize();
}
publicvoidconcat(Stringstr2){
this.str.concat(str2);
}
WOW! eBook
www.wowebook.org
publicstaticvoidmain(String[]args){
newMyString(“A”).concat(“B”);
System.gc();
}
}
Selectthetwocorrectanswers.
(a)TheprogrammayprintAB.
(b)TheprogrammayprintBA.
(c)TheprogrammayprintA.
(d)TheprogrammayprintB.
(e)Theprogrammaynotprintanything.
9.7Initializers
Initializerscanbeusedtosetinitialvaluesforfieldsinobjectsandclasses.Therearethree
kindsofinitializers:
•Fieldinitializerexpressions
•Staticinitializerblocks
•Instanceinitializerblocks
Subsequentsectionsinthischapterprovidedetailsontheseinitializers,concludingwitha
discussionoftheprocedureinvolvedinconstructingthestateofanobjectwhentheobject
iscreatedbyusingthenewoperator.
9.8FieldInitializerExpressions
Initializationoffieldscanbespecifiedinfielddeclarationstatementsusinginitializer
expressions.Thevalueoftheinitializerexpressionmustbeassignmentcompatiblewith
thedeclaredfield(see§5.6,p.158and§7.9,p.312).Wedistinguishbetweenstaticand
non-staticfieldinitializers.
Clickheretoviewcodeimage
classConstantInitializers{
intminAge=12;//(1)Non-static
staticdoublepensionPoints=10.5;//(2)Static
//…
}
Thefieldsofanobjectareinitializedwiththevaluesofinitializerexpressionswhenthe
objectiscreatedbyusingthenewoperator.Inthepreviousexample,thedeclarationat(1)
willresultinthefieldminAgebeinginitializedto12ineveryobjectoftheclass
ConstantInitializerscreatedwiththenewoperator.Ifnoexplicitinitializer
expressionsarespecified,defaultvalues(§2.4,p.42)areassignedtothefields.
Whenaclassisloaded,itisinitialized,meaningitsstaticfieldsareinitializedwiththe
valuesoftheinitializerexpressions.Thedeclarationat(2)willresultinthestaticfield
pensionPointsbeinginitializedto10.5whentheclassisloadedbytheJVM.Again,
WOW! eBook
www.wowebook.org
ifnoexplicitinitializersarespecified,defaultvaluesareassignedtothestaticfields.
Aninitializerexpressionforastaticfieldcannotrefertonon-staticmembersbytheir
simplenames.Thekeywordsthisandsupercannotoccurinastaticinitializer
expression.
Sinceaclassisalwaysinitializedbeforeitcanbeinstantiated,aninstanceinitializer
expressioncanalwaysrefertoanystaticmemberofaclass,regardlessofthemember
declarationorder.Inthefollowingcode,theinstanceinitializerexpressionat(1)refersto
thestaticfieldNO_OF_WEEKSdeclaredandinitializedat(2).Suchaforwardreferenceis
legal.Moreexamplesofforwardreferencesaregiveninthenextsubsection.
Clickheretoviewcodeimage
classMoreInitializers{
intnoOfDays=7*NO_OF_WEEKS;//(1)Non-static
staticintNO_OF_WEEKS=52;//(2)Static
//…
}
Initializerexpressionscanalsobeusedtodefineconstantsininterfaces(§7.6,p.302).
Suchinitializerexpressionsareimplicitlystatic,astheydefinevaluesofstaticfinal
fields.
Initializerexpressionsareusedtoinitializelocalvariablesaswell(§2.3,p.40).Alocal
variableisinitializedwiththevalueoftheinitializerexpressioneverytimethelocal
variabledeclarationisexecuted.
DeclarationOrderofInitializerExpressions
Whenanobjectiscreatedusingthenewoperator,instanceinitializerexpressionsare
executedintheorderinwhichtheinstancefieldsaredeclaredintheclass.
Javarequiresthatthedeclarationofafieldmustoccurbeforeitsusageinanyinitializer
expressionifthefieldisusedontheright-handsideofanassignmentintheinitializer
expression.Thisessentiallymeansthatthedeclarationofafieldmustoccurbeforethe
valueofthefieldisreadinaninitializerexpression.Usingthefieldontheleft-handside
ofanassignmentintheinitializerexpressiondoesnotviolatethedeclaration-before-
readingrule,asthisconstitutesawriteoperation.Thisruleapplieswhentheusageofthe
fieldisbyitssimplename.
Thereisonecaveattothedeclaration-before-readingrule:Itdoesnotapplyifthe
initializerexpressiondefinesananonymousclass,astheusagethenoccursinadifferent
classthathasitsownaccessibilityrulesintheenclosingcontext.Therestrictionsoutlined
earlierhelptodetectinitializationanomaliesatcompiletime.
Inthenextcodeexample,theinitializationat(2)generatesacompile-timeerror,because
thefieldwidthintheinitializerexpressionviolatesthedeclaration-before-readingrule.
Becausetheusageofthefieldwidthintheinitializerexpressionat(2)doesnotoccuron
theleft-handsideoftheassignment,thisisanillegalforwardreference.Toremedythe
error,thedeclarationofthefieldwidthat(4)canbemovedinfrontofthedeclarationat
(2).Inanycase,wecanusethekeywordthisasshownat(3),butitwillreadthedefault
value0inthefieldwidth.
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
classNonStaticInitializers{
intlength=10;//(1)
//doublearea=length*width;//(2)NotOK.Illegalforward
reference.
doublearea=length*this.width;//(3)OK,butwidthhasdefaultvalue
0.
intwidth=10;//(4)
intsqSide=height=20;//(5)OK.Legalforwardreference.
intheight;//(6)
}
Theforwardreferenceat(5)islegal.Theusageofthefieldheightintheinitializer
expressionat(5)occursontheleft-handsideoftheassignment.Theinitializerexpression
at(5)isevaluatedas(sqSide=(height=20)).Everyobjectoftheclass
NonStaticInitializerswillhavethefieldsheightandsqSidesettothevalue
20.
Thedeclaration-before-readingruleisequallyapplicabletostaticinitializerexpressions
whenstaticfieldsarereferencedbytheirsimplenames.
Example9.4showswhytheorderoffieldinitializerexpressionscanbeimportant.The
initializerexpressionsinthisexamplearecallstomethodsdefinedintheclass,and
methodsarenotsubjecttothesameaccessrulesasinitializerexpressions.Thecallat(2)
tothemethodinitMaxGuests()definedat(4)isexpectedtoreturnthemaximum
numberofguests,butthefieldoccupancyPerRoomat(3)willnothavebeenexplicitly
initializedatthispoint;therefore,itsdefaultvalue0willbeusedinthemethod
initMaxGuests(),whichwillreturnanincorrectvalue.Theprogramoutputshows
thatafterobjectcreation,theoccupancyperroomiscorrect,butthemaximumnumberof
guestsiswrong.
WOW! eBook
www.wowebook.org
Example9.4InitializerExpressionOrderandMethodCalls
Clickheretoviewcodeimage
//File:TestOrder.java
classHotel{
privateintnoOfRooms=12;//(1)
privateintmaxNoOfGuests=initMaxGuests();//(2)
Bug
privateintoccupancyPerRoom=2;//(3)
publicintinitMaxGuests(){//(4)
System.out.println(“occupancyPerRoom:”+occupancyPerRoom);
System.out.println(“maxNoOfGuests:”+noOfRooms*occupancyPerRoom);
returnnoOfRooms*occupancyPerRoom;
}
publicintgetMaxGuests(){returnmaxNoOfGuests;}//(5)
publicintgetOccupancy(){returnoccupancyPerRoom;}//(6)
}
//________________________________________________________________________
publicclassTestOrder{
publicstaticvoidmain(String[]args){
Hotelhotel=newHotel();//(7)
System.out.println(“Afterobjectcreation:“);
System.out.println(“occupancyPerRoom:”+hotel.getOccupancy());//(8)
System.out.println(“maxNoOfGuests:”+hotel.getMaxGuests());//(9)
}
}
Outputfromtheprogram:
occupancyPerRoom:0
maxNoOfGuests:0
Afterobjectcreation:
occupancyPerRoom:2
maxNoOfGuests:0
9.9StaticInitializerBlocks
Javaallowsstaticinitializerblockstobedefinedinaclass.Althoughsuchblockscan
includearbitrarycode,theyareprimarilyusedforinitializingstaticfields.Thecodeina
staticinitializerblockisexecutedonlyonce,whentheclassisloadedandinitialized.
Thesyntaxofastaticinitializerblockcomprisesthekeywordstaticfollowedbya
localblockthatcancontainarbitrarycode,asshownat(3).
Clickheretoviewcodeimage
classStaticInitializers{
staticfinalintROWS=12,COLUMNS=10;//(1)
staticlong[][]matrix=newlong[ROWS][COLUMNS];//(2)
//…
static{//(3)Static
initializer
for(inti=0;i<matrix.length;i++)
for(intj=0;j<matrix[i].length;j++)
matrix[i][j]=2*i+j;
}
WOW! eBook
www.wowebook.org
//…
}
WhentheclassStaticInitializersisfirstloadedinthepreviousexample,the
staticfinalfieldsat(1)areinitialized.Thenthearrayofarraysmatrixof
specifiedsizeiscreatedat(2),followedbytheexecutionofthestaticblockat(3).
Ifaclassreliesonnativemethodimplementations,astaticinitializercanbeusedtoload
anyexternallibrariesthattheclassneeds(§4.8,p.137).
Notethatthestaticinitializerblockisnotcontainedinanymethod.Aclasscanhavemore
thanonestaticinitializerblock.Initializerblocksarenotmembersofaclass,andthey
cannothaveareturnstatementbecausetheycannotbecalleddirectly.
Whenaclassisinitialized,theinitializerexpressionsinstaticfielddeclarationsandstatic
initializerblocksareexecutedintheorderinwhichtheyarespecifiedintheclass.Inthe
previousexample,theinitializerexpressionsat(1)and(2)areexecutedbeforethestatic
initializerblockat(3).
Similarrestrictionsapplytostaticinitializerblocksasforstaticinitializerexpressions:
Thekeywordsthisandsupercannotoccurinastaticinitializerblock,becausesucha
blockdefinesastaticcontext.
DeclarationOrderofStaticInitializers
Whenmakingforwardreferencesusingsimplenames,codeinastaticinitializerblockis
alsosubjecttothedeclaration-before-readingrulediscussedintheprevioussubsection.
Example9.5illustratesforwardreferencesandtheorderofexecutionforstaticinitializer
expressionsandstaticinitializerblocks.Anillegalforwardreferenceoccursat(4),where
anattemptismadetoreadthevalueofthefieldsf1beforeitsdeclaration.At(11),the
readoperationoccursafterthedeclaration,soitisallowed.Forwardreferencemadeon
theleft-handsideoftheassignmentisalwaysallowed,asshownat(2),(5),and(7).The
initializersareexecutedintheirdeclarationorder.Astaticfieldhasthevaluethatitwas
lastassignedinaninitializer.Ifthereisnoexplicitassignment,thefieldhasthedefault
valueofitstype.
WOW! eBook
www.wowebook.org
Example9.5StaticInitializersandForwardReferences
Clickheretoviewcodeimage
publicclassStaticForwardReferences{
static{//(1)Staticinitializerblock.
sf1=10;//(2)OK.Assignmenttosf1allowed.
//sf1=if1;//(3)NotOK.Non-staticfieldaccessinstatic
context.
//inta=2*sf1;//(4)NotOK.Readoperationbeforedeclaration.
intb=sf1=20;//(5)OK.Assignmenttosf1allowed.
intc=StaticForwardReferences.sf1;//(6)OK.Notaccessedbysimple
name.
}
staticintsf1=sf2=30;//(7)Staticfield.Assignmenttosf2allowed.
staticintsf2;//(8)Staticfield.
intif1=5;//(9)Non-staticfield.
static{//(10)Staticinitializerblock.
intd=2*sf1;//(11)OK.Readoperationafterdeclaration.
inte=sf1=50;//(12)OK.Assignmenttosf1allowed.
}
publicstaticvoidmain(String[]args){
System.out.println(“sf1:”+StaticForwardReferences.sf1);
System.out.println(“sf2:”+StaticForwardReferences.sf2);
}
}
Outputfromtheprogram:
sf1:50
sf2:30
9.10InstanceInitializerBlocks
Justasstaticinitializerblockscanbeusedtoinitializestaticfieldsinanamedclass,so
Javaprovidestheabilitytoinitializefieldsduringobjectcreationusinginstanceinitializer
blocks.Inthisrespect,suchblocksservethesamepurposeasconstructorsduringobject
creation.Thesyntaxofaninstanceinitializerblockisthesameasthatofalocalblock,as
shownat(2)inthefollowingcode.Thecodeinthelocalblockisexecutedeverytimean
instanceoftheclassiscreated.
Clickheretoviewcodeimage
classInstanceInitializers{
long[]squares=newlong[10];//(1)
//…
{//(2)InstanceInitializer
for(inti=0;i<squares.length;i++)
squares[i]=i*i;
}
//…
}
Thearraysquaresofspecifiedlengthisfirstcreatedat(1);itscreationisfollowedby
theexecutionoftheinstanceinitializerblockat(2)everytimeaninstanceoftheclass
WOW! eBook
www.wowebook.org
InstanceInitializersiscreated.Notethattheinstanceinitializerblockisnot
containedinanymethod.Aclasscanhavemorethanoneinstanceinitializerblock,and
these(andanyinstanceinitializerexpressionsininstancefielddeclarations)areexecuted
intheordertheyarespecifiedintheclass.
DeclarationOrderofInstanceInitializers
Analogoustotheotherinitializersdiscussedearlier,aninstanceinitializerblockcannot
makeaforwardreferencetoafieldthatviolatesthedeclaration-before-readingrule.In
Example9.6,anillegalforwardreferenceoccursinthecodeat(4),whichattemptstoread
thevalueofthefieldnsf1beforeitisdeclared.Thereadoperationat(11)occursafter
thedeclarationand,therefore,isallowed.Forwardreferencemadeontheleft-handsideof
theassignmentisalwaysallowed,asshownat(2),(3),(5),and(7).
Asinaninstanceinitializerexpression,thekeywordsthisandsupercanbeusedto
refertothecurrentobjectinaninstanceinitializerblock.Asinastaticinitializerblock,
thereturnstatementisnotallowedininstanceinitializerblocks.
Aninstanceinitializerblockcanbeusedtofactoroutcommoninitializationcodethatwill
beexecutedregardlessofwhichconstructorisinvoked.
Example9.6InstanceInitializersandForwardReferences
Clickheretoviewcodeimage
publicclassNonStaticForwardReferences{
{//(1)Instanceinitializerblock.
nsf1=10;//(2)OK.Assignmenttonsf1allowed.
nsf1=sf1;//(3)OK.Staticfieldaccessinnon-static
context.
//inta=2*nsf1;//(4)NotOK.Readoperationbeforedeclaration.
intb=nsf1=20;//(5)OK.Assignmenttonsf1allowed.
intc=this.nsf1;//(6)OK.Notaccessedbysimplename.
}
intnsf1=nsf2=30;//(7)Non-staticfield.Assignmenttonsf2
allowed.
intnsf2;//(8)Non-staticfield.
staticintsf1=5;//(9)Staticfield.
{//(10)Instanceinitializerblock.
intd=2*nsf1;//(11)OK.Readoperationafterdeclaration.
inte=nsf1=50;//(12)OK.Assignmenttonsf1allowed.
}
publicstaticvoidmain(String[]args){
NonStaticForwardReferencesobjRef=newNonStaticForwardReferences();
System.out.println(“nsf1:”+objRef.nsf1);
System.out.println(“nsf2:”+objRef.nsf2);
}
}
Outputfromtheprogram:
nsf1:50
nsf2:30
WOW! eBook
www.wowebook.org
9.11ConstructingInitialObjectState
Objectinitializationinvolvesconstructingtheinitialstateofanobjectwhenitiscreated
bythenewoperator.Firstthefieldsareinitializedtotheirdefaultvalues(§2.4,p.42)—
whethertheyaresubsequentlygivennon-defaultinitialvaluesornot—andthenthe
constructorisinvoked.Thiscanleadtolocalchainingofconstructors.Theinvocationof
theconstructorattheendofthelocalchainofconstructorinvocationsresultsinthe
followingactions,beforetheconstructor’sexecutionresumes:
•Implicitorexplicitinvocationofthesuperclassconstructor.Constructorchaining
ensuresthattheinheritedstateoftheobjectisconstructedfirst(§7.5,p.282).
•Initializationoftheinstancefieldsbyexecutingtheirinstanceinitializerexpressions
andanyinstanceinitializerblocks,intheordertheyarespecifiedintheclass
declaration.
Example9.7illustratesobjectinitialization.Thenewoperatorisusedat(8)tocreatean
objectofSubclassB.Theno-argumentconstructorSubclassB()at(2)usesthe
this()constructtolocallychaintothenon-zeroargumentconstructorat(3).This
constructorthenleadstoanimplicitcallofthesuperclassconstructor.Ascanbeseenfrom
theprogramoutput,theexecutionofthesuperclass’sconstructorat(1)reachescompletion
first.Thisisfollowedbytheexecutionoftheinstanceinitializerblockat(4)andthe
instanceinitializerexpressionat(6).Thentheexecutionofthebodyofthenon-zero
argumentconstructorat(3)resumes.Finally,theno-argumentconstructorcompletesits
execution,therebycompletingtheconstructionoftheobjectstate.
Notethattheinstanceinitializersareexecutedintheordertheyarespecifiedintheclass
declaration.Theforwardreferencetothefieldvalueat(5)islegal,becausetheusageof
thefieldvalueisontheleft-handsideoftheassignment(itdoesnotviolatethe
declaration-before-readingrule).Thedefaultvalueofthefieldvalueisoverwrittenby
theinstanceinitializerblockat(5).Thefieldvalueisagainoverwrittenbytheinstance
initializerexpressionat(6),andfinallybythenon-zeroargumentconstructorat(3).
WOW! eBook
www.wowebook.org
Example9.7ObjectStateConstruction
Clickheretoviewcodeimage
//File:ObjectConstruction.java
classSuperclassA{
publicSuperclassA(){//(1)
System.out.println(“ConstructorinSuperclassA”);
}
}
//_______________________________________________________________________________
classSubclassBextendsSuperclassA{
SubclassB(){//(2)No-argumentconstructor
this(3);
System.out.println(“No-argumentconstructorinSubclassB”);
}
SubclassB(inti){//(3)Non-zeroargument
constructor
System.out.println(“Non-zeroargumentconstructorinSubclassB”);
value=i;
}
{//(4)Instanceinitializer
block
System.out.println(“InstanceinitializerblockinSubclassB”);
value=2;//(5)
}
intvalue=initializerExpression();//(6)
privateintinitializerExpression(){//(7)
System.out.println(“InstanceinitializerexpressioninSubclassB”);
return1;
}
}
//_______________________________________________________________________________
publicclassObjectConstruction{
publicstaticvoidmain(String[]args){
SubclassBobjRef=newSubclassB();//(8)
System.out.println(“value:”+objRef.value);
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
ConstructorinSuperclassA
InstanceinitializerblockinSubclassB
InstanceinitializerexpressioninSubclassB
Non-zeroargumentconstructorinSubclassB
No-argumentconstructorinSubclassB
value:3
Somecareshouldbeexercisedwhenwritingconstructorsfornon-finalclasses,since
theobjectthatisconstructedmightbeasubclassinstance.Example9.8showsasituation
whereuseofoverriddenmethodsinsuperclassinitializersandconstructorscangive
unexpectedresults.Theexampleintentionallyusesthethisreferencetounderlinethat
theinstancemethodsandconstructorsareinvokedonthecurrentobject,andthatthe
WOW! eBook
www.wowebook.org
constructorcallresultsintheinitializationoftheobjectstate,asexpected.
TheprogramoutputfromExample9.8showsthatthefieldsuperValueat(1)in
SuperclassAnevergetsinitializedexplicitlywhenanobjectofSubclassBiscreated
at(8).TheSuperclassAconstructorat(2)doeshaveacalltoamethodthathasthe
namedoValueat(3).AmethodwithsuchanameisdefinedinSuperclassAat(4),
butisalsooverriddeninSubclassBat(7).Theprogramoutputindicatesthatthe
methoddoValue()fromSubclassBiscalledat(3)intheSuperclassA
constructor.TheimplementationofthemethoddoValue()at(4)nevergetsexecuted
whenanobjectofSubclassBiscreated.Methodinvocationalwaysdeterminesthe
implementationofthemethodtobeexecuted,basedontheactualtypeoftheobject.
KeepinginmindthatitisanobjectofSubclassBthatisbeinginitialized,thecalltothe
methodnameddoValueat(3)resultsinthemethodfromSubclassBbeingexecuted.
Thiscanleadtounintendedresults.TheoverridingmethoddoValue()at(7)in
SubclassBcanaccessthefieldvaluedeclaredat(5)beforeitsinitializerexpression
hasbeenexecuted;thus,themethodinvokedcanaccessthestateoftheobjectbeforethis
hasbeencompletelyinitialized.Thevalue0isthenprinted,asthefieldvaluehasnot
yetbeeninitializedwiththevalue800whenthesuperclassconstructorisexecuted.
WOW! eBook
www.wowebook.org
Example9.8InitializationAnomalyunderObjectStateConstruction
Clickheretoviewcodeimage
//File:ObjectInitialization.java
classSuperclassA{
protectedintsuperValue;//(1)
SuperclassA(){//(2)
System.out.println(“ConstructorinSuperclassA”);
this.doValue();//(3)
}
voiddoValue(){//(4)
this.superValue=911;
System.out.println(“superValue:”+this.superValue);
}
}
//_______________________________________________________________________________
classSubclassBextendsSuperclassA{
privateintvalue=800;//(5)
SubclassB(){//(6)
System.out.println(“ConstructorinSubclassB”);
this.doValue();
System.out.println(“superValue:”+this.superValue);
}
@Override
voiddoValue(){//(7)
System.out.println(“value:”+this.value);
}
}
//_______________________________________________________________________________
publicclassObjectInitialization{
publicstaticvoidmain(String[]args){
System.out.println(“CreatinganobjectofSubclassB.”);
newSubclassB();//(8)
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
CreatinganobjectofSubclassB.
ConstructorinSuperclassA
value:0
ConstructorinSubclassB
value:800
superValue:0
Classinitializationtakesplacebeforeanyinstanceoftheclasscanbecreatedorastatic
methodoftheclasscanbeinvoked.Asuperclassisinitializedbeforeitssubclassesare
initialized.Initializingaclassinvolvesinitializationofthestaticfieldsbyexecutingtheir
staticinitializerexpressionsandanystaticinitializerblocks.
Initializationofaninterfaceinvolvesexecutionofanystaticinitializerexpressionsforthe
staticfieldsdeclaredintheinterface.Aninterfacecannotspecifyinstanceinitializer
expressions,becauseithasnoinstancefields,norcanitspecifyanyinitializerblocks,
becauseitcannotbeinstantiated.
WOW! eBook
www.wowebook.org
ReviewQuestions
9.10Giventhefollowingclass,whichofthesestaticinitializerblockscanbe
independentlyinsertedat(1)?
Clickheretoviewcodeimage
publicclassMyClass{
privatestaticintcount=5;
staticfinalintSTEP=10;
booleanalive;
//(1)INSERTSTATICINITIALIZERBLOCKHERE
}
Selectthethreecorrectanswers.
(a)static{alive=true;count=0;}
(b)static{STEP=count;}
(c)static{count+=STEP;}
(d)static;
(e)static{;}
(f)static{count=1;}
9.11Whatwillbetheresultofcompilingandrunningthefollowingprogram?
Clickheretoviewcodeimage
publicclassMyClass{
publicstaticvoidmain(String[]args){
MyClassobj=newMyClass(n);
}
staticinti=5;
staticintn;
intj=7;
intk;
publicMyClass(intm){
System.out.println(i+“,”+j+“,”+k+“,”+n+“,”+m);
}
{j=70;n=20;}//Instanceinitializerblock
static{i=50;}//Staticinitializerblock
}
Selecttheonecorrectanswer.
(a)Thecodewillfailtocompile,becauseoftheinstanceinitializerblock.
(b)Thecodewillfailtocompile,becauseofthestaticinitializerblock.
(c)Thecodewillcompile,andprint50,70,0,20,0atruntime.
(d)Thecodewillcompile,andprint50,70,0,20,20atruntime.
WOW! eBook
www.wowebook.org
(e)Thecodewillcompile,andprint5,70,0,20,0atruntime.
(f)Thecodewillcompile,andprint5,70,0,20,20atruntime.
(g)Thecodewillcompile,andprint5,7,0,20,0atruntime.
(h)Thecodewillcompile,andprint5,7,0,20,20atruntime.
9.12Giventhefollowingclass,whichinstanceinitializerblockinsertedindependently
at(1)willallowtheclasstobecompiled?
publicclassFirstClass{
staticintgap=10;
doublelength;
finalbooleanactive;
//(1)INSERTCODEHERE
}
Selecttheonecorrectanswer.
(a)instance{active=true;}
(b)FirstClass{gap+=5;}
(c){gap=5;length=(active?100:200)+gap;}
(d){;}
(e){length=4.2;}
(f){active=(gap>5);length=5.5+gap;}
9.13Whatwillbetheresultofcompilingandrunningthefollowingprogram?
Clickheretoviewcodeimage
publicclassInitialization{
privatestaticStringmsg(Stringmsg){
System.out.println(msg);
returnmsg;
}
publicInitialization(){m=msg(“1”);}
{m=msg(“2”);}
Stringm=msg(“3”);
publicstaticvoidmain(String[]args){
Objectobj=newInitialization();
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompile.
(b)Theprogramwillcompile,andprint1,2,and3atruntime.
(c)Theprogramwillcompile,andprint2,3,and1atruntime.
(d)Theprogramwillcompile,andprint3,1,and2atruntime.
WOW! eBook
www.wowebook.org
(e)Theprogramwillcompile,andprint1,3,and2atruntime.
9.14Whichofthelabeledlinesinthefollowingcodecanbeindependently
uncommentedbyremovingthe//characters,suchthatthecodewillstillcompile?
Clickheretoviewcodeimage
classGeomInit{
//intwidth=14;/*LineA*/
{
//area=width*height;/*LineB*/
}
intwidth=37;
{
//height=11;/*LineC*/
}
intheight,area;
//area=width*height;/*LineD*/
{
//intwidth=15;/*LineE*/
area=100;
}
}
Selectthetwocorrectanswers.
(a)LineA
(b)LineB
(c)LineC
(d)LineD
(e)LineE
ChapterSummary
Thefollowingtopicswerecoveredinthischapter:
•Automaticgarbagecollection,includingtheworkingsofthegarbagecollectorand
guidelinesforfacilitatinggarbagecollection
•Objectfinalizationandchainingaspartofgarbagecollection
•Staticandinstanceinitializers,bothasinitializerexpressionsandasinitializer
blocks
•Theroleplayedbyinitializersininitializingobjects,classes,andinterfaces
WOW! eBook
www.wowebook.org
10.TheArrayList<E>ClassandLambdaExpressions
10.1The Class
Aprogrammanipulatesdata,soorganizingandusingdataefficientlyarenaturally
importantinaprogram.Datastructuresarewaystoorganizedata.Javausestheterm
collectiontomeanadatastructurethatcanmaintainagroupofobjectssothattheobjects
canbemanipulatedasasingleentityorunit.Objectscanbestored,retrieved,and
manipulatedaselementsofacollection.Thetermcontainerisalsousedintheliterature
forsuchdatastructures.Arraysareanexampleofonekindofcollection.Otherexamples
includelists,sets,queues,andstacks,amongmanyothers.
WOW! eBook
www.wowebook.org
Lists
Onceanarrayiscreated,itslengthcannotbechanged.Thisinflexibilitycanbea
significantdrawbackwhentheamountofdatatobestoredinanarrayisnotknowna
priori.InJava,thestructuresknownaslistsalleviatethisshortcoming.Listsare
collectionsthatmaintaintheirelementsinorderandcancontainduplicates.Theorderof
elementsinalistispositionalorder,andindividualelementscanbeaccessedaccordingto
theirpositioninthelist.Eachelement,therefore,hasapositioninthelist.Azero-based
indexcanbeusedtoaccesstheelementatthepositiondesignatedbytheindexvalue,
analogoustoaccessingelementsinanarray.However,unlikeinanarray,thepositionof
anelementinalistcanchangeaselementsareinsertedordeletedfromthelist—thatis,as
thelistischangedstructurally.
Sortingimpliesorderingtheelementsinacollectionaccordingtosomerankingcriteria,
usuallybasedonthevaluesoftheelements.However,elementsisanArrayListare
maintainedintheordertheyareinsertedinthelist,knownastheinsertionorder.The
elementsinsuchalistarethereforeordered,buttheyarenotsorted,asitisnotthevalues
oftheelementsthatdeterminetheirrankinginthelist.Thus,orderingdoesnotnecessarily
implysorting.
TheJavaCollectionsFramework
TheCollectioninterfaceinthejava.utilpackage(alsoknownastheJava
CollectionsFramework)definesthegeneraloperationsthatacollectionshouldprovide.
OthersubinterfacesintheJavaCollectionsFrameworkaugmentthisinterfacetoprovide
specificoperationsforparticularkindsofcollections.Thejava.util.Listinterface
extendsthejava.util.Collectioninterfacewiththenecessaryoperationsto
maintainthecollectionasalist(seeFigure10.1).Inadditiontotheoperationsinherited
fromthejava.util.Collectioninterface,thejava.util.Listinterface
definesoperationsthatworkspecificallyonlists:position-basedaccessofthelist
elements,searchinginalist,operationsonpartsofalist(calledopenrange-view
operations),andcreationofcustomizediteratorstotraversealist.
WOW! eBook
www.wowebook.org
Figure10.1PartialArrayListInheritanceHierarchy
Theconcreteclassjava.util.ArrayListimplementsthejava.util.List
interface.InFigure10.1,thetypeparameterEinangularbrackets(<>)afterareference
typenameindicatesthatthereferencetypeisagenerictype.ThetypeparameterE
representsthetypeoftheelementinthecollection.Useofagenerictyperequiresa
concretereferencetypetobesubstitutedforthetypeparameterE.Examplesinthissection
willmakeamplyclearhowtouseagenerictype,andinparticular,theclassArrayList.
TheArrayListclassisadynamicallyresizableimplementationoftheListinterface
usingarrays(alsoknownasdynamicarrays),providingfastrandomaccess(i.e.,position-
basedaccessinconstanttime)andfastlisttraversal—verymuchlikeusinganordinary
array.TheArrayListclassisnotthread-safe;thatis,itsintegritycanbejeopardizedby
concurrentaccess.TheJavaCollectionsFrameworkprovidesotherimplementationsofthe
Listinterface,butinmostcasestheArrayListimplementationistheoverallbest
choiceforimplementinglists.
ThissectioncoversthebasicsofusinganArrayList.TheJavaCollectionsFramework
isanextensivetopic,farbeyondthescopeofthisbook.However,divingdeepintothe
JavaCollectionsFrameworkisabeneficialexercisethatishighlyrecommendedforall
Javaprogrammers.
DeclaringReferencesandConstructing s
Inthediscussionthatfollows,weassumethatanyclassorinterfaceusedfromthe
java.utilpackagehasbeenimportedwithanappropriateimportstatement.
Thefollowingdeclarationstatementshowshowwecandeclareareferencethatcanrefer
toanArrayListofaspecificelementtype.Italsoillustrateshowwecancreatean
emptyArrayListofaspecificelementtype,andassignitsreferencevaluetoa
reference:
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
ArrayList<String>palindromes=newArrayList<String>();//(1)
Asthiscodeindicates,theelementtypeisspecifiedusingangularbrackets(<>).The
referencepalindromescanrefertoanyArrayListwhoseelementtypeisString.
ThetypeparameterEoftheclassArrayListinFigure10.1isreplacedbytheconcrete
classString.Thecompilerensuresthatthereferencepalindromescanonlyreferto
anArrayListwhoseelementsareoftypeString,andanyoperationsonthislistvia
thisreferencearetype-safe.
ThesimplestwaytoconstructanArrayLististousethedefaultconstructortocreate
anemptyArrayList,asshowninthepreviousdeclaration.Thedefaultconstructor
createsanemptylistwiththeinitialcapacityof10.Thecapacityofalistreferstohow
manyelementsitcancontainatanygiventime,nothowmanyelementsareactuallyinthe
list(calledthesize).Thecapacityofalistanditssizecanchangedynamicallyasthelistis
manipulated.TheArrayListcreatedin(1)cancontainonlyelementsoftypeString.
Theassignmentinthedeclarationstatement(1)isvalidbecausethetypesonbothsides
areassignmentcompatible—anArrayListofString.Thereferencepalindromes
cannowbeusedtomanipulatetheArrayListthatwascreated.
TheDiamondOperator:<>
Theelementtypewithintheangularbrackets(<>)canbeomittedintheArrayList
creationexpressionontheright-handsideofthedeclarationstatement.Inthisparticular
context,thecompilercaninfertheelementtypeoftheArrayListfromthedeclaration
ofthereferencetypeontheleft-handside.
Clickheretoviewcodeimage
ArrayList<String>palindromes=newArrayList<>();//Usingthediamond
operator
Theemptyangularbrackets,<>,arecommonlyreferredtoasthediamondoperator.This
operatormustbeusedwiththenewoperatorwhenconstructinganobjectofageneric
type,likeArrayList,wherethetypeinformationforitsusagecanbeinferredbythe
compilerfromthecontext,asintheprecedingdeclarationstatement.
However,ifthediamondoperatorisomitted,thecompilerwillissueanunchecked
conversionwarning,asshownat(2)inthenextcodesnippet.AnewArrayListis
createdbasedonanArrayListofIntegerthatispassedasanargumenttothe
constructor.TheArrayListofIntegeriscreatedat(1).ThereferencenewList1of
typeArrayList<String>referstoanArrayListwhoseelementtypeis
Integer,notString.Thecodeat(2)compiles,butwegeta
ClassCastExceptionatruntimeat(3)whenweretrieveanelementfromthislist.
Theget()methodcallat(3)expectsaStringintheArrayList,butgetsan
Integer.Ifthediamondoperatorisused,asshownat(4),thecompilerreportsa
compile-timeerror,andtheproblemdescribedat(3)cannotoccuratruntime.Byissuing
anuncheckedconversionwarningat(2),thecompileralertsustothefactthatitcannot
guaranteetype-safetyofthelistcreatedat(2).
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
ArrayList<Integer>intList=newArrayList<>();//(1)ArrayListof
Integer
intList.add(10);intList.add(100);intList.add(1000);
ArrayList<String>newList1=newArrayList(intList);//(2)Unchecked
conversion
//warning
System.out.println(newList1.get(0));//(3)
ClassCastException!
ArrayList<String>newList2=newArrayList<>(intList);//(4)Compile-time
error!
Bestpracticesadvocateprogrammingtoaninterface.Inpracticalterms,thismeansusing
referencesofaninterfacetypetomanipulateobjectsofaconcreteclassthatimplement
thisinterface.Sincetheclassjava.util.ArrayListimplementsthe
java.util.Listinterface,thedeclaration(1)canbewrittenasshowninthenext
codesnippet.Thisdeclarationisvalid,sincethereferencevalueofasubtypeobject
(ArrayList<String>)canbeassignedtoareferenceofitssupertype
(List<String>).
Clickheretoviewcodeimage
List<String>palindromes=newArrayList<>();//(2)Listreference
Thisbestpracticeprovidesgreatflexibilityinsubstitutingotherobjectsforataskwhen
necessary.Thecurrentconcreteclasscaneasilybereplacedbyanotherconcreteclassthat
implementsthesameinterface.Onlycodecreatingobjectsneedstobechanged.Asit
happens,theJavaCollectionsFrameworkprovidesanotherimplementationoflists:the
java.util.LinkedListclass,whichalsoimplementstheListinterface.Ifthis
classisfoundtobemoreconduciveformaintainingpalindromesinalist,weneedsimply
changethenameoftheclassindeclaration(2),andcontinueusingthereference
palindromesintheprogram:
Clickheretoviewcodeimage
List<String>palindromes=newLinkedList<>();//Changingimplementation.
TheArrayListclassalsoprovidesaconstructorthatallowsanemptyArrayListto
becreatedwithaspecificinitialcapacity.
Clickheretoviewcodeimage
List<String>palindromes=newArrayList<>(20);//Initialcapacityis20.
TheArrayListclassprovidestheadd(E)methodtoappendanelementtothelist.
Thisobjectisaddedafterthelastelementinthelist,therebyincreasingthelistsizeby1.
Clickheretoviewcodeimage
palindromes.add(“level”);palindromes.add(“Ada”);palindromes.add(“kayak”);
System.out.println(palindromes);
TheprintstatementcallsthetoString()methodintheArrayListclasstoprintthe
elementsinthelist.ThistoString()methodappliesthetoString()methodofthe
individualelementstocreateatextualrepresentationinthefollowingdefaultformat:
[level,Ada,kayak]
WOW! eBook
www.wowebook.org
AthirdconstructorallowsanArrayListtobeconstructedfromanothercollection.The
followingcodecreatesalistofwordsfromalistofpalindromes.Theorderofthe
elementsinthenewArrayLististhesameasthatintheArrayListthatwaspassed
asanargumentintheconstructor.
Clickheretoviewcodeimage
List<String>wordList=newArrayList<>(palindromes);
System.out.println(wordList);//[level,Ada,kayak]
wordList.add(“Naan”);
System.out.println(wordList);//[level,Ada,kayak,Naan]
Thenextexamplesillustratethecreationofemptylistsofdifferenttypesofelements.The
compilerensuresthatoperationsontheArrayListaretype-safewithrespecttothe
elementtype.Declaration(3)showshowwecancreatenestedliststructures(i.e.,listof
lists),analogoustoanarrayofarrays.Notethatthediamondoperatorisnotnestedin(3).
Declaration(4)showsthattheelementtypecannotbeaprimitivetype;rather,itmustbea
referencetype.
Clickheretoviewcodeimage
List<StringBuilder>synonyms=newArrayList<>();//ListofStringBuilder
List<Integer>attendance=newArrayList<>();//ListofInteger
List<List<String>>listOfLists=newArrayList<>();//(3)ListofListof
String
List<int>frequencies=newArrayList<>();//(4)Compile-time
error!
WhencomparingarraysandArrayLists,thereisoneothersignificantdifferencethat
concernsthesubtyperelationship.
Clickheretoviewcodeimage
Object[]objArray=newString[10];//(5)OK!
Indeclaration(5),sinceStringisasubtypeofObject,String[]isasubtypeof
Object[].ThuswecanmanipulatethearrayofStringusingtheobjArray
reference.
Clickheretoviewcodeimage
objArray[2]=“Green”;//(6)OK!
objArray[1]=newInteger(2016);//ArrayStoreException!
Theprecedingassignmentrequiresaruntimechecktoguaranteethattheassignmentis
typecompatible.Otherwise,anArrayStoreExceptionisthrownatruntime.
FortheArrayList,thefollowingdeclarationswillnotcompile:
Clickheretoviewcodeimage
ArrayList<Object>objList1=newArrayList<String>();//(7)Compile-time
error!
List<Object>objList2=newArrayList<String>();//(8)Compile-time
error!
AlthoughStringisasubtypeofObject,itisnotthecasethatan
ArrayList<String>isasubtypeofArrayList<Object>.Ifthiswasthecase,
wecouldusetheobjList1referencetoaddothertypesofobjectstotheArrayList
ofString,therebyjeopardizingitstype-safety.Sincethereisnoinformationaboutthe
WOW! eBook
www.wowebook.org
elementtypeEavailableatruntimetocarryoutatypecompatibilitycheck,asinthecase
ofarrays,thesubtyperelationshipisnotallowedin(7).Forthesamereason,(8)willnot
compile:ArrayList<String>isnotasubtypeofList<Object>.Ingeneral,the
subtyperelationshipdoesnotholdforgenerictypes.TheJavalanguageprovideswaysto
overcomethisrestriction,butwewillnotpursuethismatterfurther.
TheArrayListconstructorsaresummarizedhere:
Clickheretoviewcodeimage
ArrayList()
ArrayList(intinitialCapacity)
ArrayList(Collection<?extendsE>c)
Thedefaultconstructorcreatesanew,emptyArrayListwithaninitialcapacity
of10.
Thesecondconstructorcreatesanew,emptyArrayListwiththespecifiedinitial
capacity.
ThethirdconstructorcreatesanewArrayListcontainingtheelementsinthe
specifiedcollection.Thedeclarationoftheparametercessentiallymeansthat
parameterccanrefertoanycollectionwhoseelementtypeisEorwhoseelement
typeisasubtypeofE.ThenewArrayListwillretainanyduplicates.The
orderingintheArrayListwillbedeterminedbythetraversalorderofthe
iteratorforthecollectionpassedasanargument.
Modifyingan
Asummaryofselectedmethodsthatcanmodifythecontentsofalistisgivenhere:
Clickheretoviewcodeimage
booleanadd(Eelement)
voidadd(intindex,Eelement)
Thefirstmethodwillappendthespecifiedelementtotheendofthelist.Itreturns
trueifthecollectionwasmodifiedasaresultoftheoperation.
Thesecondmethodinsertsthespecifiedelementatthespecifiedindex.If
necessary,itshiftstheelementpreviouslyatthisindexandanysubsequentelements
onepositiontowardtheendofthelist.Themethodwillthrowan
IndexOutOfBoundsExceptioniftheindexisoutofrange(index<0||
index>size()).
ThetypeparameterErepresentstheelementtypeofthelist.
Clickheretoviewcodeimage
booleanaddAll(Collection<?extendsE>c)
booleanaddAll(intindex,Collection<?extendsE>c)
Thefirstmethodinsertstheelementsfromthespecifiedcollectionattheendofthe
list.Thesecondmethodinsertstheelementsfromthespecifiedcollectionatthe
WOW! eBook
www.wowebook.org
specifiedindex;thatis,themethodsplicestheelementsofthespecifiedcollection
intothelistatthespecifiedindex.Themethodsreturntrueifanyelementswere
added.Elementsareinsertedusinganiteratorofthespecifiedcollection.The
secondmethodwillthrowanIndexOutOfBoundsExceptioniftheindexis
outofrange(index<0||index>size()).
Thedeclarationoftheparametercessentiallymeansthatparameterccanreferto
anycollectionwhoseelementtypeisEorwhoseelementtypeisasubtypeofE.
Eset(intindex,Eelement)
Thismethodreplacestheelementatthespecifiedindexwiththespecifiedelement.
Itreturnsthepreviouselementatthespecifiedindex.Themethodthrowsan
IndexOutOfBoundsExceptioniftheindexisoutofrange(index<0||
index>=size()).
Clickheretoviewcodeimage
Eremove(intindex)
booleanremove(Objectelement)
Thefirstmethoddeletesandreturnstheelementatthespecifiedindex.Themethod
throwsanIndexOutOfBoundsExceptioniftheindexisoutofrange(index
<0||index>=size()).
Thesecondmethodremovesthefirstoccurrenceoftheelementfromthelist,using
objectvalueequality.Themethodreturnstrueifthecallwassuccessful.
Bothmethodswillcontractthelistaccordinglyifanyelementsareremoved.
Clickheretoviewcodeimage
booleanremoveAll(Collection<?>c)
booleanremoveIf(Predicate<?superE>filter)
TheremoveAll()methodremovesfromthislistallelementsthatarecontained
inthespecifiedcollection.
TheremoveIf()methodremovesfromthislistallelementsthatsatisfythe
filteringcriteriadefinedbyalambdaexpressionthatimplementsthe
Predicate<T>functionalinterface(p.452).
Bothmethodsreturntrueifthecallwassuccessful.Thelistiscontracted
accordinglyifanyelementsareremoved.
voidtrimToSize()
Thismethodtrimsthecapacityofthislisttoitscurrentsize.
voidclear()
Thismethoddeletesallelementsfromthelist.Thelistisemptyafterthecall,soit
hassize0.
AllthecodesnippetsisthissectioncanbefoundinExample10.1,p.427.Themethod
printListWithIndex()at(16)inExample10.1printstheelementsprefixedwith
theirindexinthelist,makingiteasiertoseehowthelistchangesstructurally:
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
[0:level,1:Ada,2:Java,3:kayak,4:Bob,5:Rotator,6:Bob]
Wehaveseenthattheadd(E)methodappendsanelementtotheendofthelist.The
followingcodeaddsthestringsfromanarrayofStringtoanArrayListofString.
TheoutputfromExample10.1at(2)showshowtheelementsareaddedattheendofthe
list.
Clickheretoviewcodeimage
System.out.println(“\n(2)Addelementstolist:”);
for(Stringstr:wordArray){
strList.add(str);
printListWithIndex(strList);
}
Wecaninsertanewelementataspecificindexusingtheoverloadedmethodadd(int,
E).Theoutputfromthefollowingcodeshowshowinsertinganelementatindex2shifted
theelementsstructurallyinthelist.
Clickheretoviewcodeimage
//[0:level,1:Ada,2:kayak,3:Bob,4:Rotator,5:Bob]
strList.add(2,“Java”);//Insertanelementatindex2inthelist.
printListWithIndex(strList);//[0:level,1:Ada,2:Java,3:kayak,4:Bob,
//5:Rotator,6:Bob]
Notethatanindexvalueequalto0orthesizeofthelistisalwaysallowedforthemethod
add(int,E).
Clickheretoviewcodeimage
List<String>list1=newArrayList<>();//[]
list1.add(0,“First”);//[First]
list1.add(list1.size(),“Last”);//[First,Last]
Wecanreplaceanelementataspecifiedindexusingtheset(int,E)method.The
methodreturnstheelementthatwasreplaced.
Clickheretoviewcodeimage
System.out.println(“(3)Replacetheelementatindex1:”);
StringoldElement=strList.set(1,“Naan”);
System.out.println(“Elementthatwasreplaced:”+oldElement);//“Ada”
printListWithIndex(strList);//[0:level,1:Naan,2:Java,3:kayak,4:Bob,
//5:Rotator,6:Bob]
Wecanalsoremoveelementsfromalist,withthelistbeingcontractedaccordingly.
Clickheretoviewcodeimage
System.out.println(“(4)Removetheelementatindex0:”);
System.out.println(“Elementremoved:”+strList.remove(0));//“level”
printListWithIndex(strList);//[0:Naan,1:Java,2:kayak,3:Bob,4:Rotator,
5:Bob]
System.out.println(“(5)Removethefirstoccurrenceof"Java":”);
System.out.println(“Elementremoved:”+strList.remove(“Java”));//true
printListWithIndex(strList);//[0:Naan,1:kayak,2:Bob,3:Rotator,4:Bob]
Theremove(int)removestheelementatthespecifiedindex.Themethod
remove(Object)needstosearchthelistandcomparetheargumentobjectwith
elementsinthelistforobjectvalueequality.Thistestrequiresthattheargumentobject
WOW! eBook
www.wowebook.org
overridetheequals()methodfromtheObjectclass,whichmerelydetermines
referencevalueequality.TheStringclassprovidestheappropriateequals()method.
However,thefollowingcodewillnotgivetheexpectedresult,becausethe
StringBuilderclassdoesnotprovideitsownequals()method.
Clickheretoviewcodeimage
List<StringBuilder>sbList=newArrayList<>();
for(Stringstr:wordArray)
strList.add(str);
System.out.println(sbList);//[level,Ada,kayak,Bob,Rotator,Bob]
StringBuilderelement=newStringBuilder(“Ada”);
System.out.println(“Elementtoberemoved:”+element);//Ada
System.out.println(“Elementremoved:”+sbList.remove(element));//false
System.out.println(sbList);//[level,Ada,kayak,Bob,Rotator,Bob]
PrimitiveValuesandArrayLists
SinceprimitivevaluescannotbestoredinanArrayList,wecanusethewrapper
classestoboxsuchvaluesfirst.Inthefollowingcode,wecreatealistofIntegerin
whichtheintvaluesareautoboxedinIntegerobjectsandthenaddedtothelist.We
trytodeletetheelementwithvalue1,butendupdeletingtheelementatindex1instead
(i.e,thevalue20).
Clickheretoviewcodeimage
List<Integer>intList=newArrayList<>();
intList.add(10);intList.add(20);intList.add(1);
System.out.println(intList);//[10,20,1]
System.out.println(“Elementtoberemoved:”+1);//1
System.out.println(“Elementremoved:”+intList.remove(1));//20
System.out.println(intList);//[10,1]
Themethodcall
intList.remove(1)
hasthesignature
intList.remove(int)
Thissignaturematchestheoverloadedmethodthatremovestheelementataspecified
index,soitisthismethodthatiscalledatruntime.Wesaythatthismethodisthemost
specificinthiscase.Forthecodetoworkasintended,theprimitivevaluemustbe
explicitlyboxed.
Clickheretoviewcodeimage
System.out.println(intList);//[10,20,1]
System.out.println(“Elementtoberemoved:”+1);//
1
System.out.println(“Elementremoved:”+intList.remove(newInteger(1)));//
true
System.out.println(intList);//[10,20]
Themethodcall
Clickheretoviewcodeimage
intList.remove(newInteger(1))
hasthesignature
WOW! eBook
www.wowebook.org
intList.remove(Integer)
Thiscallmatchestheoverloadedremove(Object)method,sinceanIntegerobject
canbepassedtoanObjectparameter.Thismethodisthemostspecificinthiscase,and
isexecuted.
Queryingan
Asummaryofusefulmethodsthatcanbeusedtoqueryalistisprovidedhere:
intsize()
Returnsthenumberofelementscurrentlyinthelist.Inanon-emptylist,thefirst
elementisatindex0andthelastelementisatsize()-1.
booleanisEmpty()
Determineswhetherthelistisempty(i.e.,whetheritssizeis0).
Eget(intindex)
Returnstheelementatthespecifiedpositionalindex.Themethodthrowsan
IndexOutOfBoundsExceptioniftheindexisoutofrange(index<0||
index>=size()).
booleanequals(Objecto)
Comparesthespecifiedobjectwiththislistforobjectvalueequality.Itreturns
trueifandonlyifthespecifiedobjectisalsoalist,bothlistshavethesamesize,
andallcorrespondingpairsofelementsinthetwolistsareequalaccordingtoobject
valueequality.
Clickheretoviewcodeimage
booleancontains(Objectelement)
Determineswhethertheargumentobjectiscontainedinthecollection,usingobject
valueequality.Thisiscalledthemembershiptest.
intindexOf(Objecto)
intlastIndexOf(Objecto)
Returntheindexesofthefirstandlastoccurrencesoftheelementthatareequal
(usingobjectvalueequality)tothespecifiedargument,respectively,ifsuchan
elementexistsinthelist;otherwise,thevalue–1isreturned.Thesemethods
provideelementsearchinthelist.
Themethodget(int)retrievestheelementatthespecifiedindex.
Clickheretoviewcodeimage
System.out.println(“Firstelement:”+strList.get(0);//
Naan
System.out.println(“Lastelement:”+strList.get(strList.size()-1));//Bob
Theequals()methodoftheArrayListclasscanbeusedtocomparetwolistsfor
equalitywithregardtosizeandcorrespondingelementsbeingequalineachlist.
Clickheretoviewcodeimage
WOW! eBook
www.wowebook.org
List<String>strList2=newArrayList<>(strList);
booleantrueOrFalse=strList.equals(strList2);//true
Themembershiptestiscarriedoutbythecontains(Object)method.Wecanfind
theindexofaspecifiedelementinthelistbyusingtheindexOf()and
lastIndexOf()methods.
Clickheretoviewcodeimage
booleanfound=strList.contains(“Naan”);//true
intpos=strList.indexOf(“Bob”);//2
pos=strList.indexOf(“BOB”);//-1(Notfound)
pos=strList.lastIndexOf(“Bob”);//4(Lastoccurrence)
Again,thesemethodsrequirethattheelementtypeprovideameaningfulequals()
methodforobjectvalueequalitytesting.
Traversingan
Averycommontaskistotraversealistsoastoperformsomeoperationoneachelement
ofthelist.Wecanusepositionalaccesstotraversealistwiththefor(;;)loop.The
genericmethodprintListWithIndex()inExample10.1usesthefor(;;)loopto
createanewArrayListofStringthatcontainseachelementoftheargumentlist
prefixedwiththeindexoftheelement.
Clickheretoviewcodeimage
publicstatic<E>voidprintListWithIndex(List<E>list){
List<String>newList=newArrayList<>();
for(inti=0;i<list.size();i++){
newList.add(i+“:”+list.get(i));
}
System.out.println(newList);
}
SampleoutputfromthemethodcallprintWithIndex(strList)isshownhere:
Clickheretoviewcodeimage
[0:level,1:Ada,2:kayak,3:Bob,4:Rotator,5:Bob]
ThemethodprintListWithIndex()inExample10.1canprintanylistinthis
format.ItsheaderdeclarationsaysthatitacceptsalistofelementtypeE.Theelement
typeEisdeterminedfromthemethodcall.Intheprecedingexample,Eisdeterminedto
beString,asaListofStringispassedinthemethodcall.
SincetheArrayListclassimplementstheIterableinterface(i.e.,theclassprovides
aniterator),wecanusethefor(:)looptotraversealist.
Clickheretoviewcodeimage
for(Stringstr:strList){
System.out.print(str+”“);
}
TheArrayListalsoprovidesspecializediteratorstotraversealist,andthediligent
readerisencouragedtomaketheiracquaintanceathisorherownleisure.
Onepertinentquestiontoaskishowtoremoveelementsfromthelistwhentraversingthe
WOW! eBook
www.wowebook.org
list.Thefor(:)loopdoesnotallowtheliststructuretobemodified:
Clickheretoviewcodeimage
for(Stringstr:strList){
if(str.length()<=3){
strList.remove(str);//Throws
ConcurrentModificationException
}
}
Wecanusepositionalaccessinalooptotraversethelist,butmustbecarefulinupdating
theloopvariable,asthelistcontractswhenanelementisremoved.Abettersolutionisto
usetheArrayListmethodremoveIf(),passingthecriteriaforselectionasan
argument(p.452).Aniteratorcanalsobeusedexplicitlyforthispurpose,butweleave
thatasanexercise.
Convertingan toanArray
ThetwofollowingmethodscanbeusedtoconvertanArrayListtoanarray:
Object[]toArray()
<T>T[]toArray(T[]a)
ThefirstmethodreturnsanarrayoftypeObjectfilledwithalltheelementsofa
collection.
Thesecondmethodisagenericmethodthatstorestheelementsofacollectioninan
arrayoftypeT.Ifthespecifiedarrayisbigenough,theelementsarestoredinthis
array.Ifthereisroomtospareinthearray—thatis,ifthelengthofthearrayis
greaterthanthenumberofelementsinthecollection—theelementfound
immediatelyafterstoringtheelementsofthecollectionissettothenullvalue
beforethearrayisreturned.Ifthearrayistoosmall,anewarrayoftypeTand
appropriatesizeiscreated.IfTisnotasupertypeoftheruntimetypeofevery
elementinthecollection,anArrayStoreExceptionisthrown.
TheactualelementtypeoftheelementsintheObjectarrayreturnedbythefirst
toArray()methodcanbeanysubtypeofObject.Itmaybenecessarytocastthe
Objectreferenceofanelementtotheappropriatetype,asinthefollowingcode:
Clickheretoviewcodeimage
System.out.println(“(14)Convertlisttoarray:”);
Object[]objArray=strList.toArray();//Object[]
System.out.println(“Object[]length:”+objArray.length);//5
System.out.print(“LengthofeachstringintheObjectarray:“);
for(Objectobj:objArray){
Stringstr=(String)obj;//Castrequired.
System.out.print(str.length()+”“);
}
System.out.println();
ThesecondtoArray()methodreturnsanarrayoftypeT,whenitispassedanarrayof
typeTasargument.Inthefollowingcode,thearrayofStringreturnedhasthesame
lengthasthesizeofthelistofString,eventhoughaStringarrayoflength0was
WOW! eBook
www.wowebook.org
passedasargument:
Clickheretoviewcodeimage
String[]strArray=strList.toArray(newString[0]);//String[]
System.out.println(“String[]length:”+strArray.length);//5
System.out.print(“LengthofeachstringintheStringarray:“);
for(Stringstr:strArray){
System.out.print(str.length()+”“);
}
System.out.println();
Sortingan
Thefollowingstaticmethodofthejava.util.Collectionsclasscanbeusedto
sortelementsofalist.Notethenameoftheclass.Italsoprovidesmanyusefulutility
methodsforcollections.
Clickheretoviewcodeimage
static<TextendsComparable<?superT>>voidsort(List<T>list)
Thisgenericmethodsortsthespecifiedlistintoascendingorder,accordingtothe
naturalorderingofitselements.Thedeclarationessentiallysaysthatelementsof
thelisthavetobecomparable;inotherwords,theycanbecomparedwiththe
compareTo()methodoftheComparableinterface.
Hereisanexampleofsortingalist:
Clickheretoviewcodeimage
System.out.println(“Unsortedlist:”+strList);//[Naan,kayak,Bob,Rotator,
Bob]
Collections.sort(strList);
System.out.println(“Sortedlist:”+strList);//[Bob,Bob,Naan,Rotator,
kayak]
TheStringclassimplementstheComparableinterface,anditsnaturalorderingis
lexicographicalordering,basedontheUnicodevaluesofthecharactersinthestring.
Arraysversus
Table10.1summarizesthedifferencesbetweenarraysandArrayLists.
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
Table10.1SummaryofArraysversusArrayLists
Example10.1UsinganArrayList
Clickheretoviewcodeimage
importjava.util.ArrayList;
importjava.util.Collections;
importjava.util.List;
publicclassUsingArrayList{
publicstaticvoidmain(String[]args){
String[]wordArray={“level”,“Ada”,“kayak”,“Bob”,“Rotator”,“Bob”
};
System.out.println(“(1)Createanemptylistofstrings:”);
List<String>strList=newArrayList<>();
printListWithIndex(strList);
System.out.println(“\n(2)Addelementstolist:”);
for(Stringstr:wordArray){
strList.add(str);
printListWithIndex(strList);
}
System.out.println(“Insertanelementatindex2inthelist:”);
strList.add(2,“Java”);
printListWithIndex(strList);
System.out.println(“\n(3)Replacetheelementatindex1:”);
StringoldElement=strList.set(1,“Naan”);
System.out.println(“Elementthatwasreplaced:”+oldElement);
printListWithIndex(strList);
System.out.println(“\n(4)Removetheelementatindex0:”);
System.out.println(“Elementremoved:”+strList.remove(0));
printListWithIndex(strList);
System.out.println(“\n(5)Removethefirstoccurrenceof"Java":”);
System.out.println(“Elementremoved:”+strList.remove(“Java”));
printListWithIndex(strList);
System.out.println(“\n(6)Determinethesizeofthelist:”);
System.out.println(“Thesizeofthelistis”+strList.size());
System.out.println(“\n(7)Determineifthelistisempty:”);
booleanresult=strList.isEmpty();
System.out.println(“Thelist”+(result?“is”:“isnot”)+”empty.”);
System.out.println(“\n(8)Gettheelementatspecificindex:”);
System.out.println(“Firstelement:”+strList.get(0));
System.out.println(“Lastelement:”+strList.get(strList.size()-1));
System.out.println(“\n(9)Comparetwolists:”);
List<String>strList2=newArrayList<>(strList);
booleantrueOrFalse=strList.equals(strList2);
System.out.println(“ThelistsstrListandstrList2are”
+(trueOrFalse?””:”not”)+”equal.”);
strList2.add(null);
printListWithIndex(strList2);
trueOrFalse=strList.equals(strList2);
WOW! eBook
www.wowebook.org
System.out.println(“ThelistsstrListandstrList2are”
+(trueOrFalse?””:”not”)+”equal.”);
System.out.println(“\n(10)Membershiptest:”);
booleanfound=strList.contains(“Naan”);
Stringmsg=found?“contains”:“doesnotcontain”;
System.out.println(“Thelist”+msg+”thestring"Naan".”);
System.out.println(“\n(11)Findtheindexofanelement:”);
intpos=strList.indexOf(“Bob”);
System.out.println(“Theindexofstring"Bob"is:”+pos);
pos=strList.indexOf(“BOB”);
System.out.println(“Theindexofstring"BOB"is:”+pos);
pos=strList.lastIndexOf(“Bob”);
System.out.println(“Thelastindexofstring"Bob"is:”+pos);
printListWithIndex(strList);
System.out.println(“\n(12)Traversingthelistusingthefor(;;)loop:”);
for(inti=0;i<strList.size();i++){
System.out.print(i+“:”+strList.get(i)+”“);
}
System.out.println();
System.out.println(“\n(13)Traversingthelistusingthefor(:)loop:”);
for(Stringstr:strList){
System.out.print(str+”“);
//strList.remove(str);//Throws
ConcurrentModificationException.
}
System.out.println();
System.out.println(“\n(14)Convertlisttoarray:”);
Object[]objArray=strList.toArray();
System.out.println(“Object[]length:”+objArray.length);
System.out.print(“LengthofeachstringintheObjectarray:“);
for(Objectobj:objArray){
Stringstr=(String)obj;//Castrequired.
System.out.print(str.length()+”“);
}
System.out.println();
String[]strArray=strList.toArray(newString[0]);
System.out.println(“String[]length:”+strArray.length);
System.out.print(“LengthofeachstringintheStringarray:“);
for(Stringstr:strArray){
System.out.print(str.length()+”“);
}
System.out.println();
System.out.println(“\n(15)Sortingalist:”);
List<StringBuilder>sbList=newArrayList<>();
for(Stringstr:strArray){
sbList.add(newStringBuilder(str));
}
//Collections.sort(sbList);//Compile-timeerror!
System.out.println(“Unsortedlist:”+strList);
Collections.sort(strList);
System.out.println(“Sortedlist:”+strList);
}
/**
*Printtheelementsofalist,togetherwiththeirindex:
*[0:value0,1:value1,…]
WOW! eBook
www.wowebook.org
*@paramlistListtoprintwithindex
*/
publicstatic<E>voidprintListWithIndex(List<E>list){//
(16)
List<String>newList=newArrayList<>();
for(inti=0;i<list.size();i++){
newList.add(i+“:”+list.get(i));
}
System.out.println(newList);
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
(1)Createanemptylistofstrings:
[]
(2)Addelementstolist:
[0:level]
[0:level,1:Ada]
[0:level,1:Ada,2:kayak]
[0:level,1:Ada,2:kayak,3:Bob]
[0:level,1:Ada,2:kayak,3:Bob,4:Rotator]
[0:level,1:Ada,2:kayak,3:Bob,4:Rotator,5:Bob]
Insertanelementatindex2inthelist:
[0:level,1:Ada,2:Java,3:kayak,4:Bob,5:Rotator,6:Bob]
(3)Replacetheelementatindex1:
Elementthatwasreplaced:Ada
[0:level,1:Naan,2:Java,3:kayak,4:Bob,5:Rotator,6:Bob]
(4)Removetheelementatindex0:
Elementremoved:level
[0:Naan,1:Java,2:kayak,3:Bob,4:Rotator,5:Bob]
(5)Removethefirstoccurrenceof“Java”:
Elementremoved:true
[0:Naan,1:kayak,2:Bob,3:Rotator,4:Bob]
(6)Determinethesizeofthelist:
Thesizeofthelistis5
(7)Determineifthelistisempty:
Thelistisnotempty.
(8)Gettheelementatspecificindex:
Firstelement:Naan
Lastelement:Bob
(9)Comparetwolists:
ThelistsstrListandstrList2areequal.
[0:Naan,1:kayak,2:Bob,3:Rotator,4:Bob,5:null]
ThelistsstrListandstrList2arenotequal.
(10)Membershiptest:
Thelistcontainsthestring“Naan”.
(11)Findtheindexofanelement:
Theindexofstring“Bob”is:2
Theindexofstring“BOB”is:-1
Thelastindexofstring“Bob”is:4
WOW! eBook
www.wowebook.org
[0:Naan,1:kayak,2:Bob,3:Rotator,4:Bob]
(12)Traversingthelistusingthefor(;;)loop:
0:Naan1:kayak2:Bob3:Rotator4:Bob
(13)Traversingthelistusingthefor(:)loop:
NaankayakBobRotatorBob
(14)Convertlisttoarray:
Object[]length:5
LengthofeachstringintheObjectarray:45373
String[]length:5
LengthofeachstringintheStringarray:45373
(15)Sortingalist:
Unsortedlist:[Naan,kayak,Bob,Rotator,Bob]
Sortedlist:[Bob,Bob,Naan,Rotator,kayak]
ReviewQuestions
10.1Whichstatementistrueaboutthejava.util.ArrayListclass?
Selecttheonecorrectanswer.
(a)Themethoddelete()canbeusedtodeleteanelementataspecificindexin
anArrayList.
(b)ThemethoddeleteAll()canbeusedtodeleteallelementsinan
ArrayList.
(c)Themethodinsert()canbeusedtoinsertanelementataspecificindexin
anArrayList.
(d)Themethodappend()canbeusedtoappendanelementattheendofan
ArrayList.
(e)Themethodreplace()canbeusedtoreplacetheelementataspecificindex
withanotherelementinanArrayList.
(f)Themethodfind()canbeusedtodeterminewhetheranelementisinan
ArrayList.
(g)Themethodcapacity()canbeusedtodeterminethecurrentcapacityofan
ArrayList.
(h)Noneoftheabove.
10.2Whatwillthefollowingprogramprintwhencompiledandrun?
Clickheretoviewcodeimage
importjava.util.ArrayList;
importjava.util.List;
publicclassRQ12A10{
publicstaticvoidmain(String[]args){
List<String>strList=newArrayList<>();
WOW! eBook
www.wowebook.org
strList.add(“Anna”);strList.add(“Ada”);strList.add(“Ada”);
strList.add(“Bob”);strList.add(“Bob”);strList.add(“Adda”);
for(inti=0;i<strList.size();/*empty*/){
if(strList.get(i).length()<=3){
strList.remove(i);
}else{
++i;
}
}
System.out.println(strList);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile.
(b)TheprogramwillthrowanIndexOutOfBoundsExceptionatruntime.
(c)TheprogramwillthrowaConcurrentModificationExceptionat
runtime.
(d)Theprogramwillnotterminatewhenrun.
(e)Theprogramwillprint:[Anna,Adda].
(f)Theprogramwillprint:[Anna,Ada,Bob,Adda].
10.3Whatwillthefollowingprogramprintwhencompiledandrun?
Clickheretoviewcodeimage
importjava.util.ArrayList;
importjava.util.List;
publicclassRQ12A15{
publicstaticvoidmain(String[]args){
doIt1();doIt2();
}
publicstaticvoiddoIt1(){
List<StringBuilder>sbListOne=newArrayList<>();
sbListOne.add(newStringBuilder(“Anna”));
sbListOne.add(newStringBuilder(“Ada”));
sbListOne.add(newStringBuilder(“Bob”));
List<StringBuilder>sbListTwo=newArrayList<>(sbListOne);
sbListOne.add(null);
sbListTwo.get(1).reverse();
System.out.println(sbListOne);//
(1)
}
publicstaticvoiddoIt2(){
List<String>listOne=newArrayList<>();
listOne.add(“Anna”);listOne.add(“Ada”);listOne.add(“Bob”);
List<String>listTwo=newArrayList<>(listOne);
StringstrTemp=listOne.get(0);
listOne.set(0,listOne.get(listOne.size()-1));
listOne.set(listOne.size()-1,strTemp);
System.out.println(listTwo);//
(2)
}
}
WOW! eBook
www.wowebook.org
Selectthetwocorrectanswers.
(a)(1)willprint[Anna,Ada,Bob,null].
(b)(1)willprint[Anna,adA,Bob,null].
(c)(2)willprint[Anna,Ada,Bob].
(d)(2)willprint[Bob,Ada,Anna].
(e)TheprogramwillthrowanIndexOutOfBoundsExceptionatruntime.
10.4Whatwillthefollowingprogramprintwhencompiledandrun?
Clickheretoviewcodeimage
importjava.util.ArrayList;
importjava.util.List;
publicclassRQ12A20{
publicstaticvoidmain(String[]args){
List<String>strList=newArrayList<>();
strList.add(“Anna”);strList.add(“Ada”);strList.add(null);
strList.add(“Bob”);strList.add(“Bob”);strList.add(“Adda”);
for(inti=0;i<strList.size();++i){
if(strList.get(i).equals(“Bob”)){
System.out.print(i);
}
}
System.out.println();
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile.
(b)TheprogramwillthrowanIndexOutOfBoundsExceptionatruntime.
(c)TheprogramwillthrowaNullPointerExceptionatruntime.
(d)Theprogramwillprint:34.
10.5Whatwillthefollowingprogramprintwhencompiledandrun?
Clickheretoviewcodeimage
importjava.util.ArrayList;
importjava.util.List;
publicclassRQ12A30{
publicstaticvoidmain(String[]args){
List<String>strList=newArrayList<>();
strList.add(“Anna”);strList.add(“Ada”);
strList.add(“Bob”);strList.add(“Bob”);
for(inti=0;i<strList.size();++i){
if(strList.get(i).equals(“Bob”)){
strList.remove(i);
}
}
System.out.println(strList);
}
}
WOW! eBook
www.wowebook.org
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile.
(b)TheprogramwillthrowanIndexOutOfBoundsExceptionatruntime.
(c)TheprogramwillthrowaNullPointerExceptionatruntime.
(d)TheprogramwillthrowaConcurrentModificationExceptionat
runtime.
(e)Theprogramwillnotterminatewhenrun.
(f)Theprogramwillprint[Anna,Ada,Bob].
(g)Theprogramwillprint[Anna,Ada].
10.6Whatwillthefollowingprogramprintwhencompiledandrun?
Clickheretoviewcodeimage
importjava.util.ArrayList;
importjava.util.List;
publicclassRQ12A40{
publicstaticvoidmain(String[]args){
List<String>strList=newArrayList<>();
strList.add(“Anna”);strList.add(“Ada”);strList.add(null);
strList.add(“Bob”);strList.add(“Bob”);strList.add(“Adda”);
while(strList.remove(“Bob”));
System.out.println(strList);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile.
(b)TheprogramwillthrowaNullPointerExceptionatruntime.
(c)Theprogramwillnotterminatewhenrun.
(d)Theprogramwillprint:[Anna,Ada,Adda].
(e)Theprogramwillprint:[Anna,Ada,Bob,Adda].
(f)Theprogramwillprint:[Anna,Ada,null,Adda].
(g)Theprogramwillprint:
[Anna,Ada,null,Bob,Adda]
[Anna,Ada,null,Adda]
10.2LambdaExpressions
Inmanyways,Java8representsawatershedinthehistoryofthelanguage.BeforeJava8,
thelanguagesupportedonlyobject-orientedprogramming.Packingstateandbehaviorinto
objectsthatcommunicateinaproceduralmannerwastheorderoftheday.Java8brings
functional-styleprogrammingintothelanguage,wherecoderepresentingfunctionalitycan
bepassedasvaluestotailorthebehaviorofmethods.
WOW! eBook
www.wowebook.org
Thissectiongivesatasteofwhatfunctional-styleprogrammingbringstoJava.Itprovides
anintroductiontotwolanguagefeatures(functionalinterfacesandlambdaexpressions)
thatarethebasisforthisprogrammingstyleinJava.Thatsufficesforthepurposesofthis
book.However,functional-styleprogrammingisapowerfulparadigmworthexploring
further,andanyJavaprogrammerwhoignoresitdoessoathisorherownperil.
BehaviorParameterization
Todemonstratehowfunctional-styleprogrammingcanbeuseful,wewillusearunning
examplethatwewillgraduallyrefinetoimplementanefficientandconcisesolutionusing
lambdaexpressionsandfunctionalinterfaces.
Acommonoperationonelementsinacollectionistoselectthoseelementsthatsatisfya
certaincriterion.Thisoperationiscalledfiltering.Example10.2createsalistofstringsat
(1).Wewouldliketofilterthislistforone-wordpalindromes,wordsthatarespelledthe
samewayforwardandbackward.Forexample,"anana"isapalindrome,but
"banana"isnot.
FilteringUsingCustomizedMethods
Astraightforwardandnaivesolutionistoimplementacustomizedmethodthattakesalist
ofwordsandreturnsalistofthewordsthatfulfillthecriteriaforbeingapalindrome.The
methodfilterPalindromes()at(4)inExample10.2doesexactlythat.Ittraverses
thelistandselectselementswiththefollowingcode:
Clickheretoviewcodeimage
if(word.equals(newStringBuilder(word).reverse().toString())){//(5)
result.add(word);
}
Theargumenttotheequals()methodcreatesaStringBuilderbasedonthe
currentwordinthelist.ThecontentsoftheStringBuilderarereversedandconverted
backtoaString.Theoriginalwordiscomparedforobjectvalueequalitywiththe
reversedwordtodeterminewhetheritisapalindrome.Becausetheequalitytestisbased
ontheUnicodevaluesofthecharacters,thiscriteriontakesintoaccountthecaseofthe
letters,ascanbeseenfromtheoutput.
Whatifwewantedtocreateafilterthatwascaseinsensitive?Weneedtoimplementa
newmethod,asshownin(6).WeseethatthemethodequalsIgnoreCase()usedfor
equalitycomparisonat(7)ignoresthecase,andtheoutputbearsthisout.
Clickheretoviewcodeimage
if(word.equalsIgnoreCase(
newStringBuilder(word).reverse().toString())){//(7)
result.add(word);
}
Creatinganewmethodeverytimewewanttofilteronanewcriterioniscertainlynot
viable.Thereislotofcodeduplication,andthemostsignificantchangeoccursonlyinthe
conditionoftheifstatementat(5)and(7).
WOW! eBook
www.wowebook.org
Example10.2ImplementingCustomizedMethodsforFilteringanArrayList
Clickheretoviewcodeimage
importjava.util.ArrayList;
importjava.util.List;
publicclassFunWithPalindromesV0{
publicstaticvoidmain(String[]args){
//Createalistof
words:(1)
List<String>words=newArrayList<>();
words.add(“Otto”);words.add(“ADA”);words.add(“Alyla”);
words.add(“Bob”);words.add(“HannaH”);words.add(“Java”);
System.out.println(“Listofwords:”+words);
//Callamethodtofilterthelistforpalindromes(case
sensitive).(2)
List<String>palindromes=filterPalindromes(words);
System.out.println(“Case-sensitivepalindromes:”+palindromes);
//Callamethodtofilterthelistforpalindromes(caseinsensitive).
(3)
List<String>palindromesIgnoreCase=filterPalindromesIgnorecase(words);
System.out.println(“Case-insensitivepalindromes:”+
palindromesIgnoreCase);
}
/**(4)
*Findspalindromesinalistofwords.Usescase-sensitivefiltering.
*@paramwordsListofstrings
*@returnListofpalindromesfound
*/
publicstaticList<String>filterPalindromes(List<String>words){
List<String>result=newArrayList<>();
for(Stringword:words){
if(word.equals(newStringBuilder(word).reverse().toString())){//
(5)
result.add(word);
}
}
returnresult;
}
/**(6)
*Findspalindromesinalistofwords.Usescase-insensitivefiltering.
*@paramwordsListofstrings
*@returnListofpalindromesfound
*/
publicstaticList<String>filterPalindromesIgnorecase(List<String>words)
{
List<String>result=newArrayList<>();
for(Stringword:words){
if(word.equalsIgnoreCase(
newStringBuilder(word).reverse().toString())){//
(7)
result.add(word);
}
}
returnresult;
}
}
WOW! eBook
www.wowebook.org
Outputfromtheprogram:
Clickheretoviewcodeimage
Listofwords:[Otto,ADA,Alyla,Bob,HannaH,Java]
Case-sensitivepalindromes:[ADA,HannaH]
Case-insensitivepalindromes:[Otto,ADA,Alyla,Bob,HannaH]
FilteringUsinganInterface
InExample10.3,wehavegeneralizedthemethodthatappliesthecriteriaandselectsthe
elements.ThemethodfilterStrings()at(9)takesasinputalistandaselection
criteriaobjectthatimplementsaninterface,andreturnsalistwithelementsthatsatisfythe
selectioncriteria.
Thebestpracticeofprogrammingtoaninterfacecertainlymakessensehere.Thatwaythe
filterStrings()methodcanbeusedforfilteringonanycriteria.Anappropriate
objectforfilteringcanbepassedtothemethodaslongasitimplementstheinterface.This
objectmustimplementtheStrPredicateinterface,declaredat(1),supplyingthe
booleanmethodtest()thatactuallydetermineswhetheranelementisselected.The
test()methodisanexampleofapredicate,afunctionthattakesanargumentand
returnsabooleanvalue.
Examples10.3showstwoapproachestohowthecriteriaobjectcanbecreated.Wecan
defineconcreteclassesthatimplementtheStrPredicateinterface.Theclasses
PalindromeCaseSensitiveandPalindromeCaseInsensitiveat(2)and(3)
inExample10.3,respectively,implementtheStrPredicateinterfaceandprovidean
implementationofthetest()method.Objectsoftheseclassesarepassedasarguments
tothefilterStrings()methodat(5)and(6)tofilterthelist.Againnotethatany
newselectioncriterionimplementedbythisapproachrequiresanewconcreteclass,
resultinginproliferationofclasses,whenallthatneedschangingisthecodeinthebodyof
thetest()method.
Insteadofconcreteclasses,wecanuseanonymousclassestoinstantiatethecriteriaobject,
asshownat(7)and(8)inExample10.3.Wewillnotgointodetailsofexplainingthe
syntaxofananonymousclass.Thebasicideaisthatwecandeclareandinstantiatethe
classatthesametime,whereitisneededinthecode—inourcase,asanargumentinthe
calltothefilterStrings()method.Thenewoperatorcreatesanobjectofthe
anonymousclasswhosebodyresemblesthatofaconcreteclass.Thenameoftheinterface
inthedeclarationensuresthatthisclasswillimplementthemethodsoftheinterface.In
ourcase,theanonymousclassesprovideimplementationofthetest()method.By
usinganonymousclassesweavoidcreatingconcreteclasses,buttheverbosityofdeclaring
anonymousclassestoencapsulateasinglemethodisinescapable.Also,westillhaveto
declareanewanonymousclassforeachselectioncriterion,duplicatingalotofboilerplate
code.
Example10.3ImplementinganInterfaceforFilteringanArrayList
Clickheretoviewcodeimage
WOW! eBook
www.wowebook.org
/**Interfacetotesttwostringsaccordingtoacriterion.*/
publicinterfaceStrPredicate{//
(1)
booleantest(Stringstr);
}
/**Testswhetherastringisapalindrome(casesensitive).*/
publicclassPalindromeCaseSensitiveimplementsStrPredicate{//
(2)
@Overridepublicbooleantest(Stringstr){
returnstr.equals(newStringBuilder(str).reverse().toString());
}
}
/**Testswhetherastringisapalindrome(caseinsensitive).*/
publicclassPalindromeCaseInsensitiveimplementsStrPredicate{//
(3)
@Overridepublicbooleantest(Stringstr){
returnstr.equalsIgnoreCase(newStringBuilder(str).reverse().toString());
}
}
importjava.util.ArrayList;
importjava.util.List;
publicclassFunWithPalindromesV1{
publicstaticvoidmain(String[]args){
//Createalistof
words:(4)
List<String>words=newArrayList<>();
words.add(“Otto”);words.add(“ADA”);words.add(“Alyla”);
words.add(“Bob”);words.add(“HannaH”);words.add(“Java”);
System.out.println(“Listofwords:”+words);
//Useaclasstofilterforpalindromes(case
sensitive).(5)
List<String>palindromes1=filterStrings(words,
newPalindromeCaseSensitive());
System.out.println(“Case-sensitivepalindromes:”+palindromes1);
//Useaclasstofilterforpalindromes(case
insensitive).(6)
List<String>palindromes2=filterStrings(words,
new
PalindromeCaseInsensitive());
System.out.println(“Case-insensitivepalindromes:”+palindromes2);
//Useananonymousclasstofilterforpalindromes(case
sensitive).(7)
List<String>palindromes3=filterStrings(words,
newStrPredicate(){
@Override
publicbooleantest(Stringstr){
returnstr.equals(newStringBuilder(str).reverse().toString());
}
}
);
System.out.println(“Case-sensitivepalindromes:”+palindromes3);
//Useananonymousclasstofilterforpalindromes(caseinsensitive).
(8)
WOW! eBook
www.wowebook.org
List<String>palindromes4=filterStrings(words,
newStrPredicate(){
@Override
publicbooleantest(Stringstr){
returnstr.equalsIgnoreCase(
newStringBuilder(str).reverse().toString());
}
}
);
System.out.println(“Case-insensitivepalindromes:”+palindromes4);
}
/**
*Filtersalistofstringsaccordingtothecriteriaofthepredicate.
*@paramstrListListofstringstofilter
*@parampredicateProvidesthecriteriaforfilteringthestrings
*@returnListofstringsthatmatchthecriteria
*/
publicstaticList<String>filterStrings(List<String>strList,//
(9)
StrPredicatepredicate){
List<String>result=newArrayList<>();
for(Stringstr:strList){
if(predicate.test(str)){//
(10)
result.add(str);
}
}
returnresult;
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
Listofwords:[Otto,ADA,Alyla,Bob,HannaH,Java]
Case-sensitivepalindromes:[ADA,HannaH]
Case-insensitivepalindromes:[Otto,ADA,Alyla,Bob,HannaH]
Case-sensitivepalindromes:[ADA,HannaH]
Case-insensitivepalindromes:[Otto,ADA,Alyla,Bob,HannaH]
FilteringUsingLambdaExpressions
Ideallywewouldliketopassthecodefortheselectioncriteriaasanargumenttothe
filterStrings()methodsothatthemethodcanapplythecriteriatotheelementsin
thelist;thatis,wewouldliketobeabletochangethebehaviorofthe
filterStrings()methoddependingontheselectioncriteria.Example10.4isastep
inthatdirection.
TheStrPredicateinterfaceandthefilterStrings()methodarestillthesame
asinExample10.3,buttheimplementationoftheStrPredicateinterfaceat(2)and
(4)inExample10.4isspecifiedbylambdaexpressions.
TheStrPredicateinterfaceisanexampleofafunctionalinterface(p.442).Suchan
interfacehasexactlyoneabstractmethod.InthecaseoftheStrPredicatemethod,
thismethodisthetest()method,whichtakesaStringobjectasanargumentand
returnsabooleanvalue.KnowingthatsomethingisaStrPredicate,allthe
WOW! eBook
www.wowebook.org
informationaboutitssoleabstractmethodcanbeinferred,asitistheonlyabstractmethod
intheinterface;inotherwords,weknowitsname,itsparameters,anyvalueitreturns,and
whetheritthrowsanyexceptions.
Implementationofthesoleabstractmethodofafunctionalinterfacecanbeprovidedbya
lambdaexpression(p.444),incontrasttoaconventionalmethodimplementationin
concreteandanonymousclasses,asseeninExample10.3.Theassignmentat(2)in
Example10.4usesalambdaexpressiontoprovideanimplementationforthe
StrPredicatefunctionalinterface:
Clickheretoviewcodeimage
StrPredicatepredicate1=(Stringstr)->
str.equals(newStringBuilder(str).reverse().toString());//(2)
Thereferencepredicate1ontheleft-handsideisoftypeStrPredicate,anditis
assignedthevalueofthelambdaexpressionontheright-handside.Alambdaexpression
hasthreeparts:
•Aparameterlistthatisanalogoustotheparameterlistofamethod.In(2),the
parameterlisthasonlyoneparameter:
(Stringstr)
•The->operator(thearrow)thatseparatestheparameterlistfromthelambdabody.
•Alambdabodythatiseitherasingleexpressionorastatementblock.In(2),the
lambdabodyisasingleexpression,whosevalueisreturnedwhenthelambda
expressionisevaluated.Thelambdabodyexpressionevaluatestoaboolean
value,sincethecalltotheequals()methodreturnsabooleanvalue.
Clickheretoviewcodeimage
str.equals(newStringBuilder(str).reverse().toString());//Lambdabody
expression
Thelambdaexpressionat(2)definesanamelessfunctionthattakesaStringastheonly
parameter,andreturnsabooleanvalue.Recallthatthetest()methodofthe
StrPredicatefunctionalinterfacedoesexactlythat.
Lambdaexpressionsarealsocalledanonymousfunctions,astheydonothavenames.
Theycanbestoredasvaluesinreferences,asinthereferencepredicate1in(2).The
compilercantypecheckthatthelambdaexpressionisassignabletothereferenceonthe
left-handside,sincetheexpressionrepresentsananonymousfunctionthatiscompatible
withthesoleabstractmethodtest()oftheStrPredicateinterface.
Thelambdaexpressionat(2)ispassedasanargumenttothefilterStrings()
methodviathereferencepredicate1at(3).Itisexecutedonlywhenthetest()
methodiscalledwithaStringargumentinthefilterStrings()methodat(7).
NowwejustneedtopassanewlambdaexpressiontothefilterStrings()method
tofilteralistofstringsbasedonaselectioncriterion.Example10.4ismoreprecise,
concise,andreadablethanthepreviousversions,especiallyasyoubecomecomfortable
withlambdaexpressions.
WOW! eBook
www.wowebook.org
Example10.4User-DefinedFunctionalInterfaceforFilteringanArrayList
Clickheretoviewcodeimage
/**Interfacetotesttwostringsaccordingtoacriterion.*/
publicinterfaceStrPredicate{//
(1)
booleantest(Stringstr);
}
importjava.util.ArrayList;
importjava.util.List;
publicclassFunWithPalindromesV2{
publicstaticvoidmain(String[]args){
//Createalistofwords:
List<String>words=newArrayList<>();
words.add(“Otto”);words.add(“ADA”);words.add(“Alyla”);
words.add(“Bob”);words.add(“HannaH”);words.add(“Java”);
System.out.println(“Listofwords:”+words);
StrPredicatepredicate1=(Stringstr)->
str.equals(newStringBuilder(str).reverse().toString());//
(2)
List<String>palindromes1=filterStrings(words,predicate1);//
(3)
System.out.println(“Case-sensitivepalindromes:”+palindromes1);
StrPredicatepredicate2=(Stringstr)->
str.equalsIgnoreCase(newStringBuilder(str).reverse().toString());//
(4)
List<String>palindromes2=filterStrings(words,predicate2);//
(5)
System.out.println(“Case-insensitivepalindromes:”+palindromes2);
}
/**//
(6)
*Filtersalistofstringsaccordingtothecriteriaofthepredicate.
*@paramstrListListofstringstofilter
*@parampredicateProvidesthecriteriaforfilteringthestrings
*@returnListofstringsthatmatchthecriteria
*/
publicstaticList<String>filterStrings(List<String>strList,
StrPredicatepredicate){
List<String>result=newArrayList<>();
for(Stringstr:strList){
if(predicate.test(str)){//
(7)
result.add(str);
}
}
returnresult;
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
Listofwords:[Otto,ADA,Alyla,Bob,HannaH,Java]
Case-sensitivepalindromes:[ADA,HannaH]
WOW! eBook
www.wowebook.org
Case-insensitivepalindromes:[Otto,ADA,Alyla,Bob,HannaH]
FilteringUsingthePredicate<T>FunctionalInterface
Example10.4usedauser-definedfunctionalinterfaceStrPredicate.TheJavaSE
platformAPIprovidesfunctionalinterfacesformanytasks(suchastestinganobjectand
creatingobjects).Forimplementingpredicates,wecanusethegeneric
java.util.function.Predicate<T>functionalinterface,whichspecifiesthe
single-parameterbooleanmethodtest(Tt).Itisamoregeneralizedversionofthe
StrPredicatefunctionalinterfacethatwehaveusedearlier.
Example10.5usesthegenericPredicate<T>functionalinterface,wherethetype
parameterTrepresentstheconcretetypeString.InExample10.4,wesimplyneedto
replacethenameStrPredicatewiththenamePredicate<String>in(2),(4),
and(6),andimportthePredicate<T>functionalinterfacefromthe
java.util.functionpackage((1)inExample10.5).Thediscussionoftype
checkingandevaluationoflambdaexpressionsinExample10.4alsoappliestoExample
10.5.
Functionalinterfacesandlambdaexpressionstogetherallowbehaviorparameterization,a
powerfulprogrammingparadigmthatallowscoderepresentingbehaviortobepassed
aroundasvalues,andexecutedwhentheabstractmethodofthefunctionalinterfaceis
invoked.Thisapproachisscalable,requiringonlyalambdaexpressiontorepresentthe
filteringcriteria.
Functional-styleprogrammingisalsobeneficialindevelopingparallelcode.Inthe
multicoreworldinwhichwelive,wecanuseallthehelpwecangettoutilizethe
computingpowerthatnewhardwarearchitecturesareputtingatourdisposal.
Therestofthissectionprovidesmoreinsightintothesetwofeaturesofthelanguage:
functionalinterfacesandlambdaexpressions.
WOW! eBook
www.wowebook.org
Example10.5UsingthePredicate<T>FunctionalInterfaceforFilteringan
ArrayList
Clickheretoviewcodeimage
importjava.util.ArrayList;
importjava.util.List;
importjava.util.function.Predicate;//
(1)
publicclassFunWithPalindromesV3{
publicstaticvoidmain(String[]args){
List<String>words=newArrayList<>();
words.add(“Otto”);words.add(“ADA”);words.add(“Alyla”);
words.add(“Bob”);words.add(“HannaH”);words.add(“Java”);
System.out.println(“Listofwords:”+words);
Predicate<String>predicate1=(Stringstr)->
str.equals(newStringBuilder(str).reverse().toString());//
(2)
List<String>palindromes1=filterStrings(words,predicate1);//
(3)
System.out.println(“Case-sensitivepalindromes:”+palindromes1);
Predicate<String>predicate2=(Stringstr)->
str.equalsIgnoreCase(newStringBuilder(str).reverse().toString());//
(4)
List<String>palindromes2=filterStrings(words,predicate2);//
(5)
System.out.println(“Case-insensitivepalindromes:”+palindromes2);
}
/**//
(6)
*Filtersalistofstringsaccordingtothecriteriaofthepredicate.
*@paramstrListListofstringstofilter
*@parampredicateProvidesthecriteriaforfilteringthestrings
*@returnListofstringsthatmatchthecriteria
*/
publicstaticList<String>filterStrings(List<String>strList,
Predicate<String>predicate){
List<String>result=newArrayList<>();
for(Stringstr:strList){
if(predicate.test(str)){//
(7)
result.add(str);
}
}
returnresult;
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
Listofwords:[Otto,ADA,Alyla,Bob,HannaH,Java]
Case-sensitivepalindromes:[ADA,HannaH]
Case-insensitivepalindromes:[Otto,ADA,Alyla,Bob,HannaH]
WOW! eBook
www.wowebook.org
FunctionalInterfaces
Afunctionalinterfacecanhaveonlyoneabstractmethod.Thisabstractmethodiscalled
thefunctionalmethodforthatinterface.Likeanyotherinterface,afunctionalinterfacecan
haveanynumberofstaticanddefaultmethods.Suchaninterfacecanalsoprovideexplicit
publicabstractmethoddeclarationsfornon-finalpublicinstancemethodsinthe
Objectclass,buttheseareexcludedfromthedefinitionofafunctionalinterface.Note
thatabstractmethodsdeclaredinaninterfaceareimplicitlyabstractandpublic.
Interfacesarediscussedin§7.6,p.290.
WedefinedandusedtheStrPredicateinterfaceearlier.Ithasexactlyoneabstract
method.
Clickheretoviewcodeimage
@FunctionalInterface
interfaceStrPredicate{
booleantest(Stringstr);//Solepublicabstract
method.
}
Theannotation@FunctionalInterfaceisusefulwhendefiningfunctional
interfaces.Thecompilerwillissueanerrorifthedeclarationviolatesthedefinitionofa
functionalinterface,asillustratedbythefollowingXStrPredicateinterface.Its
declarationhastwoabstractmethods.
Clickheretoviewcodeimage
@FunctionalInterface
interfaceXStrPredicate{//Compile-time
error!
booleantest(Stringstr);//Abstractmethod.
Stringreverse(Stringstr);//Abstractmethod.
}
ThenextfunctionalinterfaceNewStrPredicatedeclaresonlyoneabstractmethodat
(1).Inaddition,itprovidestheimplementationsofonedefaultmethodandonestatic
methodat(2)and(3),respectively.Theabstractmethoddeclarationat(4)isthatofanon-
finalpublicmethodfromtheObjectclass,butsuchdeclarationsareexcluded
fromthedefinitionofafunctionalinterface.
Clickheretoviewcodeimage
@FunctionalInterface
interfaceNewStrPredicate{
booleantest(Stringstr);//(1)Abstract
method
defaultvoidmsg(Stringstr){System.out.println(str);}//(2)Default
method
staticvoidinfo(){System.out.println(“Testing!”);}//(3)Static
method
@Overridebooleanequals(Objectobj);//(4)FromObject
class
}
TheinterfaceStrFormatprovidestheabstractmethoddeclarationofthenon-final
publicmethodtoString()fromtheObjectclass,butsuchdeclarationsare
excludedfromthedefinitionofafunctionalinterface.Effectively,thereisnoabstract
WOW! eBook
www.wowebook.org
methoddeclaredintheStrFormatinterface.Thecodewouldcompileasaninterface
withouttheannotation@FunctionalInterface,butitisnotafunctionalinterface.
Clickheretoviewcodeimage
@FunctionalInterface
interfaceStrFormat{//Compile-time
error!
@OverrideStringtoString();//FromObject
class
}
Earlierinthissection,weusedthegenericfunctionalinterface
java.util.function.Predicate<T>,whichprovidestheabstractmethod
test()toimplementpredicates.Thisfunctionalinterfacealsohasonestaticmethod
(isEqual())andthreedefaultmethods(and(),or(),negate()).Thedefault
methodsimplementshort-circuitlogicaloperatorsthatcanbeusedforcomposing
predicatesonPredicateobjects.
ThefunctionalsubinterfaceIStrPredicatethatfollowsiscustomizedtotheString
typebyextendingthejava.util.function.Predicate<T>functionalinterface,
wherethetypeparameterTisString.Itcanreadilybeusedforimplementingpredicates
onstrings.
Clickheretoviewcodeimage
@FunctionalInterface
interfaceIStrPredicateextendsPredicate<String>{}
FunctionalInterfacesinJavaSEPlatformAPI
TheJavaSEplatformAPIhasmanyfunctionalandnonfunctionalinterfaces,allofwhich
supportthepracticeofprogrammingtointerfaces.Forexample,thejava.langpackage
includesfivefunctionalinterfaces:Runnable,Comparable<T>,AutoCloseable,
Iterable<T>,andReadable.However,themainsupportforfunctionalinterfacesis
foundinthejava.util.functionpackage.Itincludesgeneral-purposefunctional
interfacesthatimplementbasicconceptsinfunctional-styleprogramming(Table10.2).In
addition,thepackageprovidesawiderangeoffunctionalinterfacesforvariouspurposes,
sothatimplementingnewextensionsshouldhardlybenecessary.
WOW! eBook
www.wowebook.org
Table10.2SelectedFunctionalInterfacesfromthejava.util.functionPackage
Thejava.util.functionpackageincludesfunctionalinterfacesthatarespecialized
forprimitivevalues.Theiruseenablesprogrammerstoavoidexcessiveboxingand
unboxingofprimitivevalueswhensuchvaluesareusedasobjects.Thefunctional
interfacesIntPredicate,LongPredicate,andDoublePredicateprovidean
abstracttest()methodtoevaluatepredicateswithint,long,anddouble
arguments,respectively.
Clickheretoviewcodeimage
Predicate<Integer>integerPred=(Integeri)->i%2==0;//iasoperand
unboxed.
System.out.println(integerPred.test(2015));//Argumentboxed.
false
IntPredicateintPred=(inti)->i%2==0;
System.out.println(intPred.test(2016));//true
DefiningLambdaExpressions
Lambdaexpressionsimplementfunctionalinterfacesbydefininganonymousfunctions
thatfacilitatebehaviorparameterization.Theycanbepassedandusedasvaluesina
program,withouttheexcessbaggageoffirstbeingpackagedintoobjectsinthesource
code.Thecompilertakescareofwhateverthatneedstobedoneinternallytomaketheir
usagefeasible.
Alambdaexpressionhasthefollowingsyntax:
Clickheretoviewcodeimage
formal_parameter_list->lambda_body
Theparameterlistandthebodyareseparatedbythe->operator.Thelambdaexpression
syntaxresemblesasimplifieddeclarationofamethod,withoutmanyofthebellsand
whistlesofamethoddeclaration.Thatstreamliningisimportant,asitavoidsverbosityand
providesasimpleandsuccinctnotationwithwhichtowritelambdaexpressionsonthefly.
Intherestofthissection,wetakeacloserlookattheparameterlist,thelambdabody,and
WOW! eBook
www.wowebook.org
thetypecheckingandevaluationoflambdaexpressions.
LambdaParameters
Theparameterlistofalambdaexpressionisacomma-separatedlistofformalparameters
thatisenclosedinparentheses,(),analogoustotheparameterlistinamethod
declaration.Thereareothershorthandformsaswell,asweshallseeshortly.
Ifthetypesoftheparametersarespecified,theyareknownasdeclared-typeparameters.
Ifthetypesoftheparametersarenotspecified,theyareknownasinferred-type
parameters.Typesoftheinferred-typeparametersarederivedfromthefunctional
interfacetypethatisthetargettypeofthelambdaexpression.
Parametersareeitheralldeclared-typeorallinferred-type.Parenthesesaremandatory
withmultipleparameters,whethertheyaredeclared-typeorinferred-type.Foraparameter
listwithasingleinferred-typeparameter,theparenthesescanbeomitted.Also,only
declared-typeparameterscanhavemodifiers.
Clickheretoviewcodeimage
()->..//Emptyparameterlist
(Integerx,Integery,Integerz)->..//Multipledeclared-type
parameters
(x,y,z)->..//Multipleinferred-type
parameters
(Stringstr)->..//Singledeclared-type
parameter
(str)->..//Singleinferred-type
parameter
str->..//Singleinferred-type
parameter
Stringstr->..//Illegal:Missingparentheses
Integerx,Integery,Integerz->..//Illegal:Missingparentheses
i,j,k->..//Illegal:Missingparentheses
(Stringstr,j)->..//Illegal:Cannotmixinferredanddeclaredtype
(finalinti,intj)->..//OK:Modifierwithdeclared-typeparameter
(finali,j)->..//Illegal:Nomodifierwithinferred-type
parameter
LambdaBody
Alambdabodyiseitherasingleexpressionorastatementblock.Executionofalambda
bodyhaseitheranon-voidreturn(i.e.,returnsavalue)oravoidreturn(i.e.,doesnot
returnavalue),oritsevaluationthrowsanexception.
Asingle-expressionlambdabodyisusedforshortandsuccinctlambdaexpressions.A
single-expressionlambdabodywithavoidreturntypeiscommonlyusedtoachieveside
effects.Thereturnkeywordisnotallowedinasingle-expressionlambdabody.
Intheexamplesthatfollow,thebodyofthelambdaexpressionsisanexpressionwhose
executionreturnsavalue(i.e.,hasanon-voidreturn):
Clickheretoviewcodeimage
()->2015//Expressionbody,non-void
return
()->null//Expressionbody,non-void
return
WOW! eBook
www.wowebook.org
(i,j)->i+j//Expressionbody,non-void
return
(i,j)->i<=j?i:j//Expressionbody,non-void
return
str->str.length()>3//Expressionbody,non-void
return
str->str!=null//Expressionbody,non-void
return
&&!str.equals(””)&&str.length()>3
&&str.equals(newStringBuilder(str).reverse().toString())
Inthenextsetofexamples,thelambdabodyisanexpressionstatementthatcanhavea
voidoranon-voidreturn.However,iftheabstractmethodofthefunctionalinterface
returnsvoid,thenon-voidreturnofalambdaexpressionwithanexpressionstatement
asbodycanbeinterpretedasavoidreturn(i.e.,thereturnvalueisignored).
Clickheretoviewcodeimage
val->System.out.println(val)//Methodinvocationstatement,voidreturn
sb->sb.trimToSize()//Methodinvocationstatement,voidreturn
sb->sb.append(“!”)//Methodinvocationstatement,non-void
return
()->newStringBuilder(“?”)//Objectcreationstatement,non-void
return
value->value++//Incrementstatement,non-voidreturn
value->value*=2//Assignmentstatement,non-voidreturn
Thefollowingexamplesarenotlegallambdaexpressions:
Clickheretoviewcodeimage
(inti)->while(i<10)++i//Illegal:notanexpressionbutastatement
(x,y)->returnx+y//Illegal:returnnotallowedinexpression
Thestatementblockcomprisesdeclarationsandstatementsenclosedinbraces({}).The
returnstatementisallowedonlyinablocklambdabody.
Clickheretoviewcodeimage
()->{}//Blockbody,voidreturn
()->{return2015;}//Blockbody,non-voidreturn
()->{return2015}//Illegal:statementterminator(;)inblock
missing
()->{newStringBuilder(“Gonuts.”);}//Blockbody,voidreturn
()->{returnnewStringBuilder(“Gonuts!”);}//Blockbody,non-void
return
(inti)->{while(i<10)++i;}//Blockbody,voidreturn
(i,j)->{if(i<=j)returni;elsereturnj;}//Blockbody,non-void
return
(done)->{//Multiplestatementsinblockbody,void
return
if(done){
System.out.println(“Youdeserveabreak!”);
return;
}
System.out.println(“Stayrighthere!”);
}
WOW! eBook
www.wowebook.org
AccessingMembersintheEnclosingClass
Sincealambdaexpressionisnotassociatedwithanyclass,thereisnonotionofathis
referenceassociatedwithit.Ifitisusedinalambdaexpression,thethisreferencerefers
totheenclosingobject,andcanbeusedtoaccessmembersofthisobject.Thenameofa
memberintheenclosingobjecthasthesamemeaningwhenusedinalambdaexpression.
Inotherwords,therearenorestrictionsonaccessingmembersintheenclosingobject.In
thecaseofshadowingmembernames,thekeywordthiscanbeexplicitlyused,andthe
keywordsupercanbeusedtoaccessanymembersinheritedbytheenclosingobject.
InExample10.6,thegetPredicate()methodat(7)definesalambdaexpressionat
(8).ThislambdaexpressionaccessesthestaticfieldstrListandtheinstancefield
bannerintheenclosingclassat(1)and(2),respectively.
Inthemain()methodinExample10.6,anArrayListisassignedtothestatic
fieldstrListat(3)andisinitialized.TheArrayListreferredtobythestaticfield
strListhasthefollowingcontent:
Clickheretoviewcodeimage
[Otto,ADA,Alyla,Bob,HannaH,Java]
AMembersOnlyobjectiscreatedat(4).ItsStringBuilderfieldbanneris
initializedwiththestring"love",andthelocalvariableobjreferstothis
MembersOnlyobject.At(5),aPredicateobjectiscreatedbycallingthe
getPredicate()methodontheMembersOnlyobjectreferredtobythelocal
variableobj.Thispredicateisfirstevaluatedwhenthetest()methodiscalledat(6)
onthePredicateobject,withtheargumentstring"neverdies!".Callingthe
test()methodresultsinthelambdaexpressioncreatedat(5)bythe
getPredicate()methodbeingevaluatedintheenclosingMembersOnlyobject
referredtobythelocalvariableobj.
Theparameterstrofthelambdaexpressionisinitializedwiththestring"never
dies!",theargumenttothetest()method.Inthebodyofthelambdaexpression,the
ArrayListreferredtobythestaticfieldstrListisfirstprintedat(9):
Clickheretoviewcodeimage
List:[Otto,ADA,Alyla,Bob,HannaH,Java]
At(10),theparameterstr(withcontents"neverdies!")isappendedtothe
StringBuilder(withcontents"love")referredtobytheinstancefieldbannerin
theenclosingobject,resultinginthefollowingcontentsinthisStringBuilder:
“loveneverdies!”
Sincethelengthofthestring"neverdies!",referredtobytheparameterstr,is
greaterthan5,thelambdaexpressionreturnstrueat(11).Thisisthevaluereturnedby
thetest()methodcallin(6).
Inthecalltotheprintln()methodat(6),theargument
Clickheretoviewcodeimage
WOW! eBook
www.wowebook.org
p.test(“neverdies!”)+””+obj.banner
nowevaluatesas
Clickheretoviewcodeimage
true+””+“loveneverdies!”
Example10.6AccessingMembersinanEnclosingObject
Clickheretoviewcodeimage
importjava.util.ArrayList;
importjava.util.List;
importjava.util.function.Predicate;
publicclassMembersOnly{
//Instancevariable
privateStringBuilderbanner;//(1)
//Staticvariable
privatestaticList<String>strList;//(2)
//Constructor
publicMembersOnly(Stringstr){
banner=newStringBuilder(str);
}
//Staticmethod
publicstaticvoidmain(String[]args){
strList=newArrayList<>();//(3)
strList.add(“Otto”);strList.add(“ADA”);strList.add(“Alyla”);
strList.add(“Bob”);strList.add(“HannaH”);strList.add(“Java”);
MembersOnlyobj=newMembersOnly(“love“);//(4)
Predicate<String>p=obj.getPredicate();//(5)
System.out.println(p.test(“neverdies!”)+””+obj.banner);//(6)
}
//Instancemethod
publicPredicate<String>getPredicate(){//(7)
returnstr->{//(8)Lambda
expression
System.out.println(“List:”+strList);//
(9)MembersOnly.strList
banner.append(str);//(10)this.banner
returnstr.length()>5;//(11)booleanvalue
};
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
List:[Otto,ADA,Alyla,Bob,HannaH,Java]
trueloveneverdies!
WOW! eBook
www.wowebook.org
AccessingLocalVariablesintheEnclosingContext
Asmentionedearlier,alambdaexpressionisnotassociatedwithaclassoranyofits
members.Apartfromnothavingathisreference,alambdaexpressionalsodoesnot
createitsownscope.Instead,itispartofthescopeoftheenclosingcontext—ithaslexical
orblockscope(§4.4,p.117).Allvariabledeclarationsinalambdaexpressionfollowthe
rulesofblockscoping.Theyarenotaccessibleoutsideofthelambdaexpression.In
addition,wecannotredeclarelocalvariablesalreadydeclaredintheenclosingscope.In
Example10.7,redeclaringthelocalvariablesbannerandwordsat(6)and(7),
respectively,resultsinacompile-timeerror.
Localvariablesdeclaredintheenclosingmethod,includingitsformalparameters,canbe
accessedinalambdaexpressionprovidedtheyareeffectivelyfinal.Thismeansthatoncea
localvariablehasbeenassignedavalue,itsvaluedoesnotchangeinthemethod.Using
thefinalmodifierinthedeclarationofalocalvariableexplicitlyinstructsthecompiler
toensurethatthisisthecase.Thefinalmodifierimplieseffectivelyfinal.Ifthefinal
modifierisomittedandalocalvariableisusedinalambdaexpression,thecompiler
effectivelyperformsthesameanalysisasifthefinalmodifierhadbeenspecified.A
lambdaexpressionmightbeexecutedatalatertime,afterthemethodhasfinished
execution.Atthatpoint,thelocalvariablesusedinthelambdaexpressionarenolonger
accessible.Toensuretheiravailability,copiesoftheirvaluesaremaintainedwiththe
lambdaexpression.Thisiscalledvariablecapture,althoughinessenceitisthevaluesthat
arecaptured.Notethatitisnottheobjectthatiscopiedinthecaseofalocalreference
variable,butratherthereferencevalue.Objectsresideontheheapandareaccessibleviaa
copyofthereferencevalue.Correctexecutionofthelambdaexpressionisguaranteed,
sincetheseeffectivelyfinalvaluescannotchange.Notethatthestateofanobjectreferred
tobyafinaloraneffectivelyfinalreferencecanchange,butnotthereferencevaluein
thereference;thus,suchareferencewillcontinuerefertothesameobjectonceitis
initialized.
InExample10.7,themethodgetPredicate()at(1)hasoneformalparameter
(banner),andalocalvariable(words)declaredat(2).Althoughthestateofthe
ArrayListobject,referredtobythereferencewords,ischangedinthemethod(we
addelementstoit),thereferencevalueinthereferencedoesnotchange;thatis,it
continuestorefertothesameobjectwhosereferencevalueitwasassignedat(2).The
parameterbannerisassignedthereferencevalueoftheargumentobjectwhenthe
methodisinvoked,andcontinuestorefertothisobjectthroughoutthemethod.Bothlocal
variablesareeffectivelyfinal.Theirvaluesarecapturedbythelambdaexpression,and
usedwhenthelambdaexpressionisexecutedafterthecalltothegetPredicate()
methodinthemain()method.
Ifweuncomment(3)and(4)inExample10.7,thenbothlocalvariablesarenoteffectively
final.Theirreferencevaluesarechangedat(3)and(4),respectively.Thecompilernow
flagserrorsin(8)and(9),respectively,becausethesenon-finallocalvariablesareusedin
thelambdaexpression.
WOW! eBook
www.wowebook.org
Example10.7AccessingLocalVariablesinanEnclosingMethod
Clickheretoviewcodeimage
importjava.util.ArrayList;
importjava.util.List;
importjava.util.function.Predicate;
publicclassLocalsOnly{
publicstaticvoidmain(String[]args){
StringBuilderbanner=newStringBuilder(“love“);
LocalsOnlyinstance=newLocalsOnly();
Predicate<String>p=instance.getPredicate(banner);
System.out.println(p.test(“neverdies!”)+””+banner);
}
publicPredicate<String>getPredicate(StringBuilderbanner){//(1)
List<String>words=newArrayList<>();//(2)
words.add(“Otto”);words.add(“ADA”);words.add(“Alyla”);
words.add(“Bob”);words.add(“HannaH”);words.add(“Java”);
//banner=newStringBuilder();//(3)Illegal:Noteffectively
final
//words=newArrayList<>();//(4)Illegal:Noteffectively
final
returnstr->{//(5)Lambdaexpression
//Stringbanner=“Don’tredeclareme!”;//(6)Illegal:
Redeclared
//String[]words=newString[6];//(7)Illegal:
Redeclared
System.out.println(“List:”+words);//(8)
banner.append(str);//(9)
returnstr.length()>5;
};
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
List:[Otto,ADA,Alyla,Bob,HannaH,Java]
trueloveneverdies!
TypeCheckingandExecutionofLambdaExpressions
Theuseoflambdaexpressionsistightlycoupledwithfunctionalinterfaces.Alambda
expressioncanbedefinedinacontextwhereafunctionalinterfacecanbeused—for
example,inanassignmentcontext,amethodcallcontext,oracastcontext.Thecompiler
determinesthetargettypethatisrequiredinthecontextwherethelambdaexpressionis
defined.Thistargettypeisalwaysafunctionalinterfacetype.Intheassignmentcontext
thatfollows,thetargettypeisPredicate<Integer>,asitisthetargetofthe
assignmentstatement.NotethatthetypeparameterTofthefunctionalinterfaceis
Integer.
Clickheretoviewcodeimage
Predicate<Integer>p1=i->i%2==0;//(1)Targettype:
WOW! eBook
www.wowebook.org
Predicate<Integer>
Themethodtypeofamethoddeclarationcomprisesitstypeparameters,formalparameter
types,returntype,andanyexceptionsthemethodthrows.
Thefunctiontypeofafunctionalinterfaceisthemethodtypeofitssingleabstractmethod.
ThetargettypePredicate<Integer>hasthefollowingmethod,wheretype
parameterTisInteger:
Clickheretoviewcodeimage
publicbooleantest(Integert);//Methodtype:Integer->boolean
ThefunctiontypeofthetargettypePredicate<Integer>isthemethodtypeofthe
thistest()method:
Integer->boolean
Thetypeofthelambdaexpressiondefinedinagivencontextmustbecompatiblewiththe
functiontypeofthetargettype.Ifthelambdaexpressionhasinferred-typeparameters,
theirtypeisinferredfromthefunctiontype,andifnecessaryfromthecontext.Fromthe
functiontypeofthetargettypePredicate<Integer>,thecompilercaninferthatthe
parameteriinthelambdaexpressionat(1)shouldbeoftypeInteger.Thelambda
bodyreturnsabooleanvalue.Thetypeofthelambdaexpressionin(1)is
Integer->boolean
Thetypeofthelambdaexpressioniscompatiblewiththefunctiontypeofthetargettype
Predicate<Integer>.
Inthefollowingassignment,thetargettypeis
java.util.function.IntPredicate:
Clickheretoviewcodeimage
IntPredicatep2=i->i%2==0;//(2)Targettype:IntPredicate
TheIntPredicatefunctionalinterfacehasthefollowingabstractmethod:
Clickheretoviewcodeimage
publicbooleantest(inti);//Methodtype:int->boolean
ThefunctiontypeofthetargettypeIntPredicateisthemethodtypeofitsabstract
method:
int->boolean
Thecompilerinfersthatthetypeoftheinferred-typeparameteriinthelambda
expressionat(2)shouldbeint.Asthelambdabodyreturnsabooleanvalue,thetype
ofthelambdaexpressionin(2)is
int->boolean
Thetypeofthelambdaexpressioniscompatiblewiththefunctiontypeofthetargettype
IntPredicate.
Notethatinbothexamples,thelambdaexpressionisthesame,buttheirtypesaredifferent
inthetwocontexts:Theyrepresenttwodifferentvalues.Thetypeofalambdaexpression
isdeterminedbythecontextinwhichitisdefined.
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
System.out.println(p1==p2);//false
Theprocessoftypecheckingalambdaexpressioninagivencontextiscalledtarget
typing.Thepresentationhereissimplified,butsufficesforourpurposestogiveanideaof
whatisinvolved.
Thecompilerdoesthetypecheckingnecessarytouselambdaexpressions,andthe
runtimeenvironmentprovidestherestofthemagictomakeitallwork.Atruntime,the
lambdaexpressionisexecutedwhenthesoleabstractmethodofthefunctionalinterfaceis
invoked.Asmentionedearlier,thisisanexampleofdeferredexecution.Lambda
executionissimilartoinvokingamethodonanobject.Wedefinealambdaexpressionas
afunctionanduseitlikeamethod,lettingthecompilerandtheruntimeenvironmentputit
alltogether.
Clickheretoviewcodeimage
booleanresult1=p1.test(2015);//false
booleanresult2=p2.test(2016);//true
FilteringRevisited:The FunctionalInterface
Example10.8includesthetwopreviousexamplesoffilteringalistforpalindromesat(2)
and(3).Inaddition,itpresentsseveralexamplesoffilteringalistusingdifferentcriteria
definedonpropertiesofastring.Determiningwhetherastringisacase-sensitiveorcase-
insensitivepalindromeisnowdonebythetwostaticmethods
isCaseSensitivePalindrome()andisCaseInsensitivePalindrome(),
respectively.AlsonotethatthefilterStrings()method,whichweusedearlier,is
nowagenericmethodtofilteranylist,notjustalistofstrings,(14).
TheexamplesinExample10.8haveintentionallybeenwrittentoillustratethesyntaxof
lambdaexpressions.Wedrawattentiontothepredicateat(11)thattakesintoaccount
whetherthestringelementhasanullvalue,whetheritisanemptystring,andwhether
itslengthisgreaterthan3,beforetestingitforapalindrome:
Clickheretoviewcodeimage
Predicate<String>predicateE=str->//(11)
str!=null&&!str.equals(””)&&str.length()>3
&&isCaseSensitivePalindrome(str);
ThislambdaexpressionavoidsthrowingaNullPointerException.Thereareother,
moresophisticatedwaysofdealingwithaNullPointerException,buttheyare
beyondthescopeofthisbook.ThePredicate<T>interfacealsoprovidesmethodsto
composecompoundpredicates.
Thefilteringexamplesinthischaptermakeheavyuseoftraversaloveralistusingaloop.
Functional-styleprogrammingfreesusfromthetyrannyofexplicittraversalover
collections,butwehavemerelyscratchedthesurfacehere.Earlierinthischapter(p.424),
wediscussedtheremovalofelementsfromalist.TheremoveIf()methodofthe
ArrayListclassprovidesasafeandconvenientwayofdeletingallelementsthatsatisfy
anycriteriaexpressedasaPredicate<T>.Thus,thetraversalprocessisnowinternal.
Thelambdaexpressionin(11)testswhetherthestringcontainsthecharactera.Allstrings
WOW! eBook
www.wowebook.org
satisfyingthiscriterionareremovedfromthelist,asconfirmedbytheoutputfromthe
program.
Clickheretoviewcodeimage
words.removeIf(str->str.indexOf(‘a’)>0);//(12)
Anotherexampleoftheuseofthismethodisgivenin(13),whereitisusedtoremoveall
stringswithlengthgreaterthan3:
Clickheretoviewcodeimage
words.removeIf(str->str.length()>3);//(13)
ItisinstructivetowalkthroughthecodeinExample10.8,andcompareittothesolution
weinitiallywroteinExample10.2,p.434.
Example10.8FilteringanArrayList
Clickheretoviewcodeimage
importjava.util.ArrayList;
importjava.util.List;
importjava.util.function.Predicate;
publicclassFunWithPalindromesV4{
privatestaticbooleanisCaseSensitivePalindrome(Stringstr){
returnstr.equals(newStringBuilder(str).reverse().toString());
}
privatestaticbooleanisCaseInsensitivePalindrome(Stringstr){
returnstr.equalsIgnoreCase(newStringBuilder(str).reverse().toString());
}
publicstaticvoidmain(String[]args){
//Createalistofwords://
(1)
List<String>words=newArrayList<>();
words.add(“Otto”);words.add(“ADA”);words.add(“Alyla”);
words.add(“Bob”);words.add(“HannaH”);words.add(“Java”);
System.out.println(“Listofwords:”+words);
List<String>palindromes1=filterStrings(words,//
(2)
str->isCaseSensitivePalindrome(str));
System.out.println(“Case-sensitivepalindromes:”+palindromes1);
List<String>palindromes2=filterStrings(words,str->//
(3)
isCaseInsensitivePalindrome(str));
System.out.println(“Case-insensitivepalindromes:”+palindromes2);
Predicate<String>predicate3=str->!isCaseSensitivePalindrome(str);//
(4)
List<String>nonPalindromes=filterStrings(words,predicate3);
System.out.println(“Non-palindromes,casesensitive:”+nonPalindromes);
Predicate<String>predicate4=str->str.length()>3;//
(5)
List<String>strGT3=filterStrings(words,predicate4);
System.out.println(“Wordswithlength>3:”+strGT3);
WOW! eBook
www.wowebook.org
Predicate<String>predicate5=str->//
(6)
str.length()>3&&isCaseSensitivePalindrome(str);
List<String>palindromesGT3=filterStrings(words,predicate5);
System.out.println(“Case-sensitivepalindromes,length>3:“
+palindromesGT3);
Predicate<String>predicateA=str->{//
(7)
returnstr.length()>3&&isCaseSensitivePalindrome(str);
};
System.out.println(“Case-sensitivepalindromes,length>3:“
+filterStrings(words,predicateA));
Predicate<String>predicateB=str->{//
(8)
booleanresult1=str.length()>3;
booleanresult2=isCaseSensitivePalindrome(str);
returnresult1&&result2;
};
System.out.println(“Case-sensitivepalindromes,length>3:“
+filterStrings(words,predicateB));
Predicate<String>predicateC=str->{//
(9)
if(str==null||str.equals(””)||str.length()<=3){
returnfalse;
}
StringBuildersb=newStringBuilder(str);
booleanresult=str.equals(sb.reverse().toString());
returnresult;
};
System.out.println(“Case-sensitivepalindromes,length>3:“
+filterStrings(words,predicateC));
Predicate<String>predicateD=str->//
(10)
(str==null||str.equals(””)||str.length()<=3)
?false:isCaseSensitivePalindrome(str);
System.out.println(“Case-sensitivepalindromes,length>3:“
+filterStrings(words,predicateD));
Predicate<String>predicateE=str->//
(11)
str!=null&&!str.equals(””)&&str.length()>3
&&isCaseSensitivePalindrome(str);
System.out.println(“Case-sensitivepalindromes,length>3:“
+filterStrings(words,predicateE));
//Removingelementsfromalist:
words.removeIf(str->str.indexOf(‘a’)>0);//
(12)
System.out.println(“Listofwords,no‘a’:”+words);
words.removeIf(str->str.length()>3);//
(13)
System.out.println(“Listofwords,length<=3:”+words);
}
/**
*Filtersalistaccordingtothecriteriaofthepredicate.
WOW! eBook
www.wowebook.org
*@paramlistListtofilter
*@parampredicateProvidesthecriteriaforfilteringthelist
*@returnListofelementsthatmatchthecriteria
*/
publicstatic<E>List<E>filterStrings(List<E>list,//
(14)
Predicate<E>predicate){
List<E>result=newArrayList<>();
for(Eelement:list)
if(predicate.test(element))
result.add(element);
returnresult;
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
Listofwords:[Otto,ADA,Alyla,Bob,HannaH,Java]
Case-sensitivepalindromes:[ADA,HannaH]
Case-insensitivepalindromes:[Otto,ADA,Alyla,Bob,HannaH]
Non-palindromes,casesensitive:[Otto,Alyla,Bob,Java]
Wordswithlength>3:[Otto,Alyla,HannaH,Java]
Case-sensitivepalindromes,length>3:[HannaH]
Case-sensitivepalindromes,length>3:[HannaH]
Case-sensitivepalindromes,length>3:[HannaH]
Case-sensitivepalindromes,length>3:[HannaH]
Case-sensitivepalindromes,length>3:[HannaH]
Case-sensitivepalindromes,length>3:[HannaH]
Listofwords,no‘a’:[Otto,ADA,Bob]
Listofwords,length<=3:[ADA,Bob]
ReviewQuestions
10.7Whichstatementistrueaboutfunctionalinterfacesandlambdaexpressions?
Selecttheonecorrectanswer.
(a)Afunctionalinterfacecanbeimplementedonlybylambdaexpressions.
(b)Afunctionalinterfacedeclarationcanhaveonlyonemethoddeclaration.
(c)Inthebodyofalambdaexpression,onlypublicmembersintheenclosing
classcanbeaccessed.
(d)Inthebodyofalambdaexpression,alllocalvariablesintheenclosingscope
canbeaccessed.
(e)Alambdaexpressioninaprogramcanimplementonlyonefunctionalinterface.
(f)Noneoftheabove.
10.8Whichstatementsaretrueaboutthefollowingcode?
Clickheretoviewcodeimage
importjava.util.function.Predicate;
publicclassRQ12A98{
publicstaticfinalStringlock1=“Brinks”;
privatestaticStringlock2=“Yale”;
WOW! eBook
www.wowebook.org
publicstaticvoidmain(String[]args){
Predicate<Object>p;
p=lock->{booleanp=lock.equals(“Master”);returnp;
};//(1)
p=lock->{returnlock.toString().equals(“YALE”);
};//(2)
p=lock->{(args.length>0)?lock.equals(args[0]):false;
};//(3)
p=lock->{returnlock.equals(lock1);
};//(4)
p=lock->{returnlock.equals(lock2);
};//(5)
p=lock2->{returnlock2.equals(RQ12A98.lock2);
};//(6)
}
}
Selectthetwocorrectanswers.
(a)(1)willnotcompile.
(b)(2)willnotcompile.
(c)(3)willnotcompile.
(d)(4)willnotcompile.
(e)(5)willnotcompile.
(f)(6)willnotcompile.
10.9Whichstatementsaretrueaboutthefollowingcode?
Clickheretoviewcodeimage
interfaceFunky1{voidabsMethod1(Strings);}
interfaceFunky2{StringabsMethod2(Strings);}
publicclassRQ12A99{
publicstaticvoidmain(String[]args){
Funky1p1;
p1=s->System.out.println(s);//(1)
p1=s->s.length();//(2)
p1=s->s.toUpperCase();//(3)
p1=s->{s.toUpperCase();};//(4)
p1=s->{returns.toUpperCase();};//(5)
Funky2p2;
p2=s->System.out.println(s);//(6)
p2=s->s.length();//(7)
p2=s->s.toUpperCase();//(8)
p2=s->{s.toUpperCase();};//(9)
p2=s->{returns.toUpperCase();};//(10)
}
}
Selectthefourcorrectanswers.
(a)(1)willnotcompile.
(b)(2)willnotcompile.
WOW! eBook
www.wowebook.org
(c)(3)willnotcompile.
(d)(4)willnotcompile.
(e)(5)willnotcompile.
(f)(6)willnotcompile.
(g)(7)willnotcompile.
(h)(8)willnotcompile.
(i)(9)willnotcompile.
(j)(10)willnotcompile.
10.10Whichstatementistrueaboutthefollowingprogram?
Clickheretoviewcodeimage
importjava.util.Arrays;
importjava.util.function.IntPredicate;
publicclassRQ12A96{
publicstaticvoidmain(String[]args){
int[]intArray={0,-1,-2,-3,-4,-5,-6,-7,-8,-9};
filterInt(intArray,val->val<0&&val%2==0);
System.out.println(Arrays.toString(intArray));
}
publicstaticvoidfilterInt(int[]intArr,
IntPredicatepredicate){
for(inti=0;i<intArr.length;++i){
if(predicate.test(intArr[i])){
intArr[i]=Math.abs(intArr[i]);
}
}
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile.
(b)Theprogramwillcompile,butwillthrowanexceptionwhenrun.
(c)Theprogramwillcompileandprintthefollowingwhenrun:
[0,1,-2,3,-4,5,-6,7,-8,9]
(d)Theprogramwillcompileandprintthefollowingwhenrun:
[0,-1,2,-3,4,-5,6,-7,8,-9]
(e)Theprogramwillcompileandprintthefollowingwhenrun:
[0,1,2,3,4,5,6,7,8,9]
10.11Whichstatementistrueaboutthefollowingcode?
Clickheretoviewcodeimage
interfaceInterfaceA{voiddoIt();}
interfaceInterfaceBextendsInterfaceA{}
interfaceInterfaceCextendsInterfaceB{
WOW! eBook
www.wowebook.org
voiddoIt();
booleanequals(Objectobj);
}
classBetaimplementsInterfaceB{
publicvoiddoIt(){
System.out.print(“Jazz|”);
}
}
publicclassRQ12A999{
publicstaticvoidmain(String[]args){
InterfaceAa=()->System.out.print(“Java|”);//(1)
InterfaceBb=()->System.out.print(“Jive|”);//(2)
InterfaceCc=()->System.out.print(“Jingle|”);//(3)
Objecto=a=c;//(4)
b=newBeta();//(5)
a.doIt();//(6)
b.doIt();//(7)
c.doIt();//(8)
((InterfaceA)o).doIt();//(9)
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile.
(b)TheprogramwillthrowaClassCastException.
(c)Theprogramwillprint:Jingle|Jingle|Jazz|Jingle|
(d)Theprogramwillprint:Jingle|Jazz|Jingle|Jingle|
(e)Theprogramwillprint:Jingle|Jingle|Jingle|Jazz|
ChapterSummary
Thefollowingtopicswerecoveredinthischapter:
•Theconceptofalistasacollection
•TheinheritancerelationshipbetweentheArrayList<E>class,theList<E>
interface,andtheCollection<E>interfaceintheJavaCollectionsFramework
•Useofthediamondoperator(<>)whencreatingobjectsofgenericclasses
•DeclaringandusingreferencesoftheArrayListtype
•Creating,querying,traversing,converting,andsortingArrayLists
•ComparisonofarraysandArrayLists
•Behaviorparameterizationinfunctional-styleprograming
•Theroleoflambdaexpressionsandfunctionalinterfacesinimplementingbehavior
parameterization
•Referencingthegeneral-purposefunctionalinterfacesinthe
WOW! eBook
www.wowebook.org
java.util.functionpackage
•ImplementingthePredicate<T>functionalinterfaceusinglambdaexpressions
•DefiningselectioncriteriaaspredicatesforfilteringArrayLists
•Definingandtypecheckinglambdaexpressionsinthecontextofafunctional
interface
•Thedeferredexecutionofalambdaexpression
•Theimplicationsofusingclassmembersfromtheenclosingclass,andofusinglocal
variablesfromtheenclosingmethod
•Passingandassigninglambdavaluesusingfunctionalinterfacereferences
ProgrammingExercise
10.1Findallelementsinalistthatsatisfyallgivenpredicates.
Skeletoncodeforthisproblemisprovidedinthisexercise.Themain()methodat
(1)createsalistofstringsfromanarrayofstrings.Italsocreatesalistof
predicates.Thefollowingpredicatesshouldbeincludedinthislist:
•Astringisnotnull.
•Astringcontainsthesubstring"up"byfirstconvertingthestringtolowercase.
•Thefirstcharacterofastringisaletter.
Themain()methodcallsthemethodsat(2),(4),and(5).Theoutputfromthe
programisshownhere.Thetextualrepresentationofthelambdaexpressionsmight
vary.
Clickheretoviewcodeimage
[Cheerup!,7Upcomingup!,null,Bottomsup!,Getdown!,What’sup?]
[FilterFun$$Lambda$1/12251916@192e0f4,
FilterFun$$Lambda$2/18340259@a418fc,
FilterFun$$Lambda$3/19888781@105068a]
[Cheerup!,Bottomsup!,What’sup?]
[Cheerup!,Bottomsup!,What’sup?]
[Cheerup!,Bottomsup!,What’sup?]
Completetheimplementationofthemain()method,andatleastimplementthe
methodsat(2)and(3).
Toimplementthemethodsat(4)and(5),seethemethodsand()andnegate()
providedbythejava.util.function.Predicate<T>interface.
Themethodsat(4)and(5)alsomakeuseoftheArrayList.removeIf()
method.
Themethodat(5)isastraightforwardgenericversionofthemethodat(4),sothat
anylistcanbefilteredthisway.
Clickheretoviewcodeimage
WOW! eBook
www.wowebook.org
importjava.util.ArrayList;
importjava.util.List;
importjava.util.function.Predicate;
publicclassFilterFun{
publicstaticvoidmain(String[]args){//
(1)
//Createalistofstrings:
String[]strings={“Cheerup!”,“7Upcomingup!”,null,
“Bottomsup!”,“Getdown!”,“What’sup?”};
List<String>strList=newArrayList<>();
/*WRITECODETOPOPULATETHELISTOFSTRINGSHERE.*/
System.out.println(strList);
//Createalistofpredicates.
List<Predicate<String>>predList=newArrayList<>();
/*WRITECODETOPOPULATETHELISTOFPREDICATESHERE.*/
System.out.println(predList);
//Applyfiltering.
applyAllPredicates(strList,predList);
applyAllPredicatesAlt(strList,predList);
applyAllPredicatesGenAlt(strList,predList);
}
/**
*Printsallthestringsinthespecifiedlistthatsatisfyallthe
*predicatesinthelistofpredicates.
*ItusestheandPredicates()methodat(3).
*@paramlistListofstringstoapplythepredicateson
*@parampredicatesListofpredicatestoapply
*/
publicstaticvoidapplyAllPredicates(List<String>list,//
(2)
List<Predicate<String>>predicates){
/*IMPLEMENTTHISMETHOD*/
}
/**
*Determineswhetherastringsatisfiesallthepredicates.
*@paramstrStringtoapplythepredicateson
*@parampredicatesListofpredicatestoapply
*@returntrueonlyifthestringsatisfiesallthepredicates
*/
publicstaticbooleanandPredicates(Stringstr,//
(3)
List<Predicate<String>>predicates){
/*IMPLEMENTTHISMETHOD*/
}
/**
*Removesalltheelementsinthespecifiedlistthatdonotsatisfyall
the
*predicatesinthelistofpredicates,andprintstheremainingelements
*thatdo.
*UsesPredicate.and(),Predicate.negate(),andList.removeIf()methods.
*@paramlistListofstringstoapplythepredicateson
*@parampredicatesListofpredicatestoapply
*/
publicstaticvoidapplyAllPredicatesAlt(List<String>list,//
(4)
List<Predicate<String>>
WOW! eBook
www.wowebook.org
predicates){
/*IMPLEMENTTHISMETHOD*/
}
/**Genericversion.
*Removesalltheelementsinthespecifiedlistthatdonotsatisfyall
the
*predicatesinthelistofpredicates,andprintstheremainingelements
*thatdo.
*UsesPredicate.and(),Predicate.negate(),andList.removeIf()methods.
*@paramlistListofelementstoapplythepredicateson
*@parampredicatesListofpredicatestoapply
*/
publicstatic<T>voidapplyAllPredicatesGenAlt(List<T>list,//
(5)
List<Predicate<T>>predicates){
/*IMPLEMENTTHISMETHOD*/
}
}
WOW! eBook
www.wowebook.org
11.DateandTime
11.1BasicDateandTimeConcepts
Java8introducedanewcomprehensiveAPIforhandlingtemporalconcepts.Inthis
chapter,weprimarilyconcentrateonclassesthatrepresentthedate,time,andperiod.The
Java8APIalsoprovidessupportforformattingandparsingtemporalobjects.These
classesareallbasedontheISOcalendarsystem,whichisthedefactoworldcalendar.The
DateandTimeAPIisfairlycomprehensive,andincludessupportforothertemporal
conceptssuchasinstants,durations,offsets,timezones,anddifferentcalendars—topics
thatarebeyondthescopeofthisbook.
Wewillusethetermtemporalobjectstomeanobjectsofclassesthatrepresenttemporal
concepts.Twopackagesprovidethemainsupportforhandling,formatting,andparsing
temporalobjects:
•Thejava.timepackageprovidestheclassesLocalDate,LocalTime,
LocalDateTime,andPeriodthatrepresentadate,a(clock)time,acombined
date-time,andaperiod,respectively.
LocalDate:Thisclassrepresentsadateintermsofdate-basedvalues(year,
month,day).Dateobjectshavenotime-basedvaluesoratimezone.
LocalTime:Thisclassrepresentstimeina24-hourdayintermsoftime-based
values(hours,minutes,seconds,nanoseconds).Timeobjectshavenodate-based
WOW! eBook
www.wowebook.org
valuesoratimezone.
LocalDateTime:Thisclassrepresentstheconceptofdateandtimecombined,in
termsofbothdate-basedandtime-basedvalues.Date-timeobjectshavenotime
zone.
Period:Thisclassrepresentsadirectedamountorquantityoftimeintermsof
numberofdays,months,andyears,whichcanbenegative.Periodobjectshaveno
notionofaclocktime,adate,oratimezone.
•Thejava.time.formatpackageprovidestheclassDateTimeFormatter
forformattingandparsingtemporalobjects.
DateTimeFormatter:Thisclassprovidesimplementationofformatters:
predefinedformatters(e.g.,DateTimeFormatter.ISO_LOCAL_TIME),and
localizedformattersthatusepredefinedformatstyles(e.g.,
FormatStyle.SHORT),andcustomizedformattersthatuseletterpatterns(e.g.,
"MM/dd/uuuu").Aformattercanbeusedtoobtainastringrepresentationofa
temporalobject(calledformatting),andconverselytoobtainatemporalobjectfrom
astring(calledparsing).
Thischapterprovidesexamplesdemonstratinghowtocreate,combine,convert,query,
compare,format,andparsetemporalobjects,includingtheuseoftemporalarithmetic.
11.2WorkingwithTemporalClasses
Thetemporalclassesimplementimmutableandthread-safetemporalobjects.Thestateof
animmutableobjectcannotbechanged.Anymethodthatissupposedtomodifysuchan
objectreturnsamodifiedcopyofthetemporalobject.Itisacommonmistaketoignore
thenewobject,thinkingthatthecurrentobjecthasbeenmodified,whichcanleadto
incorrectresults.Thread-safetyguaranteesthatthestateofsuchanobjectisnotaffected
byconcurrentaccess.
Anothercommonmistakeistoaccess,format,orparseatemporalobjectthatdoesnot
havetherequiredtemporalvalues.Forexample,aLocalTimeobjecthasonlytime-
basedvalues,sotryingtoformatitwithaformatterfordate-basedvalueswillresultina
java.time.DateTimeException.Manymethodswillalsothrowanexceptionifan
invalidoranout-of-rangeargumentispassedinthemethodcall.Itisimportanttokeepin
mindwhichtemporalvaluesconstitutethestateofatemporalobject.
Hereweignoretheimplicationsofatimezone,sincethetemporalobjectsdiscussedin
thischapteraretimezoneagnostic.However,thecoverageherewillfacilitatethe
inquisitivereadertofurtherexplorethefeaturesoftheDateandTimeAPI.
BeforedivingintotheDateandTimeAPI,weprovideanoverviewofthemethodnaming
conventionsusedinthetemporalclasses(Table11.1).Thismethodnamingconvention
makesiteasytousetheAPI,asitensuresmethodnamingisstandardizedacrossall
temporalclasses.
WOW! eBook
www.wowebook.org
Table11.1SelectedCommonMethodPrefixoftheTemporalClasses
ThetemporalclassesLocalTime,LocalDate,andLocalDateTimeareallfoundin
thejava.timepackage.Anappropriateimportstatementshouldbeincludedinthe
sourcefiletouseanyoftheseclasses.
CreatingTemporalObjects
Thetemporalclassesdonotprovideanypublicconstructorstocreatetemporalobjects.
Instead,theyprovideoverloadedstaticfactorymethodsnamedofwithwhichtocreate
temporalobjectsfromconstituenttemporalvalues.Weusethetermtemporalvaluesto
meanbothtime-basedanddate-basedvalues.Theof()methodscheckthatthevaluesof
theargumentsareinrange.Anyinvalidargumentresultsina
java.time.DateTimeException.
AllcodesnippetsinthissubsectioncanbefoundinExample11.1,p.467,readyfor
runningandexperimenting.
Thedeclarationstatementsthatfollowshowexamplesofcreatinginstancesofthe
LocalTimeclasstorepresenttimeona24-hourclockintermsofhours,minutes,
seconds,andnanoseconds.Therangesofvaluesforthehours(0–23),minutes(0–
59),seconds(0–59),andnanoseconds(0–999,999,999)aredefinedbytheISOstandard.
ThetoString()methodoftheclasswillformatthetime-basedvaluesaccordingtothe
ISOstandardasHH:mm:ss.SSSSSSSSS.Omittingtheseconds(ss)andfractionsof
WOW! eBook
www.wowebook.org
seconds(SSSSSSSSS)impliesthattheirvalueiszero.(Moreonformattingin§11.4,p.
495.)Intheseconddeclarationstatement,thesecondsandthenanosecondsarenot
specifiedinthemethodcall,resultingintheirvaluesbeingsettozero.Inthethird
statement,thehourvalue(25)isoutofrange,andifuncommented,willresultina
DateTimeException.
Clickheretoviewcodeimage
LocalTimetime1=LocalTime.of(8,15,35,900);//08:15:35.000000900
LocalTimetime2=LocalTime.of(16,45);//16:45
//LocalTimetime3=LocalTime.of(25,13,30);//DateTimeException
CreatinginstancesoftheLocalDateclassisanalogoustocreatinginstancesofthe
LocalTimeclass.Theof()methodoftheLocalDateclassispasseddate-based
values:theyear,monthoftheyear,anddayofthemonth.Therangesofthevaluesforthe
year,themonth,andthedayare(–999,999,999to+999,999,999),(1–12),and(1–31),
respectively.Themonthcanalsobespecifiedusingtheenumconstantsofthe
java.time.Monthclass,asintheseconddeclarationstatementinthenextsetof
examples.ADateTimeExceptionisthrownifthevalueofanyparameterisoutof
range,orifthedayisinvalidforthespecifiedmonthoftheyear.Inthethirddeclaration,
themonthvalue13isoutofrange.Inthelastdeclaration,themonthofFebruarycannot
have29days,sincetheyear2015isnotaleapyear.
Clickheretoviewcodeimage
LocalDatedate1=LocalDate.of(1969,7,20);//1969-07-20
LocalDatedate2=LocalDate.of(-3113,Month.AUGUST,11);//-3113-08-11
//LocalDatedate3=LocalDate.of(2015,13,11);//DateTimeException
//LocalDatedate4=LocalDate.of(2015,2,29);//DateTimeException
TheyearisrepresentedasaprolepticyearintheISOstandard,whichcanbenegative.A
yearinCE(CurrentEra,orAD)hasthesamevalueasaprolepticyear;forexample,2015
CEissameastheprolepticyear2015.However,forayearinBCE(BeforeCurrentEra,or
BC),theprolepticyear0correspondsto1BCE,theprolepticyear–1correspondsto2
BCE,andsoon.ThetoString()methodoftheclasswillformatthedate-basedvalues
accordingtotheISOstandardasuuuu-MM-dd(seealso§11.4,p.495).Inthesecond
declarationintheprecedingsetofexamples,thedate-3113-08-11correspondsto11
August3114BCE.
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
//LocalTime
staticLocalTimeof(inthour,intminute)
staticLocalTimeof(inthour,intminute,intsecond)
staticLocalTimeof(inthour,intminute,intsecond,intnanoOfSecond)
ThisoverloadedstaticfactorymethodintheLocalTimeclassreturnsaninstance
ofLocalTimefromthespecifiedtime-basedvalues.Thesecondandnanosecond
valuesaresettozero,ifnotspecified.
Clickheretoviewcodeimage
//LocalDate
staticLocalDateof(intyear,intmonth,intdayOfMonth)
staticLocalDateof(intyear,Monthmonth,intdayOfMonth)
ThisoverloadedstaticfactorymethodintheLocalDateclassreturnsaninstance
ofLocalDatefromthespecifieddate-basedvalues.Thejava.time.Month
enumtypeallowsmonthstobereferredbyname—forexample,Month.MARCH.
Notethatmonthnumberingstartswith1(Month.JANUARY).
Clickheretoviewcodeimage
//LocalDateTime
staticLocalDateTimeof(intyear,intmonth,intdayOfMonth,
inthour,intminute)
staticLocalDateTimeof(intyear,intmonth,intdayOfMonth,
inthour,intminute,intsecond)
staticLocalDateTimeof(intyear,intmonth,intdayOfMonth,inthour,
intminute,intsecond,intnanoOfSecond)
staticLocalDateTimeof(intyear,Monthmonth,intdayOfMonth,
inthour,intminute,intsecond)
staticLocalDateTimeof(intyear,Monthmonth,intdayOfMonth,
inthour,intminute)
staticLocalDateTimeof(intyear,Monthmonth,intdayOfMonth,
inthour,intminute,intsecond,intnanoOfSecond)
staticLocalDateTimeof(LocalDatedate,LocalTimetime)
ThisoverloadedstaticfactorymethodintheLocalDateTimeclassreturnsan
instanceofLocalDateTimefromthespecifiedtimeanddate-basedvalues.The
secondandnanosecondvaluesaresettozero,ifnotspecified.The
java.time.Monthenumtypeallowsmonthstobereferredbyname—for
example,Month.MARCH(i.e.,month3intheyear).
TheclassLocalDateTimeallowsthedateandthetimetobecombinedintooneentity,
whichisusefulforrepresentingsuchconceptsasappointments.Theof()methodsinthe
LocalDateTimeclassarecombinationsoftheof()methodsfromtheLocalTime
andLocalDateclasses,takingbothtime-basedanddate-basedvaluesasarguments.The
toString()methodofthisclasswillformatthetemporalvaluesaccordingtotheISO
standardasuuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS.TheletterTseparatesthedate-
basedvaluesfromthetime-basedvalues(§11.4,p.495).
Clickheretoviewcodeimage
//2015-04-28T12:15
LocalDateTimedt1=LocalDateTime.of(2015,4,28,12,15);
WOW! eBook
www.wowebook.org
//2015-08-19T14:00
LocalDateTimedt2=LocalDateTime.of(2015,Month.AUGUST,19,14,0);
TheLocalDateTimeclassalsoprovidesanof()methodthatcombinesa
LocalDateobjectandaLocalTimeobject.Thefirstdeclarationinthenextcode
snippetcombinesadateandatime.ThestaticfieldLocalTime.NOONdefinesthetime
atnoon.Inaddition,theLocalTimeclassprovidestheinstancemethodatDate(),
whichtakesaspecifieddateasanargumentandreturnsaLocalDateTimeobject.The
seconddeclarationcombinesthetimeatnoonwiththedatereferredtobythereference
date1.Conversely,theLocalDateclassprovidestheoverloadedinstancemethod
atTime()tocombineadatewithaspecifiedtime.Inthelasttwodeclarations,the
atTime()methodispassedaLocalTimeobjectandspecifictime-basedvalues,
respectively.
Clickheretoviewcodeimage
//1969-07-20T12:00
LocalDateTimedt3=LocalDateTime.of(date1,LocalTime.NOON);
LocalDateTimedt4=LocalTime.of(12,0).atDate(date1);
LocalDateTimedt5=date1.atTime(LocalTime.NOON);
LocalDateTimedt6=date1.atTime(12,0);
Asaconvenience,eachtemporalclassprovidesastaticmethodnow()thatreadsthe
systemclockandreturnstherelevanttemporalvaluesinaninstanceofthetargetclass.
Clickheretoviewcodeimage
LocalTimecurrentTime=LocalTime.now();
LocalDatecurrentDate=LocalDate.now();
LocalDateTimecurrentDateTime=LocalDateTime.now();
Example11.1includesthedifferentwaystocreatetemporalobjectsthatwehave
discussedsofar.
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
//LocalTime
LocalDateTimeatDate(LocalDatedate)
ReturnsaLocalDateTimethatcombinesthistimewiththespecifieddate.
Clickheretoviewcodeimage
//LocalDate
LocalDateTimeatTime(inthour,intminute)
LocalDateTimeatTime(inthour,intminute,intsecond)
LocalDateTimeatTime(inthour,intminute,intsecond,intnanoOfSecond)
LocalDateTimeatTime(LocalTimetime)
ReturnsaLocalDateTimethatcombinesthisdatewiththespecifiedtime-based
values.Thesecondandnanosecondvaluesaresettozero,ifnotspecified.
Clickheretoviewcodeimage
//LocalTime,LocalDate,LocalDateTime
staticTemporalTypenow()
Eachtemporalclasshasthisstaticfactorymethod,whichreturnseitherthecurrent
time,date,ordate-timefromthesystemclockinthedefaulttimezone,where
TemporalTypeiseitherLocalTime,LocalDate,orLocalDateTime,
respectively.
Example11.1CreatingTemporalObjects
Clickheretoviewcodeimage
importjava.time.LocalDate;
importjava.time.LocalDateTime;
importjava.time.LocalTime;
importjava.time.Month;
publicclassCreatingTemporals{
publicstaticvoidmain(String[]args){
//Creatingaspecifictimefromtime-basedvalues:
LocalTimetime1=LocalTime.of(8,15,35,900);//08:15:35.000000900
LocalTimetime2=LocalTime.of(16,45);//16:45
//LocalTimetime3=LocalTime.of(25,13,30);//DateTimeException
System.out.println(“Surveillancestarttime:”+time1);
System.out.println(“Closingtime:”+time2);
//Creatingaspecificdatefromdate-basedvalues:
LocalDatedate1=LocalDate.of(1969,7,20);//1969-07-20
LocalDatedate2=LocalDate.of(-3113,Month.AUGUST,11);//-3113-08-11
//LocalDatedate3=LocalDate.of(2015,13,11);//
DateTimeException
//LocalDatedate4=LocalDate.of(2015,2,29);//
DateTimeException
System.out.println(“Dateoflunarlanding:”+date1);
System.out.println(“StartDateofMayanCalendar:”+date2);
//Creatingaspecificdate-timefromdate-andtime-basedvalues.
//2015-04-28T12:15
LocalDateTimedt1=LocalDateTime.of(2015,4,28,12,15);
//2015-08-17T14:00
WOW! eBook
www.wowebook.org
LocalDateTimedt2=LocalDateTime.of(2015,Month.AUGUST,17,14,0);
System.out.println(“Carserviceappointment:”+dt1);
System.out.println(“Hospitalappointment:”+dt2);
//Combiningdateandtimeobjects.
//1969-07-20T12:00
LocalDateTimedt3=LocalDateTime.of(date1,LocalTime.NOON);
LocalDateTimedt4=LocalTime.of(12,0).atDate(date1);
LocalDateTimedt5=date1.atTime(LocalTime.NOON);
LocalDateTimedt6=date1.atTime(12,0);
System.out.println(“Factorydate-timecombo:”+dt3);
System.out.println(“Timewithdatecombo:”+dt4);
System.out.println(“Datewithtimecombo:”+dt5);
System.out.println(“Datewithexplicittimecombo:”+dt6);
//Currenttime:
LocalTimecurrentTime=LocalTime.now();
System.out.println(“Currenttime:”+currentTime);
//Currentdate:
LocalDatecurrentDate=LocalDate.now();
System.out.println(“Currentdate:”+currentDate);
//Currentdateandtime:
LocalDateTimecurrentDateTime=LocalDateTime.now();
System.out.println(“Currentdate-time:”+currentDateTime);
}
}
Possibleoutputfromtheprogram:
Clickheretoviewcodeimage
Surveillancestarttime:08:15:35.000000900
Closingtime:16:45
Dateoflunarlanding:1969-07-20
StartDateofMayanCalendar:-3113-08-11
Carserviceappointment:2015-04-28T12:15
Hospitalappointment:2015-08-17T14:00
Factorydate-timecombo:1969-07-20T12:00
Timewithdatecombo:1969-07-20T12:00
Datewithtimecombo:1969-07-20T12:00
Datewithexplicittimecombo:1969-07-20T12:00
Currenttime:10:32:03.069
Currentdate:2015-08-21
Currentdate-time:2015-08-21T10:32:03.083
QueryingTemporalObjects
Atemporalobjectprovidesgetmethodsthataretailoredtoaccessthespecifictemporal
valuesthatconstituteitsstate.TheLocalTimeclassprovidesgetmethodsforthetime-
basedvalues,andtheLocalDateclassprovidesgetmethodsforthedate-basedvalues.
Notsurprisingly,theLocalDateTimeclassprovidesgetmethodsforbothtime-and
date-basedvalues.Usageofthegetmethodsisstraightforward,asshowninExample11.2.
WOW! eBook
www.wowebook.org
//LocalTime,LocalDateTime
intgetHour()
intgetMinute()
intgetSecond()
intgetNano()
Getstheappropriatetime-basedvaluefromthecurrentLocalTimeorLocal-
DateTimeobject.
//LocalDate,LocalDateTime
intgetDayOfMonth()
DayOfWeekgetDayOfWeek()
intgetDayOfYear()
MonthgetMonth()
intgetMonthValue()
intgetYear()
Getstheappropriatedate-basedvaluefromthecurrentLocalDateor
LocalDateTimeobject.TheenumtypeDayOfWeekallowsdaysoftheweekto
bereferredtobyname—forexample,DayOfWeek.MONDAYisday1oftheweek.
TheenumtypeMonthallowsmonthsoftheyeartobereferredbyname—for
example,Month.JANUARY.Themonthvalueisfrom1(Month.JANUARY)to
12(Month.DECEMBER).
ThetemporalclassLocalDateTimealsoprovidestwomethodstoobtainthedateand
thetimeastemporalobjects,incontrasttoaccessingindividualdate-andtime-based
values.
Clickheretoviewcodeimage
LocalDateTimedoomsday=LocalDateTime.of(1945,8,6,8,15);
LocalDatedate=doomsday.toLocalDate();//1945-08-06
LocalTimetime=doomsday.toLocalTime();//08:15
//LocalDateTime
LocalDatetoLocalDate()
LocalTimetoLocalTime()
ThesemethodscanbeusedtogettheLocalDateandLocalTimepartofthis
date-time,respectively.
Itisalsopossibletocheckwhetheratemporalobjectrepresentsapointintimebeforeor
afteranothertemporalobjectofthesametype.Inaddition,theLocalDateand
LocalDateTimeclassesprovideanisEqual()methodthatdetermineswhethera
temporalobjectisequaltoanothertemporalobjectofthesametype.Incontrast,the
equals()methodallowsequalitycomparisonwithanarbitraryobject.
Clickheretoviewcodeimage
LocalDated1=LocalDate.of(-1004,3,1);//-1004-03-01
LocalDated2=LocalDate.of(1004,3,1);//1004-03-01
booleanresult1=d1.isBefore(d2);//true
booleanresult2=d2.isAfter(d1);//true
booleanresult3=d1.isAfter(d1);//false
booleanresult4=d1.isEqual(d2);//false
booleanresult5=d1.isEqual(d1);//true
WOW! eBook
www.wowebook.org
booleanresult6=d2.isLeapYear();//true
TheisLeapYear()methodoftheLocalDateclasscheckswhetherayearinadateis
aleapyear.
Clickheretoviewcodeimage
//LocalTime
booleanisAfter(LocalTimeother)
booleanisBefore(LocalTimeother)
ThesemethodsdeterminewhetherthisLocalTimerepresentsapointonthelocal
time-lineafterorbeforetheothertime,respectively.
Clickheretoviewcodeimage
//LocalDate
booleanisAfter(ChronoLocalDateother)
booleanisBefore(ChronoLocalDateother)
booleanisEqual(ChronoLocalDateother)
booleanisLeapYear()
ThefirsttwomethodsdeterminewhetherthisLocalDaterepresentsapointon
thelocaltimelineafterorbeforetheotherdate,respectively.TheLocalDate
classimplementstheChronoLocalDateinterface.
Thethirdmethoddetermineswhetherthisdateisequaltothespecifieddate.
ThelastmethodchecksforaleapyearaccordingtotheISOprolepticcalendar
systemrules.
Clickheretoviewcodeimage
//LocalDateTime
booleanisAfter(ChronoLocalDateTime<?>other)
booleanisBefore(ChronoLocalDateTime<?>other)
booleanisEqual(ChronoLocalDateTime<?>other)
ThefirsttwomethodsdeterminewhetherthisLocalDateTimerepresentsapoint
onthelocaltimelineafterorbeforethespecifieddate-time,respectively.The
LocalDateTimeclassimplementstheChronoLocalDateTimeinterface.
Thethirdmethoddetermineswhetherthisdate-timerepresentsthesamepointon
thelocaltimelineastheotherdate-time.
ComparingTemporalObjects
ThetemporalclassesimplementtheComparableinterface,providingthe
compareTo()methodsothattemporalobjectscanbecomparedinameaningfulway.
Thetemporalclassesalsooverridetheequals()methodoftheObjectclass.These
methodsmakeitpossibletobothsearchforandsorttemporalobjects.
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
intcompareTo(LocalTimeother)//LocalTime
intcompareTo(ChronoLocalDateother)//LocalDate
intcompareTo(ChronoLocalDateTime<?>other)//LocalDateTime
Thesemethodscomparethistemporalobjecttoanothertemporalobject.Thethree
temporalclassesimplementtheComparablefunctionalinterface.The
compareTo()methodreturns0ifthetwotemporalobjectsareequal,anegative
valueifthistemporalobjectislessthantheothertemporalobject,andapositive
valueifthistemporalobjectisgreaterthantheothertemporalobject.
Clickheretoviewcodeimage
booleanequals(Objectobj)//LocalTime,LocalDate,LocalDateTime
Thethreetemporalclassesoverridetheequals()methodoftheObjectclass.
Themethodcheckswhetherthistemporalobjectisequaltoanotherobject.The
specifiedobjectmustbeofthesametypeasthistemporalobject;otherwise,the
resultisfalse.
CreatingModifiedCopiesofTemporalObjects
Animmutableobjectdoesnotprovideanysetmethodsthatcanchangeitsstate.Instead,it
usuallyprovideswhatareknownaswithmethods(or“withers”)thatreturnacopyofthe
originalobjectwhereexactlyonepropertyhasbeensettoanewvalue.TheLocalTime
andLocalDateclassesprovidewithmethodstosetatime-ordate-basedvalue,
respectively.Notsurprisingly,theLocalDateTimeclassprovideswithmethodstoset
bothtime-anddate-basedvaluesindividually.Awithmethodchangesaspecific
propertyinanabsoluteway,whichisreflectedinthestateofthenewtemporalobject;the
originalobject,however,isnotaffected.Suchwithmethodsarealsocalledabsolute
adjusters,incontrasttotherelativeadjustersthatwewillmeetlater(p.474).
Clickheretoviewcodeimage
LocalDatedate2=LocalDate.of(2015,3,1);//2015-03-01
date2=date2.withYear(2016).withMonth(2).withDayOfMonth(28);//2016-02-28
TheprecedingcodelinesarefromExample11.2.Inthesecondassignmentstatement,the
methodcallsarechained.ThreeinstancesoftheLocalDateclassarecreated
consecutively,aseachwithmethodiscalledtosetaspecificdate-basedvalue.
Clickheretoviewcodeimage
date2=date2.withYear(2016);//2016-03-01
date2.withMonth(2).withDayOfMonth(28);//date2isstill2016-03-
01.
Thiscodecontainsalogicalerror,suchthatthelasttwoLocalDateinstancesreturned
bythewithmethodsareignored,andthereferencedate2nevergetsupdated.
Inthenextcodeexamples,eachcalltoawithmethodthrowsa
DateTimeException.TheminuteandhourvaluesareoutofrangeforaLocalTime
object.Certainlythemonthvalue13isoutofrangeforaLocalDateobject.Thedayof
WOW! eBook
www.wowebook.org
themonthvalue31isnotvalidfortheAprilmonth,whichhas30days.Thedayofthe
yearvalue366isoutofrangeaswell,sincetheyear2015isnotaleapyear.
Clickheretoviewcodeimage
LocalTimetime=LocalTime.of(14,45);//14:45
time=time.withMinute(100);//Outofrange.DateTimeException.
time=time.withHour(25);//Outofrange.DateTimeException.
LocalDatedate=LocalDate.of(2015,4,30);//2015-04-30
date=date.withMonth(13);//Outofrange.DateTimeException.
date=date.withDayOfMonth(31);//Outofrangeformonth.
DateTimeException.
date=date.withDayOfYear(366);//Outofrangeforyear.
DateTimeException.
ThenextcodesnippetillustrateshowthewithYear()andthewithMonth()methods
adjustthedayofthemonth,ifnecessary,whentheyearorthemonthischanged,
respectively.Theyearinthedate2016-02-29ischangedto2017,resultinginthe
followingdate:2017-02-29.Sincetheyear2017isnotaleapyear,themonthofFebruary
cannothave29days.ThewithYear()methodadjuststhedayofthemonthtothelast
validdayofthemonth,28.Similarly,themonthinthedate2015-03-31ischangedto4
(i.e.,April),resultinginthefollowingdate:2015-04-31.SincethemonthAprilhas30
days,thewithMonth()methodadjuststhedayofthemonthtothelastvaliddayofthe
month,30.
Clickheretoviewcodeimage
LocalDatedate3=LocalDate.of(2016,2,29);//Original:2016-02-29
date3=date3.withYear(2017);//Expected:2017-02-29
System.out.println(“Date3:”+date3);//Adjusted:2017-02-28
LocalDatedate4=LocalDate.of(2015,3,31);//Original:2015-03-31
date4=date4.withMonth(4);//Expected:2015-04-31
System.out.println(“Date4:”+date4);//Adjusted:2015-04-30
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
//LocalTime,LocalDateTime
LocalTime/LocalDateTimewithHour(inthour)
LocalTime/LocalDateTimewithMinute(intminute)
LocalTime/LocalDateTimewithSecond(intsecond)
LocalTime/LocalDateTimewithNano(intnanoOfSecond)
ReturnsacopyofthisLocalTimeorLocalDateTimewiththeappropriate
time-basedvaluechangedtothespecifiedvalue.ADateTimeExceptionis
throwniftheargumentvalueisoutofrange.
Clickheretoviewcodeimage
//LocalDate,LocalDateTime
LocalDate/LocalDateTimewithYear(intyear)
LocalDate/LocalDateTimewithMonth(intmonth)
LocalDate/LocalDateTimewithDayOfMonth(intdayOfMonth)
LocalDate/LocalDateTimewithDayOfYear(intdayOfYear)
ReturnsacopyofthisLocalDateorLocalDateTimewiththeappropriate
date-basedvaluechangedtothespecifiedvalue.ADateTimeExceptionis
thrown,ifthespecifiedvalueisoutofrangeorisinvalidincombinationwithother
time-ordate-basedvaluesinthetemporalobject.
Thefirstandsecondmethodswilladjustthedayofthemonthtothelastvalidday
ofthemonth,ifthedayofmonthbecomesinvalidwhentheyearorthemonthis
changed(e.g.,themonthvalue2willchangethedate2016-03-31to2016-02-29).
Incontrast,thethirdmethodwillthrowaDateTimeExceptionifthespecified
dayofthemonthisinvalidforthemonth-yearcombination(e.g.,thedayofmonth
29isinvalidforFebruary2015),aswillthelastmethodifthedayoftheyearis
invalidfortheyear(e.g.,thedayofyear366isinvalidfortheyear2015).
Example11.2UsingTemporalObjects
Clickheretoviewcodeimage
importjava.time.DayOfWeek;
importjava.time.LocalDate;
importjava.time.LocalDateTime;
importjava.time.LocalTime;
importjava.time.Month;
publicclassUsingTemporals{
publicstaticvoidmain(String[]args){
//Date-Time:1945-08-06T08:15
LocalDateTimedoomsday=LocalDateTime.of(1945,8,6,8,15);
LocalDatedate=doomsday.toLocalDate();//1945-08-06
LocalTimetime=doomsday.toLocalTime();//08:15
System.out.println(“Date-Time:”+doomsday);
//Time:08:15
inthour=time.getHour();//8
intminute=time.getMinute();//15
intsecond=time.getSecond();//0
System.out.println(“Time:”+time);
System.out.println(“Hour:”+hour);
WOW! eBook
www.wowebook.org
System.out.println(“Min:”+minute);
System.out.println(“Sec:”+second);
//Date:1945-08-06
intyear=date.getYear();//1945
intmonthValue=date.getMonthValue();//8
Monthmonth=date.getMonth();//AUGUST
DayOfWeekdow=date.getDayOfWeek();//MONDAY
intday=date.getDayOfMonth();//6
System.out.println(“Date:”+date);
System.out.println(“Year:”+year);
System.out.println(“Monthvalue:”+monthValue);
System.out.println(“Month:”+month);
System.out.println(“DoW:”+dow);
System.out.println(“DoM:”+day);
//Ordering
LocalDated1=LocalDate.of(-1004,3,1);//-1004-03-01
LocalDated2=LocalDate.of(1004,3,1);//1004-03-01
booleanresult1=d1.isBefore(d2);//true
booleanresult2=d2.isAfter(d1);//true
booleanresult3=d1.isAfter(d1);//false
booleanresult4=d1.isEqual(d2);//false
booleanresult5=d1.isEqual(d1);//true
booleanresult6=d2.isLeapYear();//true
System.out.println(d1+”isbefore“+d2+“:”+result1);
System.out.println(d2+”isafter“+d1+“:”+result2);
System.out.println(d1+”isafter“+d1+“:”+result3);
System.out.println(d1+”isequalto”+d2+“:”+result4);
System.out.println(d1+”isequalto”+d1+“:”+result5);
System.out.println(d2.getYear()+”isaleapyear:”+result6);
//Absoluteadjusters:
LocalDatedate2=LocalDate.of(2015,3,1);
System.out.println(“Datebeforeadjusting:”+date2);//2015-03-01
date2=date2.withYear(2016).withMonth(2).withDayOfMonth(28);
System.out.println(“Dateafteradjusting:”+date2);//2016-02-28
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
Date-Time:1945-08-06T08:15
Time:08:15
Hour:8
Min:15
Sec:0
Date:1945-08-06
Year:1945
Monthvalue:8
Month:AUGUST
DoW:MONDAY
DoM:6
-1004-03-01isbefore1004-03-01:true
1004-03-01isafter-1004-03-01:true
-1004-03-01isafter-1004-03-01:false
-1004-03-01isequalto1004-03-01:false
-1004-03-01isequalto-1004-03-01:true
1004isaleapyear:true
Datebeforeadjusting:2015-03-01
WOW! eBook
www.wowebook.org
Dateafteradjusting:2016-02-28
TemporalArithmetic
Thetemporalclassesprovideplusandminusmethodsthatreturnacopyoftheoriginal
objectthathasbeenincrementedordecrementedbyaspecificamountoftime—for
example,bynumberofhoursorbynumberofmonths.
TheLocalTimeandLocalDateclassesprovideplus/minusmethodsto
increment/decrementatimeoradatebyaspecificamountintermsofatimeunit(for
example,hours,minutes,andseconds)oradateunit(forexample,years,months,and
days),respectively.TheLocalDateTimeclassprovidesplus/minusmethodsto
increment/decrementadate-timebyanamountthatisspecifiedintermsofeitheratime
unitoradateunit.Forexample,theplusMonths()methodintheLocalDateclass
returnsanewLocalDateobjectafteraddingthespecifiednumberofmonthspassedas
anargumenttothemethod.Similarly,theminusMinutes()methodinthe
LocalTimeclassreturnsanewLocalTimeobjectaftersubtractingthespecified
numberofminutespassedasanargumenttothemethod.Thechangeisrelative,and
reflectedinthenewtemporalobjectthatisreturned.Suchplus/minusmethodsare
alsocalledrelativeadjusters,incontrasttoabsoluteadjusters(p.470).
Example11.3demonstrateswhatwecancalltemporalarithmetic,whereaLocalDate
objectismodifiedbyaddingorsubtractinganamountspecifiedasdays,weeks,or
months.Notehowthedate-basedvaluesareadjustedaftereachoperation.Thedate
2015-10-23iscreatedat(1),and10months,3weeks,and40daysaresuccessively
addedtothenewdateobjectreturnedbyeachplusmethodcallat(2),(3),and(4),
respectively,resultinginthedate2016-10-23.Wethensubtract2days,4weeks,and
11monthssuccessivelyfromthenewdateobjectreturnedbyeachminusmethodcallat
(5),(6),and(7),respectively,resultinginthedate2015-10-23.InExample11.3,
severalassignmentstatementsareusedtoprinttheintermediatedates,butthecodecanbe
mademorecompactbymethodchaining.
Clickheretoviewcodeimage
LocalDatedate=LocalDate.of(2015,10,23);//2015-10-23
date=date.plusMonths(10).plusWeeks(3).plusDays(40);//Methodchaining
System.out.println(date);//2016-10-23
date=date.minusDays(2).minusWeeks(4).minusMonths(11);//Methodchaining
System.out.println(date);//2015-10-23
Thefollowingcodesnippetillustratesthewrappingoftimearoundmidnight,asone
wouldexpectona24-hourclock.EachmethodcallreturnsanewLocalTimeobject.
Clickheretoviewcodeimage
LocalTimewitchingHour=LocalTime.MIDNIGHT//00:00
.plusHours(14)//14:00
.plusMinutes(45)//14:45
.plusMinutes(30)//15:15
.minusHours(15)//00:15
.minusMinutes(15);//00:00
ThenextcodesnippetillustrateshowtheplusYears()methodadjuststhedayofthe
WOW! eBook
www.wowebook.org
month,ifnecessary,whentheyearvalueischanged.Theyearinthedate2016-02-29is
changedto2017byadding1year,resultinginthefollowingdate:2017-02-29.The
plusYears()methodadjuststhedayofthemonthtothelastvaliddayofthe
month,28;astheyear2017isnotaleapyear,themonthofFebruarycannothave29
days.
Clickheretoviewcodeimage
LocalDatedate5=LocalDate.of(2016,2,29);//Original:2016-02-29
date5=date5.plusYears(1);//Expected:2017-02-29
System.out.println(“Date5:”+date5);//Adjusted:2017-02-28
Clickheretoviewcodeimage
//LocalTime,LocalDateTime
LocalTime/LocalDateTimeminusHours/plusHours(longhours)
LocalTime/LocalDateTimeminusMinutes/plusMinutes(longminutes)
LocalTime/LocalDateTimeminusSeconds/plusSeconds(longseconds)
LocalTime/LocalDateTimeminusNanos/plusNanos(longnanos)
ThesemethodsreturnacopyofthisLocalTimeorLocalDateTimeobject
withthespecifiedamounteithersubtractedoraddedtoaspecifictime-basedvalue.
Thecalculationalwayswrapsaroundmidnight.
ForthemethodsoftheLocalDateTimeclass,aDateTimeExceptionis
throwniftheresultexceedsthedaterange.
Clickheretoviewcodeimage
//LocalDate,LocalDateTime
LocalDate/LocalDateTimeminusYears/plusYears(longyears)
LocalDate/LocalDateTimeminusMonths/plusMonths(longmonths)
LocalDate/LocalDateTimeminusWeeks/plusWeeks(longweeks)
LocalDate/LocalDateTimeminusDays/plusDays(longdays)
ThesemethodsreturnacopyofthisLocalDateorLocalDateTimewiththe
specifiedamounteithersubtractedoraddedtoaspecificdate-basedvalue.
AllmethodsthrowaDateTimeExceptioniftheresultexceedsthedaterange.
Thefirstandsecondmethodswillchangethedayofthemonthtothelastvalidday
ofthemonthifnecessary,whenthedayofmonthbecomesinvalidasaresultofthe
operation.
Thethirdandlastmethodswilladjustthemonthandyearfieldsasnecessaryto
ensureavalidresult.
WOW! eBook
www.wowebook.org
Example11.3TemporalArithmetic
Clickheretoviewcodeimage
importjava.time.LocalDate;
publicclassTemporalArithmetic{
publicstaticvoidmain(String[]args){
LocalDatedate=LocalDate.of(2015,10,23);//(1)
System.out.println(“Date:”+date);//2015-10-23
date=date.plusMonths(10);//(2)
System.out.println(“10monthsafter:”+date);//2016-08-23
date=date.plusWeeks(3);//(3)
System.out.println(“3weeksafter:”+date);//2016-09-13
date=date.plusDays(40);//(4)
System.out.println(“40daysafter:”+date);//2016-10-23
date=date.minusDays(2);//(5)
System.out.println(“2daysbefore:”+date);//2016-10-21
date=date.minusWeeks(4);//(6)
System.out.println(“4weeksbefore:”+date);//2016-09-23
date=date.minusMonths(11);//(7)
System.out.println(“11monthsbefore:”+date);//2015-10-23
}
}
Outputfromtheprogram:
Date:2015-10-23
10monthsafter:2016-08-23
3weeksafter:2016-09-13
40daysafter:2016-10-23
2daysbefore:2016-10-21
4weeksbefore:2016-09-23
11monthsbefore:2015-10-23
11.3WorkingwithPeriods
Forrepresentinganamountoftime,theDateandTimeAPIprovidesthetwoclasses
PeriodandDuration.WewillbrieflymentiontheDurationclass,andconcentrate
onthePeriodclass.
TheDurationclassmodelsanamountoftimeintermsofsecondsandnanoseconds,but
aDurationobjectcanalsobeaccessedintermsofdays,hours,andminutes.It
essentiallyrepresentsatime-basedamountoftime,whereasthePeriodclassrepresents
adate-basedamountoftimeintermsofyears,months,anddays.Thetime-based
DurationclasscanbeusedwiththeLocalTimeclass,andnotsurprisingly,thedate-
basedPeriodclasscanbeusedwiththeLocalDateclass.Ofcourse,the
LocalDateTimeclasscanusebothclasses.
ThePeriodclassisinthesamepackage(java.time)asthetemporalclasses,andits
repertoireofmethodsshouldalsolookfamiliar,asitsharesmanyofthemethodprefixes
withthetemporalclasses(Table11.1,p.463).
Themantraofimmutableandthread-safeobjectsalsoappliestothePeriodclass.
WOW! eBook
www.wowebook.org
CreatingPeriods
Likethetemporalclasses,thePeriodclassdoesnotprovideanypublicconstructors,
butratherprovidesanoverloadedstaticfactorymethodof()toconstructperiodsof
differentlengths,basedonadateunit.
Clickheretoviewcodeimage
Periodp=Period.of(2,4,8);//(1)
System.out.println(p);//(2)P2Y4M8D(2Years,4Months,8
Days)
Periodp1=Period.ofYears(10);//P10Y,periodof10years.
Periodp2=Period.ofMonths(14);//P14M,periodof14months.
Periodp3=Period.ofDays(40);//P40D,periodof40days.
Periodp4=Period.ofWeeks(2);//P14D,periodof14days(2weeks).
Themostversatileof()methodrequirestheamountoftimeforalldateunits:years,
months,anddays,asin(1).ThetoString()methodofthePeriodclassreturnsa
textualrepresentationofaPeriodobjectintheISOstandard.Theoutputfrom(2),
P2Y4M8D,indicatesaperiodof2years,4months,and8days.Otherof()methods
createaperiodbasedonaparticulardateunit,asshowninthepreviousexamples.
Thenextcodesnippetdoesnotcreateaperiodof3years,4months,and5days.Thefirst
methodcallusestheclassname,andthesubsequentmethodcallsusethePeriodobject
returnedasaconsequenceofthepreviouscall.Theof()methodcreatesanewPeriod
objectbasedonitsargument.
Clickheretoviewcodeimage
Periodperiod=Period.ofYears(3).ofMonths(4).ofDays(5);//P5D.Logical
error.
Aswewouldexpect,wecancreateaperiodthatrepresentstheamountoftimebetween
twodatesbycallingthestaticmethodbetween()ofthePeriodclass.
Clickheretoviewcodeimage
LocalDated1=LocalDate.of(2015,3,1);//2015-03-01
LocalDated2=LocalDate.of(2016,3,1);//2016-03-01
Periodperiod12=Period.between(d1,d2);//P1Y
Periodperiod21=Period.between(d2,d1);//P-1Y
ThePeriodclassalsoprovidesthestaticmethodparse()tocreateaperiodfroma
stringthatcontainsatextualrepresentationofaperiodintheISOstandard.Iftheformatis
notcorrect,ajava.time.format.DateTimeParseExceptionisthrown.
Clickheretoviewcodeimage
Periodperiod2=Period.parse(“P1Y15M20D”);//1year,15months,20days
Periodperiod3=Period.parse(“P20D”);//20days
Periodperiod4=Period.parse(“P5W”);//35days(5weeks)
//PeriodpX=Period.parse(“P24H”);//
java.time.format.DateTimeParseException
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
staticPeriodof(intyears,intmonths,intdays)
staticPeriodofYears(intyears)
staticPeriodofMonths(intmonths)
staticPeriodofWeeks(intweeks)
staticPeriodofDays(intdays)
ThesestaticfactorymethodsreturnaPeriodrepresentinganamountoftime
equaltothespecifiedvalueofadateunit.Date-basedvaluesimplicitlyimpliedare
settozero.Aweekisequalto7days.Theargumentvaluecanbenegative.
Clickheretoviewcodeimage
staticPeriodbetween(LocalDatestartDateInclusive,
LocalDateendDateExclusive)
ThisstaticmethodreturnsaPeriodconsistingofthenumberofyears,months,
anddaysbetweentwodates.Thecalculationexcludestheenddate.
Clickheretoviewcodeimage
staticPeriodparse(CharSequencetext)
ThisstaticmethodreturnsaPeriodparsedfromacharactersequence—for
example,"P3Y10M2D"(3years,10months,2days).A
java.time.format.DateTimeParseExceptionisthrownifthetext
cannotbeparsedtoaperiod.
QueryingPeriods
ThePeriodclassprovidestheobviousgetmethodstoreadthedate-basedpartsofa
Periodobject.Theclassalsohasmethodstocheckifanydate-basedpartofaperiodis
negativeorifalldate-basedpartsofaperiodarezero.
Clickheretoviewcodeimage
Periodperiod5=Period.of(2,4,-10);
System.out.println(“Period:”+period5);//Period:P2Y4M-10D
System.out.println(“Years:”+period5.getYears());//Years:2
System.out.println(“Months:”+period5.getMonths());//Months:4
System.out.println(“Days:”+period5.getDays());//Days:-10
System.out.println(“Totalmonths:”+period5.toTotalMonths());//28months
System.out.println(period5.isNegative());//true
System.out.println(period5.isZero());//false
TheclassPeriodprovidesthemethodtoTotalMonths()toderivethetotalnumber
ofmonthsinaperiod.However,thiscalculationissolelybasedonthenumberofyears
andmonthsintheperiod;thenumberofdaysisnotconsidered.APeriodjustrepresents
anamountoftime,soithasnonotionofadate.Conversionbetweenmonthsandyearsis
notaproblem,as1yearis12months.However,conversionbetweenthenumbersofdays
andtheotherdateunitsisproblematic.Thenumberofdaysinayearandinamonthare
verymuchdependentonwhethertheyearisaleapyearandonaparticularmonthinthe
year,respectively.APeriodisobliviousaboutboththeyearandthemonthintheyear.
ThePeriodclassoverridestheequals()methodoftheObjectclass.Eachdate-
basedpartiscomparedindividually,andmusthavethesamevaluetobeconsideredequal.
WOW! eBook
www.wowebook.org
Aperiodof1yearand14monthsisnotequaltoaperiodof2yearsand2months,ortoa
periodof26months.
Clickheretoviewcodeimage
Periodpx=Period.of(1,14,0);
Periodpy=Period.of(2,2,0);
Periodpz=Period.ofMonths(26);
System.out.println(px.equals(py));//false
System.out.println(px.equals(pz));//false
System.out.println(px.equals(Period.ZERO));//false
intgetYears()
intgetMonths()
intgetDays()
Returnsthevalueofaspecificdateunitofthisperiod.
booleanisNegative()
Determineswhetheranyofthedate-basedvaluesofthisperiodarenegative.
booleanisZero()
Determineswhetheralldate-basedvaluesofthisperiodarezero.
longtoTotalMonths()
Returnsthetotalnumberofmonthsinthisperiod,basedontheyearsandthe
monthsvalue.Thedaysvalueisnotconsidered.
booleanequals(Objectobj)
Determineswhetherthisperiodisequaltoanotherperiod,meaningthateachdate
unithasthesamevalue.
CreatingModifiedCopiesofPeriods
ThePeriodclassprovideswithmethodstosetanewvalueforeachdateunit
individually,whilethevaluesoftheotherdateunitsremainunchanged.Notethateach
methodcallreturnsanewPeriodobject,andchainingmethodcallsworksasexpected.
Clickheretoviewcodeimage
Periodp5=Period.of(2,1,30)//P2Y1M30D
.withYears(3)//P3Y1M30D,setsthenumberofyears
.withMonths(16)//P3Y16M30D,setsthenumberofmonths
.withDays(1);//P3Y16M1D,setsthenumberofdays
PeriodwithYears(intyears)
PeriodwithMonths(intmonths)
PeriodwithDays(intdays)
Returnsacopyofthisperiodwhereaspecificdateunitissettothevalueofthe
argument.Thevaluesoftheotherdateunitsarenotaffected.
WOW! eBook
www.wowebook.org
MoreTemporalArithmetic
ThePeriodclassprovidesplusandminusmethodsthatreturnacopyoftheoriginal
objectthathasbeenincrementedordecrementedbyaspecificamountspecifiedinterms
ofadateunit—forexample,asanumberofyears,months,ordays.Asthenextcode
snippetshows,onlythevalueofaspecificdateunitischanged;theotherdate-based
valuesareunaffected.Thereisnoimplicitnormalizationperformed,unlessthe
normalized()methodiscalled.Thismethodnormalizesonlythemonths,adjusting
thevaluesofthemonthsandyearsasnecessary.
Clickheretoviewcodeimage
Periodp6=Period.of(2,10,30)//P2Y10M30D
.plusDays(10)//P2Y10M40D
.plusMonths(8)//P2Y18M40D
.plusYears(1)//P3Y18M40D
.normalized();//P4Y6M40D
Wecandosimplearithmeticwithperiods.Thenextcodeexamplesusetheplus()and
minus()methodsofthePeriodclassthattakeaTemporalAmountasanargument.
BoththePeriodandtheDurationclassesimplementtheTemporalAmount
interface.Inthelastassignmentstatement,wehaveshownthestateofbothnewPeriod
objectsthatarecreated.
Clickheretoviewcodeimage
Periodp7=Period.of(1,1,1);//P1Y1M1D
Periodp8=Period.of(2,12,30);//P2Y12M30D
Periodp9=p8.minus(p7);//P1Y11M29D
p8=p8.plus(p7).plus(p8);//P3Y13M31D,P5Y25M61D
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
PeriodminusYears/plusYears(longyears)
PeriodminusMonths/plusMonths(longmonths)
PeriodminusDays/plusDays(longdays)
Returnsacopyofthisperiod,withthespecifieddate-basedvaluesubtractedor
added.Theotherdate-basedvaluesareunaffected.
Clickheretoviewcodeimage
Periodminus/plus(TemporalAmountamount)
Returnsacopyofthisperiod,withthespecifiedamountsubtractedoradded.The
amountisoftheinterfacetypeTemporalAmountthatisimplementedbythe
classesPeriodandDuration.Thereisnonormalizationperformed.A
DateTimeExceptionisthrowniftheoperationcannotbeperformed.
Periodnormalized()
Returnsacopyofthisperiodwheretheyearsandmonthsarenormalized.The
numberofdaysisnotaffected.
Periodnegated()
ReturnsanewinstanceofPeriodwhereeachdate-basedvalueinthisperiodis
individuallynegated.
Clickheretoviewcodeimage
PeriodmultipliedBy(intscalar)
Returnsanewinstancewhereeachdate-basedvalueinthisperiodisindividually
multipliedbythespecifiedscalar.
Wecanalsodosimplearithmeticwithdatesandperiods.Thefollowingcodeusesthe
plus()andminus()methodsoftheLocalDateclassthattakea
TemporalAmountasanargument:
Clickheretoviewcodeimage
Periodp10=Period.of(1,1,1);//P1Y1M1D
LocalDatedate1=LocalDate.of(2015,4,1);//2015-04-01
LocalDatedate2=date1.plus(p10);//2016-05-02
date1=date1.minus(p10);//2014-02-28
WecanaddandsubtractperiodsfromLocalDateandLocalDateTimeobjects,but
notfromLocalTimeobjects,asaLocalTimeobjecthasonlytime-basedvalues.
Clickheretoviewcodeimage
LocalTimetime=LocalTime.NOON;
time=time.plus(p10);//
java.time.temporal.UnsupportedTemporalTypeException
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
//LocalTime,LocalDate,LocalDateTime
TemporalTypeminus(TemporalAmountamount)
TemporalTypeplus(TemporalAmountamount)
Eachtemporalclassprovidesthesetwomethods,whichreturnacopyofthis
temporalobjectwiththespecifiedamounteithersubtractedoradded,where
TemporalTypeiseitherLocalTime,LocalDate,orLocalDateTime.
TheamountisoftheinterfacetypeTemporalAmount,whichisimplementedby
theclassesPeriodandDuration.
BothmethodsthrowaDateTimeExceptioniftheoperationcannotbe
performed.
Clickheretoviewcodeimage
//LocalDate
Perioduntil(ChronoLocalDateendDateExclusive)
Thismethodcalculatestheamountoftimebetweenthisdateandanotherdateasa
Period.Thecalculationexcludestheenddate.
Example11.4isasimpleexampletoillustrateimplementingperiod-basedloops.The
methodreserveDates()at(1)isastubforreservingcertaindates,dependingonthe
periodpassedasanargument.Thefor(;;)loopat(2)usesthe
LocalDate.isBefore()methodtoterminatetheloop,andthe
LocalDate.plus()methodtoincrementthecurrentdatewiththespecifiedperiod.
WOW! eBook
www.wowebook.org
Example11.4Period-BasedLoop
Clickheretoviewcodeimage
importjava.time.LocalDate;
importjava.time.Period;
publicclassPeriodBasedLoop{
publicstaticvoidmain(String[]args){
reserveDates(Period.ofDays(7),
LocalDate.of(2015,10,20),LocalDate.of(2015,11,20));
System.out.println();
reserveDates(Period.ofMonths(1),
LocalDate.of(2015,10,20),LocalDate.of(2016,1,20));
System.out.println();
reserveDates(Period.of(0,1,7),
LocalDate.of(2015,10,20),LocalDate.of(2016,1,21));
}
publicstaticvoidreserveDates(Periodperiod,//(1)
LocalDatefromDate,
LocalDatetoDateExclusive){
System.out.println(“Startdate:”+fromDate);
for(LocalDatedate=fromDate.plus(period);//(2)
date.isBefore(toDateExclusive);
date=date.plus(period)){
System.out.println(“Reserved(”+period+“):”+date);
}
System.out.println(“Enddate:”+toDateExclusive);
}
}
Outputfromtheprogram:
Startdate:2015-10-20
Reserved(P7D):2015-10-27
Reserved(P7D):2015-11-03
Reserved(P7D):2015-11-10
Reserved(P7D):2015-11-17
Enddate:2015-11-20
Startdate:2015-10-20
Reserved(P1M):2015-11-20
Reserved(P1M):2015-12-20
Enddate:2016-01-20
Startdate:2015-10-20
Reserved(P1M7D):2015-11-27
Reserved(P1M7D):2016-01-03
Enddate:2016-01-21
WeconcludethissectionwithExample11.5,whichbringstogethersomeofthemethods
oftheDateandTimeAPI.Givenadateofbirth,themethodbirthdayInfo()at(1)
calculatestheageandthetimetonextbirthday.Theageiscalculatedat(2)usingthe
Period.between()method,whichcomputestheperiodbetweentwodates.Thedate
fornextbirthdayissetat(3)asthebirthdatewiththecurrentyear.Theifstatementat
(4)adjuststhenextbirthdaydateby1yearat(5),ifthebirthdayhasalreadypassed.The
statementat(6)calculatesthetimeuntilnextbirthdaybycallingthe
LocalDate.until()method.WecouldalsohaveusedthePeriod.between()
WOW! eBook
www.wowebook.org
methodat(6).Thechoicebetweenthesemethodsreallydependsonwhichmethodmakes
thecodemorereadableinagivencontext.
Example11.5MoreTemporalArithmetic
Clickheretoviewcodeimage
importjava.time.LocalDate;
importjava.time.Month;
importjava.time.Period;
publicclassActYourAge{
publicstaticvoidmain(String[]args){
birthdayInfo(LocalDate.of(1981,Month.AUGUST,19));
birthdayInfo(LocalDate.of(1935,Month.JANUARY,8));
}
publicstaticvoidbirthdayInfo(LocalDatedateOfBirth){//(1)
LocalDatetoday=LocalDate.now();
System.out.println(“Today:”+today);
System.out.println(“DateofBirth:”+dateOfBirth);
Periodp1=Period.between(dateOfBirth,today);//(2)
System.out.println(“Age:”+
p1.getYears()+”years,”+
p1.getMonths()+”months,and”+
p1.getDays()+”days”);
LocalDatenextBirthday=dateOfBirth.withYear(today.getYear());//(3)
if(nextBirthday.isBefore(today)||//(4)
nextBirthday.isEqual(today)){
nextBirthday=nextBirthday.plusYears(1);//(5)
}
Periodp2=today.until(nextBirthday);//(6)
System.out.println(“Birthdayin”+p2.getMonths()+”monthsand”+
p2.getDays()+”days”);
}
}
Possibleoutputfromtheprogram:
Clickheretoviewcodeimage
Today:2015-11-20
DateofBirth:1981-08-19
Age:34years,3months,and1days
Birthdayin8monthsand30days
Today:2015-11-20
DateofBirth:1935-01-08
Age:80years,10months,and12days
Birthdayin1monthsand19days
ReviewQuestions
11.1WhichstatementistrueabouttheDateandTimeAPI?
Selecttheonecorrectanswer.
(a)TheclassesLocalDateandLocalDateTimeprovidethe
WOW! eBook
www.wowebook.org
isLeapYear()methodtocheckforaleapyear.
(b)TheclassesLocalTime,LocalDate,andLocalDateTimeprovidethe
isEqual()methodtotestwhethertwotemporalobjectsofthesametypeare
equal.
(c)TheclassPeriodprovidesthewithWeeks()method,whichreturnsacopy
ofthisperiod,wherethenumberofdaysissetaccordingtothenumberofweeks
specified.
(d)TheclassesLocalTime,LocalDate,andPeriodprovidethe
plusWeeks()method,whichreturnsanewobject,wherethenumberofdays
correspondingtothespecifiednumberofweekshasbeenadded.
(e)Noneoftheabove.
11.2Whatwillthefollowingprogramprintwhencompiledandrun?
Clickheretoviewcodeimage
importjava.time.LocalDate;
publicclassRQ11A05{
publicstaticvoidmain(String[]args){
LocalDatedate=LocalDate.of(2016,3,1);
date.withMonth(4);
System.out.println(date.getYear()+“|”+
date.getMonth()+“|”+date.getDayOfMonth());
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile.
(b)Theprogramwillthrowaruntimeexceptionwhenrun.
(c)Theprogramwillprint2016|APRIL|1.
(d)Theprogramwillprint2016|4|1.
(e)Theprogramwillprint2016|MARCH|1.
(f)Theprogramwillprint2016|3|1.
(g)Theprogramwillprint2016|JULY|1.
(h)Theprogramwillprint2016|7|1.
11.3Whichdeclarationswillcorrectlycreatethedate13August2009?
Selectthefourcorrectanswers.
(a)LocalDatedate0=LocalDate.of(2009,7,13);
(b)LocalDatedate1=LocalDate.of(2009,8,13);
(c)LocalDatedate2=LocalDate.of(2009,Month.AUGUST,
13);
WOW! eBook
www.wowebook.org
(d)LocalDatedate3=LocalDate.of(0,0,
0).withYear(2009).withMonth(8).withDayOfMonth(13);
(e)LocalDatedate4=LocalDate.of(2008,7,
12).plusYears(1).plusMonths(1).plusDays(1);
(f)LocalDatedate5=newLocalDate(2009,8,13);
(g)LocalDatedate6=LocalDate.of(1,1,
1).plus(Period.of(2008,7,12));
11.4WhichdeclarationswillcorrectlyassignaninstanceoftheLocalTimeclassto
thedeclaredreference?
Selectthethreecorrectanswers.
(a)LocalTimetime1=LocalTime.of(12,60);
(b)LocalTimetime2=newLocalTime(12,60);
(c)LocalTimetime3=LocalTime.NOON.plusHours(-3);
(d)LocalTimetime4=LocalTime.NOON.minusHours(12);
(e)LocalTimetime5=LocalTime.MIDNIGHT.withHours(12);
(f)LocalTimetime6=
LocalTime.of(12,00).plusMinutes(-15);
11.5Whatwillthefollowingprogramprintwhencompiledandrun?
Clickheretoviewcodeimage
importjava.time.LocalTime;
publicclassRQ11A20{
publicstaticvoidmain(String[]args){
LocalTimetime=LocalTime.NOON;
time=time.plusHours(10).plusMinutes(120);
System.out.println(time);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile.
(b)Theprogramwillthrowaruntimeexceptionwhenrun.
(c)Theprogramwillprint00:00.
(d)Theprogramwillprint24:00.
(e)Noneoftheabove.
11.6Whatwillthefollowingprogramprintwhencompiledandrun?
Clickheretoviewcodeimage
importjava.time.Period;
publicclassRQ11A55{
WOW! eBook
www.wowebook.org
publicstaticvoidmain(String[]args){
Periodp1=Period.of(1,1,1);
Periodp2=Period.of(2,12,30);
p1=p1.plus(p2).plus(p1);
System.out.println(p1);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile.
(b)Theprogramwillthrowaruntimeexceptionwhenrun.
(c)TheprogramwillprintP6Y26M62D.
(d)TheprogramwillprintP4Y14M32D.
(e)Noneoftheabove.
11.7Whatwillthefollowingprogramprintwhencompiledandrun?
Clickheretoviewcodeimage
importjava.time.LocalDate;
publicclassRQ11A30{
publicstaticvoidmain(String[]args){
LocalDatedate=LocalDate.of(2015,1,1);
date=date.withYear(5).plusMonths(14);
System.out.println(date);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile.
(b)Theprogramwillthrowaruntimeexceptionwhenrun.
(c)Theprogramwillprint0006-03-01.
(d)Theprogramwillprint2021-03-01.
(e)Theprogramwillprint0005-15-01.
(f)Noneoftheabove.
11.8Whichexpressions,wheninsertedat(1),willresultinthefollowingoutput:
date2isafterdate1?
Clickheretoviewcodeimage
importjava.time.LocalDate;
importjava.time.Period;
publicclassRQ11A45{
publicstaticvoidmain(String[]args){
LocalDatedate1=LocalDate.of(2015,8,19);
LocalDatedate2=LocalDate.of(2015,10,23);
if(/*(1)INSERTCODEHERE*/){
System.out.println(“date2isafterdate1”);
}
}
WOW! eBook
www.wowebook.org
}
Selectthefivecorrectanswers.
(a)date2.isAfter(date1)
(b)date1.isAfter(date2)
(c)date2.isBefore(date1)
(d)date1.isBefore(date2)
(e)Period.between(date2,date1).isNegative()
(f)Period.between(date1,date2).isNegative()
(g)date2.until(date1).isNegative()
(h)date1.until(date2).isNegative()
(i)date1.compareTo(date2)<0
(j)date2.compareTo(date1)<0
11.4FormattingandParsing
Aformatterhastwoprimaryfunctions.Thefirstistocreateahuman-readabletextual
representationofanobject,aprocesscalledformattinganobject.Thesecondistocreate
anobjectfromastringcontainingatextualrepresentationofanobject,whichisthe
inverseofformatting.Thisprocessiscalledparsingastring.
Inthissectionwetakeacloserlookatformattingandparsingoftemporalobjects.In
particular,weconsiderthefollowingformatters,whichprovideincreasingflexibilityin
customizingformattingandparsingoftemporalobjects:
•DefaultformattersareimplicitlyusedbysuchmethodsasthetoString()
methodofthetemporalclasses.
•Predefinedformattersareready-madeformattersprovidedasconstantsbythe
java.time.format.DateTimeFormatterclass,suchasthosethatadhere
totheISOstandard(Table11.2,p.489).
WOW! eBook
www.wowebook.org
Table11.2SelectedISO-BasedPredefinedFormattersforDateandTime
•Localizedformattersarelocale-sensitiveformattersthatusetheformatstyles
definedbytheconstantsofthejava.time.format.FormatStyleenumtype
(Table11.3,p.490).Theseformattersarecreatedbythestaticfactorymethods
ofLocalizedType()oftheDateTimeFormatterclass,whereTypeis
eitherTime,Date,orDateTime(Table11.4,p.491).
Table11.3FormatStylesforDateandTime
•Customizedformattersusecustomizedformatstylesdefinedbypatternletters
(Table11.5,p.496).Theseformattersarecreatedbythestaticfactorymethod
ofPattern()oftheDateTimeFormatterclass.
Theidiomforusingaformatteristoobtainaformatterfirst,andthenpassittothe
methodsresponsibleforformattingandparsing.TheDateTimeFormatterclass
providesfactorymethodsforobtainingaformatter.Eachofthetemporalclasses
LocalTime,LocalDate,andLocalDateTimeprovidesthefollowingmethods:an
instancemethodformat()andastaticmethodparse().Thesetwomethodsdothe
formattingandtheparsingaccordingtotherulesoftheformatterthatispassedas
argument,respectively.Analogousmethodsforformattingandparsingarealsoprovided
bytheDateTimeFormatterclass,butarenotconsideredhere.
Itisagaintimetochantthemantraofimmutabilityandthread-safety.Formatterssupplied
WOW! eBook
www.wowebook.org
bytheDateTimeFormatterclassalsosubscribetothiscreed.Fromthemethod
headersoftheformat()andtheparse()methodsofthetemporalclasses,wecansee
thatthesemethodswillreadilycompilewithanyDateTimeFormatter.Thevalidityof
theformatterforagiventemporalobjectisresolvedatruntime,resultinginaresounding
exceptionifitisnotvalid.
Clickheretoviewcodeimage
//LocalTime,LocalDate,LocalDateTime
Stringformat(DateTimeFormatterformatter)
Thismethodformatsthetemporalobjectusingthespecifiedformatter,andreturns
theresultingstring.Eachtemporalclassprovidesthismethod.Thetemporalobject
isformattedaccordingtotherulesoftheformatter.Themethodthrowsa
java.time.DateTimeExceptionifformattingisunsuccessful.
Clickheretoviewcodeimage
//LocalTime,LocalDate,LocalDateTime
staticTemporalTypeparse(CharSequencetext)
staticTemporalTypeparse(CharSequencetext,DateTimeFormatterformatter)
Eachtemporalclassprovidesthesetwostaticmethods,whereTemporalType
canbeanyofthetemporalclassesLocalTime,LocalDate,or
LocalDateTime.
ThefirstmethodreturnsaninstanceoftheTemporalTypefromacharacter
sequence,usingthedefaultparsingrulesfortheTemporalType.
ThesecondmethodobtainsaninstanceoftheTemporalTypefromacharacter
sequence,usingthespecifiedformatter.
Bothmethodsreturnanobjectofaspecifictemporalclass,andboththrowa
java.time.format.DateTimeParseExceptionifparsingis
unsuccessful.
DefaultFormatters
SofarinthischapterwehavereliedonthetoString()methodoftheindividual
temporalclassesforcreatingatextualrepresentationofatemporalobject.Thedefault
formatterusedbythetoString()methodappliestheformattingrulesdefinedbythe
ISOstandard.Inthefollowingcode,theresultofformattingaLocalTimeobjectis
shownat(1):
Clickheretoviewcodeimage
LocalTimetime=LocalTime.of(12,30,15,99);
StringstrTime=time.toString();//(1)12:30:15.000000099
LocalTimeparsedTime=LocalTime.parse(strTime);//(2)
System.out.println(time.toString().equals(parsedTime.toString()));//true
Eachtemporalclassprovidesastaticmethodparse(CharSequencetext)that
parsesacharactersequenceusingadefaultformatterthatcomplieswiththeISOstandard.
Intheprecedingcode,thetextualrepresentationcreatedin(1)isparsedin(2)toobtaina
WOW! eBook
www.wowebook.org
newLocalTimeobject.Notsurprisingly,thetextualrepresentationsofthetwo
LocalTimeobjectsreferredtobythereferencestimeandparsedTimeareequal.
Thenextlineofcodeshowsthattheargumentstringpassedtotheparse()methodis
notinaccordancewiththeISOstandard,resultinginaruntimeexception:
Clickheretoviewcodeimage
LocalTimebadTime=LocalTime.parse(“12.30.15”);//DateTimeParseException
Example11.6showsexamplesofformattingandparsingobjectsofthethreetemporal
classesLocalTime,LocalDate,andLocalDateTime.Itisworthstudyingthe
outputfromthisexampletofamiliarizeyourselfwiththeISOstandardforformatting
temporalobjects.Tosummarize,thisstandardisemployedbythetoString()
andparse(CharSequencetext)methodswhenformattingandparsingtemporal
objects,respectively.
Example11.6UsingDefaultDateandTimeFormatters
Clickheretoviewcodeimage
importjava.time.LocalDate;
importjava.time.LocalDateTime;
importjava.time.LocalTime;
publicclassDefaultFormattingParsing{
publicstaticvoidmain(String[]args){
System.out.printf(“%70s%n”,“Defaultformatting|Defaultparsing”);
//LocalTime
LocalTimetime=LocalTime.of(12,30,15,99);
StringstrTime=time.toString();//(1)
12:30:15.000000099
LocalTimeparsedTime=LocalTime.parse(strTime);//(2)
System.out.printf(“LocalTime:%33s|%s%n”,strTime,parsedTime);
//LocalDate
LocalDatedate=LocalDate.of(2015,4,28);
StringstrDate=date.toString();//2015-04-28
LocalDateparsedDate=LocalDate.parse(strDate);
System.out.printf(“LocalDate:%33s|%s%n”,strDate,parsedDate);
//LocalDateTime
LocalDateTimedateTime=LocalDateTime.of(date,time);
StringstrDateTime=dateTime.toString();//2015-04-
28T12:30:15.000000099
LocalDateTimeparsedDateTime=LocalDateTime.parse(strDateTime);
System.out.printf(“LocalDateTime:%23s|%s%n”,strDateTime,
parsedDateTime);
}
}
Outputfromtheprogram:
Clickheretoviewcodeimage
Defaultformatting|Defaultparsing
LocalTime:12:30:15.000000099|12:30:15.000000099
LocalDate:2015-04-28|2015-04-28
LocalDateTime:2015-04-28T12:30:15.000000099|2015-04-28T12:30:15.000000099
WOW! eBook
www.wowebook.org
PredefinedFormatters
TheDateTimeFormatterclassprovidesamyriadofpredefinedformattersfor
temporalobjects,themajorityofwhichcomplywiththeISOstandard.Table11.2shows
fourISO-basedpredefinedformattersfromthisclass.Wehavealsoindicatedwhich
temporalclassestheycanbeusedwithforformattingandparsing;withcertainclasses,
however,theycanbeusedonlyforeitherformattingorparsing.
AnexampleofusinganISO-basedpredefinedformatterisgivennext.Notethatthe
formatterobtainedat(1)isaformatterfordate-basedvalues.Itcanbeusedonlywith
temporalobjectsthathavedate-basedvalues—inotherwords,theLocalDateand
LocalDateTimeclasses.Thisformatterispassedat(2)totheformat()method,to
createatextualrepresentationofadate.Theresultingstringisparsedat(3)bythe
parse()methodthatusesthesameformatter.Theresultingdateisalsoformattedusing
thesameformatterat(4).Itishardlysurprisingthatthetextualrepresentationsofboth
datesareequal.
Clickheretoviewcodeimage
DateTimeFormatterdf=DateTimeFormatter.ISO_LOCAL_DATE;//(1)
LocalDatedate=LocalDate.of(1935,1,8);
StringstrDate=date.format(df);//(2)1935-01-
08
LocalDateparsedDate=LocalDate.parse(strDate,df);//(3)
System.out.println(strDate+“|”+
parsedDate.format(df));//(4)1935-01-08|1935-
01-08
Asthiscodeshows,aformattercanbereused,bothforformattingandforparsing.The
codeat(4)inthenextexampleappliestheformatterfrom(1)intheprecedingcode
snippettoformataLocalDateTimeobject.Itshouldnotcomeasasurprisethatthe
resultingtextualrepresentationoftheLocalDateTimeobjectpertainstoonlydate-
basedvaluesintheobject;thetime-basedvaluesoftheLocalDateTimeobjectare
ignored.Parsingthistextualrepresentationbackwiththesameformatterat(5)willyield
onlyaLocalDateobject.
Clickheretoviewcodeimage
LocalDateTimedateTime=LocalDateTime.of(1935,1,8,12,45);
StringstrDate2=dateTime.format(df);//(4)1935-01-
08
LocalDateparsedDate2=LocalDate.parse(strDate2,df);//(5)LocalDate
Tosummarize,theDateTimeFormatter.ISO_LOCAL_DATEcanbeusedtoformat
andparseaLocalDate,butcanonlyformatthedatepartofaLocalDateTime
object.
Usingthisdate-basedformatterwithaLocalTimeobjectiscourtingdisaster,asshown
bythefollowingcode.Formattingwiththisformatterresultsina
java.time.temporal.UnsupportedTemporalTypeException,andparsing
resultsinajava.time.format.DateTimeParseException.
Clickheretoviewcodeimage
StringtimeStr2=LocalTime.NOON.format(df);//
UnsupportedTemporalTypeException
WOW! eBook
www.wowebook.org
LocalTimetime2=LocalTime.parse(“12:00”,df);//DateTimeParseException
LocalizedFormatters
FormoreflexibleformattersthanthepredefinedISO-basedformatters,the
DateTimeFormatterclassprovidesthestaticfactorymethods
ofLocalizedType(),whereTypeiseitherTime,Date,orDateTime.These
methodscreateformattersthatusealocale-specificformatstyle.However,theformat
stylecannotbechangedaftertheformatteriscreated.Formatstylesaredefinedbythe
enumtypejava.time.format.FormatStyle,andareshowninTable11.3.The
stylesdefinelocale-specificformatpatternsthatvaryintheirdegreeofverbosity.
Clickheretoviewcodeimage
staticDateTimeFormatterofLocalizedTime(FormatStyletimeStyle)
staticDateTimeFormatterofLocalizedDate(FormatStyledateStyle)
staticDateTimeFormatterofLocalizedDateTime(FormatStyledateTimeStyle)
staticDateTimeFormatterofLocalizedDateTime(FormatStyledateStyle,
FormatStyletimeStyle)
ThesestaticfactorymethodsoftheDateTimeFormattercreatealocale-
specificformatterthatwillformatorparseatime,adate,oradate-time,
respectively,usingthespecifiedformatstyle.
Inthecodethatfollows,thedateformattercreatedat(1)isusedat(3)toparsetheinput
stringfrom(2).
Clickheretoviewcodeimage
DateTimeFormatterdf=
DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);//(1)
StringinputStr=“2/29/15”;//(2)
LocalDatedate=LocalDate.parse(inputStr,df);//(3)
System.out.println(date.format(df));//(4)2/28/15
System.out.println(date);//(5)2015-02-28
Inthiscode,theinputstring"2/29/15"isspecifiedintheshortstyleofthedefault
locale(whichinourcaseistheUnitedStates).Theinputstringisparsedbythedate
formatter(usingtheshortformatstyle)tocreateanewLocalDateobject.Althoughthe
value29isinvalidforthenumberofdaysinFebruaryfortheyear2015,theoutputshows
thatitwasadjustedcorrectly.Theformatstyleinthedateformatter(inthiscase,
FormatStyle.SHORT)andthecontentsoftheinputstring(inthiscase,"2/29/15")
mustbecompatible.Ifthisisnotthecase,aDateTimeParseExceptionisthrown.
TheLocalDateobjectparsedfromtheinputstringisformattedat(4)usingthesame
formatter.Notethatintheprintstatementat(5),theLocalDateobjectfromtheparsing
isconvertedtoastringbytheLocalDate.toString()methodusingtheimplicit
ISO-basedformatter.
Table11.4showswhichtemporalclassescanbeformattedandparsedbyacombinationof
aformatstylefromTable11.3andanofLocalizedType()methodofthe
DateTimeFormatterclass,whereTypeiseitherTime,Date,orDateTime.The
tablealsoindicatesthatcertainclassescanonlybeeitherformattedorparsed,depending
ontheformatterreturnedbythemethod.Forexample,inTable11.4wecanseethatthe
WOW! eBook
www.wowebook.org
methodcallDateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
willreturnaformatterthatcanbeusedtobothformatandparseinstancesofthe
LocalDateclass,butitwillonlyformatthedatepartofaLocalDateTimeobject.
Thisformatterwillusethespecifiedformatstyle,FormatStyle.SHORT.
Table11.4CombinationofFormatStylesandLocalizedFormatters
Example11.7,Example11.8,andExample11.9illustratetheuseoftheformatters
suppliedbytheDateTimeFormatterclass.Itisrecommendedtostudytheoutput
fromtheseexamples,togetherwithTable11.2,Table11.3,andTable11.4.
Example11.7illustratesformattersreturnedbytheofLocalizedTime()method(the
secondcolumninTable11.4).Combinationsofthismethodandvalidformatstylesare
createdinaDateTimeFormatterarrayat(1).Theseformatterscanbeusedtoformat
andparsetemporalobjectscomprisingonlytime-basedvalues(i.e.,LocalTimeobjects),
asshownat(4)and(5),respectively.Inaddition,theseformatterscanbeusedtoformat
onlythetimepartofaLocalDateTimeobject,asshownat(6).Theseformatterscannot
beusedforLocalDateobjects,astheydonotdealwithdate-basedvalues.
WOW! eBook
www.wowebook.org
Example11.7UsingPredefinedFormatStyleswithTime-BasedValues
Clickheretoviewcodeimage
importjava.time.DateTimeException;
importjava.time.LocalDateTime;
importjava.time.LocalTime;
importjava.time.format.DateTimeFormatter;
importjava.time.format.DateTimeParseException;
importjava.time.format.FormatStyle;
publicclassFormattingParsingTime{
publicstaticvoidmain(String[]args){
//Createsometimeformatters:
DateTimeFormatter[]timeFormatters={//(1)
DateTimeFormatter.ISO_LOCAL_TIME,
DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT),
DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM),
//ThefollowingtwocombinationsresultinaDateTimeExceptionat
runtime:
//DateTimeFormatter.ofLocalizedTime(FormatStyle.LONG),
//DateTimeFormatter.ofLocalizedTime(FormatStyle.FULL)
};
String[]formatStyles={“ISO”,“SHORT”,“MEDIUM”,“LONG”,“FULL”};
//Formattingandparsingatime:
LocalTimetime=LocalTime.of(14,15,30);//
(2)
LocalDateTimedateTime=LocalDateTime.of(2015,12,1,14,15,30);//
(3)
inti=0;
System.out.println(“StyleFormattingoftime,date-time|Parsingof
time”);
for(DateTimeFormattertf:timeFormatters)
try{
StringstrTime=time.format(tf);//(4)
LocalTimeparsedTime=LocalTime.parse(strTime,tf);//(5)
StringstrTime2=dateTime.format(tf);//(6)
System.out.printf(“%-7s”,formatStyles[i++]);
System.out.printf(“%14s|%14s|%14s%n”,
strTime,strTime2,parsedTime.format(tf));
}catch(DateTimeParseExceptionpe){
System.out.println(pe);
return;
}catch(DateTimeExceptiondte){
System.out.println(dte);
return;
}
}
}
Outputfromtheprogram(defaultlocaleistheUnitedStates):
Clickheretoviewcodeimage
StyleFormattingoftime,date-time|Parsingoftime
ISO14:15:30|14:15:30|14:15:30
SHORT2:15PM|2:15PM|2:15PM
MEDIUM2:15:30PM|2:15:30PM|2:15:30PM
Example11.8illustratesformattersreturnedbytheofLocalizedDate()method(the
thirdcolumninTable11.4,p.491).Combinationsofthismethodandavalidformatstyle
WOW! eBook
www.wowebook.org
arecreatedinaDateTimeFormatterarrayat(1).Theseformatterscanbeusedto
formatandparsetemporalobjectscomprisingonlydate-basedvalues(i.e.,LocalDate
objects),asshownat(4)and(5),respectively.Inaddition,theseformatterscanbeusedto
formatonlythedatepartofaLocalDateTimeobject,asshownat(6).Theseformatters
cannotbeusedforLocalTimeobjects,astheydonotdealwithtime-basedvalues.
Example11.8UsingPredefinedFormatStyleswithDate-BasedValues
Clickheretoviewcodeimage
importjava.time.DateTimeException;
importjava.time.LocalDate;
importjava.time.LocalDateTime;
importjava.time.format.DateTimeFormatter;
importjava.time.format.DateTimeParseException;
importjava.time.format.FormatStyle;
publicclassFormattingParsingDate{
publicstaticvoidmain(String[]args){
//Createsomedateformatters:
DateTimeFormatter[]dateFormatters={//(1)
DateTimeFormatter.BASIC_ISO_DATE,
DateTimeFormatter.ISO_LOCAL_DATE,
DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT),
DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM),
DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG),
DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)
};
String[]formatStyles={“BASIC”,“ISO”,“SHORT”,“MEDIUM”,“LONG”,
“FULL”};
//Formattingandparsingadate:
LocalDatedate=LocalDate.of(2015,12,1);//
(2)
LocalDateTimedateTime=LocalDateTime.of(2015,12,1,14,15,30);//
(3)
inti=0;
System.out.printf(“%s%39s%30s%n”,“Style”,“Formattingofdate,date-
time”,
”|Parsingofdate”);
for(DateTimeFormatterdf:dateFormatters)
try{
StringstrDate=date.format(df);//(4)
LocalDateparsedDate=LocalDate.parse(strDate,df);//(5)
StringstrDate2=dateTime.format(df);//(6)
System.out.printf(“%-6s”,formatStyles[i++]);
System.out.printf(“%25s|%25s|%s%n”,
strDate,strDate2,parsedDate.format(df));
}catch(DateTimeParseExceptionpe){
System.out.println(pe);
return;
}catch(DateTimeExceptiondte){
System.out.println(dte);
return;
}
}
}
Outputfromtheprogram(defaultlocaleistheUnitedStates,outputeditedtofitonpage):
Clickheretoviewcodeimage
WOW! eBook
www.wowebook.org
StyleFormattingofdate,date-time|Parsingofdate
BASIC20151201|20151201|20151201
ISO2015-12-01|2015-12-01|2015-12-01
SHORT12/1/15|12/1/15|12/1/15
MEDIUMDec1,2015|Dec1,2015|Dec1,2015
LONGDecember1,2015|December1,2015|December1,2015
FULLTuesday,December1,2015|Tuesday,December1,2015|Tuesday,December1,
2015
Example11.9illustratesformattersreturnedbytheofLocalizedDateTime()
method(thefourthcolumninTable11.4,p.491).Combinationsofthismethodandvalid
formatstylesarecreatedinaDateTimeFormatterarrayat(1).Theseformatterscan
beusedtoformatandparsetemporalobjectscomprisingbothtime-basedanddate-based
values(i.e.,LocalDateTimeobjects),asshownat(3)and(4),respectively.Inaddition,
theseformatterscanbeusedtoparsethetimepartorthedatepartofadate-timetextual
representationtoobtainaLocalTimeobjectoraLocalDateobject,asshownat(5)
and(6),respectively.TheseformatterscannotbeusedtoformateitheraLocalTime
objectoraLocalDateobject,astheyrequirebothtime-basedanddate-basedvalues
whenusedforformatting.
Example11.9UsingPredefinedFormatStyleswithDateandTime-BasedValues
Clickheretoviewcodeimage
importjava.time.DateTimeException;
importjava.time.LocalDate;
importjava.time.LocalDateTime;
importjava.time.LocalTime;
importjava.time.format.DateTimeFormatter;
importjava.time.format.DateTimeParseException;
importjava.time.format.FormatStyle;
publicclassFormattingParsingDateTime{
publicstaticvoidmain(String[]args){
//Createsomedate-timeformatters:
DateTimeFormatter[]dtFormatters={//
(1)
DateTimeFormatter.ISO_LOCAL_DATE_TIME,
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT),
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM),
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM,
FormatStyle.SHORT),
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT,
FormatStyle.MEDIUM),
//ThefollowingtwocombinationsresultinaDateTimeExceptionat
runtime:
//DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG),
//DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL)
};
String[]formatStyles={“ISO”,“SHORT”,“MEDIUM”,
“MEDIUM,SHORT”,“SHORT,MEDIUM”};
//Formattingandparsingadate-time:
LocalDateTimedateTime=LocalDateTime.of(2015,12,1,14,15,30);//
(2)
inti=0;
System.out.printf(“%s%31s%38s%n”,“Style”,“Formattingofdate-time|”,
“Parsingofdate-time,date,time”);
WOW! eBook
www.wowebook.org
for(DateTimeFormatterdtf:dtFormatters)
try{
StringstrDateTime=dateTime.format(dtf);//(3)
LocalDateTimeparsedDateTime
=LocalDateTime.parse(strDateTime,dtf);//(4)
LocalTimeparsedTime=LocalTime.parse(strDateTime,dtf);//(5)
LocalDateparsedDate=LocalDate.parse(strDateTime,dtf);//(6)
System.out.printf(“%-12s”,formatStyles[i++]);
System.out.printf(“%23s|%22s|%s|%8s%n”,strDateTime,
parsedDateTime.format(dtf),parsedDate,
parsedTime);
}catch(DateTimeParseExceptionpe){
System.out.println(pe);
return;
}catch(DateTimeExceptiondte){
System.out.println(dte);
return;
}
}
}
Outputfromtheprogram(defaultlocaleistheUnitedStates):
Clickheretoviewcodeimage
StyleFormattingofdate-time|Parsingofdate-time,date,time
ISO2015-12-01T14:15:30|2015-12-01T14:15:30|2015-12-
01|14:15:30
SHORT12/1/152:15PM|12/1/152:15PM|2015-12-
01|14:15
MEDIUMDec1,20152:15:30PM|Dec1,20152:15:30PM|2015-12-
01|14:15:30
MEDIUM,SHORTDec1,20152:15PM|Dec1,20152:15PM|2015-12-
01|14:15
SHORT,MEDIUM12/1/152:15:30PM|12/1/152:15:30PM|2015-12-
01|14:15:30
CustomizedFormatters
Formorefine-grainedformattingandparsingcapabilitiesfordate/time-basedvalues,we
canusetheofPattern()methodoftheDateTimeFormatterclass.Thismethod
createsformattersthatinterpretdate/time-basedvaluesaccordingtoastringpatternthatis
definedusingthepatternlettersshowninTable11.5.
WOW! eBook
www.wowebook.org
Table11.5SelectedDate/TimePatternLetters
Clickheretoviewcodeimage
staticDateTimeFormatterofPattern(Stringpattern)
Thisstaticmethodcreatesaformatterusingthespecifiedpattern.Thesetof
temporalobjectsitcanbeusedwithdependsonthepatternlettersusedinthe
specificationofthepattern.Theletterpatterndefinestherulesusedbythe
formatter.ThemethodthrowsanIllegalArgumentExceptionifthepattern
isinvalid.
WOW! eBook
www.wowebook.org
Table11.5providesanoverviewofselectedpatternletters.Alllettersarereservedwhen
usedinaletterpattern.Asequenceofcharacterscanbeescapedbyenclosingitinsingle
quotes(e.g.,"EEEE'at'HH:mm").Non-lettercharactersinthestringareinterpreted
verbatimandneednotbeescapedusingsinglequotes(e.g.,"uuuu.MM.dd@
HH:mm:ss").Thenumberoftimesapatternletterisrepeatedcanhaveabearingonthe
interpretationofthecorrespondingdate/time-basedvalue.TheuppercaseletterM(Month
oftheyear)shouldnotbeconfusedwiththelowercaseletterm(minutesinthehour).
Aletterpatterncanbeusedtoformatatemporalobjectifthetemporalobjecthasthe
temporalvaluesrequiredbythepattern.Thepattern"'Hour':HH"canbeusedto
formatthehourpartofanyLocalTimeobjectoraLocalDateTimeobject,butnota
LocalDate.
Aletterpatterncanbeusedtoparseastringifthestringmatchesthepatternandtheletter
patternspecifiesthemandatorypartsneededtoconstructatemporalobject.Thepattern
"MM/dd/uuuu"canbeusedtoparsethestring"08/13/2009"toobtaina
LocalDateobject,butnotaLocalDateTimeobject.Thelatterrequiresthetimepart
aswell.
Example11.10demonstratesbothformattingandparsingoftemporalobjectsusingletter
patterns.
•Thecodeat(1)and(2)demonstratesusingaletterpatternforthetimeparttoboth
formatandparseaLocalTimeobject,respectively.Thesamepatternisusedat(3)
toformatonlythetimepartofaLocalDateTimeobject.
•Thecodeat(4)and(5)demonstratesusingaletterpatternforthedateparttoboth
formatandparseaLocalDateobject,respectively.Thesamepatternisusedat(6)
toformatonlythedatepartofaLocalDateTimeobject.
•Thecodeat(7)and(8)demonstratesusingaletterpatternforthedateandtimeparts
tobothformatandparseaLocalDateTimeobject,respectively.Thesamepattern
isusedat(9)and(10)toparsethetextualrepresentationofaLocalDateTimeto
obtainaLocalDateandaLocalTimeobject,respectively.
TheusageofletterpatternswiththeofPattern()methodinExample11.10is
analogoustotheusageofthepredefinedformatstyleswiththeofLocalizedType()
methods(Table11.4,p.491).Themaindifferenceisthatletterpatternsprovidegreat
flexibilityincreatingcustomizedformatstyles.
Example11.10FormattingandParsingwithLetterPatterns
Clickheretoviewcodeimage
importjava.time.LocalDate;
importjava.time.LocalDateTime;
importjava.time.LocalTime;
importjava.time.format.DateTimeFormatter;
publicclassFormattingParsingWithPatterns{
publicstaticvoidmain(String[]args){
WOW! eBook
www.wowebook.org
LocalTimetime=LocalTime.of(12,30,15,99);
LocalDatedate=LocalDate.of(2015,4,28);
LocalDateTimedateTime=LocalDateTime.of(date,time);
System.out.printf(“Time:%s%n”,time);
System.out.printf(“Date:%s%n”,date);
System.out.printf(“DateTime:%s%n%n”,dateTime);
//Timepart
StringtimePattern=“HH::mm::ss:SSS”;
DateTimeFormattertimeFormatter=
DateTimeFormatter.ofPattern(timePattern);
StringstrTime=time.format(timeFormatter);//(1)
LocalTimeparsedTime=LocalTime.parse(strTime,timeFormatter);//(2)
StringstrTime2=dateTime.format(timeFormatter);//(3)
System.out.printf(“Timepattern:%s%n”,timePattern);
System.out.printf(“LocalTime:%s|%s%n”,
strTime,parsedTime.format(timeFormatter));
System.out.printf(“LocalDateTime(formattedtimepart):%s%n%n”,
strTime2);
//Datepart
StringdatePattern=“EEEE,uuuu/MMMM/dd”;
DateTimeFormatterdateFormatter=
DateTimeFormatter.ofPattern(datePattern);
StringstrDate=date.format(dateFormatter);//(4)
LocalDateparsedDate=LocalDate.parse(strDate,dateFormatter);//(5)
StringstrDate2=dateTime.format(dateFormatter);//(6)
System.out.printf(“Datepattern:%s%n”,datePattern);
System.out.printf(“LocalDate:%s|%s%n”,
strDate,parsedDate.format(dateFormatter));
System.out.printf(“LocalDateTime(formatteddatepart):%s%n%n”,
strDate2);
//Dateandtimeparts
StringdtPattern=“EE,HH::mm::ss‘on’uuuu/MM/dd”;
DateTimeFormatterdtFormatter=DateTimeFormatter.ofPattern(dtPattern);
StringstrDateTime=dateTime.format(dtFormatter);//
(7)
LocalDateTimeparsedDateTime=LocalDateTime.parse(strDateTime,//
(8)
dtFormatter);
LocalDateparsedDate3=LocalDate.parse(strDateTime,dtFormatter);//
(9)
LocalTimeparsedTime3=LocalTime.parse(strDateTime,dtFormatter);//
(10)
System.out.printf(“DateTimepattern:%s%n”,dtPattern);
System.out.printf(“LocalDateTime:%s|%s%n”,
strDateTime,parsedDateTime.format(dtFormatter));
System.out.printf(“LocalDate(parseddatepart):%s%n”,
parsedDate3.format(dateFormatter));
System.out.printf(“LocalTime(parsedtimepart):%s%n”,
parsedTime3.format(timeFormatter));
}
}
Probableoutputfromtheprogram:
Clickheretoviewcodeimage
Time:12:30:15.000000099
Date:2015-04-28
DateTime:2015-04-28T12:30:15.000000099
WOW! eBook
www.wowebook.org
Timepattern:HH::mm::ss:SSS
LocalTime:12::30::15:000|12::30::15:000
LocalDateTime(formattedtimepart):12::30::15:000
Datepattern:EEEE,uuuu/MMMM/dd
LocalDate:Tuesday,2015/April/28|Tuesday,2015/April/28
LocalDateTime(formatteddatepart):Tuesday,2015/April/28
DateTimepattern:EE,HH::mm::ss‘on’uuuu/MM/dd
LocalDateTime:Tue,12::30::15on2015/04/28|Tue,12::30::15on2015/04/28
LocalDate(parseddatepart):Tuesday,2015/April/28
LocalTime(parsedtimepart):12::30::15:000
Example11.11demonstratestheversatilityofletterpatternsforformattingtemporal
objects.Notehowapatterncanbeusedtoformatspecificpartsofadate-time,andhow
theinterpretationofapatternletterchangeswiththenumberoftimesitisrepeated.
Example11.11FormattingwithDate/TimeLetterPatterns
Clickheretoviewcodeimage
importjava.time.LocalDateTime;
importjava.time.format.DateTimeFormatter;
publicclassDateTimeFormattingPatterns{
staticpublicvoidmain(String[]args){
//DateTimetoformat.
LocalDateTimedateTime=LocalDateTime.of(1972,12,2,14,45,30);
//Formattingpatterns.
String[]patterns={
“dd/MM/uu”,
“u/M/d”,
“dMMMMuuuu”,
“‘Anniversary’:dMMMM”,
“uuuu.MM.dd”,
“uuuu.MM.dd@hh:mm:ss”,
“uuuu.MMMM.ddhh:mma”,
“EEE,MMMd’th’,”uu”,
“EEEEdMMMMuuuu”,
“EEEdMMMuuu”,
“EEdMMuu”,
“EdMu”,
“h:ma”,
“hh:mm”,
“HH:mm”,
“HH:mm:ss”,
“‘Hour’:HH”,
“EEEathh:mm”,//IllegalArgumentException-Unknownpatternletter:
t
“hh::mmm”,//IllegalArgumentException-Toomanypattern
letters:m
};
System.out.println(“Formattingdate/time(”+dateTime+“)”+
”accordingtodifferentpatterns:”);
for(Stringpattern:patterns){
Stringoutput;
try{
DateTimeFormatterformatter=DateTimeFormatter.ofPattern(pattern);
output=dateTime.format(formatter);
WOW! eBook
www.wowebook.org
}catch(IllegalArgumentExceptione){
output=String.format(“%s-%s”,e.getClass().getSimpleName(),
e.getMessage());
}
System.out.printf(“%25s%s%n”,pattern,output);
}
}
}
Probableoutputfromtheprogram(defaultlocaleistheUnitedStates):
Clickheretoviewcodeimage
Formattingdate/time(1972-12-02T14:45:30)accordingtodifferentpatterns:
dd/MM/uu02/12/72
u/M/d1972/12/2
dMMMMuuuu2December1972
‘Anniversary’:dMMMMAnniversary:2December
uuuu.MM.dd1972.12.02
uuuu.MM.dd@hh:mm:ss1972.12.02@02:45:30
uuuu.MMMM.ddhh:mma1972.December.0202:45PM
EEE,MMMd’th’,”uuSat,Dec2th,‘72
EEEEdMMMMuuuuSaturday2December1972
EEEdMMMuuuSat2Dec1972
EEdMMuuSat21272
EdMuSat2121972
h:ma2:45PM
hh:mm02:45
HH:mm14:45
HH:mm:ss14:45:30
‘Hour’:HHHour:14
EEEathh:mmIllegalArgumentException-Unknownpatternletter:
t
hh::mmmIllegalArgumentException-Toomanypattern
letters:m
ReviewQuestions
11.9Whichstatementistrueaboutformattingandparsingoftemporalobjects?
Selecttheonecorrectanswer.
(a)TheDateTimeFormatterclassprovidesonlyfactorymethodstoobtain
predefinedformatters.
(b)Thestylesdefinedbythejava.time.format.FormatStyleenumtype
arebasedontheISOstandard.
(c)TheofLocalizedDate()methodoftheDateTimeFormatterclass
returnsaformatterthatisbasedonaletterpatternpassedasargumenttothe
method.
(d)Thepattern"yy-mm-dd"canbeusedtocreateaformatterthatcanformata
LocalDateobject.
(e)Noneoftheabove.
11.10Whichcode,wheninsertedat(1),willmaketheprogramcompileandexecute
normally?
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
importjava.time.LocalDate;
importjava.time.LocalDateTime;
importjava.time.LocalTime;
importjava.time.format.DateTimeFormatter;
publicclassRQ11A75{
publicstaticvoidmain(String[]args){
Stringpattern=“MM/dd/yyyy‘at’HH:mm:ss”;
StringinputStr=“02/29/2015at00:15:30”;
DateTimeFormatterdtf=DateTimeFormatter.ofPattern(pattern);
//(1)INSERTCODEHERE.
}
}
Selectthefourcorrectanswers.
(a)LocalTimetime=LocalTime.parse(inputStr,dtf);
(b)LocalDatedate=LocalDate.parse(inputStr,dtf);
(c)LocalDateTimedateTime=
LocalDateTime.parse(inputStr,dtf);
(d)StringtimeStr=LocalTime.MIDNIGHT.format(dtf);
(e)StringdateStr=LocalDate.of(2015,12,
24).format(dtf);
(f)StringdateTimeStr=LocalDateTime.of(2015,12,24,
0,0).format(dtf);
11.11Whichcode,wheninsertedat(1),willmaketheprogramcompileandexecute
normally?
Clickheretoviewcodeimage
importjava.time.LocalDate;
importjava.time.LocalDateTime;
importjava.time.LocalTime;
importjava.time.format.DateTimeFormatter;
publicclassRQ11A85{
publicstaticvoidmain(String[]args){
Stringpattern=“‘Date:’dd|MM|yyyy”;
StringinputStr=“Date:02|12|2015”;
DateTimeFormatterdtf=DateTimeFormatter.ofPattern(pattern);
//(1)INSERTCODEHERE.
}
}
Selectthethreecorrectanswers.
(a)LocalTimetime=LocalTime.parse(inputStr,dtf);
(b)LocalDatedate=LocalDate.parse(inputStr,dtf);
(c)LocalDateTimedateTime=
LocalDateTime.parse(inputStr,dtf);
(d)StringtimeStr=LocalTime.MIDNIGHT.format(dtf);
WOW! eBook
www.wowebook.org
(e)StringdateStr=LocalDate.of(2015,12,
24).format(dtf);
(f)StringdateTimeStr=LocalDateTime.of(2015,12,24,
0,0).format(dtf);
11.12Whichcode,wheninsertedat(1),willresultinthefollowingoutput:
Clickheretoviewcodeimage
5minutespast9
importjava.time.LocalTime;
importjava.time.format.DateTimeFormatter;
publicclassRQ11A96{
publicstaticvoidmain(String[]args){
//(1)INSERTCODEHERE.
StringinputStr=“5minutespast9”;
DateTimeFormatterformatter=DateTimeFormatter.ofPattern(pattern);
LocalTimetime=LocalTime.parse(inputStr,formatter);
System.out.println(time.format(formatter));
}
}
Selecttheonecorrectanswer.
(a)Stringpattern="m'minutespast'h";
(b)Stringpattern="M'minutespast'h";
(c)Stringpattern="m'minutespast'ha";
(d)Stringpattern="m'minutespast'Ha";
(e)Stringpattern="m'minutespast'H";
(f)Stringpattern="mm'minutespast'H";
(g)Stringpattern="M'minutespast'H";
11.13Whichcode,wheninsertedat(1),willmaketheprogramcompileandexecute
normally?
Clickheretoviewcodeimage
importjava.time.LocalDate;
importjava.time.LocalDateTime;
importjava.time.LocalTime;
importjava.time.format.DateTimeFormatter;
importjava.time.format.FormatStyle;
publicclassRQ11A90{
publicstaticvoidmain(String[]args){
//(1)INSERTCODEHERE.
StringtimeStr=LocalTime.NOON.format(dtf);
StringdateStr=LocalDate.of(2015,12,24).format(dtf);
StringdateTimeStr=LocalDateTime.of(2015,12,24,12,
0).format(dtf);
}
}
WOW! eBook
www.wowebook.org
Selecttheonecorrectanswer.
(a)
Clickheretoviewcodeimage
DateTimeFormatterdtf=
DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
(b)
Clickheretoviewcodeimage
DateTimeFormatterdtf=
DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT);
(c)
Clickheretoviewcodeimage
DateTimeFormatterdtf=
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT);
(d)Noneoftheabove.
ChapterSummary
Thefollowingtopicswerecoveredinthischapter:
•Anoverviewofclassesinthejava.timepackagethatrepresentapointintime:a
(clock)time(LocalTime),adate(LocalDate),adate-timecombination
(LocalDateTime),andaclassthatrepresentsanamountoftimeinyears,months,
anddays(Period).
•Theconsequencesofimmutabilityforobjectsthatrepresenttemporalconcepts
•Thenamingconventionsusedformethodsinthetemporalclassesthatfacilitatetheir
usage
•Creating,querying,converting,andcomparingtemporalobjects
•Writingcodetodotemporalarithmetic
•Formattingandparsingusingdefaultformatters
•FormattingandparsingusingISO-basedpredefinedformattersofthe
DateTimeFormatterclass
•Formattingandparsingusinglocalizedformattersthatarebasedonthepredefined
formatstylesdefinedbythejava.time.format.FormatStyleenumtype
•Formattingandparsingusingcustomizedformattersthatarebasedonletterpatterns
•Theexceptionsthrownwhenformattingandparsingtemporalobjects
ProgrammingExercise
11.1Printstatisticsaboutastronautswhohavestayedonaspacestation.
Skeletoncodefortheproblemisprovidedinthisexercise.TheclassAstronaut
WOW! eBook
www.wowebook.org
representsstatisticsaboutanastronaut:
•Thenameoftheastronaut(astronautName)
•Thedateandtimewhentheastronautarrivedatthespacestation
(arrivalDateTime)
•ThescheduleddateofreturntoEarthfortheastronaut
(scheduledReturnDate)
•Theactualperiodofstayatthespacestation(actualPeriodOfStay),which
canbelongerorshorterthanthescheduledlengthofstay
Theprogramshouldprintthefollowingreport:
Clickheretoviewcodeimage
NameArr.DateSched.ReturnAct.ReturnStatusAct.Stay
Sched.StayDiff
AstroAli2010/03/012010/05/012010/06/01
DelayedP3MP2MP1M
LailaLightyear2015/02/012015/06/302015/08/30Delayed
P210DP4M29DP2M
OrbitOrwell2014/03/012014/09/012014/09/01On
timeP6MP6MP0D
Rocket
Rogers2013/07/312013/09/302013/09/29EarlyP60DP1M30DP-
1D
Sam
Spacey2009/01/012009/11/012009/04/01EarlyP90DP10MP-
7M
Eachrowcontainsthename(Namecolumn),thearrivaldateatthespacestation
(Arr.Datecolumn),andthescheduledreturndate(Sched.Returncolumn)foreach
astronaut.Inaddition,eachrowcontainstheactualdateofreturn(Act.Returncolumn)
determinedbytheactuallengthofstay(Act.Staycolumn);whethertheastronautwas
Delayed,Ontime,orEarlyinreturningtoEarth(Statuscolumn);thescheduled
lengthofstaythatwasoriginallyplanned(Sched.Staycolumn);andthedifference
betweenthescheduledreturndateandtheactualreturndate(Diffcolumn).
Furtherinformationisprovidedinthedocumentationincludedinthecode.Implementthe
fourmethods(getActualReturnDate(),getReturnStatus(),
getPlannedPeriodOfStay(),getDiffPeriodOfStay())oftheAstronaut
class,andcompletetheimplementationoftheprintReport()methodinthe
SpaceStationStatsclass.
Clickheretoviewcodeimage
importjava.time.LocalDate;
importjava.time.LocalDateTime;
importjava.time.Period;
/**Classrepresentsstatisticsaboutanastronaut.*/
publicclassAstronaut{
privatefinalStringastronautName;
privatefinalLocalDateTimearrivalDateTime;
privatefinalLocalDatescheduledReturnDate;
WOW! eBook
www.wowebook.org
privatefinalPeriodactualPeriodOfStay;
publicAstronaut(Stringname,LocalDateTimearrival,Periodperiod,
LocalDatereturnDate){
astronautName=name;
arrivalDateTime=arrival;
actualPeriodOfStay=period;
scheduledReturnDate=returnDate;
}
publicStringgetAstronautName(){returnastronautName;}
publicLocalDateTimegetArrivalDateTime(){returnarrivalDateTime;}
publicPeriodgetActualPeriodOfStay(){returnactualPeriodOfStay;}
publicLocalDategetScheduledReturnDate(){returnscheduledReturnDate;}
/**@returnLocalDateTheactualdateofreturn.*/
publicLocalDategetActualReturnDate(){
/*IMPLEMENTTHISMETHOD.*/
}
/**
*Returnsstatusoftheactualreturncomparedtothescheduledreturn,
*whetheritwasontime,delayed,orearly.
*@returnStringIndicating“Ontime”,“Delayed”,or“Early”.
*/
publicStringgetReturnStatus(){
/*IMPLEMENTTHISMETHOD.*/
}
/**@returnPeriodTheplannedstayaccordingtothescheduledreturn.*/
publicPeriodgetPlannedPeriodOfStay(){
/*IMPLEMENTTHISMETHOD.*/
}
/**
*@returnPeriodThedifferencebetweentheactualreturndateand
*thescheduledreturndate.*/
publicPeriodgetDiffPeriodOfStay(){
/*IMPLEMENTTHISMETHOD.*/
}
}
Clickheretoviewcodeimage
importjava.time.LocalDate;
importjava.time.LocalDateTime;
importjava.time.Period;
importjava.time.format.DateTimeFormatter;
publicclassSpaceStationStats{
publicstaticvoidmain(String[]args){
//Astronautdata
Astronaut[]astronauts={
newAstronaut(“AstroAli”,
LocalDateTime.of(2010,3,1,10,45),Period.ofMonths(3),
LocalDate.of(2010,5,1)),
newAstronaut(“LailaLightyear”,
LocalDateTime.of(2015,2,1,17,0),Period.ofWeeks(30),
LocalDate.of(2015,6,30)),
newAstronaut(“OrbitOrwell”,
LocalDateTime.of(2014,3,1,20,20),Period.ofMonths(6),
LocalDate.of(2014,9,1)),
WOW! eBook
www.wowebook.org
newAstronaut(“RocketRogers”,
LocalDateTime.of(2013,7,31,15,30),Period.ofDays(60),
LocalDate.of(2013,9,30)),
newAstronaut(“SamSpacey”,
LocalDateTime.of(2009,1,1,12,15),Period.ofDays(90),
LocalDate.of(2009,11,1)),
};
printReport(astronauts);
}
/**
*Methodprintsstatisticsaboutstayonaspacestation.
*Seetheexercisetextfortheformatofthereport.
*@paramastronautsThearraywithastronautdata
*/
privatestaticvoidprintReport(Astronaut[]astronauts){
System.out.println(“NameArr.DateSched.Return”
+”Act.ReturnStatusAct.StaySched.StayDiff”);
StringreportFormatStr=“%-16s%10s%12s%12s%8s%6s%10s%9s%n”;
/*IMPLEMENTTHERESTOFTHEMETHOD.*/
}
}
WOW! eBook
www.wowebook.org
AppendixA.TakingtheJavaSE8ProgrammerIExam
PleasenotethatallinformationpresentedinthisappendixwasvalidasofJanuary2016.It
isimperativetovisitthewebsitesmentionedinthisappendixregularly,asOracleis
knowntochangethepracticalinformationabouttheexamandtheexamobjectives
intermittently.
TheprimaryfocusofthisbookistheJavaSE8ProgrammerIExam(1Z0-808)required
toqualifyasanOracleCertifiedAssociate(OCA),JavaSE8Programmer(OCAJP8).
Pertinentinformationaboutthisexamcanbefoundhere:
http://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?
page_id=5001&get_params=p_exam_id:1Z0-808
ThisexamisthefirstoftworequiredtoobtainOracleCertifiedProfessional(OCP),Java
SE8ProgrammerCertification(OCPJP8).Thesecondexamrequiredforthisprofessional
certificationistheJavaSE8ProgrammerIIExam(1Z0-809).Wewillnotgointothe
detailsaboutthesecondexaminthisappendix,butmoreinformationaboutthesecond
examcanbefoundhere:
https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?
page_id=5001&get_params=p_exam_id:1Z0-809
ForauthoritativeinformationaboutthecertificationpathforJavaSE,consultthe
followingwebpage:
https://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?
page_id=653&get_params=p_id:357#tabs-1-1
AppendixBcontainsspecificinformationabouttheexamobjectivesfortheJavaSE8
ProgrammerIexam.
A.1PreparingfortheExam
ThegoaloftheexamistotestpracticalknowledgeandusageoftheJavaprogramming
language.Theexamrequiresthoroughunderstandingofboththesyntaxandthesemantics
ofthelanguage.Theexamcoversawidevarietyoftopics,asdefinedintheobjectivesfor
theexam(AppendixB).Centraltotheexamislanguageconstructs,usageofthecoreAPI,
andspecifictopics,withheavyemphasisoninterpretingcodescenarios.
Theneedforreal-worldexperiencepriortotakingtheexamcannotbestressedenough.It
requiresverythoroughpreparationtopasstheexamwithouthavingsomeactual
experienceprogramminginJava.Simplyreadingstraightthroughthisbookisnot
recommended.Readersshouldtaketimetotryoutwhattheyhavelearnedalongevery
stepoftheway.Readersareencouragedtotesttheirnewlyacquiredknowledgeusingthe
reviewquestionsprovidedaftereverymajortopic.
Experimentingwiththeexamplesandworkingthroughtheprogrammingexercisesinthis
bookwillservetogivethereaderamuchbetterchanceofpassingtheexam.Numbered
examplesinthebookarecompleteJavaprograms,thesourcecodeforwhichisavailable
fromthebookwebsite.WhetheroneusesthetoolsintheJDKoranIDE(integrated
developmentenvironment),itisthehands-onprogrammingthatisimportant.Toolsinthe
WOW! eBook
www.wowebook.org
JDKaretobepreferredaspreparationfortheexam,asthereislessrelianceon
programmingsupportprovidedbyanIDE.
Whenthereaderfeelsready,sheshouldtestherskillsonthemockexamprovidedin
AppendixE.Thiswillgiveanindicationofhowwellthereaderispreparedfortheexam,
andwhichtopicsneedfurtherstudy.Thestructureofthebookshouldmakeiteasyforthe
readertofocusonsingletopics,ifnecessary.
Theexamisconsideredtobedifficult,andrequiresafairamountofstudyingonthepart
ofthecandidate.EvenseasonedJavaprogrammersshouldinvestsometimeinpreparing
fortheexam.Simplyhavingreal-worldexperienceisalsonotenoughtopasstheexam.
Devisingastudyplanishighlyrecommended,incorporatingtheactivitieswementioned
previously.Disruptionsinthestudyplanshouldbeavoid,asthiscanresultinrevisingthe
materialalreadycoveredwhenyoupickupthethread.Theexamshouldbescheduled
immediatelyafterthestudyperiod,whenthemomentumfromthepreparationisatits
maximum.
WealsohighlyrecommendjoininganonlineJavacertificationcommunity,suchas
CodeRanch(www.coderanch.com),whichhasdedicatedactiveforumsforthe
differentJavacertifications.AllthingsJavaarediscussedinafriendlymanneraroundthe
bonfireatthisranch,wheregreenhornsarespeciallywelcome.TheforumforOCAJPcan
befoundhere:
www.coderanch.com/forums/f-117/ocajp
A.2RegisteringfortheExam
Thewebsitefortheexamprovidesalltherelevantinformationontheprocedurefor
registering,paying,andschedulingtheexam.
ItisagoodideatohaveanOraclewebaccountandauthenticatetheaccountinthe
CertViewcertificationportal,wheretheexamresultswillbemadeavailable.Thesesteps
canbeaccomplishedatcertview.oracle.com.
ContactInformation
BothOracleandPearsonVUEhaveofficesandassociatesaroundtheworldthatcan
provideinformationabouttheexam.Theycanbecontactedtopurchaseavoucherforthe
exambeforesigningupforthetestatalocaltestingcenter.
Thebestwaytofindcontactinformationandlocaltestingcentersistovisittheirwebsites.
OracleUniversity
http://education.oracle.com/
PearsonVUE
http://pearsonvue.com/oracle/
WOW! eBook
www.wowebook.org
ObtaininganExamVoucher
ExamvouchersaresoldbyOracleandPearsonVUE.Besuretoobtainthecorrect
voucherfortheexam.Creditcardinformationisrequiredtoarrangepayment.Thecostof
thevouchermayvarydependingonthecountryyoulivein.ForU.S.residents,itcost
$245atthetimeofthisbook’swriting.
Notethatthevoucherhasanexpirationdate,usually6monthsafteritisacquired.Neither
OraclenorPearsonVUEwillreplacelostorexpiredvouchers,norwilltheyofferrefunds
forunusedvouchers.
SigningUpfortheTest
Afterobtainingtheexamvoucher,PearsonVUEcanbecontactedtosignupforthetestby
makinganappointmentatoneofthelocaltestingcenters.Theexamcanberescheduled
withoutpenaltyupto24hoursbeforetheappointmenttime.
AfterTakingtheExam
ThecandidatewillimmediatelyreceiveanemailfromOracleinformingherthattheexam
resultsareavailableinCertView.Onpassingtheexam,thecandidatewillreceiveanemail
informingherthataneCertificateisavailableinCertView.Instructionsforrequestinga
printedcopyofthecertificateareincludedinthisemail.
Acandidatewhofailstheexamcanregistertoretaketheexamaftera14-daywaiting
period.
A.3HowtheExamIsConducted
TheTestingLocations
Tobeonthesafeside,acandidateshouldbringtwoformsofIDonthedayoftheexam.
Whenacandidateshowsupatthelocaltestingcenterattheappointedtime,shewillbe
escortedtoherownlittlecubiclewithadesktopcomputer.Thetestwillbeconductedin
thiscubicle,usingatestingprogramonthecomputer.Theprogramwillaskquestions,
recordanswers,andtabulatescores.
Candidateswillnotbeallowedtobringanypersonalbelongingsorfoodwiththemtothe
cubicle.Acandidatewillbeprovidedwitheithererasableornonerasableboards.During
theexam,candidatescanusetheboardtomakenotes,buttheywillnotbeallowedtotake
anythingwiththemaftertheexam.Quiteoftentheexamareaisfittedwithsecurity
cameras.
UtilizingtheAllottedTime
Theexamconsistsofafixednumberofquestionsthatmustbeansweredwithinthe
allocatedtime.Someofthesequestionsmaybeunscored,meaningtheydonotcontribute
tothefinalscore,whethertheyareansweredcorrectlyornot.Thereisalsonowayto
distinguishwhetheraquestionisscoredorunscoredontheexam.
Thequestionsvaryindifficulty.Someareeasyandsomearedifficult.Withlimitedtime
WOW! eBook
www.wowebook.org
toanswereachquestion,thecandidatecannotaffordtogetstuckonthehardquestions.If
theanswerdoesnotbecomeapparentwithinareasonabletime,itisadvisabletomoveon
tothenextquestion.Timepermitting,itispossibletoreturntotheunansweredquestions
later.Itisimportanttoanswerallquestion.Awronganswerandablankanswercarrythe
samepenalty:lossofpoints.Thereforeitisbettertoguessananswerthantoleaveit
blank,andhopethattheguessisright.Theprocessofeliminationcansometimesbeuseful
innarrowingdowntheanswertoaquestion.Eliminatingobviousincorrectchoices
increasesthechancesofarrivingattherightanswer.
AnexperiencedJavaprogrammerusedtotakingexamsshouldbeabletocompletethe
examwithintheallottedtime.Anyremainingtimeisbestusedinreviewingtheanswers.
TheExamProgram
Thecomputerprogramusedtoconducttheexamwillselectasetofquestionsatrandom,
andpresentthemthroughagraphicaluserinterface.Theinterfaceisdesignedinsucha
waythatcandidatesareabletomovebackandforththroughthequestionsforreviewing
purposes.Questionscanbetemporarilyleftunanswered,andthecandidatecanreturnto
themlater.Questionscanalsobemarkedforreviewattheendoftheexam.
Beforetheexamstarts,thecandidateisallowedatestrunwiththecomputerprogram.A
demotestthathasnothingtodowiththeJavaexamisused.Itssolepurposeistoacquaint
thecandidatewiththeprogrambeingusedtoconducttheexam.
TheExamResult
Aftertakingtheexam,thecandidateshouldlogontotheCertViewcertificationportalto
seetheresult.Thecandidatewillbepresentedwiththefollowinginformation:
•Anindicationofwhetherthecandidatepassedorfailed.
•Thetotalscore.Onlythescoredquestionsontheexamcontributetothefinalscore.
Allthescoredquestionsareweightedequally,andthescoreiscalculatedbasedon
thepercentageofcorrectanswers.Nocreditisgivenforpartiallycorrectanswersfor
thescoredquestions.
•Indicationsonhowwellthecandidatedidoneachofthecategoriesoftheobjectives.
Candidateswhofailtheexamshouldpaycloseattentiontothisinformation.Ifthe
candidateisplanningtoretaketheexam,itmaygiveagoodindicationofwhich
topicsneedcloserattention.
Theresultwillnotdivulgewhichquestionswereansweredcorrectly.
A.4TheQuestions
AssumptionsabouttheExamQuestions
ThewebsitefortheJavaSE8ProgrammerIExamlistscertainassumptionsaboutthe
examquestions.Inthefollowinglist,weprovideashortexplanationoftheseassumptions.
•Missingpackageandimportstatements
WOW! eBook
www.wowebook.org
Unlessexplicitlyprovided,stated,orreferredtointhequestion,assumethatthe
codeisinthesamepackageandallnecessaryimportstatementsaregiven.
•Nofileordirectorypathnamesforclasses
Inthiscase,assumethateitherallclassesareinthesamefileoreachclassisina
separatefileandthesefilesareinthesamedirectory.
•Unintendedlinebreaks
Linebreaksthatmakethecodelinesappeartobewrappedunintentionallyshouldbe
ignored,andthecodeassumedtocompilewithouterrors.
•Codefragments
Assumethatthenecessarycontextexiststocompileandexecutethecode,ifsuch
contextisnotexplicitlyspecifiedbythequestion.
•Descriptivecomments
Suchcommentsshouldbetakenattheirfacevalue,providingtheintentdescribedin
thecomment.
TypesofQuestionsAsked
Mostofthequestionsfollowacommonformatthatrequirescandidatestoapplytheir
knowledgeinaspecialway.
•Analyzingprogramcode.Thequestionprovidesasourcecodesnippet,andasksa
specificquestionpertainingtothesnippet.Willrunningtheprogramprovidethe
expectedresult?Whatwillbewrittentothestandardoutputwhentheprogramis
run?Willthecodecompile?
•Identifyingtrueorfalsestatements.
Whenanalyzingprogramcode,itisusefultotrytoapplythesamerulesasthecompiler:
examiningtheexactsyntaxused,ratherthanmakingassumptionsonwhatthecodetriesto
accomplish.
Thewordingofthequestionsisprecise,andtheresponsesselectedinmultiple-choice
questionsarelikewiseexpectedtobeprecise.Thisoftencausesthetesttobeperceivedas
fastidious.Closeattentionshouldbepaidtothewordingoftheresponsesinamultiple-
choicequestion.
Noneofthequestionsisintentionallymeanttobeatrickquestion.Examquestionshave
beenreviewedbybothJavaexpertsandlanguageexpertstoremoveasmuchambiguity
fromtheirwordingaspossible.
Sincetheprogramusedintheexamwillselectandpresentthequestionsinarandom
fashion,thereisnopointintryingtoguesstheformofthequestions.Theorderofthe
answersinmultiple-choicequestionshasbeenrandomizedand,therefore,hasno
significance.
WOW! eBook
www.wowebook.org
TypesofAnswersExpected
Allexamquestionsaremultiplechoice.Thecorrectnumberofalternativestoselectis
designatedinthequestion,andallmustbeselectedforthequestionasawholetobe
consideredcorrectlyanswered.
Thereshouldbenoproblemidentifyingwhichformofanswereachquestionrequires.The
wordingofthequestionswillindicatethis,andthesoftwareusedwillpresentthe
candidatewithaninputmethodcorrespondingtotheformofanswerexpected.
Formultiple-choicequestions,theprogramwillaskthecandidatetoselectaspecific
numberofanswersfromalist.Whereasinglecorrectanswerisexpected,radiobuttons
willallowtheselectionofonlyoneanswer.Themostappropriateresponseshouldbe
selected.
Inquestionswhereallappropriateresponsesshouldbeselected,checkboxeswillallow
theselectionofeachresponseindividually.Inthiscase,allchoicesshouldbeconsidered
ontheirownmerits;thatis,responsesshouldnotbeweighedagainsteachother.Itcanbe
helpfultothinkofeachofthechoicesasanindividualtrue–falsequestion.
TopicsCoveredbytheQuestions
Topicscoveredbytheexamarebasicallyderivedfromthesetofexamobjectivesdefined
byOracle.TheobjectivesfortheJavaSE8ProgrammerIexamareincludedinAppendix
B,withreferencestowherethetopicsarecoveredinthebook.
TheultimategoalofanexamistodistinguishexperiencedJavaprogrammersfromthe
rest.Tothisend,someofthequestionsareaimedattopicsthatnewJavaprogrammers
usuallyfinddifficult.Suchtopicsinclude:
•Castingandconversion
•Polymorphism,overriding,andoverloading
•Exceptionhandlingwithtry-catch-finallyblocks
KnowledgeobtainedfromstudyingotherlanguagessuchasC++shouldbeusedwithcare.
SomeofthequestionsoftenseemtoleadastrayC++programmerswhohavenotgrasped
themanydifferencesbetweenC++andJava.ThosewithaC++backgroundshouldpay
specialattentiontothefollowingJavatopics:
•Usingnull,notNULL
•Usingtrueandfalse,not1and0
•Wideningconversions
•Conditionalandbooleanlogicoperators
•Accessibilityrules
•Polymorphism
SomeofthequestionsmayrequireintimateknowledgeofthecoreJavaAPI.Thisbook
coversthemostimportantclassesandmethodsoftheJavaSEplatformAPI,butitdoes
WOW! eBook
www.wowebook.org
notgoasfaraslistingeverymemberofeveryclass.TheJavaSEplatformAPI
documentationshouldbeconsulted.Itisessentialthatreadersfamiliarizethemselveswith
therelevantpartsoftheAPIdocumentation.
WOW! eBook
www.wowebook.org
AppendixB.ExamTopics:JavaSE8ProgrammerI
PleasenotethatallinformationpresentedinthisappendixwasvalidasofJanuary2016.It
isimperativetovisittheexamwebsitementionedinthisappendixregularlywhileyouare
preparingfortheexam,asOracleisknowntochangetheexamobjectivesintermittently.
TheJavaSE8ProgrammerIexamisrequiredtoqualifyasOracleCertifiedAssociate,
JavaSE8Programmer(OCAJP8).Pertinentinformationaboutthisexamcanbefoundat:
http://education.oracle.com/pls/web_prod-plq-dad/db_pages.getpage?
page_id=5001&get_params=p_exam_id:1Z0-808
ThewebpagealsoprovideslinkstotheexamtopicsdefinedbyOracle.Thetopicsare
organizedinsections,andeachsectionisreproducedverbatiminthisappendix.Foreach
section,wehaveprovidedreferencestowhereinthebooktheexamtopicsinthesection
arecovered.Inaddition,theextensiveindexattheendofthebookcanbeusedtolookup
specifictopics.
GeneralinformationabouttakingtheexamcanbefoundinAppendixA.Oraclehasalso
specifiedcertainimportantassumptionsabouttheexamquestions,whichcanfoundin
AppendixA,p.511.
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
AppendixC.AnnotatedAnswerstoReviewQuestions
1BasicsofJavaProgramming
1.1(d)
Amethodisanoperationdefiningthebehaviorforaparticularabstraction.Java
implementsabstractionsusingclassesthathavepropertiesandbehavior.Behavior
isdefinedbytheoperationsoftheabstraction.
1.2(b)
Anobjectisaninstanceofaclass.Objectsarecreatedfromclassesthatimplement
abstractions.Theobjectsthatarecreatedareconcreterealizationsofthose
abstractions.Anobjectisneitherareferencenoravariable.
1.3(b)
(2)isthefirstlineofaconstructordeclaration.AconstructorinJavaisdeclared
likeamethod,butdoesnotspecifyareturnvalue.(1)istheheaderofaclass
declaration,(3)isthefirststatementintheconstructorbody,and(4),(5)and(6)are
instancemethoddeclarations.
1.4(b)and(f)
Twoobjectsandthreereferencesarecreatedbythecode.Objectsarenormally
createdbyusingthenewoperator.Thedeclarationofareferencecreatesavariable
regardlessofwhetherareferencevalueisassignedtoit.
1.5(d)
Aninstancememberisafieldoraninstancemethod.Thesemembersbelongtoan
instanceoftheclassratherthantotheclassasawhole.Membersthatarenot
explicitlydeclaredasstaticinaclassdeclarationareinstancemembers.
1.6(c)
Anobjectcommunicateswithanotherobjectbycallinganinstancemethodofthe
otherobject.
1.7(d)and(f)
GiventhedeclarationclassBextendsA{...},wecanconcludethat
classBextendsclassA,classAisthesuperclassofclassB,classBisasubclassof
classA,andclassBinheritsfromclassA,whichmeansthatobjectsofclassBwill
inheritthefieldvalue1fromclassA.
1.8(b),(d),and(g)
ATrainobjectcanshareboththeTrainDriveranditsCarriageobjects
withotherTrainobjects,whenitisnotusingthem.Inotherwords,theycan
outlivetheTrainobject.Thisisanexampleofaggregation.However,aTrain
objectownsthearrayobjectusedforhandlingitscarriages.Thelifetimeofanarray
WOW! eBook
www.wowebook.org
objectisnestedinthelifetimeofitsTrainobject.Thisisanexampleof
composition.
1.9(d)
ThecompilersuppliedwiththeJDKisnamedjavac.Thenamesofthesource
filestobecompiledarelistedonthecommandlineafterthecommandjavac.
1.10(a)
JavaprogramsareexecutedbytheJavaVirtualMachine(JVM).IntheJDK,the
commandjavaisusedtostarttheexecutionbytheJVM.Thejavacommand
requiresthenameofaclassthathasavalidmain()method.TheJVMstartsthe
programexecutionbycallingthemain()methodofthegivenclass.Theexact
nameoftheclassshouldbespecified,ratherthanthenameoftheclassfile;thatis,
the.classextensionintheclassfilenameshouldnotbespecified.
1.11(e)
(a):TheJVMmustbecompatiblewiththeJavaPlatformonwhichtheprogram
wasdeveloped.
(b):TheJITfeatureoftheJVMtranslatesbytecodetomachinecode.
(c):Otherlanguages,suchasScala,alsocompiletobytecodeandcanbeexecuted
byaJVM.
(d):AJavaprogramcanonlycreateobjects;destroyingobjectsoccursatthe
discretionoftheautomaticgarbagecollector.
2LanguageFundamentals
2.1(c)
52pickupisnotalegalidentifier.Thefirstcharacterofanidentifiercannotbea
digit.Anunderscoreistreatedasaletterinidentifiernames.
2.2(b),(c),(d),and(f)
In(b),theunderscoreisnotbetweendigits.In(c),digit9isnotvalidinanoctal
literal.In(d),theunderscoreisnotbetweendigits.In(f),thereisnosuchescape
sequence.
2.3(e)
InJava,theidentifiersdelete,thrown,exit,unsigned,andnextarenot
keywords.Javahasagotokeyword,butitisreservedandnotcurrentlyused.
2.4(e)
Everythingfromthestartsequence(/*)ofamultiple-linecommenttothefirst
occurrenceoftheendsequence(*/)ofamultiple-linecommentisignoredbythe
compiler.Everythingfromthestartsequence(//)ofasingle-linecommenttothe
endofthelineisignoredbythecompiler.In(e),themultiple-linecommentends
WOW! eBook
www.wowebook.org
withthefirstoccurrenceoftheendsequence(*/),leavingthesecondoccurrence
oftheendsequence(*/)unmatched.
2.5(a)and(d)
Stringisaclass,and"hello"and"t"denoteStringobjects.Javahasthe
followingprimitivedatatypes:boolean,byte,short,char,int,long,
float,anddouble.
2.6(a),(c),and(e)
(a)isabooleandatatype,while(c)and(e)arefloating-pointdatatypes.
2.7(c)
Thebitrepresentationofintis32bitswideandcanholdvaluesintherange–231
through231–1.
2.8(a),(c),and(d)
The\uxxxxnotationcanbeusedanywhereinthesourcetorepresentUnicode
characters.
2.9(c)
Localvariableiisdeclaredbutnotinitialized.Thefirstlineofcodedeclaresthe
localvariablesiandj.Thesecondlineofcodeinitializesthelocalvariablej.
Localvariableiremainsuninitialized.
2.10(c)
Thelocalvariableoftypefloatwillremainuninitialized.Fieldsandstatic
variablesareinitializedwithadefaultvalue.Aninstancevariableoftypeint[]is
areferencevariablethatwillbeinitializedwiththenullvalue.Localvariables
remainuninitializedunlessexplicitlyinitialized.Thetypeofthevariabledoesnot
affectwhetheravariableisinitialized.
2.11(e)
Theprogramwillcompile.Thecompilercanfigureoutthatthelocalvariable
pricewillalwaysbeinitialized,sincethevalueoftheconditionintheif
statementistrue.Thetwoinstancevariablesandthetwostaticvariablesareall
initializedtotherespectivedefaultvalueoftheirtype.
3Declarations
3.1(b)
Only(b)isavalidmethoddeclaration.Methodsmustspecifyareturntypeormust
bedeclaredasvoid.Thismakes(d)and(e)invalid.Methodsmustspecifyalistof
zeroormorecomma-separatedparametersenclosedbyparentheses,().The
keywordvoidcannotbeusedtospecifyanemptyparameterlist.Thismakes(a)
and(c)invalid.
WOW! eBook
www.wowebook.org
3.2(a),(b),and(e)
Non-staticmethodshaveanimplicitthisobjectreference.Thethisreference
cannotbechanged,asin(c).Thethisreferencecanbeusedinanon-static
contexttorefertobothinstanceandstaticmembers.However,itcannotbeusedto
refertolocalvariables,asin(d).
3.3(a)and(e)
Thefirstandthirdpairsofmethodswillcompile.Thesecondpairofmethodswill
notcompile,sincetheirmethodsignaturesdonotdiffer.Thecompilerhasnoway
ofdifferentiatingbetweenthetwomethods.Notethatthereturntypeandthenames
oftheparametersarenotapartofthemethodsignature.Bothmethodsinthefirst
pairarenamedflyandhavedifferentnumbersofparameters,thusoverloading
thismethodname.Themethodsinthelastpairdonotoverloadthemethodname
glide,sinceonlyonemethodhasthatname.ThemethodnamedGlideis
distinctfromthemethodnamedglide,asidentifiersarecasesensitiveinJava.
3.4(a)
Aconstructorcannotspecifyanyreturntype,notevenvoid.Aconstructorcannot
befinal,static,orabstract.
3.5(b)and(e)
Aconstructorcanbedeclaredasprivate,butthismeansthatthisconstructorcan
beusedonlywithintheclass.Constructorsneednotinitializeallthefieldswhena
classisinstantiated.Afieldwillbeassignedadefaultvalueifnotexplicitly
initialized.Aconstructorisnon-staticand,assuch,itcandirectlyaccessboththe
staticandnon-staticmembersoftheclass.
3.6(c)
Acompile-timeerrorwilloccurat(3),sincetheclassdoesnothaveaconstructor
acceptingasingleargumentoftypeint.Thedeclarationat(1)declaresamethod,
notaconstructor,sinceitisdeclaredasvoid.Themethodhappenstohavethe
samenameastheclass,butthatisirrelevant.Theclasshasadefaultconstructor,
sincetheclasscontainsnoconstructordeclarations.Thisconstructorwillbe
invokedtocreateaMyClassobjectat(2).
3.7(d)
InJava,arraysareobjects.Eacharrayobjecthasapublicfinalfieldnamed
lengththatstoresthesizeofthearray.
3.8(a)
Javaallowsarraysoflengthzero.Suchanarrayispassedasanargumenttothe
main()methodwhenaJavaprogramisrunwithoutanyprogramarguments.
3.9(c)
The[]notationcanbeplacedbothafterthetypenameandafterthevariablename
WOW! eBook
www.wowebook.org
inanarraydeclaration.Multidimensionalarraysarecreatedbyconstructingarrays
thatcancontainreferencestootherarrays.Theexpressionnewint[4][]will
createanarrayoflength4,whichcancontainreferencestoarraysofintvalues.
Theexpressionnewint[4][4]willalsocreateatwo-dimensionalarray,but
willinadditioncreatefourmoreone-dimensionalarrays,eachoflength4andof
thetypeint[].Referencestoeachofthesearraysarestoredinthetwo-
dimensionalarray.Theexpressionint[][4]willnotwork,becausethearrays
forthedimensionsmustbecreatedfromlefttoright.
3.10(b)and(e)
Thesizeofthearraycannotbespecified,asin(b)and(e).Thesizeofthearrayis
givenimplicitlybytheinitializationcode.Thesizeofthearrayisneverspecifiedin
thedeclarationofanarrayreference.Thesizeofanarrayisalwaysassociatedwith
thearrayinstance(ontheright-handside),notthearrayreference(ontheleft-hand
side).
3.11(e)
Thearraydeclarationisvalid,andwilldeclareandinitializeanarrayoflength20
containingintvalues.Allthevaluesofthearrayareinitializedtotheirdefault
valueof0.Thefor(;;)loopwillprintallthevaluesinthearray;thatis,itwill
print0twentytimes.
3.12(d)
Theprogramwillprint0false0nullatruntime.Alltheinstancevariables,
andthearrayelement,willbeinitializedtotheirdefaultvalues.Whenconcatenated
withastring,thevaluesareconvertedtotheirstringrepresentation.Noticethatthe
nullpointerisconvertedtothestring“null",ratherthanthrowinga
NullPointerException.
3.13(b)
Evaluationoftheactualparameteri++yields0,andincrementsito1inthe
process.Thevalue0iscopiedintotheformalparameteriofthemethod
addTwo()duringmethodinvocation.However,theformalparameterislocalto
themethod,andchangingitsvaluedoesnotaffectthevalueintheactualparameter.
Thevalueofthevariableiinthemain()methodremains1.
3.14(d)
Thevariablesaandbarelocalvariablesthatcontainprimitivevalues.Whenthese
variablesarepassedasargumentstoanothermethod,themethodreceivescopiesof
theprimitivevaluesinthevariables.Theactualvariablesareunaffectedby
operationsperformedonthecopiesoftheprimitivevalueswithinthecalled
method.ThevariablebArrcontainsareferencevaluethatdenotesanarrayobject
containingprimitivevalues.Whenthevariableispassedasaparametertoanother
method,themethodreceivesacopyofthereferencevalue.Usingthisreference
value,themethodcanmanipulatetheobjectthatthereferencevaluedenotes.This
WOW! eBook
www.wowebook.org
allowstheelementsinthearrayobjectreferencedbybArrtobeaccessedand
modifiedinthemethodinc2().
3.15(a)and(f)
Avaluecanbeassignedtoafinalvariableonlyonce.Afinalformal
parameterisassignedthevalueoftheactualparameteratmethodinvocation.
Withinthemethodbody,itisillegaltoreassignormodifythevaluestoredina
finalparameter.Thiscausesa++andc=dtofail.Whethertheactual
parameterisfinaldoesnotconstraintheclientthatinvokedthemethod,sincethe
actualparametervaluesareassignedtotheformalparameters.
3.16(a),(d),and(f)
Theellipses(...)mustbespecifiedbeforetheparametername.Onlyonevariable
arityparameterispermitted,anditmustbethelastparameterintheformal
parameterlist.
3.17(c)
In(a)and(b),theargumentsareencapsulatedaselementsintheimplicitlycreated
arraythatispassedtothemethod.In(c),theintarrayobjectitselfisencapsulated
asanelementintheimplicitlycreatedarraythatispassedtothemethod.(a),(b)
and(c)arefixedaritycalls.Notethatint[]isnotasubtypeofObject[].In
(d),(e),and(f),theargumentisasubtypeofObject[],andtheargumentitselfis
passedwithouttheneedofanimplicitlycreatedarray;thatis,thesearefixedarity
methodcalls.However,in(d)and(e),thecompilerissuesawarningthatbothfixed
arityandvariablearitymethodcallsarefeasible,butchoosesfixedaritymethod
calls.
4AccessControl
4.1(a)and(c)
Bytecodeofallreferencetypedeclarationsinthefileisplacedinthedesignated
package,andallreferencetypedeclarationsinthefilecanaccesstheimported
types.
4.2(e)
Bothclassesareinthesamepackageapp,sothefirsttwoimportstatementsare
unnecessary.Thepackagejava.langisalwaysimportedinallcompilationunits,
sothenexttwoimportstatementsareunnecessary.Thelaststaticimportstatement
isnecessarytoaccessthestaticvariableframeintheWindowclassbyitssimple
name.
4.3(b),(c),(d),and(e)
(a):Theimportstatementimportstypesfromthemainpkgpackage,butWindow
isnotoneofthem.
(b):Theimportstatementimportstypesfromthemainpkg.subpkg1package,
WOW! eBook
www.wowebook.org
andWindowisoneofthem.
(c):Theimportstatementimportstypesfromthemainpkg.subpkg2package,
andWindowisoneofthem.
(d):Thefirstimportstatementistype-import-on-demandandthesecondimport
statementissingle-type-import.BothimportthetypeWindow.Thesecond
overridesthefirstone.
(e):Thefirstimportstatementissingle-type-importandthesecondimport
statementistype-import-on-demand.BothimportthetypeWindow.Thefirst
overridesthesecondone.
(f):BothimportstatementsimportthetypeWindow,makingtheimport
ambiguous.
(g):Bothsingle-type-importstatementsimportthetypeWindow.Thesecond
importstatementcausesaconflictwiththefirst.
4.4(c)and(e)
Thenameoftheclassmustbefullyqualified.Aparameterlistafterthemethod
nameisnotpermitted.(c)illustratessinglestaticimportand(e)illustratesstatic
importondemand.
4.5(b),(d),and(f)
In(a),thefileA.classwillbeplacedinthesamedirectoryasthefileA.java.
Thereisno-Doptionforthejavaccommand,asin(c).Thecompilermapsthe
packagestructuretothefilesystem,creatingthenecessary(sub)directories.
4.6(b)and(d)
In(a)and(c),classAcannotbefound.In(e)and(f),classBcannotbefound—
thereisnopackageunderthecurrentdirectory/top/wrk/pkgtosearchforclass
B.Notethatspecifyingpkgintheclasspathin(d)issuperfluous.Theparent
directoryofthepackagemustbespecified,meaningthelocationofthepackage.
4.7(d)and(f)
Theparentdirectory(orlocation)ofthepackagemustbespecified.Only(d)and
(f)dothat.(d)specifiesthecurrentdirectoryfirst,butthereisnofile
top/sub/A.classunderthecurrentdirectory.Searchingunder../bin(i.e.,
/proj/bin)findsthefiletop/sub/A.class.
4.8(c)and(d)
Aclassorinterfacenamecanbereferredtobyusingeitheritsfullyqualifiedname
oritssimplename.Usingthefullyqualifiednamewillalwayswork,buttousethe
simplenameithastobeimported.Whennet.basemaster.*isimported,all
thetypenamesfromthepackagenet.basemasterwillbeimportedandcan
nowbereferredtousingsimplenames.Importingnet.*willnotimportthe
subpackagebasemaster.
WOW! eBook
www.wowebook.org
4.9(c)
Anynon-finalclasscanbedeclaredasabstract.Aclasscannotbeinstantiatedif
theclassisdeclaredasabstract.Thedeclarationofanabstractmethod
cannotprovideanimplementation.Thedeclarationofanonabstractmethod
mustprovideanimplementation.Ifanymethodinaclassisdeclaredas
abstract,thentheclassmustbedeclaredasabstract,so(a)isinvalid.The
declarationin(b)isnotvalid,sinceitomitsthekeywordabstractinthemethod
declaration.Thedeclarationin(d)isnotvalid,sinceitomitsthekeywordclass.
In(e),thereturntypeofthemethodismissing.
4.10(e)
Onlyafinalclasscannotbeextended,asin(d).(c)and(e)willalsonotcompile.
Thekeywordnativecanbeusedonlyformethods,notforclassesandfields.A
classcannotbedeclaredasbothfinalandabstract.
4.11(b)
Outsidethepackage,thememberjisaccessibletoanyclass,whereasthemember
kisaccessibleonlytosubclassesofMyClass.
Thefieldihaspackageaccessibility,andisaccessibletoonlyclassesinsidethe
package.Thefieldjhaspublicaccessibility,andisaccessiblefromanywhere.The
fieldkhasprotectedaccessibility,andisaccessiblefromanyclassinsidethe
packageandfromsubclassesanywhere.Thefieldlhasprivateaccessibility,andis
accessibleonlywithinitsownclass.
4.12(c)
Thedefaultaccessibilityformembersismorerestrictivethanprotected
accessibility,butlessrestrictivethanprivateaccessibility.Memberswithdefault
accessibilityareaccessibleonlywithintheclassitselfandfromclassesinthesame
package.Protectedmembersare,inaddition,accessiblefromsubclassesanywhere.
Memberswithprivateaccessibilityareaccessibleonlywithintheclassitself.
4.13(b)
Aprivatememberisaccessibleonlywithintheclassofthemember.Ifno
accessibilitymodifierhasbeenspecifiedforamember,thememberhasdefault
accessibility,alsoknownaspackageaccessibility.Thekeyworddefaultisnotan
accessibilitymodifier.Amemberwithpackageaccessibilityisaccessibleonlyfrom
classesinthesamepackage.Subclassesinotherpackagescannotaccessamember
withdefaultaccessibility.
4.14(a),(c),(d),(e),and(h)
Thelines(1),(3),(4),(5),and(8)willcompile.Aprotectedmemberofa
superclassisalwaysinheritedbyasubclass.Directaccesstotheprotectedfield
pfispermittedinsubclassesBandCat(1)and(5),respectively.
Asubclassinanotherpackagecanaccessprotectedmembersinthesuperclassonly
WOW! eBook
www.wowebook.org
viareferencesofitsowntypeoritssubtypes.InpackageB,thesubclassBcan
accesstheprotectedfieldpfinthesuperclasspackageA.Aviareferencesoftype
B(i.e.,parameterobj2)andreferencesofitssubclassC(i.e.,parameterobj3).
However,thesubclassCcanaccesstheprotectedfieldpfinthesuperclass
packageA.AonlyviareferencesoftypeC(i.e.,parameterobj3).Thisisthe
caseat(3),(4),and(8).
TheclassDdoesnothaveanyinheritancerelationshipwithanyoftheotherclasses,
andthereforetheprotectedfieldpfisnotaccessibleintheclassD.Thisrules
outthelinesfrom(9)to(12).
4.15(b)and(e)
Ifnoaccessibilitymodifier(public,protected,orprivate)isgiveninthe
memberdeclarationofaclass,thememberisaccessibleonlytoclassesinthesame
package.
Asubclassdoesnothaveaccesstomemberswithdefaultaccessibilitydeclaredina
superclass,unlesstheyareinthesamepackage.
Localvariablescannotbedeclaredasstaticorhaveanaccessibilitymodifier.
4.16(c)
Line(3)voidk(){i++;}canbereinsertedwithoutintroducingerrors.
Reinsertingline(1)willcausethecompilationtofail,sinceMyOtherClasswill
trytooverrideafinalmethod.Reinsertingline(2)willfail,since
MyOtherClasswillnolongerhavethe(no-argument)defaultconstructor.The
main()methodneedstocalltheno-argumentconstructor.Reinsertingline(3)
willworkwithoutanyproblems,butreinsertingline(4)willfail,sincethemethod
willtrytoaccessaprivatememberofthesuperclass.
4.17(b)
Thekeywordthiscanbeusedonlyinnon-staticcode,asinnon-staticmethods,
constructors,andinstanceinitializerblocks.Onlyoneoccurrenceofeachstatic
variableofaclassiscreated,whentheclassisloadedbytheJVM.Thisoccurrence
issharedamongalltheobjectsoftheclass(andforthatmatter,byotherclients).
Localvariablesareaccessibleonlywithintheblockscope,regardlessofwhether
theblockscopeisdefinedwithinastaticcontext.
4.18(c)
Thedeclarationin(c)isnotlegal,asvariablescannotbedeclaredasabstract.
Thekeywordsstaticandfinalarevalidmodifiersforbothfieldandmethod
declarations.Themodifiersabstractandnativearevalidformethods,but
nottogether.Theycannotbespecifiedforfields.
4.19(a)and(c)
Abstractclassescandeclarebothfinalmethodsandnon-abstractmethods.
Non-abstractclassescannot,however,containabstractmethods.Norcan
WOW! eBook
www.wowebook.org
abstractclassesbefinal.Onlymethodscanbedeclarednative.
4.20(a)
Thekeywordtransientsignifiesthatthefieldsshouldnotbestoredwhen
objectsareserialized.Constructorscannotbedeclaredasabstract.Whenan
arrayobjectiscreated,asin(c),theelementsinthearrayobjectareassignedthe
defaultvaluecorrespondingtothetypeoftheelements.Whetherthereference
variabledenotingthearrayobjectisalocalvariableoramembervariableis
irrelevant.Abstractmethodsfromasuperclassneednotbeimplementedbya
subclass,butthesubclassmustthenbedeclaredasabstract.Staticmethodscan
alsobeaccessedinanon-staticcontext—forexample,ininstancemethods,
constructors,andinstanceinitializerblocks.
5OperatorsandExpressions
5.1(a)
Avalueoftypecharcanbeassignedtoavariableoftypeint.Awidening
conversionwillconvertthevaluetoanint.
5.2(d)
Anassignmentstatementisanexpressionstatement.Thevalueoftheexpression
statementisthevalueoftheexpressionontheright-handside.Sincethe
assignmentoperatorisrightassociative,thestatementa=b=c=20is
evaluatedasfollows:(a=(b=(c=20))).Thisresultsinthevalue20
beingassignedtoc,thenthesamevaluebeingassignedtobandfinallytoa.The
programwillcompile,andprint20atruntime.
5.3(c)
Stringsareobjects.Thevariablesa,b,andcarereferencesthatcandenotesuch
objects.Assigningtoareferenceonlychangesthereferencevalue;itdoesnot
createacopyofthesourceobjectorchangetheobjectdenotedbytheoldreference
valueinthetargetreference.Inotherwords,assignmenttoreferencesaffectsonly
whichobjectthetargetreferencedenotes.Thereferencevalueofthe"cat"object
isfirstassignedtoa,thentob,andlatertoc.Theprogramprintsthestring
denotedbyc,"cat".ThelocalfinalStringvariablebisinitializedonly
onceinthecode.
5.4(a),(d),and(e)
Abinaryexpressionwithanyfloating-pointoperandwillbeevaluatedusing
floating-pointarithmetic.Expressionssuchas2/3,wherebothoperandsare
integers,willuseintegerarithmeticandevaluatetoanintegervalue.In(e),the
resultof(0x10*1L)ispromotedtoafloating-pointvalue.
5.5(b)
The/operatorhashigherprecedencethanthe+operator.Thismeansthatthe
WOW! eBook
www.wowebook.org
expressionisevaluatedas((1/2)+(3/2)+0.1).Theassociativityofthe
binaryoperatorsisfromlefttoright,giving(((1/2)+(3/2))+0.1).
Integerdivisionresultsin((0+1)+0.1),whichevaluatesto1.1.
5.6(e)
0x10isahexadecimalliteralequivalenttothedecimalvalue16.10isadecimal
literal.010isanoctalliteralequivalenttothedecimalvalue8.0b10isabinary
literalequivalenttothedecimalvalue2.Theprintln()methodwillprintthe
sumofthesevalues,whichis36,indecimalform.
5.7(b),(c),and(f)
Theunary+and-operatorswithrightassociativityareusedinthevalid
expressions(b),(c),and(f).Expression(a)triestouseanonexistentunary-
operatorwithleftassociativity,expression(d)triestouseadecrementoperator(--
)onanexpressionthatdoesnotresolvetoavariable,andexpression(e)triestouse
anonexistentunary*operator.(c)compilesbecausetheunaryoperatorscannotbe
interpretedasincrement(++)ordecrement(--)operators:(+(-(+(-(+
(-1)))))).
5.8(b)
Theexpressionevaluatesto–6.Thewholeexpressionisevaluatedas(((-(-1))
-((3*10)/5))-1)accordingtotheprecedenceandassociativity
rules.
5.9(a),(b),(d),and(e)
In(a),theconditionsforimplicitnarrowingconversionarefulfilled:Thesourceisa
constantexpressionoftypeint,thedestinationtypeisoftypeshort,andthe
valueofthesource(12)isintherangeofthedestinationtype.Theassignmentsin
(b),(d),and(e)arevalid,sincethesourcetypeisnarrowerthanthetargettypeand
animplicitwideningconversionwillbeapplied.Theexpression(c)isnotvalid.
Valuesoftypebooleancannotbeconvertedtoothertypes.
5.10(a),(c),and(d)
Theleftassociativityofthe+operatormakestheevaluationof(1+2+"3")
proceedasfollows:(1+2)+"3"→3+"3"→"33".Evaluationofthe
expression("1"+2+3),however,willproceedasfollows:("1"+2)+
3→"12"+3→"123".(4+1.0f)evaluatesas4.0f+1.0f→
5.0fand(10/9)performsintegerdivision,resultinginthevalue1.Theoperand
'a'intheexpression('a'+1)willbepromotedtoint,andtheresulting
valuewillbeoftypeint.
5.11(d)
Theexpression++k+k++++kisevaluatedas((++k)+(k++))+
(+k)→((2)+(2)+(3)),resultinginthevalue7.
WOW! eBook
www.wowebook.org
5.12(d)
Thetypescharandintarebothintegral.Acharvaluecanbeassignedtoan
intvariablesincetheinttypeiswiderthanthechartypeandanimplicit
wideningconversionwillbedone.Aninttypecannotbeassignedtoachar
variablebecausethechartypeisnarrowerthantheinttype.Thecompilerwill
reportanerroraboutapossiblelossofprecisionin(4).
5.13(c)
Variablesofthetypebytecanstorevaluesintherange–128to127.The
expressionontheright-handsideofthefirstassignmentistheintliteral128.Had
thisliteralbeenintherangeofthebytetype,animplicitnarrowingconversion
wouldhavebeenappliedtoconvertittoabytevalueduringassignment.Since
128isoutsidetherangeofthetypebyte,theprogramwillnotcompile.
5.14(a)
First,theexpression++iisevaluated,resultinginthevalue2.Nowthevariablei
alsohasthevalue2.Thetargetoftheassignmentisnowdeterminedtobethe
elementarray[2].Evaluationoftheright-handexpression,--i,resultsinthe
value1.Thevariableinowhasthevalue1.Thevalueoftheright-hand
expression,1,isthenassignedtothearrayelementarray[2],causingthearray
contentstobecome{4,8,1}.Theprogramcomputesandprintsthesumof
thesevalues,13.
5.15(a)and(c)
In(a)and(e),bothoperandsareevaluated,with(a)yieldingtrue,but(e)yielding
false.Thenullliteralcanbecompared,so(null!=null)yieldsfalse.
Theexpression(4<=4)istrue.(!true)isfalse.
5.16(c)and(e)
Theremainderoperator%isnotlimitedtointegralvalues,butcanalsobeapplied
tofloating-pointoperands.Short-circuitevaluationoccursonlywiththeconditional
operators(&&,||).Theoperators*,/,and%havethesamelevelofprecedence.
Thedatatypeshortisa16-bitsignedtwo’scomplementinteger,sotherangeof
valuesisfrom-32768to+32767,inclusive.(+15)isalegalexpressionusing
theunary+operator.
5.17(a),(c),and(e)
The!=and^operators,whenusedonbooleanoperands,willreturntrueifand
onlyifoneoperandistrue,andfalseotherwise.Thismeansthatdandeinthe
programwillalwaysbeassignedthesamevalue,givenanycombinationoftruth
valuesinaandb.Theprogramwill,therefore,printtruefourtimes.
5.18(b)
Theelementreferencedbya[i]isdeterminedbasedonthecurrentvalueofi,
WOW! eBook
www.wowebook.org
whichis0—thatis,theelementa[0].Theexpressioni=9willevaluatetothe
value9,whichwillbeassignedtothevariablei.Thevalue9isalsoassignedtothe
arrayelementa[0].Aftertheexecutionofthestatement,thevariableiwill
containthevalue9,andthearrayawillcontainthevalues9and6.Theprogram
willprint996atruntime.
5.19(c)and(d)
Notethatthelogicalandconditionaloperatorshavelowerprecedencethanthe
relationaloperators.Unlikethe&and|operators,the&&and||operatorsshort-
circuittheevaluationoftheiroperandsiftheresultoftheoperationcanbe
determinedfromthevalueofthefirstoperand.Thesecondoperandofthe||
operatorintheprogramisneverevaluatedbecauseofshort-circuiting.Allthe
operandsoftheotheroperatorsareevaluated.Variableiendsupwiththevalue3,
whichisthefirstdigitprinted,andjendsupwiththevalue1,whichisthesecond
digitprinted.
5.20(d)and(f)
&&=and%%arenotoperatorsinJava.Theoperators%,&&,%=,<=,and->are
calledremainder,conditionalAND,remaindercompoundassignment,relational
lessthanorequal,andarrowoperator,respectively.
5.21(c),(e),and(f)
In(a),thethirdoperandhasthetypedouble,whichisnotassignmentcompatible
withthetypeintofthevariableresult1.Blocksarenotlegaloperandsinthe
conditionaloperator,asin(b).In(c),thelasttwooperandsresultinwrapperobjects
withtypeIntegerandDouble,respectively,whichareassignmentcompatible
withthetypeNumberofthevariablenumber.Theevaluationoftheconditional
expressionresultsinthereferencevalueofanIntegerobject,withvalue20
beingassignedtothenumbervariable.Allthreeoperandsoftheoperatorare
mandatory,whichisnotthecasein(d).In(e),thelasttwooperandsareoftype
int,andtheevaluationoftheconditionalexpressionresultsinanintvalue(21),
whosestringrepresentationisprinted.In(f),thevalueofthesecondoperandis
boxedintoaBoolean.Theevaluationoftheconditionalexpressionresultsina
stringliteral("inotequaltoj"),whichisprinted.Theprintln()
methodcreatesandprintsastringrepresentationofanyobjectwhosereference
valueispassedasparameter.
5.22(d)
Theconditionintheouterconditionalexpressionisfalse.Theconditioninthe
nestedconditionalexpressionistrue,resultinginthevalueofm1(i.e.,20)being
printed.
6ControlFlow
6.1(d)
WOW! eBook
www.wowebook.org
Theprogramwilldisplaytheletterbwhenrun.Thesecondifstatementis
evaluatedsincethebooleanexpressionofthefirstifstatementistrue.The
elseclausebelongstothesecondifstatement.Sincethebooleanexpressionof
thesecondifstatementisfalse,theifblockisskippedandtheelseclauseis
executed.
6.2(a),(b),and(e)
Theconditionofanifstatementcanbeanyexpression,includingmethodcalls,as
longasitevaluatesorcanbeunboxedtoavalueoftypeboolean.Theexpression
(a=b)doesnotcomparethevariablesaandb,butassignsthevalueofbtothe
variablea.Theresultoftheexpressionisthevaluebeingassigned.Sinceaandb
areeitherbooleanorBooleanvariables,thevaluereturnedbytheexpressionis
alsoeitherbooleanorBoolean.Thisallowstheexpressiontobeusedasthe
conditionforanifstatement.Anifstatementmustalwayshaveanifblock,but
theelseclauseisoptional.Theexpressionif(false);else;islegal.
Inthiscase,boththeifblockandtheelseblockaresimplytheemptystatement.
6.3(f)
Thereisnothingwrongwiththecode.Thecaseanddefaultlabelsdonothave
tobespecifiedinanyspecificorder.Theuseofthebreakstatementisnot
mandatory,andwithoutitthecontrolflowwillsimplyfallthroughthelabelsofthe
switchstatement.
6.4(c)
Thecaselabelvalue2*iLocisaconstantexpressionwhosevalueis6,the
sameastheswitchexpression.Fall-throughresultsintheprogramoutputshown
in(c).
6.5(b)
Theswitchexpression,whenunboxed,hasthevalue5.Thestatementassociated
withthedefaultlabelisexecuted,andthefall-throughcontinuesuntilthe
breakstatement.
6.6(a),(b),(f),and(j)
In(a),(b),(f),and(j),thestringexpressioninvolvesconstantvaluesandevaluates
to"TomTom".Programoutputis"Hi,TomTom!"In(i),theconstantstring
expressionevaluatesto"304Tom"(84+111+109+"Tom").Thefirstthree
literalsareoftypechar,andtheirintvaluesareaddedbeforebeing
concatenatedwithlastStringoperand.Programoutputis"Whatever!"In(c),
(d),(e),(g),and(h),thecaselabelisnotaconstantstringexpression,andthe
programwillnotcompile.
6.7(e)
Theloopbodyisexecutedtwiceandtheprogramwillprint3.Thefirsttimethe
WOW! eBook
www.wowebook.org
loopisexecuted,thevariableichangesfrom1to2andthevariablebchanges
fromfalsetotrue.Thentheloopconditionisevaluated.Sincebistrue,the
loopbodyisexecutedagain.Thistimethevariableichangesfrom2to3andthe
variablebchangesfromtruetofalse.Theloopconditionisthenevaluated
again.Sincebisnowfalse,theloopterminatesandthecurrentvalueofiis
printed.
6.8(b)and(e)
Boththefirstandsecondnumbersprintedwillbe10.Boththeloopbodyandthe
updateexpressionwillbeexecutedexactly10times.Eachexecutionoftheloop
bodywillbedirectlyfollowedbyanexecutionoftheupdateexpression.Afterward,
theconditionj<10isevaluatedtoseewhethertheloopbodyshouldbe
executedagain.
6.9(c)
Only(c)containsavalidforloop.Theinitializationinafor(;;)statementcan
containeitherdeclarationsoralistofexpressionstatements,butnotbothas
attemptedin(a).Theloopconditionmustbeoftypeboolean.(b)triestousean
assignmentofanintvalue(noticetheuseof=ratherthan==)asaloopcondition
and,therefore,isnotvalid.Theloopconditionintheforloop(d)triestousethe
uninitializedvariablei,andthefor(;;)loopin(e)issyntacticallyinvalid,as
thereisonlyonesemicolon.
6.10(f)
Thecodewillcompilewithouterror,butwillneverterminatewhenrun.Allthe
sectionsintheforheaderareoptionalandcanbeomitted(butnotthe
semicolons).Anomittedloopconditionisinterpretedasbeingtrue.Thus,a
for(;;)loopwithanomittedloopconditionwillneverterminate,unlessan
appropriatecontroltransferstatementisencounteredintheloopbody.Theprogram
willenteraninfiniteloopat(4).
6.11(b),(d),and(e)
Theloopconditioninawhilestatementisnotoptional.Itismissingin(a).Itis
notpossibletobreakoutoftheifstatementin(c).Noticethatifthisifstatement
hadbeenplacedwithinaswitchstatementoraloop,theusageofbreakwould
bevalid.Insidealabeledblock,alabeledbreakstatementwouldberequired.
6.12(a)and(d)
“i=1,j=0”and“i=2,j=1”arepartoftheoutput.Thevariableiiterates
throughthevalues0,1,and2intheouterloop,whilejtogglesbetweenthevalues
0and1intheinnerloop.Ifthevaluesofiandjareequal,theprintingofthe
valuesisskippedandtheexecutioncontinueswiththenextiterationoftheouter
loop.Thefollowingcanbededucedwhentheprogramisrun:Variablesiandjare
both0andtheexecutioncontinueswiththeupdateexpressionoftheouterloop.
“i=1,j=0”isprintedandthenextiterationoftheinnerloopstarts.Variablesi
WOW! eBook
www.wowebook.org
andjareboth1andtheexecutioncontinueswiththeupdateexpressionofthe
outerloop.“i=2,j=0”isprintedandthenextiterationoftheinnerloopstarts.
“i=2,j=1”isprinted,jisincremented,j<2isfalse,andtheinnerloop
ends.Variableiisincremented,i<3isfalse,andtheouterloopends.
6.13(b)
Thecodewillfailtocompile,sincetheconditionoftheifstatementisnotoftype
boolean.Thevariableiisoftypeint.Thereisnoconversionbetween
booleanandotherprimitivetypes.
6.14(c)and(d)
Theelementtypeofthearraynumsmustbeassignmentcompatiblewiththetype
oftheloopvariable,int.Onlytheelementtypein(c),Integer,canbe
automaticallyunboxedtoanint.Theelementtypein(d)isint.
6.15(d)and(e)
Intheheaderofafor(:)loop,wecandeclareonlyonelocalvariable.Thisrules
out(a)and(b),astheyspecifytwolocalvariables.Alsothearrayexpressionin(a),
(b),and(c)isnotvalid.Only(d)and(e)specifyalegalfor(:)header.
6.16(d)
Theprogramwillprint1,4,and5,inthatorder.Theexpression5/kwillthrowan
ArithmeticException,sincekequals0.Controlistransferredtothefirst
catchclause,sinceitisthefirstclausethatcanhandlethearithmeticexceptions.
Thisexceptionhandlersimplyprints1.Theexceptionhasnowbeencaughtand
normalexecutioncanresume.Beforeleavingthetrystatement,thefinally
clauseisexecuted.Thisclauseprints4.Thelaststatementofthemain()method
prints5.
6.17(b)and(e)
Ifrunwithnoarguments,theprogramwillprintTheend.Ifrunwithone
argument,theprogramwillprintthegivenargumentfollowedby"Theend".
Thefinallyclausewillalwaysbeexecuted,nomatterhowcontrolleavesthe
tryblock.
6.18(c)and(d)
Normalexecutionwillresumeonlyiftheexceptioniscaughtbythemethod.The
uncaughtexceptionwillpropagateuptheJVMstackuntilsomemethodhandlesit.
Anoverridingmethodneedsimplydeclarethatitcanthrowasubsetofthechecked
exceptionsthattheoverriddenmethodcanthrow.Themain()methodcandeclare
thatitthrowscheckedexceptionsjustlikeanyothermethod.Thefinallyclause
willalwaysbeexecuted,nomatterhowcontrolleavesthetryblock.
6.19(a)
Theprogramwillprint2andthrowanInterruptedException.An
WOW! eBook
www.wowebook.org
InterruptedExceptionisthrowninthetryblock.Thereisnocatch
clausetohandletheexception,soitwillbesenttothecallerofthemain()
method—thatis,tothedefaultexceptionhandler.Beforethishappens,the
finallyclauseisexecuted.Thecodetoprint3isneverreached.
6.20(b)
Theonlythingthatiswrongwiththecodeistheorderingofthecatchand
finallyclauses.Ifpresent,thefinallyclausemustalwaysappearlastina
try-catch-finallyconstruct.
6.21(a)
Overridingmethodscanspecifyall,none,orasubsetofthecheckedexceptions
thattheoverriddenmethoddeclaresinitsthrowsclause.The
InterruptedExceptionistheonlycheckedexceptionspecifiedinthe
throwsclauseoftheoverriddenmethod.Theoverridingmethodcompute()
neednotspecifytheInterruptedExceptionfromthethrowsclauseofthe
overriddenmethod,becausetheexceptionisnotthrownhere.
7Object-OrientedProgramming
7.1(a)and(b)
Theextendsclauseisusedtospecifythataclassextendsanotherclass.A
subclasscanbedeclaredasabstractregardlessofwhetherthesuperclasswas
declaredasabstract.Private,overridden,andhiddenmembersfromthe
superclassarenotinheritedbythesubclass.Aclasscannotbedeclaredasboth
abstractandfinal,sinceanabstractclassneedstobeextendedtobe
useful,andafinalclasscannotbeextended.Theaccessibilityoftheclassisnot
limitedbytheaccessibilityofitsmembers.Aclasswithallthemembersdeclared
privatecanstillbedeclaredaspublic.
7.2(b)and(e)
TheObjectclasshasapublicmethodnamedequals,butitdoesnothave
anymethodnamedlength.SinceallclassesaresubclassesoftheObjectclass,
theyallinherittheequals()method.Thus,allJavaobjectshaveapublic
methodnamedequals.InJava,aclasscanextendonlyasinglesuperclass,but
thereisnolimitonhowmanysubclassescanextendasuperclass.
7.3(a),(b),and(d)
BarisasubclassofFoothatoverridesthemethodg().Thestatementa.j=5
isnotlegal,sincethememberjintheclassBarcannotbeaccessedthroughaFoo
reference.Thestatementb.i=3isnotlegaleither,sincetheprivatemember
icannotbeaccessedfromoutsideoftheclassFoo.
7.4(g)
ItisnotpossibletoinvokethedoIt()methodinAfromaninstancemethodin
WOW! eBook
www.wowebook.org
classC.ThemethodinCneedstocallamethodinasuperclasstwolevelsupinthe
inheritancehierarchy.Thesuper.super.doIt()strategywillnotwork,since
superisakeywordandcannotbeusedasanordinaryreference,norcanitbe
accessedlikeafield.Ifthemembertobeaccessedhadbeenafield,thesolution
wouldbetocastthethisreferencetotheclassofthefieldandusetheresulting
referencetoaccessthefield.Fieldaccessisdeterminedbythedeclaredtypeofthe
reference,whereastheinstancemethodtoexecuteisdeterminedbytheactualtype
oftheobjectdenotedbythereferenceatruntime.
7.5(e)
Thecodewillcompilewithouterrors.Noneofthecallstoamax()methodare
ambiguous.Whentheprogramisrun,themain()methodwillcallthemax()
methodontheCobjectreferredtobythereferencebwiththeparameters13and
29.Thismethodwillcallthemax()methodinBwiththeparameters23and39.
Themax()methodinBwillinturncallthemax()methodinAwiththe
parameters39and23.Themax()methodinAwillreturn39tothemax()
methodinB.Themax()methodinBwillreturn29tothemax()methodinC.
Themax()methodinCwillreturn29tothemain()method.
7.6(c)
ThesimplestwaytoprintthemessageintheclassMessagewouldbetouse
msg.text.Themain()methodcreatesaninstanceofMyClass,whichresults
inthecreationofaMessageinstance.ThefieldmsgdenotesthisMessage
objectinMySuperclassandisinheritedbytheMyClassobject,asthisfield
hasdefaultaccessibility.Thus,themessageintheMessageobjectcanbeaccessed
directlybymsg.textintheprint()methodofMyClass,andalsoby
this.msg.textandsuper.msg.text.
7.7(g)
IntheclassCar,thestaticmethodgetModelName()hidesthestaticmethodof
thesamenameinthesuperclassVehicle.IntheclassCar,theinstancemethod
getRegNo()overridestheinstancemethodofthesamenameinthesuperclass
Vehicle.Thedeclaredtypeofthereferencedeterminesthemethodtoexecute
whenastaticmethodiscalled,buttheactualtypeoftheobjectatruntime
determinesthemethodtoexecutewhenanoverriddenmethodiscalled.
7.8(e)
TheclassMySuperdoesnothaveano-argumentconstructor.Thismeansthat
constructorsinsubclassesmustexplicitlycallthesuperclassconstructorand
providetherequiredparameters.Thesuppliedconstructoraccomplishesthisby
callingsuper(num)initsfirststatement.Additionalconstructorscanaccomplish
thiseitherbycallingthesuperclassconstructordirectlyusingthesuper()call,or
bycallinganotherconstructorinthesameclassusingthethis()call,whichin
turncallsthesuperclassconstructor.(a)and(b)arenotvalid,sincetheydonotcall
WOW! eBook
www.wowebook.org
thesuperclassconstructorexplicitly.(d)fails,sincethesuper()callmustalways
bethefirststatementintheconstructorbody.(f)fails,sincethesuper()and
this()callscannotbecombined.
7.9(b)
Inasubclasswithoutanydeclaredconstructors,thedefaultconstructorwillcall
super().Theuseofthesuper()andthis()statementsarenotmandatoryas
longasthesuperclasshasadefaultconstructor.Ifneithersuper()northis()
isdeclaredasthefirststatementinthebodyofaconstructor,thenthedefault
super()willimplicitlybethefirststatement.Aconstructorbodycannothave
bothasuper()andathis()statement.Callingsuper()willnotalways
work,sinceasuperclassmightnothaveadefaultconstructor.
7.10(d)
Theprogramwillprint12followedbyTest.Whenthemain()methodis
executed,itwillcreateanewinstanceofBbypassing"Test"asanargument.
ThisresultsinacalltotheconstructorofB,whichhasoneStringparameter.The
constructordoesnotexplicitlycallanysuperclassconstructororanyoverloaded
constructorinBusingathis()call;instead,theno-argumentconstructorofthe
superclassAiscalledimplicitly.Theno-argumentconstructorofAcallsthe
constructorinAthathastwoStringparameters,passingittheargumentlist
("1","2").ThisconstructorcallstheconstructorwithoneStringparameter,
passingtheargument"12".Thisconstructorprintstheargument,afterimplicitly
invokingtheno-argumentconstructorofthesuperclassObject.Nowthe
executionofalltheconstructorsinAiscompleted,andexecutioncontinuesinthe
constructorofB.Thisconstructornowprintstheoriginalargument"Test"and
returnstothemain()method.
7.11(b)and(c)
Interfacedeclarationsdonotprovideanymethodimplementationsandpermitonly
multipleinterfaceinheritance.Aninterfacecanextendanynumberofinterfaces
andcanbeextendedbyanynumberofinterfaces.Fieldsininterfacesarealways
static,andcanbedeclaredasstaticexplicitly.Abstractmethoddeclarations
ininterfacesarealwaysnon-static,andcannotbedeclaredstatic.
Interfacesallowonlymultipleinterfaceinheritance.Aninterfacecanextendany
numberofinterfaces,andcanbeextendedbyanynumberofinterfaces.Fieldsin
interfacesarealwaysstatic,andcanbedeclaredasstaticexplicitly.Static
methods,ofcourse,canbedeclaredasstatic.Abstractmethoddeclarationsin
interfacesarealwaysnon-static,andcannotbedeclaredasstatic.
7.12(a),(d),(e),and(f)
Thekeywordsprotected,private,andfinalcannotbeappliedtointerface
methods.Thekeywordpublicisimplied,butcanbespecifiedforallinterface
methods.Thekeywordsdefault,abstract,andstaticcanbespecifiedfor
WOW! eBook
www.wowebook.org
default,abstract,andstaticmethods,respectively.Thekeywordsdefaultand
staticarerequiredfordefaultandstaticmethods,respectively,butthekeyword
abstractisoptionalandisimplicitlyimpliedforabstractmethods.
7.13(a),(f),and(g)
Onlythekeywordspublic,static,andfinalareimplicitlyimpliedfor
interfacevariables.
7.14(e)
(1):Thefinalstaticconstantisnotinitialized.
(2):Theabstractmethodcannothaveanimplementation.
(3):Thestaticmethodismissingtheimplementation.
(4):Thedefaultmethodcannotbefinal.
7.15(b)and(c)
ThedefaultinstancemethodprintSlogan()isinheritedbytheclass
Company.
(a):Itcanbecalledfromanon-staticcontext(instancemethodtestSlogan())
byitssimplename,butnotfromastaticcontext(staticmethodmain()).
(b),(c):Aninstancemethodcanbeinvokedonaninstanceviaareference,
regardlessofwhetheritisinastaticornon-staticcontext.
(d),(e):Aninstancemethodcannotbeinvokedviaareferencetype,butonlyonan
instanceviaareference;thatis,youcannotmakeastaticreferencetoanon-static
method.
7.16(e)
ThestaticmethodprintSlogan()isnotinheritedbytheclassFirm.Itcan
beinvokedbyusingastaticreference,thenameoftheinterfaceinwhichitis
declared,regardlessofwhetherthecallisinastaticoranon-staticcontext.
7.17(c)
Theinstancemethodat(3)overridesthedefaultmethodat(1).Thestaticmethodat
(2)isnotinheritedbytheclassRaceA.Theinstancemethodat(4)doesnot
overridethestaticmethodat(2).
Themethodtobeinvokedbythecallat(5)isdeterminedatruntimebytheobject
typeofthereference,whichinthiscaseisAthlete,resultinginthemethodat(3)
beinginvoked.Similarly,thecallat(6)willinvoketheinstancemethodat(4).
7.18(a)
Theprogramwillnotcompile,becausetheoverridingmethodat(2)cannothave
narroweraccessibilitythantheoverriddenmethodat(1).Themethodat(1)has
publicaccessibility,whereasthemethodat(2)haspackageaccessibility.
WOW! eBook
www.wowebook.org
7.19(a),(c),and(d)
Fieldsininterfacesdeclarenamedconstants,andarealwayspublic,static,
andfinal.Noneofthesemodifiersismandatoryinaconstantdeclaration.All
namedconstantsmustbeexplicitlyinitializedinthedeclaration.
7.20(a)and(d)
Thekeywordimplementsisusedwhenaclassimplementsaninterface.The
keywordextendsisusedwhenaninterfaceinheritsfromanotherinterfaceora
classinheritsfromanotherclass.
7.21(d)
Thecodewillcompilewithouterrors.TheclassMyClassdeclaresthatit
implementstheinterfacesInterface1andInterface2.Sincetheclassis
declaredasabstract,itdoesnotneedtoimplementallabstractmethod
declarationsdefinedintheseinterfaces.Anynon-abstractsubclassesof
MyClassmustprovidethemissingmethodimplementations.Thetwointerfaces
shareacommonabstractmethoddeclarationvoidg().MyClassprovidesan
implementationforthisabstractmethoddeclarationthatsatisfiesboth
Interface1andInterface2.Bothinterfacesprovidedeclarationsof
constantsnamedVAL_B.ThiscanleadtoambiguitywhenreferringtoVAL_Bby
itssimplenamefromMyClass.Theambiguitycanberesolvedbyusingthe
qualifiednames:Interface1.VAL_BandInterface2.VAL_B.However,
therearenoproblemswiththecodeasitstands.
7.22(a)and(c)
Declaration(b)fails,sinceitcontainsanillegalforwardreferencetoitsownnamed
constant.Thetypeoftheconstantismissingindeclaration(d).Declaration(e)tries
(illegally)tousetheprotectedmodifier,eventhoughnamedconstantsalways
havepublicaccessibility.Suchconstantsareimplicitlypublic,static,and
final.
7.23(c)
Theprogramwillthrowajava.lang.ClassCastExceptioninthe
assignmentat(3)atruntime.Thestatementat(1)willcompile,sincethe
assignmentisdonefromasubclassreferencetoasuperclassreference.Thecastat
(2)assuresthecompilerthatarrAreferstoanobjectthatcanbecasttotypeB[].
Thiswillworkwhenrun,sincearrAwillrefertoanobjectoftypeB[].Thecast
at(3)assuresthecompilerthatarrAreferstoanobjectthatcanbecasttotype
B[].Thiswillnotworkwhenrun,sincearrAwillrefertoanobjectoftypeA[].
7.24(d)and(f)
(4)and(6)willcauseacompile-timeerror,sinceanattemptismadetoassigna
referencevalueofasupertypeobjecttoareferenceofasubtype.Thetypeofthe
sourcereferencevalueisMyClassandthetypeofthedestinationreferenceis
WOW! eBook
www.wowebook.org
MySubclass.(1)and(2)willcompile,sincethereferenceisassignedareference
valueofthesametype.(3)willalsocompile,sincethereferenceisassigneda
referencevalueofasubtype.
7.25(e)
OnlytheassignmentI1b=obj3isvalid.Theassignmentisallowed,sinceC3
extendsC1,whichimplementsI1.Theassignmentobj2=obj1isnotlegal,
sinceC1isnotasubclassofC2.Theassignmentsobj3=obj1andobj3=
obj2arenotlegal,sinceneitherC1norC2isasubclassofC3.Theassignment
I1a=obj2isnotlegal,sinceC2doesnotimplementI1.AssignmentI2c
=obj1isnotlegal,sinceC1doesnotimplementI2.
7.26(b)
Thecompilerwillallowthestatement,asthecastisfromthesupertype(Super)to
thesubtype(Sub).However,ifatruntimethereferencexdoesnotdenoteanobject
ofthetypeSub,aClassCastExceptionwillbethrown.
7.27(b)
Theexpression(oinstanceofB)willreturntrueiftheobjectreferredto
byoisoftypeBorasubtypeofB.Theexpression(!(oinstanceofC))
willreturntrueunlesstheobjectreferredtobyoisoftypeCorasubtypeofC.
Thus,theexpression(oinstanceofB)&&(!(oinstanceofC))
willreturntrueonlyiftheobjectisoftypeBorasubtypeofBthatisnotCora
subtypeofC.GivenobjectsoftheclassesA,B,andC,thisexpressionwillreturn
trueonlyforobjectsofclassB.
7.28(d)
TheprogramwillprintallthelettersI,J,C,andDatruntime.Theobjectreferred
tobythereferencexisofclassD.ClassDextendsclassCandimplementsJ,and
classCimplementsinterfaceI.ThismakesI,J,andCsupertypesofclassD.The
referencevalueofanobjectofclassDcanbeassignedtoanyreferenceofits
supertypesand,therefore,isaninstanceofthesetypes.
7.29(a)
Thesignaturesyingyang(Integer[])andyingyang(Integer…)are
equivalentand,therefore,arenotpermittedinthesameclass.
7.30(c)
Thecallstothecompute()methodinthemethoddeclarationsat(2)andat(3)
aretothecompute()methoddeclarationat(1),astheargumentisalwaysan
int[].
Themethodcallat(4)callsthemethodat(2).Thesignatureofthecallat(4)is
compute(int[],int[])
whichmatchesthesignatureofthemethodat(2).Noimplicitarrayiscreated.
WOW! eBook
www.wowebook.org
Themethodcallin(5)callsthemethodat(1).Animplicitarrayofintiscreatedto
storetheargumentvalues.
Themethodcallsin(6)and(7)callthemethodin(3).Notethetypeofthevariable
arityparameterin(3):anint[][].Thesignatureofthecallsat(6)and(7)is
compute(int[],int[][])
whichmatchesthesignatureofthemethodat(3).Noimplicitarrayiscreated.
7.31(e)
Theprogramwillprint2whenSystem.out.println(ref2.f())is
executed.Theobjectreferencedbyref2isofclassC,butthereferenceisoftype
B.SinceBcontainsamethodf(),themethodcallwillbeallowedatcompiletime.
DuringexecutionitisdeterminedthattheobjectisofclassC,anddynamicmethod
lookupwillcausetheoverridingmethodinCtobeexecuted.
7.32(c)
Theprogramwillprint1whenrun.Thef()methodsinAandBareprivate,
andarenotaccessiblebythesubclasses.Becauseofthis,thesubclassescannot
overloadoroverridethesemethods,butsimplydefinenewmethodswiththesame
signature.TheobjectbeingcalledisofclassC.Thereferenceusedtoaccessthe
objectisoftypeB.SinceBcontainsamethodg(),themethodcallwillbeallowed
atcompiletime.DuringexecutionitisdeterminedthattheobjectisofclassC,and
dynamicmethodlookupwillcausetheoverridingmethodg()inBtobeexecuted.
Thismethodcallsamethodnamedf.Itcanbedeterminedduringcompilationthat
thiscanrefertoonlythef()methodinB,sincethemethodisprivateand
cannotbeoverridden.Thismethodreturnsthevalue1,whichisprinted.
7.33(b),(c),and(d)
Thecodeasitstandswillcompile.Theuseofinheritanceinthiscodedefinesa
Planetis-aStarrelationship.Thecodewillfailifthenameofthefield
starNameischangedintheStarclass,sincethesubclassPlanettriesto
accessitusingthenamestarName.AninstanceofPlanetisnotaninstanceof
HeavenlyBody.NeitherPlanetnorStarimplementsHeavenlyBody.
7.34(b)
Thecodewillcompile.Thecodewillnotfailtocompileifthenameofthefield
starNameischangedintheStarclass,sincethePlanetclassdoesnottryto
accessthefieldbyname,butinsteadusesthepublicmethoddescribe()in
theStarclassforthatpurpose.AninstanceofPlanetisnotaninstanceof
HeavenlyBody,sinceitneitherimplementsHeavenlyBodynorextendsa
classthatimplementsHeavenlyBody.
7.35(e)
(a)to(f)arealltrue;therefore(e)isnot.
WOW! eBook
www.wowebook.org
8FundamentalClasses
8.1(b)
ThemethodhashCode()intheObjectclassreturnsahashcodevalueoftype
int.
8.2(e)
AllarraysaregenuineobjectsandinheritallthemethodsdefinedintheObject
class,includingtheclone()method.NeitherthehashCode()methodnorthe
equals()methodisdeclaredasfinalintheObjectclass,anditcannotbe
guaranteedthatimplementationsofthesemethodswilldifferentiateamongall
objects.
8.3(a)
Theclone()methodoftheObjectclasswillthrowa
CloneNotSupportedExceptioniftheclassoftheobjectdoesnotimplement
theCloneableinterface.
8.4(a),(c),and(d)
Theclassjava.lang.Voidisconsideredawrapperclass,althoughitdoesnot
wrapanyvalue.Thereisnoclassnamedjava.lang.Int,butthereisawrapper
classnamedjava.lang.Integer.Aclassnamedjava.lang.Stringalso
exists,butitisnotawrapperclasssinceallstringsinJavaareobjects.
8.5(c)and(d)
TheclassesCharacterandBooleanarenon-numericwrapperclassesanddo
notextendtheNumberclass.TheclassesByte,Short,Integer,Long,
Float,andDoublearenumericwrapperclassesthatextendtheabstract
Numberclass.
8.6(a),(b),and(d)
Allinstancesofconcretewrapperclassesareimmutable.TheNumberclassisan
abstractclass.
8.7(b)and(c)
AllinstancesofwrapperclassesexceptVoidandCharacterhaveaconstructor
thatacceptsasingleStringparameter.TheclassObjecthasonlyano-
argumentconstructor.
8.8(e)
WhileallnumericwrapperclasseshavethemethodsbyteValue(),
doubleValue(),floatValue(),intValue(),longValue(),and
shortValue(),onlytheBooleanclasshasthebooleanValue()method.
Likewise,onlytheCharacterclasshasthecharValue()method.
8.9(b)and(d)
WOW! eBook
www.wowebook.org
Stringisnotawrapperclass.AllwrapperclassesexceptVoidhavea
compareTo()method.OnlythenumericwrapperclasseshaveanintValue()
method.TheByteclass,likeallothernumericwrapperclasses,extendsthe
Numberclass.
8.10(a)
Usingthenewoperatorcreatesanewobject.Boxingalsocreatesanewobjectif
oneisnotalreadyinternedfrombefore.
8.11(b)and(e)
Theoperators-and&cannotbeusedinconjunctionwithaStringobject.The
operators+and+=performconcatenationonstrings,andthedotoperatoraccesses
membersoftheStringobject.
8.12(d)
Theexpressionstr.substring(2,5)willextractthesubstring"kap".The
methodextractsthecharactersfromindex2toindex4,inclusive.
8.13(d)
Theprogramwillprintstr3str1whenrun.Theconcat()methodwillcreate
andreturnanewStringobject,whichistheconcatenationofthecurrent
StringobjectandtheStringobjectgivenasanargument.Theexpression
statementstr1.concat(str2)createsanewStringobject,butitsreference
valueisnotstoredaftertheexpressionisevaluated.ThereforethisStringobject
getsdiscarded.
8.14(c)
Thetrim()methodoftheStringclassreturnsastringwhereboththeleading
andtrailingwhitespaceoftheoriginalstringhavebeenremoved.
8.15(a)and(c)
TheStringclassandallwrapperclassesaredeclaredasfinaland,therefore,
cannotbeextended.Theclone()methodisdeclaredasprotectedinthe
Objectclass.Stringobjectsandwrapperclassobjectsareimmutableand,
therefore,cannotbemodified.TheclassStringandchararraytypesare
unrelated,resultinginacompile-timeerror.
8.16(d)
Theconstantexpressions"ab"+"12"and"ab"+12will,atcompiletime,
beevaluatedtothestring-valuedconstant"ab12".Bothvariablessandtare
assignedareferencetothesameinternedStringobjectcontaining"ab12".The
variableuisassignedanewStringobject,createdbyusingthenewoperator.
8.17(a),(c),(d),(f),and(j)
TheStringclasshasconstructorswiththeparameterlistsgivenin(a),(c),(d),
WOW! eBook
www.wowebook.org
(f),and(j).
8.18(e)
TheStringclasshasnoreverse()method.
8.19(b)
Thereferencevalueinthereferencestr1neverchanges;italwaysreferstothe
stringliteral"lower".ThecallstotoUpperCase()andreplace()returna
newStringobjectwhosereferencevalueisignored.
8.20(d)
ThecalltotheputO()methoddoesnotchangetheStringobjectreferredtoby
thes1referenceinthemain()method.Thereferencevaluereturnedbythecall
totheconcat()methodisignored.
8.21(a)
Thecodewillfailtocompile,sincetheexpression(s==sb)isillegal.It
comparesreferencesoftwoclassesthatarenotrelated.
8.22(e)
Theprogramwillcompilewithouterrorsandwillprinthaveawhenrun.The
contentsofthestringbufferaretruncatedto6charactersbythemethodcall
sb.setLength(6).
8.23(a),(b),(d),and(e)
TheStringBuilderclasshasonlyconstructorswiththeparameterlistsgiven
in(a),(b),(d),and(e).
8.24(a)
TheStringBuilderclassdoesnotdefineatrim()method.
8.25(b)
Thereferencessb1andsb2arenotaliases.TheStringBuilderclassdoesnot
overridetheequals()method;hencetheansweris(b).
8.26(a)
TheStringBuilderclassdoesnotoverridethehashCode()method,butthe
Stringclassdoes.Thereferencess1ands2refertoaStringobjectanda
StringBuilderobject,respectively.Thehashvaluesoftheseobjectsare
computedbythehashCode()methodintheStringandtheObjectclass,
respectively—givingdifferentresults.Thereferencess1ands3refertotwo
differentStringobjectsthatareequal;hencetheyhavethesamehashvalue.
8.27(b)
ThecalltotheputO()methodchangestheStringBuilderobjectreferredto
WOW! eBook
www.wowebook.org
bythes1referenceinthemain()method.Sodoesthecalltotheappend()
method.
9ObjectLifetime
9.1(e)
Anobjectiseligibleforgarbagecollectiononlyifallremainingreferencestothe
objectarefromotherobjectsthatarealsoeligibleforgarbagecollection.Therefore,
ifanobjectobj2iseligibleforgarbagecollectionandobjectobj1containsa
referencetoit,thenobjectobj1mustalsobeeligibleforgarbagecollection.Java
doesnothaveakeyworddelete.Anobjectwillnotnecessarilybegarbage
collectedimmediatelyafteritbecomesunreachable,buttheobjectwillbeeligible
forgarbagecollection.Circularreferencesdonotpreventobjectsfrombeing
garbagecollected;onlyreachablereferencesdo.Anobjectisnoteligiblefor
garbagecollectionaslongastheobjectcanbeaccessedbyanylivethread.An
objectthatiseligibleforgarbagecollectioncanbemadenon-eligibleifthe
finalize()methodoftheobjectcreatesareachablereferencetotheobject.
9.2(b)
Before(1),theStringobjectinitiallyreferencedbyarg1isdenotedbyboth
msgandarg1.After(1),theStringobjectisdenotedbyonlymsg.At(2),
referencemsgisassignedanewreferencevalue.Thisreferencevaluedenotesa
newStringobjectcreatedbyconcatenatingthecontentsofseveralother
Stringobjects.After(2),therearenoreferencestotheStringobjectinitially
referencedbyarg1.TheStringobjectisnoweligibleforgarbagecollection.
9.3(d)
Itisdifficulttosayhowmanyobjectsareeligibleforgarbagecollectionwhen
controlreaches(1),becausesomeoftheeligibleobjectsmayhavealreadybeen
finalized.
9.4(a)
Alltheobjectscreatedinthelooparereachableviap,whencontrolreaches(1).
9.5(b)
TheObjectclassdefinesaprotectedfinalize()method.Allclasses
inheritfromObject;thus,allobjectshaveafinalize()method.Classescan
overridethefinalize()methodand,aswithalloverriding,thenewmethod
mustnotreducetheaccessibility.Thefinalize()methodofaneligibleobject
iscalledbythegarbagecollectortoallowtheobjecttodoanycleaningupbefore
theobjectisdestroyed.Whenthegarbagecollectorcallsthefinalize()
method,itwillignoreanyexceptionsthrownbythefinalize()method.Ifthe
finalize()methodiscalledexplicitly,normalexceptionhandlingoccurswhen
anexceptionisthrownduringtheexecutionofthefinalize()method;thatis,
exceptionsarenotsimplyignored.Callingthefinalize()methoddoesnotin
WOW! eBook
www.wowebook.org
itselfdestroytheobject.Chainingofthefinalize()methodisnotenforcedby
thecompiler,anditisnotmandatorytocalltheoverriddenfinalize()method.
9.6(d)
Thefinalize()methodislikeanyothermethod:Itcanbecalledexplicitlyifit
isaccessible.However,suchamethodisintendedtobecalledbythegarbage
collectortocleanupbeforeanobjectisdestroyed.Overloadingthefinalize()
methodisallowed,butonlythemethodwiththeoriginalsignaturewillbecalledby
thegarbagecollector.Thefinalize()methodintheObjectclassis
protected.Thismeansthatanyoverridingmethodmustbedeclaredaseither
protectedorpublic.Thefinalize()methodintheObjectclass
specifiesaThrowableobjectinitsthrowsclause.Anoverridingdefinitionof
thismethodcanthrowanytypeofThrowable.Overridingmethodscanlimitthe
rangeofthrowablestouncheckedexceptionsorspecifynoexceptionsatall.Further
overridingdefinitionsofthismethodinsubclasseswillthennotbeabletothrow
checkedexceptions.
9.7(d)and(g)
(a),(b),(c),(j),(k),and(l)reducethevisibilityoftheinheritedmethod.In(e),(f),
(h),and(i),thecalltothefinalize()methodofthesuperclasscanthrowa
Throwable,whichisnothandledbythemethod.TheThrowablesuperclassis
notassignabletotheExceptionsubclass.
9.8(e)
Itisnotguaranteedifandwhengarbagecollectionwilloccur,norinwhichorder
theobjectswillbefinalized.However,itisguaranteedthatthefinalizationofan
objectwillberunonlyonce.Hence,(e)cannotpossiblybearesultfromrunning
theprogram.
9.9(c)and(e)
Itisnotguaranteedifandwhengarbagecollectionwilloccur,norinwhichorder
theobjectswillbefinalized.Thus,theprogrammaynotprintanything.Ifgarbage
collectiondoestakeplace,theMyStringobjectcreatedintheprogrammayget
finalizedbeforetheprogramterminates.Inthatcase,thefinalize()method
willprintA,asthestringinthefieldstrisnotchangedbytheconcat()
method.KeepinmindthataStringobjectisimmutable.
9.10(c),(e),and(f)
Thestaticinitializerblocks(a)and(b)arenotlegal,sincethefieldsaliveand
STEParenon-staticandfinal,respectively.(d)isnotasyntacticallylegal
staticinitializerblock.Thestaticblockin(e)willhavenoeffect,asitexecutesthe
emptystatement.Thestaticblockin(f)willchangethevalueofthestaticfield
countfrom5to1.
9.11(c)
WOW! eBook
www.wowebook.org
Theprogramwillcompile,andprint50,70,0,20,0atruntime.Allfields
aregivendefaultvaluesunlesstheyareexplicitlyinitialized.Fieldiisassignedthe
value50inthestaticinitializerblockthatisexecutedwhentheclassisinitialized.
Thisassignmentwilloverridetheexplicitinitializationoffieldiinitsdeclaration
statement.Whenthemain()methodisexecuted,thestaticfieldiis50andthe
staticfieldnis0.Whenaninstanceoftheclassiscreatedusingthenewoperator,
thevalueofstaticfieldn(i.e.,0)ispassedtotheconstructor.Beforethebodyof
theconstructorisexecuted,theinstanceinitializerblockisexecuted,whichassigns
thevalues70and20tothefieldsjandn,respectively.Whenthebodyofthe
constructorisexecuted,thefieldsi,j,k,andnandtheparametermhavethe
values50,70,0,20,and0,respectively.
9.12(f)
Thisclasshasablankfinalbooleaninstancevariableactive.Thisvariable
mustbeinitializedwhenaninstanceisconstructed,orelsethecodewillnot
compile.Thisalsoappliestoblankfinalstaticvariables.Thekeyword
staticisusedtosignifythatablockisastaticinitializerblock.Nokeywordis
usedtosignifythatablockisaninstanceinitializerblock.(a)and(b)arenot
instanceinitializersblocks,and(c),(d),and(e)failtoinitializetheblankfinal
variableactive.
9.13(c)
Theprogramwillcompile,andprint2,3,and1atruntime.Whentheobjectis
createdandinitialized,theinstanceinitializerblockisexecutedfirst,printing2.
Thentheinstanceinitializerexpressionisexecuted,printing3.Finally,the
constructorbodyisexecuted,printing1.Theforwardreferenceintheinstance
initializerblockislegal,astheuseofthefieldmisontheleft-handsideofthe
assignment.
9.14(c)and(e)
LineAwillcauseanillegalredefinitionofthefieldwidth.LineBusesanillegal
forwardreferencetothefieldswidthandheight.TheassignmentinLineCis
legal.LineDisanassignmentstatement,soitisillegalinthiscontext.LineE
declaresalocalvariableinsideaninitializerblock,withthesamenameasthe
instancevariablewidth,whichisallowed.Thesimplenameinthisblockwill
refertothelocalvariable.Toaccesstheinstancevariablewidth,thethis
referencemustbeusedinthisblock.
10TheArrayList<E>ClassandLambdaExpressions
10.1(h)
Themethodremove()canbeusedtodeleteanelementataspecificindexinan
ArrayList.
Themethodclear()canbeusedtodeleteallelementsinanArrayList.
WOW! eBook
www.wowebook.org
Themethodadd(int,E)canbeusedtoinsertanelementataspecificindexin
anArrayList.
Themethodadd()canbeusedtoappendanelementattheendofan
ArrayList.
Themethodset()canbeusedtoreplacetheelementataspecificindexwith
anotherelementinanArrayList.
Themethodcontains()canbeusedtodeterminewhetheranelementisinan
ArrayList.
ThereisnomethodtodeterminethecurrentcapacityofanArrayList.
10.2(e)
Thefor(;;)loopcorrectlyincrementstheloopvariablesothatalltheelements
inthelistaretraversed.Removingelementsusingthefor(;;)loopdoesnot
throwaConcurrentModificationExceptionatruntime.
10.3(b)and(c)
InthemethoddoIt1(),oneofthecommonelements("Ada")betweenthetwo
listsisreversed.Thevaluenullisaddedtoonlyoneofthelistsbutnottheother.
InthemethoddoIt2(),thetwolistshavecommonelements.Swappingthe
elementsinonelistdoesnotchangetheirpositionsintheotherlist.
10.4(c)
Theelementatindex2hasthevaluenull.Callingtheequals()methodonthis
elementthrowsaNullPointerException.
10.5(f)
Deletingelementswhentraversingalistrequirescare,asthesizechangesandany
elementstotherightofthedeletedelementareshiftedleft.Incrementingtheloop
variableafterdeletinganelementwillmissthenextelement,asisthecasewiththe
lastoccurrenceof"Bob".Removingelementsusingthefor(;;)loopdoesnot
throwaConcurrentModificationExceptionatruntime.
10.6(f)
Thewhileloopwillexecuteaslongastheremove()methodsreturnstrue—
thatis,aslongasthereisanelementwiththevalue"Bob"inthelist.Thewhile
loopbodyistheemptystatement.Theremove()methoddoesnotthrowan
exceptionifanelementvalueisnull,orifitispassedanullvalue.
10.7(f)
Afunctionalinterfacecanbeimplementedbylambdaexpressionsandclasses.
Afunctionalinterfacedeclarationcanhaveonlyoneabstractmethoddeclaration.
Inthebodyofalambdaexpression,allmembersintheenclosingclasscanbe
WOW! eBook
www.wowebook.org
accessed.
Inthebodyofalambdaexpression,onlyeffectivelyfinallocalvariablesinthe
enclosingscopecanbeaccessed.
Alambdaexpressioninaprogramcanimplementmorethanonefunctional
interface.Forexample,thelambdaexpression(i->i%2==0)canbethe
targettypeofboththefunctionalinterfacesIntPredicateand
Predicate<Integer>.
10.8(a)and(c)
(1)redeclaresthelocalvariablepfromtheenclosingscope,whichisnotlegal.
In(2),theequals()methodoftheStringclassiscalled,becauseitisinvoked
onthetextualrepresentationoftheparameter.Intheotherstatements,the
equals()methodoftheobjectreferredtobytheparameteriscalled.
Thelambdabodyin(3)isastatementblockwithanexpressionwhosevaluemust
bereturnedbythereturnstatement.
(4)and(5)accessstaticmembersintheclass,whichislegal.
In(6),theparameternamelock2shadowsthestaticvariablebythesamename,
butisalocalvariableinthelambdaexpression.Thestaticvariableisreferredto
usingtheclassname.
10.9(e),(f),(g),and(i)
Assignmentsin(5),(6),(7),and(9)willnotcompile.Wemustcheckwhetherthe
functiontypeofthetargettypeandthetypeofthelambdaexpressionare
compatible.Thefunctiontypeofthetargettypep1intheassignmentstatements
from(1)to(5)isString->void,oravoidreturn.Thefunctiontypeofthe
targettypep2intheassignmentstatementsfrom(6)to(10)isString->
String,oranon-voidreturn.Inthefollowingcode,thefunctionaltypeofthe
targettypeisshowninacommentwiththeprefixLHS(left-handside),andthe
typeofthelambdaexpressionforeachassignmentfrom(1)to(10)isshownina
commentwiththeprefixRHS(right-handside).
Clickheretoviewcodeimage
Funky1p1;//LHS:String->void
p1=s->System.out.println(s);//(1)RHS:String->void
p1=s->s.length();//(2)RHS:String->int
p1=s->s.toUpperCase();//(3)RHS:String->
String
p1=s->{s.toUpperCase();};//(4)RHS:String->void
//p1=s->{returns.toUpperCase();};//(5)RHS:String->
String
Funky2p2;//LHS:String->
String
//p2=s->System.out.println(s);//(6)RHS:String->void
//p2=s->s.length();//(7)RHS:String->int
p2=s->s.toUpperCase();//(8)RHS:String->
String
WOW! eBook
www.wowebook.org
//p2=s->{s.toUpperCase();};//(9)RHS:String->void
p2=s->{returns.toUpperCase();};//(10)RHS:String->
String
Thenon-voidreturnofalambdaexpressionwithanexpressionstatementasthe
bodycanbeinterpretedasavoidreturn,ifthefunctiontypeofthetargettype
returnsvoid.Thisisthecasein(2)and(3).Thereturnvalueisignored.Thetype
String->Stringofthelambdaexpressionin(5)isnotcompatiblewiththe
functiontypeString->voidofthetargettypep1.
Thetypeofthelambdaexpressionin(6),(7),and(9)isnotcompatiblewiththe
functiontypeString->Stringofthetargettypep2.
10.10(d)
Thelambdaexpressionfiltersallintegervaluesthatarebothnegativeandeven
numbers.Thesevaluesarereplacedwiththeirabsolutevaluesintheintegerarray.
Thefunctionalinterfacejava.util.function.IntPredicatehasthe
abstractmethod:booleantest(inti).
10.11(d)
Thethreeinterfacesarefunctionalinterfaces.InterfaceBexplicitlyprovidesan
abstractmethoddeclarationofthepublicmethodequals()fromtheObject
class,butsuchdeclarationsareexcludedfromthedefinitionofafunctional
interface.ThusInterfaceBeffectivelyhasonlyoneabstractmethod.A
functionalinterfacecanbeimplementedbyaconcreteclass,suchasBeta.The
functiontypeofthetargettypeintheassignments(1)to(3)isvoid->void.
Thetypeofthelambdaexpressionin(1)to(3)isalsovoid->void.The
assignments(1)to(3)arelegal.
Theassignmentin(4)islegal.Subtypereferencesareassignedtosupertype
references.Referenceso,a,andcrefertothelambdaexpressionin(3).
Theassignmentin(5)islegal.ThereferencebhasthetypeInterfaceB,and
classBetaimplementsthisinterface.
(6),(7),and(8)invokethemethoddoIt().(6)evaluatesthelambdaexpressionin
(3),printingJingle|.(7)invokesthedoIt()methodonanobjectofclass
Beta,printingJazz|.(8)alsoevaluatesthelambdaexpressionin(3),printing
Jingle|.
In(9),thereferenceoiscastdowntoInterfaceA.Thereferenceoactually
referstothelambdaexpressionin(3),whichhastargettypeInterfaceC.This
interfaceisasubtypeofInterfaceA.Thesubtypeiscasttoasupertype,which
isallowed,sonoClassCastExceptionisthrownatruntime.Invokingthe
doIt()methodagainresultsinevaluationofthelambdaexpressionin(3),
printingJingle|.
Apartfromthedeclarationsofthelambdaexpressions,therestofthecodeisplain-
vanillaJava.Notealsothatthefollowingassignmentthatdefinesalambda
WOW! eBook
www.wowebook.org
expressionwouldnotbevalid,sincetheObjectclassisnotafunctionalinterface
andthereforecannotprovideatargettypeforthelambdaexpression:
Clickheretoviewcodeimage
Objectobj=()->System.out.println(“Jingle”);//Compile-time
error!
11DateandTime
11.1(e)
TheLocalDateTimeclassdoesnotprovidetheisLeapYear()method.
TheLocalTimeclassdoesnotprovidetheisEqual()method.
ThePeriodclassdoesnotprovidethewithWeeks()method,butdoesprovide
theofWeeks()staticmethod.
BoththePeriodandLocalTimeclassesdonotprovidetheplusWeeks()
method.
11.2(e)
Thedatereferencenevergetsupdated,asthereturnvalueisignored.Ifithad
beenupdated,thecorrectanswerwouldhavebeen(c).The
LocalDate.getMonth()methodreturnsaMonthenumconstant—inthis
case,Month.MARCH.TheLocalDate.getMonthValue()methodreturns
themonthasavaluebetween1and12—inthiscase,3.
11.3(b),(c),(e),and(g)
(a):Themonthnumbersstartwith1.Augusthasmonthvalue8.
(d):Invalidmonth(0)andday(0)argumentsinthecalltotheof()methodresult
inaDateTimeExceptionbeingthrownatruntime.
(f):TheLocalDateclassdoesnotprovideapublicconstructor.
11.4(c),(d),and(f)
(a):Invalidargumentfortheminutes(0–59).
(b):TheLocalTimeclassdoesnotprovideapublicconstructor.
(c):Thetimeassignedis09:00.
(d):Thetimeassignedis00:00.
(e):ThereisnowithHours()method,butthereisawithHour()methodin
theLocalTimeclass.
(f):Thetimeassignedis11:45.
11.5(c)
Boththehourandminutesarenormalizedbytheplusmethods,andthetimeof
daywrapsaroundmidnight.Thecalculationof
WOW! eBook
www.wowebook.org
time.plusHours(10).plusMinutes(120)proceedsasfollows:
Clickheretoviewcodeimage
12:00+10hours==>22:00+120min(i.e.,2hrs.)==>00:00
11.6(d)
Thecalculationofp1.plus(p2).plus(p1)proceedsasfollows:
Clickheretoviewcodeimage
P1Y1M1D+P2Y12M30D==>P3Y13M31D+P1Y1M1D==>P4Y14M32D
11.7(c)
Thecalculationofdate.withYear(5).plusMonths(14)proceedsas
follows:
Clickheretoviewcodeimage
2015-01-01withyear5==>0005-01-01+14months(i.e.,1year2months)
==>
0006-03-01
11.8(a),(d),(e),(g),and(i)
Thebetween()anduntil()methodsreturnaPeriod,whichcanbe
negative.TheisAfter(),isBefore(),between(),anduntil()methods
arestrictinthesensethattheenddateisexcluded.ThecompareTo()method
returns0ifthetwodatesareequal,anegativevalueifdate1islessthandate2,
andapositivevalueifdate1isgreaterthandate2.
11.9(e)
(a):TheDateTimeFormatterclassprovidesfactorymethodstoobtainboth
predefinedandcustomizedformatters.
(b):Thestylesdefinedbythejava.time.format.FormatStyleenumtype
arelocalesensitive.
(c):TheofLocalizedDate()methodoftheDateTimeFormatterclass
returnsaformatterthatisbasedonaformatstyle(aconstantofthe
FormatStyleenumtype)passedasanargumenttothemethod.
(d):Thepattern"yy-mm-dd"cannotbeusedtocreateaformatterthatcanformat
aLocalDateobject.Thelettermstandsforminutesofthehour,whichisnota
partofadate.
11.10(a),(b),(c),and(f)
(a),(b),(c):Theinputstringmatchesthepattern.Theinputstringspecifiesthe
mandatorypartsofbothadateandatime,neededbytherespectivemethodto
constructeitheraLocalTime,aLocalDate,oraLocalDateTime.
Tousethepatternforformatting,thetemporalobjectmustprovidetheparts
correspondingtothepatternlettersinthepattern.TheLocalTimeobjectin(d)
doesnothavethedatepartrequiredbythepattern.TheLocalDateobjectin(e)
WOW! eBook
www.wowebook.org
doesnothavethetimepartrequiredbythepattern.Both(d)and(e)willthrowan
UnsupportedTemporalTypeException.OnlytheLocalDateTime
objectin(f)hasboththedateandtimepartsrequiredbythepattern.
11.11(b),(e),and(f)
Theinputstringmatchesthepattern.Itspecifiesthedate-basedvaluesthatcanbe
usedtoconstructaLocalDateobjectin(b),basedonthedate-relatedpattern
lettersinthepattern.Notime-basedvaluescanbeinterpretedfromtheinputstring,
asthispatternhasonlydate-relatedpatternletters.(a)and(c),whichrequireatime
part,willthrowaDateTimeParseException.
Tousethepatternforformatting,thetemporalobjectmustprovidevaluesforthe
partscorrespondingtothepatternlettersinthepattern.TheLocalTimeobjectin
(d)doesnothavethedatepartrequiredbythepattern.(d)willthrowan
UnsupportedTemporalTypeException.TheLocalDateobjectin(e)has
thedatepartrequiredbythepattern,asdoestheLocalDateTimeobjectin(f).In
(f),onlythedatepartoftheLocalDateTimeobjectisformatted.
11.12(e)
(a),(b),(c),(d),and(f)resultinaDateTimeParseExceptionwhenparsing.
(a):Thepatternletterhrepresentshourintheday,butrequiresAM/PM
informationtoresolvethehourina24-hourclock(i.e.,patternlettera),whichis
missing.
(b):ThepatternletterMisinterpretedcorrectlyasmonthoftheyear(value5).
Matchingthepatternletterhistheproblem,asexplainedfor(a).
(c),(d):Thepatternletteracannotberesolvedfromtheinputstring,asanAM/PM
markerismissingintheinputstring.
(e):Theparsesucceeds,withtheLocalTimeobjecthavingthevalue09:05.
Formattingthisobjectwiththeformatterresultsintheoutputstring:5minutes
past9.
(f):Theletterpatternmmcannotberesolved,astheminutesvaluehasonlyone
digit(i.e.,5)intheinputstring.
(g):Theparsesucceeds,withtheresultingLocalTimeobjecthavingthevalue
09:00.Themonthvalue5isignored.Formattingthisobjectwiththeformatter
resultsinanUnsupportedTemporalTypeException,becausenowthe
patternletterMrequiresamonthvalue,whichisnotpartofaLocalTimeobject.
11.13(d)
(a):TheformatterwillformataLocalTimeobject,orthetimepartofa
LocalDateTimeobject,butnotaLocalDateobject,asitknowsnothingabout
formattingthedatepart.
(b):TheformatterwillformataLocalDateobject,orthedatepartofa
WOW! eBook
www.wowebook.org
LocalDateTimeobject,butnotaLocalTimeobject,asitknowsnothingabout
formattingthetimepart.
(c):TheformatterwillformataLocalDateTimeobject,butnotaLocalDate
objectoraLocalTimeobject,asitwillformatonlytemporalobjectswithboth
dateandtimeparts.
Theprogramthrowsa
java.time.temporal.UnsupportedTemporalTypeExceptioninall
cases.
WOW! eBook
www.wowebook.org
AppendixD.SolutionstoProgrammingExercises
1BasicsofJavaProgramming
1.1TheprintStackElements()methodofthePrintableCharStackclass
doesnotpoptheelements.
Clickheretoviewcodeimage
//File:CharStack.java
publicclassCharStack{
//Instancevariables:
protectedchar[]stackArray;//Thearrayimplementingthestack.
protectedinttopOfStack;//Thetopofthestack.
//Staticvariable
privatestaticintcounter;//(1)
//Constructornowincrementsthecounterforeachobjectcreated.
publicCharStack(intcapacity){//(2)
stackArray=newchar[capacity];
topOfStack=-1;
counter++;
}
//Instancemethods:
publicvoidpush(charelement){stackArray[++topOfStack]=element;}
publiccharpop(){returnstackArray[topOfStack—];}
publiccharpeek(){returnstackArray[topOfStack];}
publicbooleanisEmpty(){returntopOfStack==-1;}
publicbooleanisFull(){returntopOfStack==stackArray.length
-1;}
//Staticmethod(3)
publicstaticintgetInstanceCount(){returncounter;}
}
Clickheretoviewcodeimage
//File:PrintableCharStack.java
publicclassPrintableCharStackextendsCharStack{//
(1)
//Instancemethod
publicvoidprintStackElements(){//
(2)
for(inti=0;i<=topOfStack;i++)
System.out.print(stackArray[i]);//printeachcharonterminal
System.out.println();
}
//Constructorcallstheconstructorofthesuperclassexplicitly.
PrintableCharStack(intcapacity){super(capacity);}//
(3)
}
Clickheretoviewcodeimage
//File:Client.java
publicclassClient{
WOW! eBook
www.wowebook.org
publicstaticvoidmain(String[]args){
//Createaprintablecharacterstack.
PrintableCharStackstack=newPrintableCharStack(40);
//Createastringtopushonthestack:
Stringstr=“!notisotnuferaskcatS”;
System.out.println(“Originalstring:”+str);
intlength=str.length();
//Pushthestringcharbycharontothestack:
for(inti=0;i<length;i++){
stack.push(str.charAt(i));
}
System.out.print(“Stackcontents:“);
stack.printStackElements();
System.out.print(“Reversedstring:“);
//Popandprinteachcharfromthestack:
while(!stack.isEmpty()){
System.out.print(stack.pop());
}
System.out.println();
System.out.print(“Stackcontents:“);
stack.printStackElements();
}
}
2LanguageFundamentals
2.1Thefollowingprogramcompilesandrunswithouterrors:
Clickheretoviewcodeimage
//File:Temperature.java
/*IdentifiersandkeywordsinJavaarecasesensitive.Therefore,the
thenameofthepublicclassmustmatchthenameofthefile,and
keywordsmust
allbewritteninlowercase.ThenameoftheStringclasshasan
uppercaseS.Themainmethodmustbestaticandtakesanarrayof
Stringobjectsasanargument.*/
publicclassTemperature{
publicstaticvoidmain(String[]args){//Correctmethodsignature
doublefahrenheit=62.5;
//Amultiple-linecomment,whichcanspanseverallines,startswith
//thecharactersequence/*andendswiththecharactersequence*/.
/*Convert*/
doublecelsius=f2c(fahrenheit);
//Characterliteralsareenclosedinsinglequotes;
//stringliteralsareenclosedindoublequotes.
//Onlythefirstcharacterliteralisquotedasastringtoavoid
addition.
//Thesecondcharliteralisimplicitlyconvertedtoitsstring
//representation,asstringconcatenationisperformedby
//thelast+operator.
//Javaiscasesensitive.ThenameCelsiusshouldbechangedto
//thevariablenamecelsius.
System.out.println(fahrenheit+“F”+”=”+celsius+‘C’);
}
/*Methodshouldbedeclaredstatic.*/
staticdoublef2c(doublefahr){//Noteparametertypeshouldbe
WOW! eBook
www.wowebook.org
double.
return(fahr-32.0)*5.0/9.0;
}
}
3Declarations
3.1
Clickheretoviewcodeimage
publicclassQuizGrader{
/**Enumtypetorepresenttheresultofansweringaquestion.*/
enumResult{CORRECT,WRONG,UNANSWERED}
privatestaticfinalintPASS_MARK=5;
privatestaticString[]correctAnswers={“C”,“A”,“B”,“D”,
“B”,“C”,“C”,“A”};
publicstaticvoidmain(String[]args){
System.out.println(“QuestionSubmittedAns.CorrectAns.Result”);
//Countersformiscellaneousstatistics:
intnumOfCorrectAnswers=0;
intnumOfWrongAnswers=0;
intnumOfUnanswered=0;
//Loopthroughsubmittedanswersandcorrectanswers:
for(inti=0;i<args.length;i++){
StringsubmittedAnswer=args[i];
StringcorrectAnswer=correctAnswers[i];
Resultresult=determineResult(submittedAnswer,correctAnswer);
//Printreportforcurrentquestion.
System.out.printf(“%5d%10s%15s%15s%n”,
i+1,submittedAnswer,correctAnswer,result);
//Accumulatestatistics:
switch(result){
caseCORRECT:numOfCorrectAnswers++;break;
caseWRONG:numOfWrongAnswers++;break;
caseUNANSWERED:numOfUnanswered++;break;
}
}
//Printsummaryofstatistics:
System.out.println(“No.ofcorrectanswers:”+
numOfCorrectAnswers);
System.out.println(“No.ofwronganswers:”+
numOfWrongAnswers);
System.out.println(“No.ofquestionsunanswered:”+
numOfUnanswered);
System.out.println(“Thecandidate”+
(numOfCorrectAnswers>=PASS_MARK?“PASSED.”:
“FAILED.”));
}
/**Determinestheresultofanswertoaquestion.*/
publicstaticResultdetermineResult(StringsubmittedAnswer,
StringcorrectAnswer){
Resultresult=null;
if(submittedAnswer.equals(correctAnswer))
result=Result.CORRECT;
WOW! eBook
www.wowebook.org
elseif(submittedAnswer.equals(“X”))
result=Result.UNANSWERED;
else
result=Result.WRONG;
returnresult;
}
}
4AccessControl
4.1
Clickheretoviewcodeimage
//File:Account.java
packagecom.megabankcorp.records;
publicclassAccount{}
//File:Database.java
//Specifypackage.
packagecom.megabankcorp.system;
//RefertotheAccountclassbyusingitssimplename.
importcom.megabankcorp.records.Account;
//Classmustbeabstractsinceithasabstractmethods.
publicabstractclassDatabase{
//Abstractandaccessibletoallclassesinanypackage.
publicabstractvoiddeposit(Accountacc,doubleamount);
//Abstractandaccessibletoallclassesinanypackage.
publicabstractvoidwithdraw(Accountacc,doubleamount);
//Abstractandaccessibletoallclasseswithinitsownpackage
//andtosubclassesinotherpackages.
protectedabstractdoublebalance(Accountacc);
//Cannotbeoverriddenbyasubclassandaccessibleonly
//toclasseswithinitsownpackage.
finalvoidtransfer(Accountfrom,Accountto,doubleamount){
withdraw(from,amount);
deposit(to,amount);
}
}
5OperatorsandExpressions
5.1
Clickheretoviewcodeimage
//File:SunlightSolution.java
publicclassSunlightSolution{
publicstaticvoidmain(String[]args){
//Distancefromsun(150millionkilometers)
/*Themaxvalueforintis2_147_483_647,sousingintherewill
work.*/
intkmFromSun=150_000_000;
//Again,usingintforthisvalueisOK.
intlightSpeed=299_792_458;//Meterspersecond
WOW! eBook
www.wowebook.org
//Convertdistancetometers.
/*Theresultofthisequationwillnotfitinanint,
soweusealonginstead.Weneedtoensurethatthevaluesthat
aremultipliedareactuallymultipliedusinglong
datatypes,andnotmultipliedasintdatatypesandlater
convertedtolong.TheLsuffixonthe1000Linteger
literalensuresthis.ThevalueofthevariablekmFromSunwill
implicitlybeconvertedfrominttolongtomatchthe
datatypeoftheotherfactor.Theconversioncanbedone
implicitlybythecompilersincetheconversionrepresents
awideningofthedatatype.*/
longmFromSun=kmFromSun*1000L;
/*Weknowthattheresultvaluewillfitinanint.
However,thenarrowingconversiononassignmentfromlongtoint
inthiscaserequiresacast.*/
intseconds=(int)(mFromSun/lightSpeed);
System.out.print(“Lightwilluse“);
printTime(seconds);
System.out.println(”totravelfromthesuntotheearth.”);
}
/*Nochangesnecessaryinthismethod.*/
publicstaticvoidprintTime(intsec){
intmin=sec/60;
sec=sec-(min*60);
System.out.print(min+”minute(s)and”+sec+”second(s)”);
}
}
6ControlFlow
6.1Findingprimesusingforloops.
Clickheretoviewcodeimage
//File:ForPrimes.java
publicclassForPrimes{
privatestaticfinalintMAX=100;
publicstaticvoidmain(String[]args){
numbers:
for(intnum=1;num<MAX;num++){
intdivLim=(int)Math.sqrt(num);
for(intdiv=2;div<=divLim;div++){
if((num%div)==0){
continuenumbers;
}
}
System.out.println(num);
}
}
}
Findingprimesusingwhileloops.
Clickheretoviewcodeimage
//File:WhilePrimes.java
publicclassWhilePrimes{
privatestaticfinalintMAX=100;
publicstaticvoidmain(String[]args){
WOW! eBook
www.wowebook.org
intnum=1;
numbers:
while(num<MAX){
intnumber=num++;
intdivLim=(int)Math.sqrt(number);
intdiv=2;
while(div<=divLim){
if((number%div++)==0){
continuenumbers;
}
}
System.out.println(number);
}
}
}
6.2
Clickheretoviewcodeimage
packageenergy;
/**APowerPlantwithareactorcore.
ThesolutionpresentedhereisprovidedbyJennieYip.*/
publicclassPowerPlant{
/**Eachpowerplanthasareactorcore.
ThisfieldhaspackageaccessibilitysothattheControlclass,
definedinthesamepackage,canaccessit.*/
finalReactorcore;
/**Initializesthepowerplant,createsareactorcore.*/
PowerPlant(){
core=newReactor();
}
/**Soundsthealarmtoevacuatethepowerplant.*/
publicvoidsoundEvacuateAlarm(){
//…implementationunspecified…
}
/**@returnthelevelofreactoroutputthatismostdesirableatthis
time.
(Unitsareunspecified.)*/
publicintgetOptimalThroughput(){
//…implementationunspecified…
return0;
}
/**Themainentrypointoftheprogram:setsupaPowerPlantobject
andaControlobjectandletstheControlobjectrunthepower
plant.*/
publicstaticvoidmain(String[]args){
PowerPlantplant=newPowerPlant();
Controlctrl=newControl(plant);
ctrl.runSystem();
}
}
//______________________________________________________________________________
/**Areactorcorethathasathroughputthatcanbeeitherdecreasedor
increased.*/
classReactor{
/**@returnthecurrentthroughputofthereactor.(Unitsare
WOW! eBook
www.wowebook.org
unspecified.)*/
publicintgetThroughput(){
//…implementationunspecified…
return0;
}
/**@returntrueifthereactorstatusiscritical,falseotherwise.*/
publicbooleanisCritical(){
//…implementationunspecified…
returnfalse;
}
/**Asksthereactortoincreasethroughput.*/
voidincreaseThroughput()throwsReactorCritical{
//…implementationunspecified…
}
/**Asksthereactortodecreasethroughput.*/
voiddecreaseThroughput(){
//…implementationunspecified…
}
}
//______________________________________________________________________________
/**Thisexceptionclassshouldbeusedtoreportthatthereactorstatus
is
critical.*/
classReactorCriticalextendsException{}
//______________________________________________________________________________
/**Acontrollerthatwillmanagethepowerplanttomakesurethatthe
reactorrunswithoptimalthroughput.*/
classControl{
privatefinalPowerPlantthePlant;
staticfinalintTOLERANCE=10;
/**@parampthepowerplanttocontrol*/
publicControl(PowerPlantp){
thePlant=p;
}
/**Runthepowerplantbycontinuouslymonitoringthe
optimalthroughputandtheactualthroughputofthereactor.
Ifthethroughputsdifferbymorethan10units(i.e.tolerance),
adjustthereactorthroughput.
Ifthereactorgoescritical,theevacuatealarmis
soundedandthereactorisshutdown.
TherunSystem()methodcallsthemethodsneedAdjustment(),
adjustThroughput(),andshutdown().*/
publicvoidrunSystem(){
try{
while(true){//infiniteloop
intoptimalThroughput=thePlant.getOptimalThroughput();
if(needAdjustment(optimalThroughput)){
adjustThroughput(optimalThroughput);
}
}
}catch(ReactorCriticalrc){
thePlant.soundEvacuateAlarm();
WOW! eBook
www.wowebook.org
}finally{
shutdown();
}
}
/**Reportswhetherthethroughputofthereactorneedsadjusting.
Thismethodshouldalsomonitorandreportifthereactorgoes
critical.
@paramtargetthedesiredthroughput.
@returntrueiftheoptimalandactualthroughputvaluesdifferby
morethan10units.
@throwsReactorCriticalifthereactorgoescritical*/
publicbooleanneedAdjustment(inttarget)throwsReactorCritical{
/*Weaddedthethrowsclausetothemethoddeclarationsothat
themethodcanthrowaReactorCriticalexceptionifthereactor
goescritical.*/
if(thePlant.core.isCritical()){
thrownewReactorCritical();
}
returnMath.abs(thePlant.core.getThroughput()-target)>TOLERANCE;
}
/**Adjuststhethroughputofthereactorbycalling
increaseThroughput()
anddecreaseThroughput()methodsuntiltheactualthroughputis
within
10unitsofthetargetthroughput.
@paramtargetthedesiredthroughput.
@throwsReactorCriticalifthereactorgoescritical.*/
publicvoidadjustThroughput(inttarget)throwsReactorCritical{
/*Weaddedthethrowsclausetothemethoddeclarationbecause
thismethoddoesnotwanttohandleanyReactorCriticalexception
thrownbytheincreaseThroughput()method.*/
while(needAdjustment(target)){
if((thePlant.core.getThroughput()-target)>TOLERANCE){
thePlant.core.increaseThroughput();
}else{
thePlant.core.decreaseThroughput();
}
}
}
/**Shutsdownthereactorbyloweringthethroughputto0.*/
publicvoidshutdown(){
while(thePlant.core.getThroughput()>0){
thePlant.core.decreaseThroughput();
}
}
}
7Object-OrientedProgramming
7.1
Clickheretoviewcodeimage
//File:Exercise1.java
packagechap07pe1;
interfaceFunction{
intevaluate(intarg);
}
WOW! eBook
www.wowebook.org
classHalfimplementsFunction{
@Overridepublicintevaluate(intarg){
returnarg/2;
}
}
publicclassExercise1{
publicstaticint[]applyFunction(int…arrIn){
intlength=arrIn.length;
int[]arrOut=newint[length];
Functionfunc=newHalf();
for(inti=0;i<length;i++){
arrOut[i]=func.evaluate(arrIn[i]);
}
returnarrOut;
}
publicstaticvoidmain(String[]args){
//Halvethevalues.
int[]myArr=applyFunction(2,4,6,8);
System.out.println(“Arraywithvalueshalvedbyintegerdivision:”);
for(intvalue:myArr){
System.out.println(value);
}
}
}
7.2
Clickheretoviewcodeimage
//File:Exercise2.java
packagechap07pe2;
interfaceFunction{
intevaluate(intarg);
}
classHalfimplementsFunction{
@Overridepublicintevaluate(intarg){
returnarg/2;
}
}
classPrintimplementsFunction{
@Overridepublicintevaluate(intarg){
System.out.println(arg);
returnarg;
}
}
publicclassExercise2{
publicstaticint[]applyFunction(Functionfunc,int…arrIn){
intlength=arrIn.length;
int[]arrOut=newint[length];
for(inti=0;i<length;i++){
arrOut[i]=func.evaluate(arrIn[i]);
}
returnarrOut;
}
WOW! eBook
www.wowebook.org
publicstaticvoidmain(String[]args){
//Createaprintfunction.
Functionprint=newPrint();
System.out.println(“Originalvalues:”);
int[]myArr=applyFunction(print,2,4,6,8);
//Halvethearrayvalues.
myArr=applyFunction(newHalf(),myArr);
System.out.println(“Halvedvalues:”);
applyFunction(print,myArr);
}
}
8FundamentalClasses
8.1
Clickheretoviewcodeimage
/**
*Aggregate(non-generic)pairsofarbitraryobjects.
*/
publicfinalclassPair{
privatefinalObjectfirst,second;
/**ConstructaPairobject.*/
publicPair(Objectone,Objecttwo){
first=one;
second=two;
}
/**@returnthefirstconstituentobject.*/
publicObjectgetFirst(){returnfirst;}
/**@returnthesecondconstituentobject.*/
publicObjectgetSecond(){returnsecond;}
/**@returntrueifthepairofobjectsareidentical.*/
@Override
publicbooleanequals(Objectother){
if(this==other)returntrue;
if(!(otherinstanceofPair))returnfalse;
PairotherPair=(Pair)other;
returnfirst.equals(otherPair.first)&&
second.equals(otherPair.second);
}
/**@returnahashcodefortheaggregatepair.*/
@Override
publicinthashCode(){
//XORingthehashcodestocreateahashcodeforthepair.
returnfirst.hashCode()^second.hashCode();
}
/**@returnatextualrepresentationoftheaggregatedobject.*/
@Override
publicStringtoString(){
return“[”+first+“,”+second+“]”;
}
}
WOW! eBook
www.wowebook.org
8.2
Clickheretoviewcodeimage
/**Determinewhetherastringisacase-sensitivepalindrome.*/
publicclassPalindrome{
publicstaticvoidmain(String[]args){
if(args.length!=1){
System.out.println(“Usage:javaPalindrome<word>”);
return;
}
Stringword=args[0];
StringBuilderreverseWord=newStringBuilder(word).reverse();
booleanisPalindrome=word.equals(reverseWord.toString());
System.out.println(“Theword”+word+”is”+
(isPalindrome?””:“not“)+“apalindrome”);
}
}
9ObjectLifetime
Noprogrammingexercises.
10TheArrayList<E>ClassandLambdaExpressions
10.1
Clickheretoviewcodeimage
/*Findallelementsinalistthatsatisfyallpredicates.*/
importjava.util.ArrayList;
importjava.util.List;
importjava.util.function.Predicate;
publicclassFilterFunSolution{
publicstaticvoidmain(String[]args)
{//(1)
//Createalistofstrings:
String[]strings={“Cheerup!”,“7Upcomingup!”,null,
“Bottomsup!”,“Getdown!”,“What’sup?”};
List<String>strList=newArrayList<>();
/*WRITECODETOPOPULATETHELISTOFSTRINGSHERE.*/
for(Stringstr:strings)
strList.add(str);
System.out.println(strList);
//Createalistofpredicates.
List<Predicate<String>>predList=newArrayList<>();
/*WRITECODETOPOPULATETHELISTOFPREDICATESHERE.*/
predList.add(str->str!=null);
predList.add(str->str.toLowerCase().contains(“up”));
predList.add(str->Character.isLetter(str.charAt(0)));
System.out.println(predList);
//Applyfiltering.
applyAllPredicates(strList,predList);
applyAllPredicatesAlt(strList,predList);
applyAllPredicatesGenAlt(strList,predList);
}
/**
*Printsallthestringsinthespecifiedlistthatsatisfyallthe
WOW! eBook
www.wowebook.org
*predicatesinthelistofpredicates.
*ItusestheandPredicates()methodat(3).
*@paramlistListofstringstoapplythepredicateson
*@parampredicatesListofpredicatestoapply
*/
publicstaticvoidapplyAllPredicates(List<String>
list,//(2)
List<Predicate<String>>
predicates){
/*IMPLEMENTTHISMETHOD*/
List<String>resultList=newArrayList<>();
for(Stringstr:list){
if(andPredicates(str,predicates)){
resultList.add(str);
}
}
System.out.println(resultList);
}
/**
*Determineswhetherastringsatisfiesallthepredicates.
*@paramstrStringtoapplythepredicateson
*@parampredicatesListofpredicatestoapply
*@returntrueonlyifthestringsatisfiesallthe
predicates
*/
publicstaticbooleanandPredicates(String
str,//(3)
List<Predicate<String>>predicates)
{
/*IMPLEMENTTHISMETHOD*/
booleanproceed=true;
for(Predicate<String>p:predicates){
proceed=proceed&&p.test(str);
if(!proceed)break;
}
returnproceed;
}
/**
*Removesalltheelementsinthespecifiedlistthatdonotsatisfy
allthe
*predicatesinthelistofpredicates,andprintstheremaining
elements
*thatdo.
*UsesPredicate.and(),Predicate.negate(),andList.removeIf()
methods.
*@paramlistListofstringstoapplythepredicateson
*@parampredicatesListofpredicatestoapply
*/
publicstaticvoidapplyAllPredicatesAlt(List<String>
list,//(4)
List<Predicate<String>>
predicates){
/*IMPLEMENTTHISMETHOD*/
Predicate<String>compPred=s->true;
for(Predicate<String>p:predicates){
compPred=compPred.and(p);
}
list.removeIf(compPred.negate());
System.out.println(list);
}
WOW! eBook
www.wowebook.org
/**Genericversion.
*Removesalltheelementsinthespecifiedlistthatdonotsatisfy
allthe
*predicatesinthelistofpredicates,andprintstheremaining
elements
*thatdo.
*UsesPredicate.and(),Predicate.negate(),andList.removeIf()
methods.
*@paramlistListofelementstoapplythepredicateson
*@parampredicatesListofpredicatestoapply
*/
publicstatic<T>voidapplyAllPredicatesGenAlt(List<T>
list,//(5)
List<Predicate<T>>predicates){
/*IMPLEMENTTHISMETHOD*/
Predicate<T>compPred=s->true;
for(Predicate<T>p:predicates){
compPred=compPred.and(p);
}
list.removeIf(compPred.negate());
System.out.println(list);
}
}
11DateandTime
11.1
Clickheretoviewcodeimage
importjava.time.LocalDate;
importjava.time.LocalDateTime;
importjava.time.Period;
/**Classrepresentsstatisticsaboutanastronaut.*/
publicclassAstronaut{
privatefinalStringastronautName;
privatefinalLocalDateTimearrivalDateTime;
privatefinalLocalDatescheduledReturnDate;
privatefinalPeriodactualPeriodOfStay;
publicAstronaut(Stringname,LocalDateTimearrival,Periodperiod,
LocalDatereturnDate){
astronautName=name;
arrivalDateTime=arrival;
actualPeriodOfStay=period;
scheduledReturnDate=returnDate;
}
publicStringgetAstronautName(){returnastronautName;}
publicLocalDateTimegetArrivalDateTime(){returnarrivalDateTime;}
publicPeriodgetActualPeriodOfStay(){returnactualPeriodOfStay;
}
publicLocalDategetScheduledReturnDate(){returnscheduledReturnDate;
}
/**@returnLocalDateTheactualdateofreturn.*/
publicLocalDategetActualReturnDate(){
/*IMPLEMENTTHISMETHOD.*/
returnarrivalDateTime.toLocalDate().plus(actualPeriodOfStay);
}
WOW! eBook
www.wowebook.org
/**
*Returnsstatusoftheactualreturncomparedtothescheduled
return,
*whetheritwasontime,delayed,orearly.
*@returnStringIndicating“Ontime”,“Delayed”,or“Early”.
*/
publicStringgetReturnStatus(){
/*IMPLEMENTTHISMETHOD.*/
Stringstatus=“Ontime”;
LocalDateactualReturnDate=getActualReturnDate();
if(scheduledReturnDate.isBefore(actualReturnDate)){
status=“Delayed”;
}elseif(scheduledReturnDate.isAfter(actualReturnDate)){
status=“Early”;
}
returnstatus;
}
/**@returnPeriodTheplannedstayaccordingtothescheduled
return.*/
publicPeriodgetPlannedPeriodOfStay(){
/*IMPLEMENTTHISMETHOD.*/
returnPeriod.between(arrivalDateTime.toLocalDate(),
scheduledReturnDate);
}
/**
*@returnPeriodThedifferencebetweentheactualreturndateand
*thescheduledreturndate.*/
publicPeriodgetDiffPeriodOfStay(){
/*IMPLEMENTTHISMETHOD.*/
returnscheduledReturnDate.until(getActualReturnDate());
//Followingcodehaslogicalerror,asaperiodhasnonotionofa
date.
//returnactualPeriodOfStay.minus(getPlannedPeriodOfStay());
}
}
Clickheretoviewcodeimage
importjava.time.LocalDate;
importjava.time.LocalDateTime;
importjava.time.Period;
importjava.time.format.DateTimeFormatter;
publicclassSpaceStationStats{
publicstaticvoidmain(String[]args){
//Astronautdata
Astronaut[]astronauts={
newAstronaut(“AstroAli”,
LocalDateTime.of(2010,3,1,10,45),Period.ofMonths(3),
LocalDate.of(2010,5,1)),
newAstronaut(“LailaLightyear”,
LocalDateTime.of(2015,2,1,17,0),Period.ofWeeks(30),
LocalDate.of(2015,6,30)),
newAstronaut(“OrbitOrwell”,
LocalDateTime.of(2014,3,1,20,20),Period.ofMonths(6),
LocalDate.of(2014,9,1)),
newAstronaut(“RocketRogers”,
LocalDateTime.of(2013,7,31,15,30),Period.ofDays(60),
LocalDate.of(2013,9,30)),
newAstronaut(“SamSpacey”,
WOW! eBook
www.wowebook.org
LocalDateTime.of(2009,1,1,12,15),Period.ofDays(90),
LocalDate.of(2009,11,1)),
};
printReport(astronauts);
}
/**
*Methodprintsstatisticsaboutstayonaspacestation.
*Seetheexercisetextfortheformatofthereport.
*@paramastronautsThearraywithastronautdata
*/
privatestaticvoidprintReport(Astronaut[]astronauts){
System.out.println(“NameArr.DateSched.Return”
+”Act.ReturnStatusAct.StaySched.StayDiff”);
StringreportFormatStr=“%-16s%10s%12s%12s%8s%6s%10s%9s%n”;
/*IMPLEMENTTHERESTOFTHEMETHOD.*/
DateTimeFormatterdf=DateTimeFormatter.ofPattern(“uuuu/MM/dd”);
for(Astronautastro:astronauts){
StringastronautName=astro.getAstronautName();
LocalDatearrivalDate=astro.getArrivalDateTime().toLocalDate();
LocalDatescheduledReturnDate=astro.getScheduledReturnDate();
LocalDateactualReturnDate=astro.getActualReturnDate();
Stringstatus=astro.getReturnStatus();
PeriodperiodOfStay=astro.getActualPeriodOfStay();
PeriodplannedPeriodOfStay=astro.getPlannedPeriodOfStay();
PerioddiffPeriodOfStay=astro.getDiffPeriodOfStay();
System.out.printf(reportFormatStr,astronautName,
arrivalDate.format(df),
scheduledReturnDate.format(df),
actualReturnDate.format(df),status,
periodOfStay,plannedPeriodOfStay,
diffPeriodOfStay);
}
}
}
WOW! eBook
www.wowebook.org
AppendixE.MockExam:JavaSE8ProgrammerI
ThisisamockexamfortheJavaSE8ProgrammerIexam.Itcomprisesbrand-new
questions,whicharesimilartothequestionsthatcanbeexpectedontherealexam.
Workingthroughthisexamwillgiveyouagoodindicationofhowwellyouareprepared
fortherealexam,andwhetheranytopicsneedfurtherstudy.Annotatedanswerstothe
questionscanbefoundinAppendixF.
Questions
Q1Whichexpressionstatements,wheninsertedat(1),willcausethefollowingclassto
compilewithouterrors?
publicclassQ6db8{
privateinta;
privateintb=0;
privatestaticintc;
publicvoidm(){
intd;
inte=0;
//(1)INSERTCODEHERE.
}
}
Selectthefourcorrectanswers.
(a)a++;
(b)b++;
(c)c++;
(d)d++;
(e)e++;
Q2Whatwillbeprintedwhenthefollowingprogramisrun?
Clickheretoviewcodeimage
publicclassQd803{
publicstaticvoidmain(String[]args){
Stringword=“restructure”;
System.out.println(word.substring(2,3));
}
}
Selecttheonecorrectanswer.
(a)est
(b)es
(c)str
(d)st
WOW! eBook
www.wowebook.org
(e)s
Q3Whatwillbeprintedwhenthefollowingprogramisrun?
Clickheretoviewcodeimage
publicclassQ8929{
publicstaticvoidmain(String[]args){
for(inti=12;i>0;i-=3)
System.out.print(i);
System.out.println(””);
}
}
Selecttheonecorrectanswer.
(a)12
(b)129630
(c)12963
(d)36912
(e)Noneoftheabove.
Q4Whatwillbetheresultofcompilingandrunningthefollowingprogram?
Clickheretoviewcodeimage
publicclassQ275d{
privatestaticinta;
privateintb;
publicQ275d(){
intc;
c=a;//(1)
a++;//(2)
b+=c;//(3)
a-=b;//(4)
}
publicstaticvoidmain(String[]args){
newQ275d();
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompilebecauseofthelinemarked(1).
(b)Theprogramwillfailtocompilebecauseofthelinemarked(2).
(c)Theprogramwillfailtocompilebecauseofthelinemarked(3).
(d)Theprogramwillfailtocompilebecauseofthelinemarked(4).
(e)Theprogramwillcompileandrunwithoutanyproblems.
Q5Whatwillbeprintedwhenthefollowingprogramisrun?
Clickheretoviewcodeimage
classBase{
protectedinti;
WOW! eBook
www.wowebook.org
Base(){add(1);}
voidadd(intv){i+=v;}
voidprint(){System.out.println(i);}
}
classExtensionextendsBase{
Extension(){add(2);}
voidadd(intv){i+=v*2;}
}
publicclassQd073{
publicstaticvoidmain(String[]args){
bogo(newExtension());
}
staticvoidbogo(Baseb){
b.add(8);
b.print();
}
}
Selecttheonecorrectanswer.
(a)9
(b)11
(c)13
(d)21
(e)22
Q6Whichisthefirstlineinthefollowingcodeafterwhichtheobjectcreatedintheline
marked(0)willbeacandidateforgarbagecollection,assumingnocompiler
optimizationsaredone?
Clickheretoviewcodeimage
classWidget{
privateStringmessage;
Widget(Stringmessage){
this.message=message;
}
publicStringtoString(){
returnthis.message;
}
}
publicclassQ76a9{
staticWidgetfiddle(){
Widgeta=newWidget(“hello”);
Widgetb=newWidget(“bye”);//(0)
Widgetc=newWidget(b+“!”);//(1)
Widgetd=b;//(2)
b=a;//(3)
d=a;//(4)
returnc;//(5)
}
publicstaticvoidmain(String[]args){
Widgetgiz=fiddle();
WOW! eBook
www.wowebook.org
System.out.println(giz);//(6)
}
}
Selecttheonecorrectanswer.
(a)Thelinemarked(1)
(b)Thelinemarked(2)
(c)Thelinemarked(3)
(d)Thelinemarked(4)
(e)Thelinemarked(5)
(f)Thelinemarked(6)
Q7WhichmethodsfromtheStringortheStringBuilderclassmodifythe
objectonwhichtheyareinvoked?
Selectthetwocorrectanswers.
(a)ThecharAt()methodoftheStringclass
(b)ThetoUpperCase()methodoftheStringclass
(c)Thereplace()methodoftheStringclass
(d)Thereplace()methodoftheStringBuilderclass
(e)Thereverse()methodoftheStringBuilderclass
(f)ThecharAt()methodoftheStringBuilderclass
Q8Whichofthefollowingstatements,wheninsertedindependentlyat(1),willthrowa
runtimeexception?
Clickheretoviewcodeimage
classA{}
classBextendsA{}
classCextendsA{}
publicclassQ3ae4{
publicstaticvoidmain(String[]args){
Ax=newA();
By=newB();
Cz=newC();
//(1)INSERTCODEHERE.
}
}
Selecttheonecorrectanswer.
(a)x=y;
(b)z=x;
WOW! eBook
www.wowebook.org
(c)y=(B)x;
(d)z=(C)y;
(e)y=(A)y;
Q9Giventhefollowingprogram:
Clickheretoviewcodeimage
publicclassQ400A60{
publicstaticvoidmain(String[]args){
Stringstr=“loopornottoloop”;
String[]strs={“loop”,“or”,“not”,“to”,“loop”};
//(1)INSERTLOOPHERE.
}
}
Whichcode,wheninsertedindependentlyat(1),willcompilewithouterrors?
Selectthefourcorrectanswers.
(a)
for(charch:str)
System.out.print(ch);
(b)
Clickheretoviewcodeimage
for(charch:str.toCharArray())
System.out.print(ch);
(c)
Clickheretoviewcodeimage
for(Characterch:str.toCharArray())
System.out.print(ch);
(d)
Clickheretoviewcodeimage
for(Characterch:str.toCharArray())
System.out.print(ch.charValue());
(e)
for(Stringstr:strs)
System.out.print(str);
(f)
for(Stringelt:strs[])
System.out.print(elt);
(g)
for(Stringelt:strs)
System.out.print(elt);
(h)
Clickheretoviewcodeimage
for(Characterch:strs[strs.length-1].toArray())
System.out.print(ch);
WOW! eBook
www.wowebook.org
Q10Whichcodeinitializesthetwo-dimensionalarraymatrixsothatmatrix[3]
[2]isavalidelement?
Selectthetwocorrectanswers.
(a)
int[][]matrix={
{0,0,0},
{0,0,0}
};
(b)
Clickheretoviewcodeimage
intmatrix[][]=newint[4][];
for(inti=0;i<matrix.length;i++)matrix[i]=newint[3];
(c)
intmatrix[][]={
0,0,0,0,
0,0,0,0,
0,0,0,0,
0,0,0,0
};
(d)intmatrix[3][2];
(e)int[]matrix[]={{0,0,0},{0,0,0},{0,0,0},
{0,0,0}};
Q11Whatwillbetheresultofattemptingtorunthefollowingprogram?
Clickheretoviewcodeimage
publicclassQaa75{
publicstaticvoidmain(String[]args){
String[][][]arr={
{{},null},
{{“1”,“2”},{“1”,null,“3”}},
{},
{{“1”,null}}
};
System.out.println(arr.length+arr[1][2].length);
}
}
Selecttheonecorrectanswer.
(a)TheprogramwillthrowanArrayIndexOutOfBoundsExceptionand
terminate.
(b)TheprogramwillthrowaNullPointerExceptionandterminate.
(c)Theprogramwillprint4.
(d)Theprogramwillprint6.
(e)Theprogramwillprint7.
Q12Whichexpressionswillevaluatetotrueifprecededbythefollowingcode?
WOW! eBook
www.wowebook.org
Clickheretoviewcodeimage
Stringa=“hello”;
Stringb=newString(a);
Stringc=a;
char[]d={‘h’,‘e’,‘l’,‘l’,‘o’};
Selectthetwocorrectanswers.
(a)(a=="Hello")
(b)(a==b)
(c)(a==c)
(d)a.equals(b)
(e)a.equals(d)
Q13Whichstatementsaretrueaboutthevalueofafield,whennoexplicitinitialvalue
hasbeenassigned?
Selectthetwocorrectanswers.
(a)Thevalueofafieldoftypeintisundetermined.
(b)Thevalueofafieldofanynumerictypeis0.
(c)Thecompilermayissueanerrorifthefieldisusedinamethodbeforeitis
initialized.
(d)AfieldoftypeStringwilldenotetheemptystring("").
(e)Thevalueofallfieldsthatarereferencesisnull.
Q14Whichmain()methodwillsucceedinprintingthelastprogramargumentand
terminatenormallywithnooutput,ifnoprogramargumentsarespecified?
Selecttheonecorrectanswer.
(a)
Clickheretoviewcodeimage
publicstaticvoidmain(String[]args){
if(args.length!=0)
System.out.println(args[args.length-1]);
}
(b)
Clickheretoviewcodeimage
publicstaticvoidmain(String[]args){
try{System.out.println(args[args.length]);}
catch(ArrayIndexOutOfBoundsExceptione){}
}
(c)
Clickheretoviewcodeimage
publicstaticvoidmain(String[]args){
intix=args.length;
Stringlast=args[ix];
WOW! eBook
www.wowebook.org
if(ix!=0)System.out.println(last);
}
(d)
Clickheretoviewcodeimage
publicstaticvoidmain(String[]args){
intix=args.length-1;
if(ix>0)System.out.println(args[ix]);
}
(e)
Clickheretoviewcodeimage
publicstaticvoidmain(String[]args){
try{System.out.println(args[args.length-1]);}
catch(NullPointerExceptione){}
}
Q15Whatwillbeprintedwhenthefollowingprogramisexecuted?
Clickheretoviewcodeimage
publicclassQcb90{
privateinta;
privateintb;
publicvoidf(){
a=0;
b=0;
int[]c={0};
g(b,c);
System.out.println(a+””+b+””+c[0]+”“);
}
publicvoidg(intb,int[]c){
a=1;
b=1;
c[0]=1;
}
publicstaticvoidmain(String[]args){
Qcb90obj=newQcb90();
obj.f();
}
}
Selecttheonecorrectanswer.
(a)000
(b)001
(c)010
(d)100
(e)101
Q16Whatwillbetheresultofattemptingtocompileandrunthefollowingprogram?
Clickheretoviewcodeimage
publicclassQ28fd{
WOW! eBook
www.wowebook.org
publicstaticvoidmain(String[]args){
intcounter=0;
l1:
for(inti=0;i<10;i++){
l2:
intj=0;
while(j++<10){
if(j>i)breakl2;
if(j==i){
counter++;
continuel1;
}
}
}
System.out.println(counter);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompile.
(b)Theprogramwillnotterminatenormally.
(c)Theprogramwillprint10andterminatenormally.
(d)Theprogramwillprint0andterminatenormally.
(e)Theprogramwillprint9andterminatenormally.
Q17Giventhefollowinginterfacedeclaration,whichdeclarationisvalid?
interfaceI{
voidsetValue(intval);
intgetValue();
}
Selecttheonecorrectanswer.
(a)
Clickheretoviewcodeimage
classAextendsI{
intvalue;
voidsetValue(intval){value=val;}
intgetValue(){returnvalue;}
}
(b)
interfaceBextendsI{
voidincrement();
}
(c)
Clickheretoviewcodeimage
abstractclassCimplementsI{
intgetValue(){return0;}
abstractvoidincrement();
}
(d)
WOW! eBook
www.wowebook.org
interfaceDimplementsI{
voidincrement();
}
(e)
Clickheretoviewcodeimage
classEimplementsI{
intvalue;
publicvoidsetValue(intval){value=val;}
}
Q18Whatwillbetheresultofattemptingtocompileandrunthefollowingcode?
Clickheretoviewcodeimage
publicclassQ6b0c{
publicstaticvoidmain(String[]args){
inti=4;
floatf=4.3;
doubled=1.8;
intc=0;
if(i==f)c++;
if(((int)(f+d))==((int)f+(int)d))c+=2;
System.out.println(c);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompile.
(b)Theprogramwillprint0.
(c)Theprogramwillprint1.
(d)Theprogramwillprint2.
(e)Theprogramwillprint3.
Q19Whichoperatorswillalwaysevaluatealltheoperands?
Selectthetwocorrectanswers.
(a)||
(b)+
(c)&&
(d)?:
(e)%
Q20Whichstatementabouttheswitchconstructistrue?
Selecttheonecorrectanswer.
(a)Allswitchstatementsmusthaveadefaultlabel.
(b)Astatementwithinaswitchstatementcanhaveonlyonecaselabel.
(c)Thekeywordcontinuecanneveroccurwithinthebodyofaswitch
WOW! eBook
www.wowebook.org
statement.
(d)Nocaselabelmayfollowadefaultlabelinasingleswitchstatement.
(e)Acharacterliteralcanbeusedasavalueforacaselabel.
Q21Whatwillbeprintedwhenthefollowingprogramisrun?
Clickheretoviewcodeimage
publicclassQ03e4{
publicstaticvoidmain(String[]args){
Stringspace=”“;
Stringcomposite=space+“hello”+space+space;
composite.concat(“world”);
Stringtrimmed=composite.trim();
System.out.println(trimmed.length());
}
}
Selecttheonecorrectanswer.
(a)5
(b)6
(c)7
(d)12
(e)13
Q22Whichmethoddeclarations,wheninsertedat(1),willcorrectlyoverloadthe
methodsum()?
Clickheretoviewcodeimage
publicclassQdd1f{
publiclongsum(longa,longb){returna+b;}
//(1)INSERTCODEHERE.
}
Selectthetwocorrectanswers.
(a)publicintsum(inta,intb){returna+b;}
(b)publicintsum(longa,longb){return0;}
(c)abstractintsum();
(d)privatelongsum(longa,longb){returna+b;}
(e)publiclongsum(longa,intb){returna+b;}
Q23Whatwillthefollowingprogramprintwhencompiledandrun?
Clickheretoviewcodeimage
publicclassQ200A80{
WOW! eBook
www.wowebook.org
publicstaticvoidmain(String[]args){
callType(10);
}
privatestaticvoidcallType(Numbernum){
System.out.println(“Numberpassed”);
}
privatestaticvoidcallType(Objectobj){
System.out.println(“Objectpassed”);
}
}
Selecttheonecorrectanswer.
(a)Theprogramcompilesandprints:Objectpassed.
(b)Theprogramcompilesandprints:Numberpassed.
(c)Theprogramfailstocompile,becausethecalltothecallType()methodis
ambiguous.
(d)Noneoftheabove.
Q24Whichofthesemethoddeclarationsarevaliddeclarationsofthemain()method
thatwouldbecalledbytheJVMtostarttheexecutionofaJavaapplication?
Selectthethreecorrectanswers.
(a)staticvoidmain(String[]args){/*...*/}
(b)publicstaticintmain(String[]args){/*...*/}
(c)publicstaticvoidmain(Stringargs){/*...*/}
(d)finalpublicstaticvoidmain(String[]arguments){/*
...*/}
(e)publicintmain(Strings[]args,intargc){/*...*/
}
(f)staticpublicvoidmain(Stringargs[]){/*...*/}
(g)staticpublicvoidmain(String…args){/*...*/}
Q25Giventheclass
Clickheretoviewcodeimage
publicclassArgs{
publicstaticvoidmain(String[]args){
System.out.println(args[0]+””+args[args.length-1]);
}
}
whatwouldbetheresultofexecutingthefollowingcommandline?
Clickheretoviewcodeimage
>javaArgsInpoliticsstupidityisnotahandicap
Selecttheonecorrectanswer.
WOW! eBook
www.wowebook.org
(a)TheprogramwillthrowanArrayIndexOutOfBoundsException.
(b)Theprogramwillprintjavahandicap.
(c)TheprogramwillprintArgshandicap.
(d)TheprogramwillprintInhandicap.
(e)TheprogramwillprintArgsa.
(f)TheprogramwillprintIna.
Q26Whichstatementaboutthefollowingprogramistrue?
Clickheretoviewcodeimage
classMyClass{
publicstaticvoidmain(String[]args){
String[]numbers={“one”,“two”,“three”,“four”};
if(args.length==0){
System.out.println(“noarguments”);
}else{
System.out.println(numbers[args.length]+”arguments”);
}
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompile.
(b)TheprogramwillthrowaNullPointerExceptionwhenrunwithno
programarguments.
(c)Theprogramwillprintnoargumentsandtwoargumentswhencalled
withzeroandthreeprogramarguments,respectively.
(d)Theprogramwillprintnoargumentsandthreeargumentswhen
calledwithzeroandthreeprogramarguments,respectively.
(e)Theprogramwillprintnoargumentsandfourargumentswhencalled
withzeroandthreeprogramarguments,respectively.
(f)Theprogramwillprintoneargumentsandfourargumentswhencalled
withzeroandthreeprogramarguments,respectively.
Q27Whichstatementsaretrueabouttheimportstatement?
Selectthetwocorrectanswers.
(a)Staticimportfromaclassautomaticallyimportsthenamesofstaticmembersof
anynestedtypesdeclaredinthatclass.
(b)Staticmembersofthedefaultpackagecannotbeimported.
(c)Staticimportstatementsmustbespecifiedafteranytypeimportstatements.
(d)Inthecaseofanameconflict,thenameinthelaststaticimportstatementis
chosen.
WOW! eBook
www.wowebook.org
(e)Adeclarationofanameinacompilationunitcanshadowanamethatis
imported.
Q28Whatwouldbetheresultofcompilingandrunningthefollowingprogram?
Clickheretoviewcodeimage
classMyClass{
staticMyClassref;
String[]arguments;
publicstaticvoidmain(String[]args){
ref=newMyClass();
ref.func(args);
}
publicvoidfunc(String[]args){
ref.arguments=args;
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompile,sincethestaticmethodmain()cannothavea
calltothenon-staticmethodfunc().
(b)Theprogramwillfailtocompile,sincethenon-staticmethodfunc()cannot
accessthestaticvariableref.
(c)Theprogramwillfailtocompile,sincetheargumentargspassedtothestatic
methodmain()cannotbepassedtothenon-staticmethodfunc().
(d)Theprogramwillcompile,butwillthrowanexceptionwhenrun.
(e)Theprogramwillcompileandrunsuccessfully.
Q29Giventhefollowingmemberdeclarations,whichstatementistrue?
Clickheretoviewcodeimage
inta;//(1)
staticinta;//(2)
intf(){returna;}//(3)
staticintf(){returna;}//(4)
Selecttheonecorrectanswer.
(a)Declarations(1)and(3)cannotoccurinthesameclassdeclaration.
(b)Declarations(2)and(4)cannotoccurinthesameclassdeclaration.
(c)Declarations(1)and(4)cannotoccurinthesameclassdeclaration.
(d)Declarations(2)and(3)cannotoccurinthesameclassdeclaration.
Q30Whichofthesecombinationsofswitchexpressiontypesandcaselabelvalue
typesarelegalwithinaswitchstatement?
Selectthethreecorrectanswers.
(a)switchexpressionoftypeintandcaselabelvalueoftypechar
WOW! eBook
www.wowebook.org
(b)switchexpressionoftypefloatandcaselabelvalueoftypeint
(c)switchexpressionoftypebyteandcaselabelvalueoftypefloat
(d)switchexpressionoftypecharandcaselabelvalueoftypelong
(e)switchexpressionoftypebooleanandcaselabelvalueoftypeboolean
(f)switchexpressionoftypeByteandcaselabelvalueoftypebyte
(g)switchexpressionoftypebyteandcaselabelvalueoftypeByte
(h)switchexpressionoftypeStringandcaselabelvalueoftypeString
Q31Whatwillbetheresultofattemptingtocompileandrunthefollowingprogram?
Clickheretoviewcodeimage
publicclassSwitcheroo{
publicstaticvoidmain(String[]args){
finalintiLoc=3;
finalIntegeriFour=4;
IntegeriRef=4;
switch(iRef){
caseiFour:
System.out.println(“It’sOK.”);
case1:
caseiLoc:
case2*iLoc:
System.out.println(“IamnotOK.”);
default:
System.out.println(“YouareOK.”);
}
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompile.
(b)Theprogramwillcompile,butwillthrowaruntimeexception.
(c)Theprogramwillcompilecorrectlyandwillprintthefollowingatruntime:
It’sOK.
IamnotOK.
YouareOK.
(d)Theprogramwillcompilecorrectlyandwillprintthefollowingatruntime:
It’sOK.
IamnotOK.
(e)Theprogramwillcompilecorrectlyandwillprintthefollowingatruntime:
It’sOK.
Q32Whichofthefollowingimplementationsofamax()methodwillcorrectlyreturn
thelargestvalue?
Clickheretoviewcodeimage
//(1)
intmax(intx,inty){
return(if(x>y){x;}else{y;});
WOW! eBook
www.wowebook.org
}
//(2)
intmax(intx,inty){
return(if(x>y){returnx;}else{returny;});
}
//(3)
intmax(intx,inty){
switch(x<y){
casetrue:
returny;
default:
returnx;
};
}
//(4)
intmax(intx,inty){
if(x>y)returnx;
returny;
}
Selecttheonecorrectanswer.
(a)Implementationlabeled(1)
(b)Implementationlabeled(2)
(c)Implementationlabeled(3)
(d)Implementationlabeled(4)
Q33Giventhefollowingcode,whichstatementistrue?
Clickheretoviewcodeimage
classMyClass{
publicstaticvoidmain(String[]args){
intk=0;
intl=0;
for(inti=0;i<=3;i++){
k++;
if(i==2)break;
l++;
}
System.out.println(k+“,”+l);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompile.
(b)Theprogramwillprint3,3atruntime.
(c)Theprogramwillprint4,3atruntime,ifthebreakstatementisreplacedby
thecontinuestatement.
(d)Theprogramwillfailtocompileifthebreakstatementisreplacedbythe
returnstatement.
(e)Theprogramwillfailtocompileifthebreakstatementisreplacedbyanempty
WOW! eBook
www.wowebook.org
statement.
Q34Whichstatementsaretrue?
Selectthetwocorrectanswers.
(a){{}}isavalidblockstatement.
(b){continue;}isavalidblockstatement.
(c)block:{breakblock;}isavalidblockstatement.
(d)block:{continueblock;}isavalidblockstatement.
(e)Thebreakstatementcanbeusedonlyinaloop(while,do-whileorfor)
oraswitchstatement.
Q35Giventhedeclaration:
Clickheretoviewcodeimage
int[][]nums={{20},{30},{40}};
Whichcodewillcompileandprint90atruntime?
Selecttheonecorrectanswer.
(a)
{
intsum=0;
for(int[]row:nums[])
for(intval:nums[row])
sum+=val;
System.out.println(sum);
}
(b)
{
intsum=0;
for(int[]row:nums[][])
for(intval:nums[row])
sum+=val;
System.out.println(sum);
}
(c)
{
intsum=0;
for(int[]row:nums)
for(intval:nums[row])
sum+=val;
System.out.println(sum);
}
(d)
{
intsum=0;
for(int[]row:nums)
for(intval:row)
sum+=val;
WOW! eBook
www.wowebook.org
System.out.println(sum);
}
(e)
{
intsum=0;
for(Integer[]row:nums)
for(intval:row)
sum+=val;
System.out.println(sum);
}
Q36Whichdigits,andinwhatorder,willbeprintedwhenthefollowingprogramis
compiledandrun?
Clickheretoviewcodeimage
publicclassMyClass{
publicstaticvoidmain(String[]args){
try{
interruptForLunch();
}catch(InterruptedExceptione){
System.out.println(“1”);
thrownewRuntimeException();
}catch(RuntimeExceptione){
System.out.println(“2”);
return;
}catch(Exceptione){
System.out.println(“3”);
}finally{
System.out.println(“4”);
}
System.out.println(“5”);
}
//InterruptedExceptionisadirectsubclassofException.
staticvoidinterruptForLunch()throwsInterruptedException{
thrownewInterruptedException(“Timeforlunch.”);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillprint5.
(b)Theprogramwillprint1and4,inthatorder.
(c)Theprogramwillprint1,2,and4,inthatorder.
(d)Theprogramwillprint1,4,and5,inthatorder.
(e)Theprogramwillprint1,2,4,and5,inthatorder.
(f)Theprogramwillprint3and5,inthatorder.
Q37Howmanyobjectsarereachablewhencontrolreaches(1)?
Clickheretoviewcodeimage
publicclassNullify{
privatestaticvoidnullify(Object[]array){array=null;}
WOW! eBook
www.wowebook.org
publicstaticvoidmain(String[]args){
args=null;
Object[]array=newObject[4];
for(inti=0;i<4;i++){
array[i]=newObject();
}
nullify(array);
System.gc();//(1);
}
}
Selecttheonecorrectanswer.
(a)0
(b)1
(c)4
(d)5
(e)Itisdifficulttosay.
Q38Whichstatementdescribestheguaranteedbehaviorofthegarbagecollectionand
finalizationmechanisms?
Selecttheonecorrectanswer.
(a)Objectswillnotbedestroyeduntiltheyhavenoreferencestothem.
(b)Anobjecteligibleforgarbagecollectionwilleventuallybedestroyedbythe
garbagecollector.
(c)IfobjectAbecameeligibleforgarbagecollectionbeforeobjectB,thenobjectA
willbedestroyedbeforeobjectB.
(d)Anobject,onceeligibleforgarbagecollection,canneverbecomeaccessibleby
alivethread.
(e)Noneoftheabove.
Q39Whichoftheseexpressionsarelegal?
Selectthefourcorrectanswers.
(a)"co".concat("ol")
(b)("co"+"ol")
(c)('c'+'o'+'o'+'l')
(d)("co"+newString('o'+'l'))
(e)("co"+newString("co"))
Q40WhichstatementaboutthecharAt()methodoftheStringclassistrue?
Selecttheonecorrectanswer.
(a)ThecharAt()methodtakesacharvalueasanargument.
WOW! eBook
www.wowebook.org
(b)ThecharAt()methodreturnsaCharacterobject.
(c)Theexpression("abcdef").charAt(3)isillegal.
(d)Theexpression"abcdef".charAt(3)evaluatestothecharacter'd'.
(e)Theindexofthefirstcharacteris1.
Q41Whichexpressionwillevaluatetotrue?
Selecttheonecorrectanswer.
(a)"hello:there!".equals("hellothere")
(b)"HELLOTHERE".equals("hellothere")
(c)("hello".concat("there")).equals("hellothere")
(d)"HelloThere".compareTo("hellothere")==0
(e)"Hellothere".toLowerCase().equals("hellothere")
Q42Whatwillthefollowingprogramprintwhenrun?
Clickheretoviewcodeimage
publicclassSearch{
publicstaticvoidmain(String[]args){
Strings=“Contentment!”;
intmiddle=s.length()/2;
Stringnt=s.substring(middle-1,middle+1);
System.out.println(s.lastIndexOf(nt,middle));
}
}
Selecttheonecorrectanswer.
(a)2
(b)4
(c)5
(d)7
(e)9
(f)11
(g)Noneoftheabove.
Q43Whatwillbetheresultofattemptingtocompileandrunthefollowingprogram?
Clickheretoviewcodeimage
publicclassStringMethods{
publicstaticvoidmain(String[]args){
Stringstr=newString(“eeny”);
str.concat(”meeny”);
StringBuilderstrBuilder=newStringBuilder(”miny”);
strBuilder.append(”mo”);
System.out.println(str+strBuilder);
}
WOW! eBook
www.wowebook.org
}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompile.
(b)Theprogramwillprinteenymeenyminymoatruntime.
(c)Theprogramwillprintmeenyminymoatruntime.
(d)Theprogramwillprinteenyminymoatruntime.
(e)Theprogramwillprinteenymeenyminyatruntime.
Q44Whatwillbetheresultofattemptingtocompilethiscode,containedinasourcefile
namedAClass.java?
importjava.util.*;
packagecom.acme.toolkit;
publicclassAClass{
publicOtheranInstance;
}
classOther{
intvalue;
}
Selecttheonecorrectanswer.
(a)Thecodewillfailtocompile,sincetheclassOtherhasnotyetbeendeclared
whenreferencedintheclassAClass.
(b)Thecodewillfailtocompile,sinceanimportstatementcannotoccurasthe
firststatementinasourcefile.
(c)Thecodewillfailtocompile,sincethepackagedeclarationcannotoccurafter
animportstatement.
(d)Thecodewillfailtocompile,sincetheclassOthermustbedefinedinafile
calledOther.java.
(e)Thecodewillfailtocompile,sincetheclassOthermustbedeclaredas
public.
(f)Theclasswillcompilewithouterrors.
Q45Whichcodecanbeinsertedat(1)sothattheexceptionthrownbytheprogramis
caughtbythecatchclause?
Clickheretoviewcodeimage
publicclassQ1408a{
publicstaticvoidmain(String[]args){
try{
String[][]trio={null,{null},{“Tom”},{},{“Dick”,“Harry”}};
Stringsubstr=trio[3][0].substring(1,2);
}catch(/*(1)INSERTCODEHERE*/){
System.out.println(“Mindtheindex!”);
WOW! eBook
www.wowebook.org
}
}
}
Selectthetwocorrectanswers.
(a)ArrayIndexOutOfBoundsExceptione
(b)IndexOutOfBoundsExceptione
(c)StringIndexOutOfBoundsExceptione
(d)IllegalIndexFoundExceptione
(e)NullPointerExceptione
Q46Whatistheoutputfromrunningthefollowingprogram?
Clickheretoviewcodeimage
publicclassQ1408b{
publicstaticvoidmain(String[]args){
inti=0;
while(++i==i){
System.out.println(i++);
}
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillexecuteandterminatenormally,butwillnotprintanything.
(b)Theprogramwillexecuteindefinitely,printingallnumbersfrom1andupward.
(c)Theprogramwillexecuteindefinitely,printingallnumbersfrom2andupward.
(d)Theprogramwillexecuteindefinitely,printingallevennumbersfrom2and
upward.
(e)Theprogramwillexecuteindefinitely,printingalloddnumbersfrom1and
upward.
(f)Theprogramwillexecuteindefinitely,printingalloddnumbersfrom3and
upward.
Q47Whatistheoutputfromrunningthefollowingprogram?
Clickheretoviewcodeimage
publicclassRemainderFun{
publicstaticvoidmain(String[]args){
inti=24,k=7;
System.out.print(i%k+“|”);
System.out.print(i%-k+“|”);
System.out.print(-i%k+“|”);
System.out.println(-i%-k);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompile.
WOW! eBook
www.wowebook.org
(b)Theprogramwillcompile,butwillthrowaruntimeexception.
(c)3|-3|-3|3
(d)3|3|-3|-3
(e)3|-3|-3|-3
(f)3|-3|3|-3
Q48Whatistheoutputfromrunningthefollowingprogram?
Clickheretoviewcodeimage
publicclassThingy{
privateStringname;
publicThingy(Stringname){
this.name=name;
}
publicstaticvoidmain(String[]args){
Thingything1=newThingy(“thing1”);
Thingything2=newThingy(“thing2”);
System.out.print(thing1.equals(thing2)+“,”);
thing2.name=“thing1”;
System.out.print(thing1.equals(thing2)+“,”);
thing2=thing1;
System.out.println(thing1.equals(thing2));
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompile.
(b)Theprogramwillcompile,butwillthrowaruntimeexception.
(c)false,true,true
(d)false,false,false
(e)false,false,true
(f)false,true,false
Q49Whichstatementistrueaboutthefollowingprogram?
Clickheretoviewcodeimage
publicclassSwitchy{
publicstaticvoidmain(String[]args){
finalStrings1=“January”;
finalStringyr=”2014”;
s1.concat(yr);
switch(s1){
default:
System.out.println(“Sorry.”);
case“January”+yr:cases1+”2015”:
System.out.println(“OK.”);
}
}
}
WOW! eBook
www.wowebook.org
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile.
(b)Theprogramwillcompile.Whenrun,itwillprint:
Sorry.
OK.
(c)Theprogramwillcompile.Whenrun,itwillprint:
Sorry.
(d)Theprogramwillcompile.Whenrun,itwillprint:
OK.
Q50Whichstatementswillcompilewithouterrors?
Selectthethreecorrectanswers.
(a)IntegeriRef=0b111_000;
(b)byteb=0B1111_1111;
(c)doubled=0B1111_1111D;
(d)DoubledRef=3_____141.592_653_589_793e-3;
(e)intdate1=Integer.parseInt("_2014_01_11");
(f)intdate2=_2014_01_11;
(g)longdate3=2014_01_11_L;
Q51Whicharraydeclarationswillnotcompile?
Selectthethreecorrectanswers.
(a)int[]array1=newint[0];
(b)int[]array2={};
(c)int[]array3=newint[]{};
(d)int[]array4=newint[4]{};
(e)int[]array5=newint[4]{0,1,2,3};
(f)int[]array6=newint[]{0,1,2,3};
(g)int[]arr2d1[]=newint[4][];
(h)int[][]arr2d2=newint[4][];
(i)int[][]arr2d3=newint[][4];
(j)int[][]arr2d4=newint[4][0];
Q52Whichstatements,whenconsideredindividually,aretrueaboutthefollowingcode?
Clickheretoviewcodeimage
publicclassOverloading{
WOW! eBook
www.wowebook.org
privateStringxqt(inti){returnnull;}//(1)
publicvoidxqt(){}//(2)
publicIntegerxqt(intj){return1;}//(3)
}
Selectthetwocorrectanswers.
(a)Themethodsat(1)and(2)arecorrectlyoverloaded.
(b)Themethodsat(1)and(3)arecorrectlyoverloaded.
(c)Themethodsat(2)and(3)arecorrectlyoverloaded.
(d)Allmethodsarecorrectlyoverloaded.
Q53Whatistheoutputfromthefollowingprogram?
Clickheretoviewcodeimage
publicclassGizmo{
privateStringBuildername;
privatedoubleweight;
publicGizmo(){
name=newStringBuilder(“MyGizmo”);
weight=10.0;
}
publicStringtoString(){return“Name:”+name+“,Weight:”+
weight;}
privatestaticvoidchangeName(StringBuildersb){sb.append(“2014”);}
privatestaticvoidchangeWeight(doubleweight){weight=2*weight;
}
publicstaticvoidmain(String[]arguments){
Gizmogiz=newGizmo();
changeName(giz.name);
changeWeight(giz.weight);
System.out.println(giz);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompile.
(b)Theprogramwillcompile,butwillthrowaruntimeexception.
(c)Name:MyGizmo,Weight:10.0
(d)Name:MyGizmo2014,Weight:10.0
(e)Name:MyGizmo,Weight:20.0
(f)Name:MyGizmo2014,Weight:20.0
Q54Whichcodecanbeinsertedindependentlyat(1)sothattheprogramprintsthe
following:FreeMeal|FreeMeal|FreeMeal|.
Clickheretoviewcodeimage
publicclassLoopDeLoop{
publicstaticvoidmain(String[]args){
WOW! eBook
www.wowebook.org
StringBuildermeals[]={
newStringBuilder(),newStringBuilder(),newStringBuilder()
};
//(1)INSERTCODEHERE
for(StringBuildermeal:meals)System.out.print(meal+“|”);
}
}
Selectthefourcorrectanswers.
(a)for(StringBuildermeal:meals)meal.insert(0,"Free
Meal");
(b)for(StringBuildermeal:meals)meal=meal.insert(0,
"FreeMeal");
(c)
Clickheretoviewcodeimage
StringBuilderfreeMeal=newStringBuilder(“FreeMeal”);
for(StringBuildermeal:meals)meal=freeMeal;
(d)for(StringBuildermeal:meals)meal=new
StringBuilder("FreeMeal");
(e)for(StringBuildermeal:meals)meal.append("Free
Meal");
(f)for(StringBuildermeal:meals)meal=
meal.append("FreeMeal");
Q55Whatistheoutputfromthefollowingprogram?
Clickheretoviewcodeimage
importjava.util.ArrayList;
publicclassWeekend{
publicstaticvoidmain(String[]args){
ArrayList<String>longWeekend=newArrayList<>();
longWeekend.add(“Friday”);
longWeekend.add(2,“Saturday”);
longWeekend.add(“Sunday”);
longWeekend.remove(0);
System.out.println(longWeekend);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile.
(b)Theprogramwillcompile.Whenrun,itwillprint[Saturday,Sunday].
(c)Theprogramwillcompile.Whenrun,itwillprint[Sunday,Saturday].
(d)Theprogramwillcompile.Whenrun,itwillthrowa
java.lang.IndexOutOfBoundsException.
Q56Whatistheoutputfromthefollowingprogram?
Clickheretoviewcodeimage
WOW! eBook
www.wowebook.org
classRoom{
staticintnumOfGuests;
}
publicclassHotel{
publicstaticvoidmain(String[]args){
Roomr1=newRoom();
Roomr2=newRoom();
r1.numOfGuests=2;
r2.numOfGuests=3;
System.out.println(“Numberofguests:”+r1.numOfGuests+
r2.numOfGuests);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillfailtocompile.
(b)Theprogramwillcompile,butwillthrowaruntimeexception.
(c)Numberofguests:4
(d)Numberofguests:5
(e)Numberofguests:6
(f)Numberofguests:22
(g)Numberofguests:33
Q57Inwhichscenarioswouldado-whileloopbepreferabletoawhileloop?
Selectthethreecorrectanswers.
(a)Admitoneticket-holderatatimeintoamovietheateruntiltherearenomore
ticket-holderstoadmit.
(b)Guessanansweruntiltheansweriscorrect.
(c)Addalittlesalttothefooduntilthefoodtastesright.Assumethefoodhastoo
littlesalttostartwith.
(d)Addcandlestoabirthdaycakeuntiltherearetherightnumberofcandles.
(e)Letthemiceplayalittlewhilethecatisaway.
Q58Whatistheoutputfromthefollowingprogram?
Clickheretoviewcodeimage
publicclassCodeMe{
publicstaticvoidmain(String[]args){
booleanflag=false;
if(false)//(1)
flag=!flag;
System.out.println(flag);
}
}
Selectthetwocorrectanswers.
(a)Theprogram,asitstands,doesnotcompile.
WOW! eBook
www.wowebook.org
(b)Theprogramcompileswithouterrors.Whenrun,itwillprintfalse.
(c)Theprogramcompileswithouterrors.Whenrun,itwillprinttrue.
(d)Ifthekeywordifat(1)isreplacedwiththekeywordwhile,theprogram
compileswithouterrors.Whenrun,itwillprintfalse.
(e)Ifthekeywordifat(1)isreplacedwiththekeywordwhile,theprogram
compileswithouterrors.Whenrun,itwillprinttrue.
(f)Ifthekeywordifat(1)isreplacedwiththekeywordwhile,theprogramwill
notcompile.
Q59Whatcodecanbeinsertedindependentlyat(1)sothattheprogramprintsthevalue
2014?
Clickheretoviewcodeimage
publicclassCastMe{
publicstaticvoidmain(String[]args){
Numbernum=2014;
//(1)INSERTCODEHERE.
System.out.println(iRef);
}
}
Selecttheonecorrectanswer.
(a)IntegeriRef=((Integer)num).intValue();
(b)IntegeriRef=(Integer)num.intValue();
(c)IntegeriRef=(Integer)(num.intValue());
(d)IntegeriRef=num.intValue();
(e)Anyoneoftheabovestatementscanbeinsertedat(1)
(f)Noneoftheabove.
Q60Whatistheoutputfromthefollowingprogram?
Clickheretoviewcodeimage
classPerson{
publicvoidcompare(Personp){
System.out.print(“Personsareequal.”);
}
}
classStudentextendsPerson{
publicvoidcompare(Students){
System.out.print(“Studentsareequal.”);
}
}
publicclassCalling{
publicstaticvoidmain(String[]args){
Personp1=newPerson();
Students1=newStudent();
Students2=newStudent();
Personp2=s2;
WOW! eBook
www.wowebook.org
p1.compare(s1);p1.compare(p2);System.out.println();
p2.compare(s1);p2.compare(p1);System.out.println();
s1.compare(p1);s1.compare(p2);s1.compare(s2);System.out.println();
}
}
Selecttheonecorrectanswer.
(a)
Clickheretoviewcodeimage
Personsareequal.Personsareequal.
Studentsareequal.Personsareequal.
Personsareequal.Personsareequal.Studentsareequal.
(b)
Clickheretoviewcodeimage
Personsareequal.Personsareequal.
Personsareequal.Personsareequal.
Personsareequal.Personsareequal.Studentsareequal.
(c)
Clickheretoviewcodeimage
Personsareequal.Personsareequal.
Studentsareequal.Personsareequal.
Personsareequal.Studentsareequal.Studentsareequal.
(d)
Clickheretoviewcodeimage
Personsareequal.Personsareequal.
Personsareequal.Personsareequal.
Personsareequal.Studentsareequal.Studentsareequal.
Q61Whatwillthefollowingprogramprintwhencompiledandrun?
Clickheretoviewcodeimage
importjava.util.ArrayList;
importjava.util.List;
publicclassMEQ12A56{
publicstaticvoidmain(String[]args){
List<String>strList=newArrayList<>();
strList.add(0,“Ada”);
strList.add(“Alyla”);
strList.set(strList.size()-1,“Otto”);
strList.add(strList.size()-1,“Anna”);
System.out.println(strList);//(1)
intsize=strList.size();
for(inti=0;i<size;++i){
strList.add(strList.get(size-1-i));
}
System.out.println(strList);//(2)
}
}
Selectthetwocorrectanswers.
(a)(1)willprint[Ada,Alyla,Anna].
WOW! eBook
www.wowebook.org
(b)(1)willprint[Ada,Anna,Otto].
(c)(1)willprint[Ada,Otto,Alyla].
(d)(2)willprint[Ada,Alyla,Anna,Anna,Alyla,Ada].
(e)(2)willprint[Ada,Anna,Otto,Otto,Anna,Ada].
(f)(2)willprint[Ada,Otto,Alyla,Alyla,Otto,Ada].
Q62Whatwillthefollowingprogramprintwhencompiledandrun?
Clickheretoviewcodeimage
importjava.util.ArrayList;
importjava.util.List;
publicclassMEQ12A70{
publicstaticvoidmain(String[]args){
List<String>list1=newArrayList<>(20);
list1.add(“Ada”);
List<String>list2=newArrayList<>(list1);
list2.add(null);
System.out.print(list1.size()==list2.size());
System.out.print(“-”+(list1==list2));
System.out.println(“-”+list1.equals(list2));
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile.
(b)Theprogramwillthrowanexception.
(c)Theprogramwillprintfalse-true-true.
(d)Theprogramwillprinttrue-false-true.
(e)Theprogramwillprintfalse-false-false.
Q63Whichlineswillbeintheoutputwhenthefollowingprogramiscompiledandrun?
Clickheretoviewcodeimage
importjava.util.ArrayList;
importjava.util.List;
publicclassMEQ12A99{
publicstaticvoidmain(String[]args){
List<Integer>numList=newArrayList<>();
numList.add(3);numList.add(1);numList.add(1,4);
numList.add(null);numList.add(0);
System.out.println(“(1)prints”+numList.get(3));
System.out.println(“(2)prints”+numList.set(1,3));
System.out.println(“(3)prints”+numList.lastIndexOf(3));
System.out.println(“(4)prints”+numList.contains(3));
System.out.println(“(5)prints”+numList.remove(3));
System.out.println(“(6)prints”+numList.indexOf(3));
System.out.println(“(7)prints”+numList.remove(newInteger(4)));
}
}
Selectthesixcorrectanswers.
WOW! eBook
www.wowebook.org
(a)(1)printsnull
(b)(2)prints3
(c)(2)prints4
(d)(3)prints2
(e)(3)prints1
(f)(4)printstrue
(g)(5)printsnull
(h)(5)prints1
(i)(6)prints1
(j)(7)printstrue
(k)(7)printsfalse
Q64Whichlineswillresultinacompile-timeerror?
Clickheretoviewcodeimage
importjava.util.ArrayList;
importjava.util.List;
publicclassMEQ12A80{
publicstaticvoidmain(String[]args){
List<String>strList=newArrayList<>(0);//
(1)
List<Object>objList=strList;//
(2)
List<Number>numList=newArrayList<>();//
(3)
numList.add(1);//
(4)
numList.add(1.5);//
(5)
List<>intList=newArrayList<Integer>();//
(6)
ArrayList<ArrayList<Integer>>loList1=newArrayList<Integer>();//
(7)
ArrayList<ArrayList<Integer>>loList2=newArrayList();//
(8)
}
}
Selectthethreecorrectanswers.
(a)Compile-timeerrorin(1)
(b)Compile-timeerrorin(2)
(c)Compile-timeerrorin(3)
(d)Compile-timeerrorin(4)
(e)Compile-timeerrorin(5)
(f)Compile-timeerrorin(6)
WOW! eBook
www.wowebook.org
(g)Compile-timeerrorin(7)
(h)Compile-timeerrorin(8)
Q65Whatwillthefollowingprogramprintwhencompiledandrun?
Clickheretoviewcodeimage
importjava.util.ArrayList;
importjava.util.List;
publicclassMEQ12A85{
publicstaticvoidmain(String[]args){
List<String>list=newArrayList<>(20);
list.add(“Taco”);
for(inti=0;i<3;++i){
list.add(””+list);
}
System.out.println(list);//(1)
System.out.println(list.size());//(2)
}
}
Selectthetwocorrectanswers.
(a)(1)willprint:
[Taco,Taco,Taco,Taco,Taco,Taco,Taco,Taco]
(b)(1)willprint:
[Taco,[Taco,Taco],[Taco,Taco,Taco],[Taco,Taco,Taco,Taco]]
(c)(1)willprint:
[Taco,[Taco],Taco,[Taco],Taco,[Taco],Taco,[Taco]]
(d)(1)willprint:
[Taco,[Taco],[Taco,[Taco]],[Taco,[Taco],[Taco,[Taco]]]]
(e)(2)willprint4.
(f)(2)willprint8.
Q66Whatwillthefollowingprogramprintwhencompiledandrun?
Clickheretoviewcodeimage
importjava.util.ArrayList;
importjava.util.List;
publicclassMEQ12A55{
publicstaticvoidmain(String[]args){
List<String>strList=newArrayList<>();
strList.add(strList.size(),“Anna”);
strList.add(strList.size()-1,“Ada”);
strList.add(strList.size()-1,“Otto”);
strList.add(0,“Alyla”);
System.out.println(strList);
intsize=strList.size();
for(inti=0;i<size/2;++i){
StringstrTemp=strList.get(i);
strList.set(i,strList.get(size-1-i));
strList.set(size-1-i,strTemp);
}
WOW! eBook
www.wowebook.org
System.out.println(strList);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile.
(b)TheprogramwillthrowanIndexOutOfBoundsException.
(c)TheprogramwillthrowaNullPointerException.
(d)Theprogramwillprint:
[Alyla,Ada,Otto,Anna]
[Anna,Otto,Ada,Alyla]
(e)Theprogramwillprint:
[Ada,Otto,Alyla,Anna]
[Anna,Alyla,Otto,Ada]
Q67Whichstatementsaretrueaboutlambdaexpressions?
Selectthetwocorrectanswers.
(a)Areturnstatementismandatoryinalambdaexpressionifthelambdabodyis
astatementblock.
(b)Areturnstatementismandatoryinalambdaexpressionifthelambdabodyis
asingleexpressionthatreturnsavalue.
(c)Theformalparametersofalambdaexpressionarelocalvariablesintheblock
scopeofthelambdaexpression.
(d)Alocalvariabledeclarationintheblockscopeofalambdaexpressioncan
shadowaclassmemberwiththesamenameintheenclosingclass.
(e)Alocalvariabledeclarationintheblockscopeofalambdaexpressioncan
shadowalocalvariablewiththesamenameintheenclosingmethod.
Q68Whichstatementsaretrueaboutthefollowingcode?
Clickheretoviewcodeimage
importjava.util.function.Predicate;
publicclassMEQ12A92{
publicstaticvoidmain(String[]args){
Predicate<String>p1=Stringobj->obj.equals(“Java”);//
(1)
Predicate<String>p2=(finalStringobj)->obj.equals(“Java”);//
(2)
Predicate<String>p3=(finalobj)->obj.equals(“Java”);//
(3)
Predicate<String>p4=(Stringobj)->obj.equals(“Java”);//
(4)
Predicate<String>p5=(obj)->obj.equals(“Java”);//
(5)
Predicate<String>p6=obj->obj.equals(“Java”);//
(6)
Predicate<String>p7=obj->returnobj.equals(“Java”);//
(7)
WOW! eBook
www.wowebook.org
Predicate<String>p8=obj->{obj.equals(“Java”)};//
(8)
Predicate<String>p9=obj->{obj.equals(“Java”);};//
(9)
Predicate<String>p10=obj->{returnobj.equals(“Java”);};//
(10)
Predicate<Object>p11=obj->obj.equals(“Java”);//
(11)
}
}
Selectthefivecorrectanswers.
(a)(1)willnotcompile.
(b)(2)willnotcompile.
(c)(3)willnotcompile.
(d)(4)willnotcompile.
(e)(5)willnotcompile.
(f)(6)willnotcompile.
(g)(7)willnotcompile.
(h)(8)willnotcompile.
(i)(9)willnotcompile.
(j)(10)willnotcompile.
(k)(11)willnotcompile.
Q69Whichstatementsaretrueaboutthefollowingcode?
Clickheretoviewcodeimage
importjava.util.function.Predicate;
publicclassMEQ12A95{
publicstaticvoidmain(String[]args){
finalStringlock3=“Trio”;
Stringlock4=“Chubb”;
Predicate<Object>p;
p=lock->{lock=lock.toString();returnlock.equals(“TRIO”);
};//(1)
p=lock->{if(args.length>0)returnlock.equals(args[0]);
};//(2)
p=lock->{Stringlock3=“CHUBB”;returnlock.equals(lock3);
};//(3)
p=lock->{returnlock.equals(lock3);
};//(4)
p=lock->{returnlock.equals(lock4);
};//(5)
p=lock4->{returnlock4.equals(“Chubb”);
};//(6)
}
}
Selectthethreecorrectanswers.
WOW! eBook
www.wowebook.org
(a)(1)willcompile.
(b)(2)willcompile.
(c)(3)willcompile.
(d)(4)willcompile.
(e)(5)willcompile.
(f)(6)willcompile.
Q70Giventhefollowingprogram:
Clickheretoviewcodeimage
importjava.util.function.Predicate;
publicclassMEQ12A97{
publicstaticvoidmain(String[]args){
int[]intArray={-12,12,-123,123,-1234,1234};
filterInt(intArray,/*(1)INSERTCODEHERE*/);
}
privatestaticvoidfilterInt(int[]intArr,Predicate<Integer>
predicate){
for(inti=0;i<intArr.length;++i){
intintValue=intArr[i];
if(predicate.test(intValue)){
System.out.print(intValue+”“);
}
}
System.out.println();
}
}
Whichlambdaexpressionscanbeinsertedat(1)sothattheprogramprintsallodd
numbersthathavethreedigits(i.e.,-123and123)?
Selectthefourcorrectanswers.
(a)val->val%2!=0&&
String.valueOf(Math.abs(val)).length()==3
(b)val->returnval%2!=0&&
String.valueOf(Math.abs(val)).length()==3
(c)val->val%2!=0&&(""+Math.abs(val)).length()
==3
(d)val->{val%2!=0&&(""+Math.abs(val)).length()
==3;}
(e)val->val%2!=0&&new
String(Math.abs(val)).length()==3
(f)val->{returnval%2!=0&&new
String(Math.abs(val)).length()==3;}
(g)val->val%2!=0&&
WOW! eBook
www.wowebook.org
Integer.toString(Math.abs(val)).length()==3
(h)val->val%2!=0&&new
Integer(Math.abs(val)).toString().length()==3
Q71Whichstatementistrueaboutthefollowinginterfaces?
Clickheretoviewcodeimage
interfaceIA{booleanequals(Objectobj);}
interfaceIBextendsIA{booleandoIt(Stringstr);}
interfaceICextendsIB{booleandoIt(Stringstr);}
interfaceIDextendsIC{booleanequals(Objectobj);}
Selecttheonecorrectanswer.
(a)IAisafunctionalinterface.
(b)IBisafunctionalinterface.
(c)ICisnotafunctionalinterface.
(d)IDisnotafunctionalinterface.
(e)Noneoftheabove.
Q72WhichstatementistrueabouttheDateandTimeAPI?
Selecttheonecorrectanswer.
(a)TheisBefore()andisAfter()methodsoftheLocalTime,
LocalDate,andLocalDateTimeclassesalwaysreturntruewhenthis
objectisthesameastheobjectpassedasanargument.
(b)ThewithmethodsoftheLocalDateandLocalDateTimeclasseswill
adjustthedayofthemonthtothelastvaliddayofthemonth,ifthedayofmonth
becomesinvalidwhentheirdate-basedvaluesarechanged.
(c)ThetoTotalDays()methodofthePeriodclassreturnsthelengthofthe
periodasthetotalnumberofdays.
(d)TheclassesLocalTime,LocalDate,LocalDateTime,andPeriod
implementtheComparableinterface,providinganimplementationofthe
compareTo()methodsothattwotemporalobjectsofthesametypecanbe
compared.
(e)Noneoftheabove.
Q73Whatwillthefollowingprogramprintwhencompiledandrun?
Clickheretoviewcodeimage
importjava.time.LocalTime;
publicclassMEQ11A25{
publicstaticvoidmain(String[]args){
LocalTimetime=LocalTime.NOON;
time=time.withHour(10).plusMinutes(120);
System.out.println(time);
}
WOW! eBook
www.wowebook.org
}
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile.
(b)Theprogramwillthrowaruntimeexception.
(c)Theprogramwillprint00:00.
(d)Theprogramwillprint12:00.
(e)Theprogramwillprint24:00.
(f)Noneoftheabove.
Q74Whatwillthefollowingprogramprintwhencompiledandrun?
Clickheretoviewcodeimage
importjava.time.LocalDate;
publicclassMEQ11A35{
publicstaticvoidmain(String[]args){
LocalDatedate=LocalDate.of(2015,1,1);
date.withYear(5);
System.out.println(date.plusMonths(12));
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile.
(b)Theprogramwillthrowaruntimeexception.
(c)Theprogramwillprint0006-01-01.
(d)Theprogramwillprint2021-01-01.
(e)Theprogramwillprint2015-01-01.
(f)Theprogramwillprint2016-01-01.
(g)Noneoftheabove.
Q75Whatwillthefollowingprogramprintwhencompiledandrun?
Clickheretoviewcodeimage
importjava.time.Period;
publicclassMEQ11A40{
publicstaticvoidmain(String[]args){
Periodperiod=Period.ofYears(10).ofMonths(16);
System.out.println(period);
}
}
Selecttheonecorrectanswer.
(a)Theprogramwillnotcompile.
(b)Theprogramwillthrowaruntimeexception.
WOW! eBook
www.wowebook.org
(c)TheprogramwillprintP16M.
(d)TheprogramwillprintP1Y4M.
(e)TheprogramwillprintP11Y4M.
(f)TheprogramwillprintP10Y16M.
(g)Noneoftheabove.
Q76Whichcode,wheninsertedat(1),willmaketheprogramcompileandexecute
normally?
Clickheretoviewcodeimage
importjava.time.LocalDate;
importjava.time.LocalDateTime;
importjava.time.LocalTime;
importjava.time.format.DateTimeFormatter;
publicclassMEQ11A90{
publicstaticvoidmain(String[]args){
//(1)INSERTCODEHERE.
StringtimeStr=LocalTime.of(12,5).format(dtf);
StringdateStr=LocalDate.of(2016,4,1).format(dtf);
StringdateTimeStr=LocalDateTime.of(2016,4,1,12,5).format(dtf);
}
}
Selecttheonecorrectanswer.
(a)DateTimeFormatterdtf=
DateTimeFormatter.ISO_LOCAL_TIME;
(b)DateTimeFormatterdtf=
DateTimeFormatter.ISO_LOCAL_DATE;
(c)DateTimeFormatterdtf=
DateTimeFormatter.ISO_LOCAL_DATE_TIME;
(d)Noneoftheabove.
Q77Whichcode,wheninsertedat(1),willmaketheprogramcompileandexecute
normally?
Clickheretoviewcodeimage
importjava.time.LocalDate;
importjava.time.LocalDateTime;
importjava.time.LocalTime;
importjava.time.format.DateTimeFormatter;
publicclassMEQ11A95{
publicstaticvoidmain(String[]args){
StringinputStr=“Thetimeis15minutespast10PM.”;
Stringpattern=“‘Thetimeis‘m’minutespast‘ha.”;
DateTimeFormatterdtf=DateTimeFormatter.ofPattern(pattern);
//(1)INSERTCODEHERE.
}
}
WOW! eBook
www.wowebook.org
Selectthethreecorrectanswers.
(a)LocalTimetime=LocalTime.parse(inputStr,dtf);
(b)LocalDatedate=LocalDate.parse(inputStr,dtf);
(c)LocalDateTimedateTime=LocalDateTime.parse(inputStr,
dtf);
(d)StringtimeStr=LocalTime.of(9,20).format(dtf);
(e)StringdateStr=LocalDate.of(2015,12,
24).format(dtf);
(f)StringdateTimeStr=LocalDateTime.of(2015,12,24,
22,15).format(dtf);
WOW! eBook
www.wowebook.org
AppendixF.AnnotatedAnswerstoMockExamI
ThisappendixprovidesannotatedanswerstothequestionsinthemockexamfortheJava
SE8ProgrammerIcertificationfoundinAppendixE.
AnnotatedAnswers
Q1(a),(b),(c),and(e)
Onlylocalvariablesneedtobeexplicitlyinitializedbeforeuse.Fieldsareassigneda
defaultvalueifnotexplicitlyinitialized.
Q2(e)
Givingparameters(2,3)tothemethodsubstring()constructsastring
consistingofthecharactersfromindex2(inclusive)toindex3(exclusive)ofthe
originalstring;thatis,thestringreturnedcontainsthecharacteratindex2.Thefirst
characterisatindex0andthelastcharacterisatindex1lessthanthenumberof
charactersinthestring.
Q3(c)
Theloopprintsoutthevalues12,9,6,and3beforeterminating.Theloop
terminateswhenthevalueintheloopvariableibecomeslessthanorequalto0.
Thishappensafterthevalue3hasbeenprinted.
Q4(e)
Thefactthatafieldisstaticdoesnotmeanthatitisnotaccessiblefromnon-static
methodsandconstructors.Allfieldsareassignedadefaultvalueifnoinitializeris
specified.Staticfieldsareinitializedwhentheclassisloaded,andinstancefieldsare
initializedwhentheclassisinstantiated.Onlylocalvariablesmustbeexplicitly
initializedbeforeuse.
Q5(e)
AnobjectoftheclassExtensioniscreated.Thefirstthingtheconstructorof
ExtensiondoesisinvoketheconstructorofBase,usinganimplicitsuper()
call.Allcallstothemethodvoidadd(int)aredynamicallyboundtothe
add()methodintheExtensionclass,sincetheactualobjectisoftype
Extension.Therefore,thismethodiscalledbytheconstructorofBase,the
constructorofExtension,andthebogo()methodwiththeparameters1,2,and
8,respectively.Theinstancefieldichangesvalueaccordingly:2,6,and22.The
finalvalueof22isprinted.
Q6(d)
At(1),anewWidgetobjectisconstructedwiththemessagethatisaconcatenation
ofthemessage"bye"intheWidgetobjectdenotedbybandthestring"!".
Afterline(2),dandbarealiases.Afterline(3),bandaarealiases,butdstill
denotestheWidgetobjectwiththemessage"bye"fromline(0).Afterline(4),d
WOW! eBook
www.wowebook.org
andaarealiases.ReferencednolongerdenotestheWidgetobjectcreatedinline
(0).ThisWidgetobjecthasnoreferencesthatrefertoitand,therefore,isa
candidateforgarbagecollection.
Q7(d)and(e)
Stringobjectsareimmutable.NoneofthemethodsoftheStringclassmodifies
aStringobject.MethodstoUpperCase()andreplace()intheString
classwillreturnanewStringobjectthatcontainsthemodifiedstring.However,
StringBuilderobjectsaremutable.ThecharAt()methodofthe
StringBuilderclassisagetmethod,returningthecharacterataspecificindex,
withoutmodifyingthecontentsoftheStringBuilderobject.
Q8(c)
Statement(a)willexecutewithoutproblem,but(b),(d),and(e)willcausecompile-
timeerrors.Statements(b)and(e)willcausecompile-timeerrorsbecauseitisnot
possibletoconvertfromthesuperclassAtothesubclassesCandB,respectively.
Statement(d)willcausecompile-timeerrorsbecauseacastfromBtoCisinvalid.
BeinganinstanceofBexcludesthepossibilityofbeinganinstanceofC.Statement
(c)willcompile,butwillthrowaruntimeexceptionbecausetheobjectthatiscastto
BisnotaninstanceofB.
Q9(b),(c),(d),and(g)
In(a),aStringisneitheranarraynoranIterable.Themethod
toCharArray()oftheStringclassreturnsanarrayoftypechar.Achar
valueisassignabletothelocalvariableoftypecharin(b),andafterautoboxing,
assignabletothelocalvariableoftypeCharacterin(c)and(d).In(e),thelocal
variablestrisredeclared.In(f),theoccurrenceofthearrayoperator[]isnot
permitted.In(g),thearraystrsispermissibleinthefor(:)loop.In(h),the
StringclassdoesnothaveamethodnamedtoArray,butithasamethodnamed
toCharArray.
Q10(b)and(e)
Fortheexpressionmatrix[3][2]toaccessavalidelementofatwo-dimensional
array,thearraymusthaveatleastfourrowsandthefourthrowmusthaveatleast
threeelements.(a)producesa2×3array.(c)triestoinitializeatwo-dimensional
arrayasaone-dimensionalarray.(d)triestospecifyarraydimensionsinthetypeof
thearrayreferencedeclaration.
Q11(a)
Theexpressionarr.lengthwillevaluateto4.Theexpressionarr[1]will
accessthearray{{"1","2"},{"1",null,"3"}},andarr[1]
[2]willtrytoaccessthethirdelementofthisarray.Thisresultsinan
ArrayIndexOutOfBoundsException,sincethisarrayhasonlytwoelements.
Q12(c)and(d)
WOW! eBook
www.wowebook.org
Stringobjectscanhaveidenticalsequencesofcharacters.The==operator,when
usedonStringobjectreferences,willreturntrueifandonlyifbothreferences
denotethesameobject(i.e.,arealiases).Theequals()methodwillreturntrue
wheneverthecontentsoftheStringobjectsareidentical.Anarrayofcharanda
Stringaretwototallydifferenttypes,andwhencomparedusingtheequals()
methodoftheStringclass,thevaluereturnedwillbefalse.
Q13(b)and(e)
Unlikelocalvariables,allfieldsareinitializedwithdefaultinitialvalues.All
numericfieldsareinitializedtozero,booleanfieldstofalse,charfieldsto
'\u0000',andallreferencefieldstonull.
Q14(a)
Themain()methodin(b)willalwaysthrowandcatchan
ArrayIndexOutOfBounds-Exception,sinceargs.lengthisanillegal
indexintheargsarray.Themain()methodin(c)willalwaysthrowan
ArrayIndexOutOfBoundsExceptionsinceitalsousesargs.lengthas
anindex,butthisexceptionisnevercaught.Themain()methodin(d)willfailto
printtheargumentifonlyoneprogramargumentissupplied.Themain()method
in(e)willthrowanuncaughtArrayIndexOutOfBoundsExceptionifno
programargumentsarespecified.
Q15(e)
Methodg()modifiesthefielda.Methodg()modifiestheparameterb,notthe
fieldb,sincetheparameterdeclarationshadowsthefield.Variablesarepassedby
value,sothechangeofvalueinparameterbisconfinedtothemethodg().Method
g()modifiesthearraywhosereferencevalueispassedasaparameter.Changeto
thefirstelementisvisibleafterreturnfromthemethodg().
Q16(a)
Theprogramwillfailtocompilesincethelabell2cannotprecedethedeclaration
intj=0.Foralabeltobeassociatedwithaloop,itmustimmediatelyprecede
theloopconstruct.Iflabell2precededthewhileloop(insteadofthedeclaration
ofj),theprogramwouldcompileandprint9.
Q17(b)
Classescannotextendinterfaces;theymustimplementthem.Interfacescanextend
otherinterfaces,butcannotimplementthem.Aclassmustbedeclaredas
abstractifitdoesnotprovideanimplementationforallabstractmethodsofthe
interfacesthatitimplements.Methodsdeclaredininterfacesareimplicitlypublic
andabstract.Classesthatimplementthesemethodsmustexplicitlydeclarethese
methodstobepublic.
Q18(a)
WOW! eBook
www.wowebook.org
Thecodewillfailtocompilebecausetheliteral4.3hasthetypedouble.
Assignmentofadoublevaluetoafloatvariablewithoutanexplicitcastisnot
allowed.Thecodewouldcompileandprint0atruntime,iftheliteral4.3was
replacedwith4.3F.
Q19(b)and(e)
The&&and||operatorsexhibitshort-circuitbehavior.Thefirstoperandofthe
ternaryoperator(?:)isalwaysevaluated.Basedontheresultofthisevaluation,
eitherthesecondorthirdoperandisevaluated.
Q20(e)
Nolabelsaremandatory(includingthedefaultlabel),andlabelscanbeplacedin
anyorderwithintheswitchbody.Thekeywordcontinuemayoccurwithinthe
bodyofaswitchstatementaslongasitpertainstoaloop.Anenumconstant,a
non-longintegralconstantexpression,orastringconstantexpressioncanbeused
forcaselabelsaslongasthetypeiscompatiblewiththeexpressionintheswitch
expression.
Q21(a)
Stringsareimmutable,sotheconcat()methodhasnoeffectontheoriginal
Stringobject.Thestringonwhichthetrim()methodiscalledconsistsofeight
characters,wherethefirstandtwolastcharactersarespaces("hello").The
trim()methodreturnsanewStringobjectinwhichthewhitespacecharacters
ateachendhavebeenremoved.Thisleavesthefivecharactersoftheword
"hello".
Q22(a)and(e)
Methodoverloadingrequiresthatthemethodsignaturesaredifferent,butthemethod
nameisthesame.Thereturntypeisirrelevantinthisregard.Thesignatureofthe
existingmethodissum(long,long).
Thesignatureofthemethodin(a)issum(int,int).Thesignatureofthe
methodin(e)issum(long,int).Bothsignaturesaredifferentfromthe
signatureoftheexistingmethod.
Declarations(b)and(d)fail,sincethemethodsignatureisidenticaltotheexisting
method.Declaration(c)fails,sinceitdeclaresanabstractmethodinanon-
abstractclass.
Q23(b)
Themethodwiththemostspecificsignatureischosen.Inthiscasetheint
argument10isboxedtoanInteger,whichispassedtotheNumberformal
parameter,astypeNumberismorespecificthanObject.
Q24(d),(f),and(g)
Themain()methodmustbedeclaredaspublicandstatic,withreturntype
WOW! eBook
www.wowebook.org
void,andtakesasinglearrayofStringobjectsasargument.Theorderofthe
staticandpublickeywordsisirrelevant.Also,declaringthemethodfinalis
irrelevantinthisrespect.
Q25(d)
Thelengthofthearraypassedtothemain()methodisequaltothenumberof
programargumentsspecifiedinthecommandline.Unlikesomeotherprogramming
languages,theelementatindex0doesnotcontainthenameoftheprogram.The
firstprogramargumentspecifiedisretrievedusingargs[0],andthelastprogram
argumentspecifiedisretrievedusingargs[args.length-1],when
args.lengthisgreaterthan0.Aprogramargumentisastring,andseveral
argumentsareseparatedbyspacesonthecommandline.Topassseveralarguments
asoneargument,thesemustbeenclosedindoublequotes.
Q26(e)
Whentheprogramiscalledwithnoprogramarguments,theargsarraywillbeof
length0.Theprogramwillinthiscaseprintnoarguments.Whentheprogramis
calledwiththreearguments,theargsarraywillhavelength3.Usingtheindex3in
thenumbersarraywillretrievethestring"four",becausethestartindexis0.
Q27(b)and(e)
Staticimportfromaclassdoesnotautomaticallyimportstaticmembersofany
nestedtypesdeclaredinthatclass.Theorderoftheimportstatementsisarbitraryas
longastheyaredeclaredafteranypackagestatementandbeforeanytype
declaration.Nameconflictsmustbedisambiguatedexplicitly.
Q28(e)
Anobjectreferenceisneededtoaccessnon-staticmembers.Staticmethodsdonot
havetheimplicitobjectreferencethis,andmustalwayssupplyanexplicitobject
referencewhenreferringtonon-staticmembers.Thestaticmethodmain()legally
referstothenon-staticmethodfunc(),usingthereferencevariableref.Static
membersareaccessiblefrombothstaticandnon-staticmethods,usingtheirsimple
names.NoNullPointerExceptionisthrown,asrefreferstoaninstanceof
MyClass.
Q29(c)
Declaration(4)definesastaticmethodthattriestoaccessavariablenameda,which
isnotlocallydeclared.Sincethemethodisstatic,thisaccesswillbevalidonlyif
variableaisdeclaredasstaticwithintheclass.Therefore,declarations(1)and
(4)cannotoccurinthesameclassdeclaration,whiledeclarations(2)and(4)can.
Q30(a),(f),and(h)
ThetypeoftheswitchexpressionmustbeeitheranenumtypeorStringtype
oroneofthefollowing:byte,char,short,int,orthecorrespondingwrapper
typefortheseprimitivetypes.Thisexcludes(b)and(e).Thetypeofthecaselabels
WOW! eBook
www.wowebook.org
mustbeassignabletothetypeoftheswitchexpression.Thisexcludes(c)and(d).
Thecaselabelvaluemustbeaconstantexpression,whichisnottruein(g),where
thecaselabelvalueisoftypeByte.
Q31(a)
ThevalueofthecaselabeliFourisnotaconstantexpressionand,therefore,the
codewillnotcompile.
Q32(d)
Implementation(4)willcorrectlyreturnthelargestvalue.Theifstatementdoesnot
returnanyvalueand,therefore,cannotbeusedasanexpressionstatementin
implementations(1)and(2).Implementation(3)isinvalidsinceneitherthe
switchexpressionnorthecaselabelvaluescanbeoftypeboolean.
Q33(c)
Asitstands,theprogramwillcompilecorrectlyandwillprint3,2atruntime.If
thebreakstatementisreplacedwithacontinuestatement,theloopwillperform
allfouriterationsandwillprint4,3.Ifthebreakstatementisreplacedwitha
returnstatement,thewholemethodwillendwheniequals2,beforeanythingis
printed.Ifthebreakstatementissimplyremoved,leavingtheemptystatement(;),
theloopwillcompleteallfouriterationsandwillprint4,4.
Q34(a)and(c)
Theblockstatement{}isacompoundstatement.Thecompoundstatementcan
containzeroormorearbitrarystatements.Thus,{{}}isalegalcompound
statement,containingonestatementthatisalsoacompoundstatement.Thisinner
compoundstatementhasnostatements.Theblock{continue;}byitselfis
notvalid,sincethecontinuestatementcannotbeusedoutsidethecontextofa
loop.(c)isavalidexampleofbreakingoutofalabeledblock.(d)isnotvalidforthe
samereasonsthat(b)wasnotvalid.Thestatementat(e)isnottrue,sincethe
breakstatementcanalsobeusedtobreakoutoflabeledblocks,asillustratedby
(c).
Q35(d)
Thetypeofnumsisint[][].Theouterloopiteratesovertherows,sothetypeof
theloopvariableintheouterloopmustbeint[],andtheloopexpressionisnums.
Theinnerloopiteratesovereachrow,int[].Theloopvariableintheinnerloop
mustbeint,andtheloopexpressionintheinnerloopisarowgivenbytheloop
variableoftheouterloop.Onlyintheloopheadersin(d)arebothelementtypes
compatible.
Q36(b)
Theprogramwillprint1and4,inthatorder.AnInterruptedExceptionis
handledinthefirstcatchclause.Insidethisclause,anewRuntimeException
isthrown.Thisexceptionwasnotthrowninsidethetryblockandwillnotbe
WOW! eBook
www.wowebook.org
handledbythecatchclauses,butwillbesenttothecallerofthemain()method.
Beforethishappens,thefinallyclauseisexecuted.Thecodetoprint5isnever
reached,sincetheRuntimeExceptionremainsuncaughtaftertheexecutionof
thefinallyclause.
Q37(d)
Themethodnullify()doesnotaffectthearrayreferenceinthemain()
method.Thearrayreferencedbyargsisnolongerreachablewhencontrolreaches
(1).OnlythearrayobjectanditsfourObjectelements(i.e.,fiveobjects)are
reachablewhencontrolreaches(1).
Q38(e)
Anobjectcanbeeligibleforgarbagecollectioneveniftherearereferencesdenoting
theobject,aslongastheobjectsowningthesereferencesarealsoeligiblefor
garbagecollection.Thereisnoguaranteethatthegarbagecollectorwilldestroyan
eligibleobjectbeforetheprogramterminates.Theorderinwhichtheobjectsare
destroyedisnotguaranteed.Athreadcannotaccessanobjectonceitbecomes
eligibleforgarbagecollection.
Q39(a),(b),(c),and(e)
Theexpressions('c'+'o'+'o'+'l')and('o'+'l')areoftype
intduetonumericpromotion.Theirevaluationwouldresultinthevalues429and
219,respectively.Expression(d)isillegal,sincetheStringclasshasno
constructortakingasingleintparameter.Expression(a)islegal,sincestring
literalsarereferencesthatdenoteStringobjects.
Q40(d)
Theexpression"abcdef".charAt(3)evaluatestothecharacter'd'.The
charAt()methodtakesanintvalueasanargumentandreturnsacharvalue.
Theexpression("abcdef").charAt(3)islegal;italsoevaluatestothe
character'd'.Theindexofthefirstcharacterinastringis0.
Q41(e)
Theexpression"Hellothere".toLowerCase().equals("hello
there")willevaluatetotrue.Theequals()methodintheStringclasswill
returntrueonlyifthetwostringshavethesamesequenceofcharacters.The
compareTo()methodintheStringclasswillreturn0onlyifthetwostrings
havethesamesequenceofcharacters.Thestringcomparisonbythesetwomethods
iscasesensitive,beingbasedontheUnicodevalueofthecharactersinthestrings.
Q42(c)
Thevariablemiddleisassignedthevalue6.Thevariablentisassignedthestring
"nt".Thesubstring"nt"occursthreetimesinthestring"Contentment!",
startingatindices2,5,and9.Thecalls.lastIndexOf(nt,middle)returns
thestartindexofthelastoccurrenceof"nt",searchingbackwardfromposition6.
WOW! eBook
www.wowebook.org
Q43(d)
TheprogramwillconstructanimmutableStringobjectcontaining"eeny"anda
mutableStringBuilderobjectcontaining"miny".Theconcat()method
returnsareferencevaluetoanewimmutableStringobjectcontaining"eeny
meeny",butthereferencevalueisnotstored;consequently,thisStringobject
cannotbereferenced.Theappend()methodappendsthestring"mo"tothe
stringbuilder.
Q44(c)
Thecodewillfailtocompile,sincethepackagedeclarationcannotoccurafteran
importstatement.Thepackageandimportstatements,ifpresent,mustalways
precedeanytypedeclarations.Ifafilecontainsbothimportstatementsanda
packagestatement,thepackagestatementmustoccurbeforetheimport
statements.
Q45(a)and(b)
NotethatArrayIndexOutOfBoundsExceptionand
StringIndexOutOfBoundsExceptionaresubclassesof
IndexOutOfBoundsException.Theelementsofthearrayareinitializedas
follows:
Clickheretoviewcodeimage
trio[0]=null;
trio[1][0]=null;
trio[2][0]=“Tom”;
trio[3]=newString[0];//{},i.e.,zero-lengtharray
trio[4][0]=“Dick”;
trio[4][1]=“Harry”;
Elementtrio[3][0]doesnotexistbecausethearraytrio[3]isofzerolength,
resultinginanArrayIndexOutOfBoundsExceptionbeingthrown;this
exceptionisalsoasubtypeofIndexOutOfBoundsException.
IllegalIndexFoundExceptionisnotdefined.
Q46(e)
Theloopcondition++i==iisalwaystrue,aswearecomparingthevalueofito
itself,andtheloopwillexecuteindefinitely.Theevaluationoftheloopcondition
proceedsasfollows:((++i)==i),withtheoperandshavingthesamevalue.For
eachiteration,theloopvariableiisincrementedtwice:onceintheloopcondition
andasecondtimeintheparameterexpressioni++.However,thevalueofiis
printedbeforeitisincrementedthesecondtime,resultinginoddnumbersfrom1
andupwardbeingprinted.Iftheprefixoperatorisalsousedintheprintln
statement,allevennumbersfrom2andupwardwouldbeprinted.
Q47(d)
Theexpressioni%kevaluatestotheremaindervalue3.Theexpressioni%-k
alsoevaluatestotheremaindervalue3.Weignorethesignoftheoperands,and
WOW! eBook
www.wowebook.org
negatetheremainderonlyifthedividend(jinthiscase)isnegative.
Q48(e)
TheclassThingydoesnotoverridetheequals()method,sotheequals()
methodfromtheObjectclassisexecutedeachtime.ThemethodintheObject
classcomparesthereferencevalueforequalitywiththe==operator.Havingthe
samenameinthesecondcalltotheequals()methoddoesnotmaketheThingy
objectsequal.Inthelastcalltotheequals()method,thetworeferencesare
aliases;thatis,theyhavethesamereferencevalue.
Q49(b)
Stringsareimmutable,sothemethodconcat()doesnotchangethestateofthe
s1string.Thedefaultcaseisexecutedintheswitchstatement.Becauseofthe
fall-throughintheswitchstatement,thelastprintstatementisalsoexecuted.
Q50(a),(d),and(e)
In(b),theright-handsideintvalue255requiresacasttoconverttoabyte.In
(c),onlyintegerliteralscanbespecifiedinbinarynotation,notfloating-pointvalues.
(e)willcompile,butwillthrowaNumberFormatExceptionatruntime.In(f),
anunderscorecannotoccuratthestartofanintegervalue.Thecompilerwill
interpretitasanidentifier.In(g),anunderscorecannotoccurbeforeorafterany
typedesignator(L).
Q51(d),(e),and(i)
In(d)and(e),eitherthearraylengthortheinitializerblockcanbespecified,asin
(a),(c),and(f).In(i),thelengthoftheleftmostdimensionmustbespecified;the
otherdimensionsareoptional,asin(g)and(h).
Q52(a)and(c)
Themethodsat(1)and(3)differonlyinthereturntype,whichisnotsufficientfor
correctoverloading.Methodoverloadingrequiresthatthemethodsignaturesare
different,butthemethodnameisthesame.Thereturntypeisirrelevantinthis
regard.Thecodewillnotcompile.
Q53(d)
StringBuilderismutable.Thereferencevalueingiz.nameiscopiedtothe
formalparametersbwhenthemethodiscalled.Referencesgiz.nameandsbare
aliasestothesamestringbuilder.Changesmadetothestringbuilderinthemethod
areapparentwhenthecallreturns.Incontrast,thedoublevalueingiz.weight
iscopiedtotheformalparameterweight,whosevalueischangedinthemethod,
butthisdoesnotaffectthevalueintheactualparameter,whichremainsunchanged.
Q54(a),(b),(e),and(f)
StringBuilderismutable.Themethodsinsert()andappend()ofthe
StringBuilderreturnthereferencevalueofthestringbuilder,inadditionto
WOW! eBook
www.wowebook.org
modifyingit.Theassignmentin(b)and(f)issuperfluous.In(c)and(d),onlythe
localvariablemealisassignedareferencevalueofastringbuilder,butitdoesit
notchangethestringbuilderinthearraymeals.
Q55(d)
Afterthefirstcalltotheoverloadedadd()method,thesizeofthearraylistis1.
Tryingtoinsertanelementatindex2inthesecondcalltotheadd()method
resultsinajava.lang.IndexOutOfBoundsException,becauseindex2is
strictlygreaterthanthecurrentsizeofthearraylist.
Q56(g)
ThefieldnumOfGuestsisstatic,meaningthefieldbelongstotheclassRoom
andnottoanyobjectoftheclass.Suchafieldcanbereferencedbyareference
whosetypeisthesameastheclass.Thetworeferencesr1andr2refertothesame
staticfieldnumOfGuests,whichhasthevalue3.Becauseofstringconcatenation,
theexpression"Numberofguests:"+r1.numOfGuests+
r2.numOfGuestsevaluatesto"Numberofguests:33".
Q57(b),(c),and(d)
In(a),thetheatercannotadmitanyoneunlessthereisaticket-holder,sothetestto
seewhetherthereisaticket-holdercomesfirst.
In(b),atleastoneguesshastobemade,sothetestcanbedoneaftermakingthe
guess.
In(c),somesalthastobeadded,asthefoodhastoolittlesaltinitially.Thetestto
seeifthefoodtastesrightcanbedoneaftersomesalthasbeenadded.
In(d),atleastonecandlehastobeadded,sothetestfortherightnumberofcandles
canbedoneafteraddingacandle.
In(e),itagoodideatocheckfirstwhetherthecatisawaybeforelettingthemice
playalittle.
Q58(b)and(f)
Inbothcases,thecodeintheifstatementandthewhileloopisunreachable,soit
canneverbeexecuted.Incaseofthewhileloop,thecompilerflagsanerror.The
ifstatementistreatedasaspecialcasebythecompilertosimulateconditional
compilation,allowingcodethatshouldnotbeexecuted.
Q59(e)
Thevalue2014isboxedintoanInteger.ThesubclassIntegeroverridesthe
abstractmethodintValue()fromthesuperclassNumber,sothatnocastor
explicitparenthesesarenecessary.However,ifthiswasnotthecase,onlythesyntax
withthecastin(a)wouldbecorrect.
Q60(b)
Thethingtonoteisthatthemethodcompare()isoverloadedinthesubclass
WOW! eBook
www.wowebook.org
Student,andnotoverridden.ThusobjectsoftheclassStudenthavetwo
methodswiththesamenamecompare.Foroverloadedmethods,themethodtobe
executedisdeterminedatcompiletime,dependingonthetypeofthereferenceused
toinvokethemethod,andthetypeoftheactualparameters.Whenthetypeofthe
referenceisPerson(asisthecaseforp1andp2),themethodcompare()in
Personwillalwaysbeexecuted.ThemethoddefinedinthesubclassStudentis
executedonlybythelastcalls1.compare(s2)inthemain()method.
Q61(b)and(e)
Theadd(element)methodaddsanelementattheendofthelist.The
add(index,element)methodaddstheelementatthespecifiedindexinthe
list,shiftingelementstotherightfromthespecifiedindex.Theindexsatisfies
(index>=0&&index<=size()).Theset(index,element)
methodreplacestheelementatthespecifiedindexinthelistwiththespecified
element.Theindexsatisfies(index>=0&&index<size()).The
for(;;)loopaddstheelementscurrentlyinthelistattheendofthelist.Thelist
changesasfollows:
Clickheretoviewcodeimage
[Ada]
[Ada,Alyla]
[Ada,Otto]
[Ada,Anna,Otto]
[Ada,Anna,Otto,Otto,Anna,Ada]
Q62(e)
Elementswiththenullvaluecounttowardthesizeofthelist.Thelistshave
differentsizes.Thelistsaretwodistinctlists,havinguniquereferencevalues.The
equals()testfailsbecausethelistshavedifferentsizes.
Q63(a),(c),(e),(f),(g),and(k)
Theprogramprintsthefollowing,wherethelistcontentsareshownbeforeandafter
eachprintstatement.NotethereturnvaluefromtheArrayListmethods.
[3,4,1,null,0]
(1)printsnull
[3,4,1,null,0]
(2)prints4
[3,3,1,null,0]
(3)prints1
[3,3,1,null,0]
(4)printstrue
[3,3,1,null,0]
(5)printsnull
[3,3,1,0]
(6)prints0
[3,3,1,0]
(7)printsfalse
[3,3,1,0]
Q64(b),(f),and(g)
(1):Theinitialcapacitycanbe0.Thecapacitycanchangeasthelistchanges
WOW! eBook
www.wowebook.org
structurally.
(2):List<String>isnotasubtypeofList<Object>.Assignmentisnot
allowed.
(3),(4),(5):AlthoughtheNumberclassisabstract,wecancreateanArrayList
ofanabstractclass.However,onlyreferencevaluesofobjectsofitsconcrete
subtypescanbestoredinsuchalist.
(6):Thediamondoperatorcanbeusedonlywiththenewoperator.
(7):ArrayList<Integer>isnotasubtypeof
ArrayList<ArrayList<Integer>>.Assignmentisnotallowed.The
ArrayListcreationexpressionmustdeclarethefullelementtypeorusethe
diamondoperator.
(8):Thedeclarationstatementcompiles,butanuncheckedconversionwarningis
issuedbythecompiler.Allbetsareoffregardingthetype-safetyofthe
ArrayList.
Q65(d)and(e)
Textualrepresentationofthecurrentcontentsofthelistisaddedasastringoneach
iterationoftheloop.Theloopbodyisexecuted3times.Thedefaulttextual
representationofalistisenclosedinbrackets([]),wheretextualrepresentationof
eachelementisseparatedbyacomma(,).
Q66(d)
Theadd(index,element)methodacceptsanindexthatsatisfiesthe
condition(index>=0&&index<=size()).Thefor(;;)loopswaps
elementstoreversetheelementsinthelist.
Q67(c)and(d)
(a):Thereturnstatementismandatoryinalambdaexpressiononlyifthelambda
bodyisastatementblockthathasanon-voidreturn.
(b):Areturnstatementisillegalinalambdaexpressionifthelambdabodyisa
singleexpression.
(e):Alocalvariabledeclarationintheblockscopeofalambdaexpressioncannot
shadoworredeclarealocalvariablewiththesamenameintheenclosingmethod.
Q68(a),(c),(g),(h),and(i)
Thedeclarationsat(1),(3),(7),(8),and(9)willnotcompile.In(1),thedeclared-
typeparametermustbeinparentheses.In(3),thefinalmodifiercanbeapplied
onlytodeclared-typeparameters.In(7),thereturnkeywordcannotbeusedwhen
thelambdabodyisasingleexpression.In(8)and(9),thereturnkeywordis
requiredforanon-voidreturnfromalambdaexpressionwithastatementblock.In
(8),thestatementterminator(;)isalsomissing.
WOW! eBook
www.wowebook.org
Q69(a),(d),and(e)
Thedeclarationsat(1),(4),and(5)willcompile.In(1),theparameterlockislocal
intheblockscopeofthelambdaexpression.In(2),thelambdaexpressionmust
explicitlyreturnavalue,regardlessofwhethertheifstatementisexecuted.In(3),
thelocalfinalvariablelock3intheenclosingscopecannotberedeclared.In(4)
and(5),localvariableslock3andlock4intheenclosingscopecanbeaccessed
inthelambdaexpression,astheyarebothfinalandeffectivelyfinal,respectively.
In(6),thelocalvariablelock4intheenclosingscopecannotberedeclaredas
parameter.
Q70(a),(c),(g),and(h)
In(b),thereturnkeywordcannotbeusedinalambdaexpressionwithasingle
expressionbody.In(d),thereturnkeywordmustbeusedinalambdaexpression
withanon-voidstatementblockbody.In(e)and(f),theclassStringdoesnot
haveaconstructorthattakesanintegervalue.
Q71(b)
Afunctionalinterfaceisaninterfacethathasonlyoneabstractmethod,asidefrom
theabstractmethoddeclarationsofpublicmethodsfromtheObjectclass.This
singleabstractmethoddeclarationcanbetheresultofinheritingmultiple
declarationsoftheabstractmethodfromsuperinterfaces.
AllexceptIAarefunctionalinterfaces.IAdoesnotdefineanabstractmethod,asit
providesonlyanabstractmethoddeclarationoftheconcretepublicmethod
equals()fromtheObjectclass.IBdefinesasingleabstractmethod,doIt().
ICoverridestheabstractmethodfromIB,soeffectivelyithasonlyoneabstract
method.ICinheritstheabstractmethoddoIt()fromIBandoverridesthe
equals()methodfromIA,soeffectivelyitalsohasonlyoneabstractmethod.
Q72(e)
(a):TheisBefore()andisAfter()methodsarestrictintheircomparison.
(b):ThewithYear()andwithMonth()methodswilladjusttheday.The
withDayOfMonth()andwithDayOfYear()methodswillthrowa
DateTimeExceptioniftheargumentvaluewillresultinaninvaliddate.
(c):ThePeriodclassdoesnothavethemethodtoTotalDays(),butitdoes
havethemethodtoTotalMonths()thatconsidersonlytheyearsandthe
months.ThePeriodclasshasnonotionoftimeofdayordateintheyear.
(d):ThePeriodclassdoesnotimplementtheComparableinterface.
Q73(d)
Thecalculationoftime.withHour(10).plusMinutes(120)proceedsas
follows:
Clickheretoviewcodeimage
WOW! eBook
www.wowebook.org
12:00with10hour==>10:00+120min(i.e.,2hours)==>12:00
Q74(f)
Thedatevalue2015-01-01inthedatereferenceneverchanges.The
withYear()methodreturnsanewLocalDateobject(withthedatevalue
0005-01-01)thatisignored.TheplusMonths()methodalsoreturnsanew
LocalDateobjectwhosevalueisprinted.Thecalculationof
date.plusMonths(12)proceedsasfollows:
Clickheretoviewcodeimage
2015-01-01+12months(i.e.,1year)==>2016-01-01
Q75(c)
ThestaticmethodcallPeriod.ofYears(10)returnsaPeriodwiththevalue
P10Y.ThisPeriodobjectisusedtoinvokethestaticmethodofMonths()with
theargumentvalueof16months,resultinginanewPeriodobjectwiththeperiod
valueP16M.Itsreferencevalueisassignedtotheperiodreference.Theof()
methodsdonotnormalizethedate-basedvaluesofaPeriod.
Q76(d)
(a):TheformatterwillformataLocalTimeobjectandthetimepartofa
LocalDateTimeobject,butnotaLocalDateobject,asitknowsnothingabout
formattingthedatepart.ItwillusetheISOstandard.
(b):TheformatterwillformataLocalDateobjectandthedatepartofa
LocalDateTimeobject,butnotaLocalTimeobject,asitknowsnothingabout
formattingthetimepart.ItwillusetheISOstandard.
(c):TheformatterwillformataLocalDateTimeobject,butneithera
LocalDateobjectnoraLocalTimeobject,asitrequiresboththedateandthe
timeparts.ItwillusetheISOstandard.
Q77(a),(d),and(f)
Theinputstringmatchesthepattern.Theinputstringspecifiesthetime-basedvalues
thatcanbeusedtoconstructaLocalTimeobjectin(a)byaformatter,basedon
thetime-relatedpatternlettersinthepattern.Nodate-basedvaluescanbeinterpreted
fromtheinputstring,asthispatternhasonlytime-relatedpatternletters.(b)and(c),
whichrequireadatepart,willthrowaDateTimeParseException.
Tousethepatternforformatting,thetemporalobjectmustprovidevaluesforthe
partscorrespondingtothepatternlettersinthepattern.TheLocalTimeobjectin
(d)hasthetimepartrequiredbythepattern.TheLocalDateobjectin(e)doesnot
havethetimepartrequiredbythepattern,soan
UnsupportedTemporalTypeExceptionwillbethrown.The
LocalDateTimeobjectin(f)hasthetimepartrequiredbythepattern.In(f),only
thetimepartoftheLocalDateTimeobjectisformatted.
WOW! eBook
www.wowebook.org
Index
Symbols
-169
--176
^184,189
^=185
_32
;50
:110
!184
!=181,342
?:194
.7,72,97,108
...81,85
‘32,33
"34
[]59,61,195
{}50,60,117
@FunctionalInterface442,443
@Override270
@param49,56
@return225
@throws253
*100,163,167
*=172
/167
/*and*/35
/**and*/36
//35
WOW! eBook
www.wowebook.org
/=172
\33
&184,189
&&186
&=185
%167,168
%=172
+169,174
+concatenation364
++176
+=172
<180
<=180
<>414,415,416
-=172
=158
==181,342,351,359
>195,439,444
>180
>=180
|184,189
|=185
||186
~189
A
abilityinterfaces
seemarkerinterfaces
abruptmethodcompletion232
absoluteadjusters470
abstract
WOW! eBook
www.wowebook.org
classes120
interfaces290
methods136,291,442
abstract120,136,290,291,442
abstractmethoddeclarations442
ininterfaces290,291
abstraction2,10
accessibility7,17,114
default118,127
members114,120,123
modifiers118
package118
private128
protected126
public124
UMLnotation124
accessibilitymodifiers48,53
activationframe384
seemethodexecution230
actualparameter72
actualparameterlist72,315
addingtoclass264
additiveoperators169
aggregation10,12,267
hierarchy267
versusinheritance331
aliases6,75,182,183
seealsoreferences
ambiguouscall316
analyzingprogramcode512
andoperator189
annotations
WOW! eBook
www.wowebook.org
@Override270
anonymousarrays63,66
[]63
anonymousclasses436
anonymousfunctions439
API(applicationprogramminginterface)22
apostrophe33
application16
architectureneutral23
argument
seeactualparameter
argumentstomainmethod85
arithmeticcompoundassignmentoperators172
ArithmeticException236
arity81
arraycreationexpression59,63
arrayinitializer60,63,66
arraystorecheck311
arraytypes
seearrays
ArrayIndexOutOfBoundsException61,236
ArrayList366,414
addcollection419
addelement417,419
autoboxing421
capacity416
clearlist420
comparisonwitharrays425
constructing415
constructors418
convertingtoarray424
elementsearch423
WOW! eBook
www.wowebook.org
elementtype415
filtering434
import415
inheritancehierarchy415
initialcapacity417
insertionorder414
listoflists417
membershiptest422
modifying419
nestedlists417
objectvalueequality422
openrange-viewoperations414
ordered414
position-basedaccess415
positionalindex422
positionalorder414
positionalretrieve422
querying422
references415
removecollection420
removeelement419
replaceelement419
size416,422
sorting425
subtyperelationship418
textualrepresentation417
traversing423
trimtosize420
type-safety416,417,418
uncheckedconversionwarning416
zero-basedindex414
arrays58,342
WOW! eBook
www.wowebook.org
[]59,61
{}60
anonymous63,66
arraycreationexpression59
arrayinitializelist60,63
arrayinitializer60,66
arrayname59
arraysize60
arraystorecheck311
ArrayIndexOutOfBoundsException61
bounds61
construction59
declarations59
defaultinitialization59,60
dynamic415
elementaccessexpression61
elementdefaultvalue310
elementtype59
elements58,61
index58
indexexpression61
initialization60,65
iteratingover217
length58
multidimensional63,65
objects342
ragged65
reference59,62,311
searching69
sorting68
subtypecovariance309
traverseanarray62
WOW! eBook
www.wowebook.org
using61
arraysofarrays59,65
multidimensional65
ArrayStoreException311,418,424
arrow>195,439,444
ASCII32,38
AssertionError237
assignable147,314
assignmentcompatible148,314,416
assignmentconversions147
assignmentoperator5
assignments
arithmeticcompoundoperators172
bitwise192
cascading159
compoundoperators185,192
expressionstatement159
implicitnarrowing160
multiple159
numericconversions160
operator151,158
primitivevalues159
references159
wideningreferenceconversions267
association12
aggregation267
composition267
realization296
associativity152
atomicvalues13
attributesseeproperties
autoboxing68,348
WOW! eBook
www.wowebook.org
for(:)statement218
AutoCloseable387
automaticgarbagecollection6,384
automaticvariablesseelocalvariables
B
backslash33
backspace33
base30,349,352
baseclass264
basicforstatement215
BeforeCurrentEra(BCE)464
behavior433
behaviorparameterization434,441
binary
numericpromotion150
operators151
binarysearch
arrays69
bitmask190
bitpatterns154
bitwise
andoperator189
assignment192
complement189
compoundassignment192
operators189
oroperator189
xor189
bitwiseAND
&189
bitwisecomplement
~189
WOW! eBook
www.wowebook.org
bitwiseexclusiveOR
^189
bitwiseOR
|189
bitwiseXOR
^189
blankfinalvariable80,134
blocks49,50,117
scope117,448
try240
boilerplatecode436
Boolean
condition200
Booleanwrapperclass355
booleans37,39
casting149
expressions180
literals32
boxingconversions145,146
breakstatement205,206,221
BSseebackspace
buildingabstractions10
byte30,38
bytecode16,23
C
C137
C++23,137
cache139
callbyreference77
callbyvalue77
callchaining72
WOW! eBook
www.wowebook.org
callsignature316
callstack
seeJVMstack230
callee72
caller72,224
capacity416
carriagereturn33,35
cascadingassignments159
cascadingif-elsestatements203
caselabels203,205
casesensitivity28
castoperator145,148,151,162,172,182,320
casting147,148,149
seealsoconversions
catchclause240
uni-239
catchingexceptions230
catch-or-declare251
CertView509
chaining406
constructors287,406
finalizers391
char38
charactercase364
charactersequences
seestringsandstringbuilders
characterset
ASCII32,38
ISOLatin-132,38
Unicode32,38
Characterwrapperclass354
characters38
WOW! eBook
www.wowebook.org
literals32
searchingfor367
CharSequenceinterface360,365,369
checkedexceptions237
childclass264
choosingbetweenStringandStringBuilderclass374
Classclass343
classfile16
classhierarchy
seeinheritancehierarchy
classinheritance
seeimplementationinheritance
classmethod10
classmodifiers48
classpath107
absolutepathnames110
entriesorder110
entry-separatorcharacter110
fullyqualifiedpackagename109
path-separatorcharacter110
relativepathnames110
searchinanamedpackage109
searchingforclasses107
whitespace110
classsearchpath
seeclasspath
classvariable10
ClassCastException236,321
classes
abstract120
accessibility118
addingto264
WOW! eBook
www.wowebook.org
base264
body48
child264
cohesion335
concrete121,122,436
constructors53,282
coupling336
declarations48,96
definitions2,5
derived264
diagram8,9
encapsulation335
extending122,264
final122
finalvs.abstract122
fullyqualifiedname107
fullyqualifiedpackagename98
generalized266
grouping97
header48
implementinginterfaces291
initialization409
instancemembers48
instances4
members7
methods132
modifiers120
name97
normal121
Object342
parent264
runtime343
WOW! eBook
www.wowebook.org
scope114
searchingfor107
specialized266
staticmembers48
subclass10,264
superclass10,264
variables132
wrappers342,346
ClassLoaderclass342
ClassNotFoundException235
CLASSPATHenvironmentvariable
seeclasspath
-classpathoption
seeclasspath
clauses
catch240
extends264
finally240,245
implements291
throws251
cleaningup386
clean-upcode245
client7,16
Cloneableinterface343
CloneNotSupportedException343
cloningobjects343
codeoptimizations134
codereuse23,264,334
CodeRanch508
cohesion335
coincidental335
functional335
WOW! eBook
www.wowebook.org
high335
coincidentalcohesion335
Collection414
collections414
assingleentity414
elements414
ordered414
sorting414
command17
java17
javac17
commandline17,86
commandprompt17
comments35
communication7,72
Comparableinterface350,363,376,425
comparingobjects342
comparingstrings363
comparison180
compilationunit98
compilingJavasourcecode17
complement
~189
completesabruptly
seeexceptionpropagation232
compositeobject10
composition12,267
compoundstatement50
concatenationofstrings364
concatenationoperator174
concreteclasses436
concretemethod134
WOW! eBook
www.wowebook.org
ConcurrentModificationException424
condition
Boolean200
expressions200
conditional180
and186
operators186,194
or186
statements200
conditionalexpressions194
associativity195
nested195
precedence194
short-circuitevaluation194
sideeffects194
conditions180
connectingpunctuationcharacter28
const29
constantdeclarations290
constantexpression147,160,161,176
constantfieldvalues
caselabels208
constantstringexpressions208
constantvalues30,133
constantvariable161
constants302
constituentobjects10
constituents12
constructingarray59
constructorchaining283,287,406
constructors3,53,282
accessibility124
WOW! eBook
www.wowebook.org
accessibilitymodifier53
body53
chaining283,287
classname53
declaration48
default54
header53
implicitdefault54
localdeclarations53
no-argument53,54,283,287
non-zeroargument55,287,288
overloading56
superclassconstructor54
constructs28
high-level28
loopsseeiterationstatements
container
seecollections
containscharacters368
continuestatement223
contract2,291,293,334,335
controlflow
break205,221
continue223
do-while214
for(;;)215
for(:)217
if200
if-else201
iterationseeiterationstatements
loopsseeiterationstatements
return224
WOW! eBook
www.wowebook.org
statements50,200
switch203
throw249
transferstatements219
while213
controltransfer219
conversioncategories147
conversioncontexts147
conversions144,311
assignment147
contexts147
identity172
implicitnarrowing173
methodinvocation148
narrowingreference320
numbersystems157
numericpromotions149
parameters73
referencecasting320
stringconcatenation175
tostrings369
truncation161
type-safe315
unsafecasts321
wideningreference267,320
convertingnumbersystems157
convertingvalues348,349,350,352,353,355,369
counter-controlledloops215
coupling336
loose336
covariantreturn269,273
-cpoption
WOW! eBook
www.wowebook.org
seeclasspath
CRseecarriagereturn
crab217
creating
objects195
criteriaobject436
currencysymbol28
currentdirectory
.108
CurrentEra(CE)464
currentobject50
D
-doption106
danglingreferences384
datastructures414
datatypesseetypes
date
seetemporalobjects
dateunits474
date/timeformatters
customized486,495
formatstyles490
formatting487
immutability487
ISO-baseddefault486,487
ISO-basedpredefined486,488
letterpattern495
localized486,490
parsing487
patternletters495,496
thread-safety487
date-basedvalues462
WOW! eBook
www.wowebook.org
date-time
seetemporalobjects
DateTimeException463
DateTimeFormatterclass
seedate/timeformatters
DateTimeParseException477,491
DayOfWeekenumtype468
declarationstatement4,41,171,177,187,216
declarations
arrays59,196
classes48,96
interfaces96
local50
mainmethod85
methods49
multidimensionalarrays63
packages96,98
statements50
variablearitymethod81
declaredtype268,274,275,315
declared-typeparameters445
declaringseedeclarations
decoupling330
decrementoperator176
deepcopying343
default
accessibility118,124,127
constructor54
exceptionhandler232
method297
values42,400,406
default297
WOW! eBook
www.wowebook.org
label204
method297
defaultconstructor54
defaultmethod297,442,443
multipleinheritance298
overriding298
defaultpackage98
deferredexecution451
definitions
inheritance296
interfaces290
delegatingrequests334
derivedclass264
destinationdirectory106
destinationstream18
destroyingobjects390
diagrams
class3
object5
seealsoUML
diamondoperator(<>)416
dictionaryorder363
distributed23
divide-and-conqueralgorithm69
dividend168
division
floating-point167
integer167
divisionoperator
/167
divisor168
documentation35
WOW! eBook
www.wowebook.org
documentationcomment35,36
tags36
documentingseedocumentation
dot97
double31,39
doublequote33
do-whilestatement214
downcasting145
duplicatingobjects343
Durationclass476
time-based476
dynamic23
dynamicarrays415
dynamicbinding
seedynamicmethodlookup
dynamicmethodlookup277,329,330
dynamictype268,274,275
E
effectivelyfinal448
elementtype59,415
elements58,414
eligibleforgarbagecollection385
ellipsis81
elseclausematching203
embeddedapplications22
emptystatement50
emptystring358
encapsulation22,97,335
encapsulationofimplementation334
endswithcharacters368
enhancedforloop213
enterpriseapplications22
WOW! eBook
www.wowebook.org
enumconstant87
symbolicnames87
values87
enumtypes87,103,209,303
declaring87
finalization391
namedconstants87
naturalorder90
ordinalvalue90,209
switchexpression204
using88
enumeratedtypes
seeenumtypes
EOFException235
equality181,342
equalsmethod183,342
objectvalue183
objects183
primitivevalues181
referencevalues182
equalsmethod183,342
Error237
escapesequences33
evaluationorder152,187
arithmeticexpressions164
evaluationshort-circuits187
exam507
multiple-choice513
program510
questions511
registration508
result511
WOW! eBook
www.wowebook.org
testinglocations510
voucher509
examobjectives
OCAJP8515
Exceptionclass236
exceptionhandler230
seealsoexceptions
exceptionhandling
advantages254
exceptions230,239
customized238
defaulthandler232
handler230
ignored390
propagation230
situations235
throw249
throwingseethrowingexceptions
thrownbyJVM235
thrownbymethod49
thrownprogrammatically235
throws251
types233
uncaught232
unchecked237
exchanginginformation72
explicit
garbagecollection393
explicittraversal452
exponent31
expressionstatements50,159,177,216,217,446
expressions205
WOW! eBook
www.wowebook.org
actualparameters72
boolean180
caselabels205
conditional194
deterministicevaluation150
label205
return224
statements50
throw249
extending
classes264
interfaces294
extendsclause
seeextending
extensions
.class16
.java16
externallibraries403
extractingsubstrings369
F
fall-through204,205
falseliteral32
FFseeformfeed
fielddeclarations48
fieldhiding275
fieldinitialization406
fields2
filename96
filepath105
separatorcharacter105
filtering434
WOW! eBook
www.wowebook.org
final
classes122
members133
parameters80
finalization385
finalizationmechanism385
finalizemethod343,390
finalizerchaining391
finalizerseefinalizemethod
finallyclause240,245
fixedaritymethod81
fixedaritymethodcall84
float31,39
floating-point37
double39
float39
literals31
floating-pointarithmetic165
strictfp166
floating-pointdatatypes31
floating-pointdivision167
floating-pointremainder169
flowcontrolseecontrolflow
for(;;)statement215
backward216
forward215
traversearray62
for(:)statement217
traversearray62
for-eachloop213
formfeed33,35
formalparameters49,53,72,117,315
WOW! eBook
www.wowebook.org
modifier49
name49
type49
formaltypeparameter290
formatspecifications18,370
formatspecifier19
formatstyles486,490
FormatStyleenumtype486,490
formattedoutput18
formatspecifier19
formattedstring370
formatting35,462,486
forwardreference400,401,403,405,406
fractionalsignednumbers37
fullyqualifiedclassname107
fullyqualifiedpackagename97,98,100
fullyqualifiedtypename97,101
function451
functiontype450
functionalcohesion335
functionalinterface438
@FunctionalInterface442,443
abstractmethod442
functiontype450
functionalmethod442
general-purpose443
generic441
Predicate<T>440,451
primitivevalues444
targettype450
seealsolambdaexpressions
functionalmethod442
WOW! eBook
www.wowebook.org
functionalprogramming24
functionality433
functional-styleprogramming433
G
garbagecollection387,389,390,393
automatic384
facilitate387
generalabstractions266
generalloops215
generalization10
generalizedclasses266
genericmethod423
generictype414
goto29,220
grammarrules28
grouping97
H
handlesseereferences
has-arelationship267
hashcode52,343
hashtables52
heap384
hidinginternals335
highcohesion335
high-performance24
horizontaltab33
hotspots24
HTseehorizontaltab
I
IDE(integrateddevelopmentenvironment)508
identifiers28
WOW! eBook
www.wowebook.org
predefined29
reserved29
variable40
identityconversion146,172
identityofobject5
IEEE754-198538
ifblock200
if-elsestatement201
ignoredexceptions390
IllegalArgumentException236,495
immediatesuperclass285
immutable462
immutableobjects346,357
immutablestrings357
implementationinheritance264
implementations2,266,335
inheritancehierarchy122
implementing
interfaces291
implementsclause291
implicit
inheritance264
narrowingconversions173
implicitdefaultconstructor54
import
declaration100
seealsostaticimport
single-type-importdeclaration100
statement96
type-import-on-demanddeclaration100
importing
enumconstants103
WOW! eBook
www.wowebook.org
referencetypes99
staticmembers101
incrementoperator176
index58
indexexpression61
IndexOutOfBoundsException361,369,375,376,419,422
individualarrayelements61
inequality181
seealsoequality
inferred-typeparameters445
infiniteloop217
infinity165,349
negative165
positive165
informationhiding335
inheritance10,267
hierarchy266
supertype–subtyperelationship267
initialcapacity417
initialstateofobject406
initialization
arrays60,65
code60
defaultvalues42
forstatement215
objects5
references41
variables41
initializer399
declaration-before-readingrule401
static400,401,405,409
initializerblock
WOW! eBook
www.wowebook.org
instance404
static402
initializerexpression400
initializers
non-staticblock48
non-staticfield48
staticblock48
staticfield48
initializingseeinitialization
insertionorder414
insertionpoint69
instance
members9,48
methods9,49,50
variableinitialization42
variables9,44
seealsoobject
instanceinitializerblock404
instancemethods6
instancevariables6,406
instanceofoperator195,320,321
instantiation4
int30,38
integerarithmetic165
integerbitwiseoperators189
integerconstantexpressions148
integerdatatypes30
integerdivision167
integerremainderoperation168
integers38
andoperator189
byte38
WOW! eBook
www.wowebook.org
complement189
datatypes38
int38
literals30
long38
oroperator189
representation154
short38
types38
xor189
integraltypes37,38,144
interfaceconstantantipattern102
interfaces290
abstract290
abstractmethods291
accessibility118
body290
constants302
declarations96
defaultmethods297
extending294
header290
implementing291
initialization409
marker291
realization296
references296
staticmethods300
subinterfaces294
superinterfaces294
UML295
variables302
WOW! eBook
www.wowebook.org
internaltraversal452
internedstrings358,359
internedvalues351
interpackageaccessibility335
interpreter17
intraclassdependencies336
invocationstack
seeJVMstack
invoker224
invokinggarbagecollection393
IOException235
is-arelationship266,267,334
ISOLatin-132,38
ISOstandard486,487,488
Iterableinterface366,424
iteration215
iterationstatements213
nextiteration223
termination213,222
iterators414,424
J
Java
NativeInterfaceseeJNI
java17
Javabytecode16
JavaCollectionsFramework414
Javacompiler17
JavaDevelopmentKit(JDK)21
Javaecosystem21
JavaEE(EnterpriseEdition)22
JavaME(MicroEdition)22
JavaNativeInterfaceseeJNI
WOW! eBook
www.wowebook.org
JavaPlatforms22
JavaRuntimeEnvironment(JRE)22
JavaSE(StandardEdition)22
JavaVirtualMachineseeJVM
java.timepackage462
java.time.formatpackage462
java.utilpackage414
java.util.function<T>package444
javac17
Javadoccomment35
@paramtag49,56
@returntag225
@throwstag253
javadocutility36
JDK17,508
JNI137
just-in-time(JIT)23
JVM17,22,384,393
JVMstack230,384
K
key69
keywords29
abstract120,136,291,442
boolean39
breakstatement221
byte38
case203
catch240
char38
class48,290
const29
WOW! eBook
www.wowebook.org
continue223
default204,297
do214
double39
else201
extends264
final80,122,133
finally245
float39
for215,217
if200
implements291
import100
instanceof195,320,321
int38
interface290
long38
native137
newseenewoperator
null149,183,320
package98
private128
protected126
public124
reservedwords29
return224
short38
static17,101,132,300,402
strictfp166
super54,272,276,285,299
WOW! eBook
www.wowebook.org
switch203
synchronized136
this50
throw249
throws251
transient138
try240
unusedwords29
void17,347
volatile139
while213,214
L
labeledbreakstatement222
labels220,222
break222
case203
default204
expressions205
labeledstatement220
switchstatement203
lambdabody439,444,445
lambdaexpressions433,438,444
accessclassmembers446
anonymousfunctions439
arrow>439,444
asvalues439
blocks
scope448
declared-typeparameters445
deferredexecution451
expression445
WOW! eBook
www.wowebook.org
expressionstatements446
function451
inferred-typeparameters445
lambdabody439,444,445
lambdaparameters445
non-voidreturn445
parameterlist439,444
singleexpression439,445
statementblock439,446
targettype450
targettyping451
typechecking450
variablecapture449
voidreturn445
lambdaparameters445
latebinding
seedynamicmethodlookup
leastsignificantbit155
leftassociativity152
legalassignments314
lengthmethod361
letterpattern495
lexicalscope
seeblocks:scope
lexicaltokens28
lexicographicalordering363,425
LFseelinefeed
libraries403
lifetime385
seescope44
lineseparator19
lineterminator35
WOW! eBook
www.wowebook.org
linearimplementationinheritance266
linefeed33
LinkageError237
LinkedList417
List414
lists
seeArrayList
literals30
boolean32
character32
defaulttype30,31
double31
escapesequences33
false32
float31
floating-point31
integer30
null30
predefined29
prefix30
quoting32
scientificnotation31
string34
suffix30,31
true32
litmustest
designbyinheritance266
local43
chainingofconstructors283,406
variables44,117
localdeclarations49,50
localvariables53
WOW! eBook
www.wowebook.org
blocks
scope448
LocalDateclass
seetemporalobjects
LocalDateTimeclass
seetemporalobjects
locale364,490,492
localizinginformation335
LocalTimeclass
seetemporalobjects
locations
seeclasspath
logicalAND
&184
logicalcomplement
!184
logicalexclusiveOR
^184
logicalinclusiveOR
|184
logicalXOR
^184
long30,38
suffix30
loopbody213,215
loopcondition213,215
loopsseeiterationstatements
loosecoupling336
lossofprecision144
M
magnitude144
WOW! eBook
www.wowebook.org
mainmethod17,18,85
arguments86
modifiers85
manifestconstant134
markerinterfaces291
Mathclass52
MAX_VALUEconstant351
memberdeclarations48,290
members3,114
access50
accessibility120,123
defaultvalues42
final133
inheritance264
instance48
modified264
modifiers131
ofobjects7
scope114
short-hand51
static7,48,132
terminology9
variablesseefields
memorymanagement384
memoryorganization384
message
receiver7
methodcall7,49,72
chaining376,378
fixedarity84
variablearity84
methodchaining471,474,479
WOW! eBook
www.wowebook.org
methoddeclaration48
methodheader136,137
methodinvocationconversions148,315
methodmodifiers49
methodoverloading52,273
methodoverriding268,273,407
methodsignature49,269
methodtype450
methods3
@Override270
abstract136,291,442
abstractmethoddeclarations291
accessibility49
ambiguouscall316
automaticvariablesseelocalvariables
behavior433
blocks49
body49,117
callchaining72
callseemethodcall
callingvariablearitymethod82
chained365
clone343
concrete134
declaration49,72
default297
dynamiclookup330
equals183,342
exceptions49
final134
finalize343,390
fixedarity81
WOW! eBook
www.wowebook.org
functional442
getClass343
header49
implementation136
invocationseemethodcall
localdeclarations49
localvariables
mainseemainmethod
methodinvocationconversions315
methodtype450
modifiers49
mostspecific316,422
name72
native137,251
objects50
overloadedresolution316
overloadingseemethodoverloading
overridingseemethodoverriding
overridingvs.overloading273
parameters49
recursive237
return224
returnvalue49
signature49,52,273
static132,300
synchronized136
termination224
throwsclause251
toString343
variablearity81
MIN_VALUEconstant351
minimizingoverhead386
WOW! eBook
www.wowebook.org
mobileapplications22
modifiers
abstract120,136,291
accessibility118,123
classes120
default297
final133
members131
native137
static132,300
strictfp166
synchronized136
transient138
volatile139
Monthenumtype465
mostspecificmethod316,422
multicore441
multicorearchitectures24
multidimensionalarrays63,65
multipleassignments159
multiplecatchclauses239
multipleimplementationinheritance290
multipleinheritance298
multipleinterfaceinheritance290
multiple-linecomment35
multiplicationoperator
*167
multiplicativeoperators167
multithreaded24
mutablecharactersequences374
mutuallycomparable68,69
mutuallyexclusive
WOW! eBook
www.wowebook.org
actions202
MVC335
N
name28
namedconstants134
namespaces53
NaN166,349
narrowerrange144
narrowingconversions
primitive144
reference145
narrowingreferenceconversions320
nativelibraries403
nativemethods137,251
header137
naturalordering68,69,425
negativezero165
nestedlists417
nestedloops66
newoperator5,53,59,195,406
newlineseelinefeed
NLseenewline
no-argumentconstructor53,54,283,287
non-associativity151
non-staticcode48
seenon-staticcontext48
non-staticcontext48
non-staticfield9
non-staticfieldinitializers48
non-staticinitializerblock48
non-varargscall
seefixedaritycall
WOW! eBook
www.wowebook.org
non-voidreturn445
non-zeroargumentconstructor55,287,288
normalclass121
normalexecution232
notifyingthreads344
nullreference30
casting320
nullreferenceliteral
casting149
equalitycomparison183
nullingreferences387
NullPointerException236
Numberclass351
numbersystems
base30
converting157
decimal30
hexadecimal30
octal30
radix30
NumberFormatException236,347,348
numericpromotions149
assignment160
binary150
unary149
numericwrapperclasses351
numericalliterals
usingunderscore32
O
object4
Objectclass266,342
WOW! eBook
www.wowebook.org
objecthierarchy267
objectreferences4,40
objectstate6,53,77,406
object-orienteddesign334
cohesion335
object-orientedparadigm22
object-orientedprogramming2
objects13
aggregate12
alive385
arrays58
callee72
caller72
Classclass343
cleaningup386
cloning343
communication72
comparing342
composite385
constituent12,385
constructing406
contract335
decoupling330
destroying390
eligible387
equality183,342
exchanginginformation72
finalization385
garbagecollection384
identity5
immutable346
implementation335
WOW! eBook
www.wowebook.org
initialstate406
initialization5,53
initializerblock404
internals335
lifetime385
members7
methods50
Objectclass342
persistence138
reachable384,385
resurrection385
services335
state133
seeobjectstate
valueequality183
OCAJP8507
examobjectives515
examquestionassumptions511
OCPJP8507
one-dimensionalarrays59
operands148
evaluationorder152
operations2
operators150
-163,169
--176
^184,189
^=185,192
!184
!=181,182
?:194
.7,97
WOW! eBook
www.wowebook.org
[]61,195
*163,167
*=172
/163,167
/=172
&184,189
&&186
&=185,192
%163,167,168
%=172
+163,169,174
++176
+=172
<180
<=180
-=172
=158
==181,182
>195
>180
>=180
|184,189
|=185,192
||186
~189
arithmeticcompoundassignment172
assignment151,158
associativity150
binary151
bitwise189
boolean180,181,184
WOW! eBook
www.wowebook.org
cast151
comparisons180
compoundassignment185,192
conditional186,194
decrement176
dot7
equality181
executionorder152
floating-point165
floating-pointdivision167
floating-pointremainder169
increment176
instanceof195,320,321
integer189
integerarithmetic165
integerdivision167
integerremainder168
logical184
multiplicative167
newseenewoperator
overflow165
overloaded164,167
postfix151
precedence150
relational180
short-circuited186
stringconcatenation174
ternary151
unary150,151,167
unary-167
unary+167
optimizations24
WOW! eBook
www.wowebook.org
oroperator189
OracleUniversity509
ordinalvalue90,209
OutOfMemoryException395
output18
overflow155,165
overloaded164
overloadedmethodresolution316
overloading
constructors56
methodresolution316
methods52,273
overloadingvs.overriding273
overriding253
equals183
finalizers390
methods268,273
toString175
overridingmethods
covariantreturn273
overridingvs.overloading273
ownership12
P
packageaccessibility118,124
packagedirectory106
packagestatement96,98
packages97
accessibilityseepackageaccessibility
declaration96
definition98
destinationdirectory106
hierarchy97
WOW! eBook
www.wowebook.org
java.lang342
members97
namingscheme98
packagedirectory106
runningcodefrom106
short-hand100
statementseepackagestatement
subpackages97
unnamed98
using99
palindromes382,434
parallelcode441
parameter
variablearity81
parameterlist439,444
parameterlistseeformalparameters
parameterpassing
byvalue72
variablearity81
parameters49
actual72
arrayelements78
final80
fixedarity81
formalseeformalparameters
implicit50
mainmethod86
passing72
primitives73
program86
references75
this50
WOW! eBook
www.wowebook.org
variablearity81
parentclass264
parentheses150
parseTypemethod352
parsing462,486
parsingnumericvalues352
partialimplementation293
passbyvalue72
passing
parameters72
references75
variablearityparameter81
paths
seeclasspath
path-separatorcharacter110
patternletters486,495,496
PearsonVUE509
performance24
period462,476
creating476
date-based476
equality478
getmethods478
immutable476
normalization479
parsing477
period-basedloop481
plus/minusmethods479
querying478
temporalarithmetic479
textualrepresentation477
thread-safe476
WOW! eBook
www.wowebook.org
withmethods479
Periodclass
seeperiod
persistentobjects138
polymorphism311,329,334
portability23
positionalorder414
positivezero165
postfixoperators151
precedencerules151
precision160
predefinedidentifiers29
predefinedliterals29
predicate436
Predicate<T>440,451
prefix30
030
0x30
primitivedatatypes
seeprimitivetypes
primitivetypes13,144
autoboxing348
unboxing350
seealsoprimitivevalues
primitivevalues
assignment159
equality181
passing73
printingvalues18
private11
privatemembers128
processofelimination510
WOW! eBook
www.wowebook.org
program
application16
arguments86
commandline86
compiling17
formatting35
running17
programarguments86
programoutput18
programmingtoaninterface417
prolepticyear464
promotion149
properties2
seealsoclassmembers
protected11
protectedmembers126
public17
publicmembers124
punctuators29
Q
quotationmark33,34
quotient168
R
radix
prefix30
seebase349
raggedarrays65
range
charactervalues38
floating-pointvalues39
integervalues38
WOW! eBook
www.wowebook.org
rangeofdate-basedvalues464
rangeoftime-basedvalues464
rankingcriteria414
realization296
reclaimingmemory384
reducingcomplexity335
referencetypes41,267
classes48
enumtypes87
referencevalues4
referencevariables40
references4,9,40,41,72
abstracttypes121
aliases75,183
array59,62,311
assignment159
casting149,320
dangling384
declaredtype268
downcasting145
dynamictype268
equality182
field385
interfacetype296
local384
narrowingconversions145
nullseenullreference
passing75
reachable384,385
super276
this50
upcasting145
WOW! eBook
www.wowebook.org
wideningconversions145
relationaloperators180
relativeadjusters474
reliability24
remainder168
remainderoperator
%168
removewhitespace369
replacingcharacters367
reservedidentifiers29
reservedkeywords29
const29
goto220
reservedliterals
false32
nullseenullreference
true32
resources387
resurrectingobjects385,391
returnstatement224
@returntag225
returntype
covariant
returnvalue7
reuseofcode264,334
rightassociativity152
rightmostbit155
rippleeffect334
robustness24,254
rolerelationship334
root
seeinheritancehierarchy
WOW! eBook
www.wowebook.org
runningaJavaapplication17
runtime
boundschecking61
runtimechecks148,418
Runtimeclass342,393
runtimeclass343
runtimeenvironment384
runtimestack
seeJVMstack
RuntimeException236
S
scientificnotation31
scope114
block117
catchclause244
class114
disjoint118
searching
arrays69
searchinginstring367
secure24
SecurityManagerclass342
selectionstatements200
semanticdefinition28
semicolon50
separators29,151
serialization138
services335
shadowing446
shallowcopying343
short30,38
short-circuit186
WOW! eBook
www.wowebook.org
evaluation187
signature52,273
simple
assignmentoperator158
if200
statement50
simpletypename97
simplicity23
singleexpression439
singleimplementationinheritance266,290,296
singlequote(‘)32,33
singlestaticimport101
single-linecomment3,35
skeletalsourcefile96
sortingarrays68
source
file15,98
filename96
filestructure96
spaces35
specialcharactervalues33
specialization10
specializedclasses266
stack3
stackframe
seemethodexecution
stacktrace232,235
seemethodexecution
StackOverflowError237
standarderrorstream235
standardout18
startswithcharacters368
WOW! eBook
www.wowebook.org
stateseeobjectstate
statementblock439,446
statements50
break221
compound50
conditional200
continue223
controlflow50,200
controltransfer219
declaration171,177,187
declarations50
do-while214
empty50
expression50,177
for(;;)215
for(:)217
if200
if-else201
iteration213
labeled220
return224
selection200
simple50
simpleif200
switch203
throw249
transfer219
try240
while213
static
membersseestaticmembers
WOW! eBook
www.wowebook.org
methods7,10,49
variableinitialization42
variablesseestaticvariables
static101,132,300
staticcode
seestaticcontext48
staticcontext48
staticfield10
staticfieldinitializers48
staticimport101
conflicts104
ondemand101
shadowstaticmembers103
singlestaticimport101
staticinitializerblock48,137,402
statickeyword402
staticmembers7,9,10,48
statictype
seedeclaredtype
staticvariables7,10,44
storingobjects138
strictfp166
stringbuilders176
appending376
capacity374,378
constructing374
deleting376
differenceswithstrings376
individualcharacters375
inserting376
joining366
length375
WOW! eBook
www.wowebook.org
thread-safety374
Stringclass
seestrings
stringconversion146,175
stringconversions370
stringliteralpool358
interned358
stringliterals357
caselabels208
hashvalue208
interned358
StringBufferclass374
seestringbuilders
thread-safe374
StringBuilderclass374,434
seestringbuilders
strings
appending376
buffers374
builders374
capacity378
changingcase364
compareTo363
comparing363
concatenation174,364
concatenationoperator+176
constructing374
contains368
conversions370
converttocharacterarray361
copyingcharacters361
creating357
WOW! eBook
www.wowebook.org
deleting376
differenceswithstringbuilders376
empty358
endswith368
equals363
extractingsubstrings369
findingindex367
formatted370
ignoringcaseincomparison363
immutable357
individualcharacters361,375
initializing357
inserting376
interned358
joining365,366
length361,375
lexicographicalordering363
literals34,357
mutable374
readcharacteratindex361
replacing367
searching367
startswith368
stringliteralpool358
substrings369
trimming369
stronglytypedlanguage148
subclass10,11,264
subinterface294
subpackages97
subsequence361
substringsearching367
WOW! eBook
www.wowebook.org
substrings367,369
subtypecovariance309,310
subtyperelationship418
subtypes293
subtype–supertyperelationship145
suffix
D31
F31
L30
super299
construct285
keyword272,276
reference276
superclass10,11,264
superclassconstructor54
superclass–subclassrelationship266
superinterfaces294
supertypes293
supertype–subtyperelationship267
supplementarycharacters357
suppressedexceptions235
switchstatement203
break205,206
defaultclause204
enumtypes209
usingstrings208
synchronized
methods136
syntacticallylegal28
System
out18
Systemclass342
WOW! eBook
www.wowebook.org
systemclock466
T
TABseehorizontaltab
tabs35
tabulators35
tags36
targettype450
targettyping451
telephonedirectoryorder363
temporalarithmetic474,479
temporalobjects
before/aftermethods469
combiningdateandtime466
commonmethodprefix463
comparing470
creatingwithfactorymethods464
date462
dateunits474
date-basedvalues462
date-time462
formatting486
getmethods468
immutable462
methodnamingconvention463
parsing486
plus/minusmethods474
querying468
rangeofdate-basedvalues464
rangeoftime-basedvalues464
temporalarithmetic474,479,480
temporalvalues464
thread-safe462
WOW! eBook
www.wowebook.org
time462
timeunits474
time-basedvalues462
withmethods470
temporalvalues464
TemporalAmountinterface479
terminatingloops221
ternaryconditionalexpressions
seealsoconditionalexpressions194
ternaryconditionaloperator151,194
textualrepresentation343
this
reference50
this()constructorcall282,406
ThreadDeath237
threads24,342,384
death232
exceptionpropagation232
JVMstack385
live384
notifying344
synchronization136
waiting344
thread-safe357,374,415,462
throwstatement249
Throwable233,342
throw-and-catchparadigm230
throwingexceptions230
throwsclause251
time
seetemporalobjects
timeunits474
WOW! eBook
www.wowebook.org
time-basedvalues462
tokens28
toStringmethod343,349
transferstatements219
transientvariables138
transitiverelation267
trimmethod369
trueliteral32
truth-values32,39
tryblock240
try-catch-finallyconstruct238
two’scomplement154
type
declared274
dynamic274
typecast148
typecastexpression320
typechecking450
typedeclarations96
typehierarchy145,267
typeimport
seeimport
typeparameter290,414,441
types
boolean37,39
byte30,38
casting148
char38
classesseeclasses
comparing321
compatibility148
double39
WOW! eBook
www.wowebook.org
exceptions233
float39
floating-point37,38
int30,38
integers38
integraltypes37
interface290
long30,38
parsing352
short30,38
wrappers346
seealsoclasses
type-safe315
type-safety416,417,418
typeValuemethod350,352
U
UML2
accessibility124
aggregation12
associations12
classes3
composition12
inheritance10
seealsodiagrams
unaryarithmeticoperators167
unarynumericpromotion149
unaryoperators150,151
unboxing350
do-whilestatement214
for(;;)statement215
for(:)statement218
WOW! eBook
www.wowebook.org
ifstatement200
if-elsestatement202
switchstatement204
whilestatement213
unboxingconversions145,146
uncaughtexceptions232
unchangeablevariables134
uncheckedconversionwarning416
uncheckedconversions146
uncheckedexceptions237
uncheckedwarnings145
underflow155,165
uni-catchclause239
Unicode32,38,354,357,363,434
UnifiedModelingLanguageseeUML
unreachablecode244
unsafecasts321
unsignedinteger353
UnsupportedTemporalTypeException480,490
unusedkeywords29
upcasting145
updateexpression215
usingarrays61
usingpackages99
usingvariables41
UTF-16357
supplementarycharacters357
V
valueOfmethod348,349,369
values155
constants30
WOW! eBook
www.wowebook.org
overflow155
underflow155
wrap-around155
seealsovariables
varargs81
variablearitycall84
variablearitymethod81
variablearityparameter81
variablecapture449
variabledeclarations41,117
variableinitialization8,43
variables4,41
blankfinal80,134
constantvalues133
defaultvalues42
effectivelyfinal448
final133
identifiers40
ininterfaces302
initializationseevariableinitialization
lifetime44
local117
parameters49,72
referencevariable41
references41
static7
storing138
transient138
volatile139
virtualmethodinvocation
seedynamicmethodlookup
VirtualMachineError237
WOW! eBook
www.wowebook.org
void17,224,347
voidreturn445
Voidwrapperclass346
volatilevariables139
voucher509
W
waitingthreads344
whilestatement213
whitespace35,369
whole–partrelationship267
wideningconversions
primitive144
references145
wideningreferenceconversions267,320
widerrange144
withers470
wrapperclasses38,342,343,346,347
internedvalues351
wrappertype146,164,177
X
xor189
Z
zero
negative165
positive165
zero-basedindex414
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org
WOW! eBook
www.wowebook.org