Vous êtes sur la page 1sur 322

12/10/2015 Javadevelopmentuserguide

Javadevelopmentuserguide

Contents
1.Javadevelopmentoverview
2.GettingStarted
2.1.Basictutorial
2.1.1.PreparingEclipse
2.1.2.CreatingyourfirstJavaproject
2.1.3.BrowsingJavaelementsusingthepackageexplorer
2.1.4.EditingJavaelements
2.1.4.1.OpeningaJavaeditor
2.1.4.2.Usingquickviews
2.1.4.3.Addingnewmethods
2.1.4.4.Usingcontentassist
2.1.4.5.Identifyingproblemsinyourcode
2.1.4.6.Usingcodetemplates
2.1.4.7.Organizingimportstatements
2.1.4.8.Usingthelocalhistory
2.1.4.9.Extractinganewmethod
2.1.5.CreatingaJavaclass
2.1.6.RenamingJavaelements
2.1.7.MovingandcopyingJavaelements
2.1.8.NavigatetoaJavaelement'sdeclaration
2.1.9.ViewingthetypeHierarchy
2.1.10.Searchingtheworkbench
2.1.11.Runningyourprograms
2.1.12.Debuggingyourprograms
2.1.13.Evaluatingexpressions
2.1.14.Evaluatingsnippets
2.1.15.UsingtheJavabrowsingperspective
2.1.16.WritingandrunningJUnittests
2.2.Projectconfigurationtutorial
2.2.1.Detectingexistinglayout
2.2.2.Organizingsources
2.2.3.Siblingproductsinacommonsourcetree
2.2.4.Overlappingproductsinacommonsourcetree
2.2.5.Productwithnestedtests
2.2.6.Productssharingacommonsourceframework
2.2.7.Productnestingresourcesinoutputdirectory
2.2.8.Projectusingasourceframeworkwithrestrictedaccess
2.3.EclipseandJ2SE5.0
2.4.EclipseandJava7
3.Concepts
3.1.JavaProjects
3.2.JavaBuilder
3.2.1.BuildClasspath
3.2.1.1.InclusionandExclusionPatterns
3.2.1.2.AccessRules
3.2.1.3.ClasspathVariables
3.3.JavaPerspectives
3.4.JavaViews
3.4.1.FilteringinJavaViews
3.4.2.SortinginJavaViews
3.4.3.JavaElementDecorations
3.4.4.PresentationOptionsforJavaViews
3.5.JavaEditor
3.6.QuickFixandAssist
3.7.Templates
3.7.1.Templatevariables
3.8.JavaSearch
3.9.RefactoringSupport
3.10.Debugger
3.11.Scrapbook
3.12.LocalDebugging
3.13.RemoteDebugging
3.14.Breakpoints
3.15.StringExternalization
4.Tasks
4.1.CustomizingtheDebuggerandConsole
4.1.1.Changingtheactiveperspectivewhenlaunching
4.1.2.Changingtheappearanceoftheconsoleview
4.2.CreatingJARFiles
4.2.1.CreatinganewJARfile
4.2.2.Settingadvancedoptions
4.2.3.DefiningtheJARfile'smanifest
4.2.4.RegeneratingaJARFile
4.2.5.CreatinganewrunnableJARfile
4.3.UsingtheLocalHistory
4.3.1.ComparingaJavaelementwithalocalhistoryedition
4.3.2.ReplacingaJavaelementwithalocalhistoryedition
4.3.3.Restoringadeletedworkbenchelement
4.4.ExternalizingStrings
4.4.1.Findingstringstoexternalize
4.4.2.Findingunusedandincorrectlyusedkeysinpropertyfiles
4.5.NavigatingtheWorkbench
4.5.1.Openinganeditorforaselectedelement
4.5.2.ShowinganelementinthePackageExplorerview
4.5.3.OpeningatypeinthePackageExplorerview
4.5.4.Openinganeditoronatype
4.5.5.Openingapackage
4.6.WorkingwithJREs

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 1/322
12/10/2015 Javadevelopmentuserguide
4.6.1.AssigningthedefaultJREfortheworkbench
4.6.2.AddinganewJREdefinition
4.6.3.ChoosingaJREforlaunchingaproject
4.6.4.DeletingaJREdefinition
4.7.RunningandDebugging
4.7.1.Breakpoints
4.7.1.1.AddingLineBreakpoints
4.7.1.2.RemovingLineBreakpoints
4.7.1.3.EnablingandDisablingBreakpoints
4.7.1.4.SettingMethodBreakpoints
4.7.1.5.ApplyingHitCounts
4.7.1.6.ManagingConditionalBreakpoints
4.7.1.7.CatchingJavaExceptions
4.7.1.8.CreatingExceptionBreakpointFilters
4.7.2.LocalDebugging
4.7.2.1.PreparingtoDebug
4.7.2.2.LaunchingaJavaprograminDebugMode
4.7.2.3.SuspendingThreads
4.7.2.4.ResumingThreads
4.7.2.5.Steppingthroughtheexecutionofaprogram
4.7.2.6.InspectingValues
4.7.2.7.Evaluatingexpressions
4.7.3.RemoteDebugging
4.7.3.1.UsingtheremoteJavaapplicationlaunchconfiguration
4.7.3.2.DisconnectingfromaVM
4.7.4.CreatingaJavaapplicationlaunchconfiguration
4.7.5.LaunchingaJavaprogram
4.7.6.LaunchingaJavaapplet
4.7.7.Settingexecutionarguments
4.7.8.Relaunchingaprogram
4.7.9.InspectingmemoryintheMemoryview
4.7.9.1.Addingavariable,expression,orregistertotheMemoryview
4.7.9.2.Addingmultiplememoryrenderingsandremovingrenderings
4.7.9.3.Workingwithmemorymonitors
4.7.9.4.Changingthecontentsofamemorylocation
4.7.9.5.Memoryviewpreferences
4.7.9.6.WorkingwithmultipleMemoryviews
4.7.9.7.RemovingmemorymonitorsfromtheMemoryview
4.8.UsingtheScrapbook
4.8.1.CreatingaJavaScrapbookPage
4.8.2.Inspectingtheresultofevaluatinganexpression
4.8.3.Displayingtheresultofevaluatinganexpression
4.8.4.Runninganexpression
4.8.5.Usingcodeassist
4.8.6.Scrapbookerrorreporting
4.8.6.1.Viewingcompilationerrors
4.8.6.2.Viewingruntimeexceptions
4.9.CompilingJavacode
4.9.1.Usingthebatchcompiler
4.9.2.Usingtheantjavacadapter
4.9.3.Excludingwarnings
4.10.ImprovingJavacodequality
4.10.1.Usingnullannotations
4.10.1.1.Interproceduralnullananlysis
4.10.1.2.Availableannotations
4.10.1.3.Setupofthebuildpath
4.10.1.4.Interpretationofnullannotations
4.10.1.5.Designbycontract:APIspecification
4.10.1.6.Completespecificationusinganextendedtypesystem
4.10.1.7.Compilermessagesexplained
4.10.1.8.Tipsformakingcodebetteranalyzable
4.10.1.9.Tipsforadoptingnullannotations
4.10.2.Usingnulltypeannotations
4.10.2.1.Generics
4.10.2.1.1.Typeparameters
4.10.2.1.2.Typevariables
4.10.2.1.3.Typearguments
4.10.2.2.Inference
4.10.2.3.Morelocations
4.10.2.4.Compatibility
4.10.2.4.1.Syntax
4.10.2.4.2.Projectconfiguration
4.10.2.4.3.Semantics
4.10.2.5.Compilermessagesexplained
4.10.3.Usingexternalnullannotations
4.10.3.1.Structureofexternalannotations
4.10.3.2.Configuringaprojecttouseexternalannotations
4.10.3.3.Creatingexternalannotations
4.10.3.4.Inspectingexternalannotations
4.10.3.5.Declarationannotationsvstypeannotations
4.10.4.Avoidingresourceleaks
4.10.5.Ensuringcompletenessofswitchstatements
4.11.UsingtheFormatterApplication
4.11.1.Runningtheformatterapplication
4.11.2.Generatingaconfigfilefortheformatterapplication
5.Reference
5.1.Breakpoints
5.1.1.ConditionOption
5.1.2.EnabledOption
5.1.3.ExceptionBreakpointCaughtOption
5.1.4.ExceptionBreakpointSuspendonSubclassOption
5.1.5.ExceptionBreakpointUncaughtOption
5.1.6.HitCountOption
5.1.7.MethodBreakpointEntryOption

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 2/322
12/10/2015 Javadevelopmentuserguide
5.1.8.MethodBreakpointExitOption
5.1.9.SuspendPolicyOption
5.1.10.WatchpointModificationOption
5.1.11.WatchpointAccessOption
5.2.MenusandActions
5.2.1.FileMenuActions
5.2.2.EditMenuActions
5.2.3.SourceMenuActions
5.2.4.RefactorMenuActions
5.2.5.NavigateMenuActions
5.2.6.SearchMenuActions
5.2.7.ProjectMenuActions
5.2.8.RunMenuActions
5.2.9.JavaToolbarActions
5.2.10.RunandDebugToolbarActions
5.2.11.JavaEditorActions
5.3.Preferences
5.3.1.Java
5.3.1.1.Appearance
5.3.1.1.1.MemberSortOrder
5.3.1.1.2.TypeFilters
5.3.1.2.BuildPath
5.3.1.2.1.ClasspathVariables
5.3.1.2.2.UserLibraries
5.3.1.3.CodeStyle
5.3.1.3.1.CleanUp
5.3.1.3.2.CodeTemplates
5.3.1.3.3.Formatter
5.3.1.3.4.OrganizeImports
5.3.1.4.Compiler
5.3.1.4.1.Building
5.3.1.4.2.Errors/Warnings
5.3.1.4.3.Javadoc
5.3.1.4.4.TaskTags
5.3.1.5.Debug
5.3.1.5.1.DetailFormatters
5.3.1.5.2.HeapWalking
5.3.1.5.3.LogicalStructures
5.3.1.5.4.PrimitiveDisplayOptions
5.3.1.5.5.StepFiltering
5.3.1.6.Editor
5.3.1.6.1.ContentAssist
5.3.1.6.1.1.Advanced
5.3.1.6.1.2.Favorites
5.3.1.6.2.Folding
5.3.1.6.3.Hovers
5.3.1.6.4.MarkOccurrences
5.3.1.6.5.SaveActions
5.3.1.6.6.SyntaxColoring
5.3.1.6.7.Templates
5.3.1.6.7.1.TemplateEditing
5.3.1.6.8.Typing
5.3.1.7.InstalledJREs
5.3.1.7.1.ExecutionEnvironments
5.3.1.8.JUnit
5.3.1.9.PropertiesFilesEditor
5.3.2.Run/Debug
5.3.2.1.Console
5.3.2.2.Launching
5.3.2.2.1.DefaultLaunchers
5.3.2.2.2.LaunchConfigurations
5.3.2.3.Perspectives
5.3.2.4.StringSubstitution
5.3.2.5.ViewManagement
5.4.PropertyPages
5.4.1.JavadocLocation
5.4.2.JavaBuildPath
5.4.3.JavaCompiler
5.4.4.JavaTaskTags
5.4.5.SourceAttachment
5.4.6.Run/Debug
5.5.Refactoring
5.5.1.RefactorActions
5.5.2.RefactorWizard
5.5.3.ExtractMethodErrors
5.6.Search
5.6.1.JavaSearchTab
5.6.2.JavaSearchActions
5.7.Toolbar
5.7.1.JavaToolbarActions
5.7.2.JavaEditorToolbarActions
5.7.3.RunandDebugToolbarActions
5.8.Views
5.8.1.BreakpointsView
5.8.1.1.Access
5.8.1.2.AddJavaExceptionBreakpoint
5.8.1.3.BreakpointProperties
5.8.1.4.Caught
5.8.1.5.CollapseAll
5.8.1.6.Copy
5.8.1.7.Disable
5.8.1.8.Enable
5.8.1.9.Entry
5.8.1.10.Exit

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 3/322
12/10/2015 Javadevelopmentuserguide
5.8.1.11.ExpandAll
5.8.1.12.ExportBreakpoints
5.8.1.13.GotoFileforBreakpoint
5.8.1.14.GroupBy
5.8.1.15.HitCount
5.8.1.16.ImportBreakpoints
5.8.1.17.LinkwithDebugView
5.8.1.18.Modification
5.8.1.19.Paste
5.8.1.20.RemoveSelectedBreakpoints
5.8.1.21.RemoveAllBreakpoints
5.8.1.22.SelectAll
5.8.1.23.SelectDefaultWorkingSet
5.8.1.24.ShowQualifiedNames
5.8.1.25.ShowSupportedBreakpoints
5.8.1.26.SkipAllBreakpoints
5.8.1.27.SuspendPolicy
5.8.1.28.WorkingSets...
5.8.1.29.Uncaught
5.8.2.ConsoleView
5.8.2.1.CVSConsole
5.8.2.1.1.Copy
5.8.2.1.2.Cut
5.8.2.1.3.Find/Replace
5.8.2.1.4.OpenLink
5.8.2.1.5.Paste
5.8.2.1.6.SelectAll
5.8.2.2.ProcessConsole
5.8.2.2.1.Copy
5.8.2.2.2.Cut
5.8.2.2.3.ConsolePreferences
5.8.2.2.4.Find/Replace
5.8.2.2.5.Paste
5.8.2.2.6.RemoveAllTerminatedLaunches
5.8.2.2.7.RemoveLaunch
5.8.2.2.8.SelectAll
5.8.2.2.9.ShowConsoleWhenStandardOutChanges
5.8.2.2.10.ShowConsoleWhenStandardErrorChanges
5.8.2.2.11.Terminate
5.8.2.3.StacktraceConsole
5.8.2.3.1.AutoformatConsole
5.8.2.3.2.Copy
5.8.2.3.3.Cut
5.8.2.3.4.Find/Replace
5.8.2.3.5.Format
5.8.2.3.6.OpenLink
5.8.2.3.7.Paste
5.8.2.3.8.SelectAll
5.8.2.4.CleartheConsole
5.8.2.5.DisplaySelectedConsole
5.8.2.6.OpenConsole
5.8.2.7.PintheConsole
5.8.2.8.ScrollLock
5.8.3.DebugView
5.8.3.1.ExecutionControlCommands
5.8.3.1.1.Resume
5.8.3.1.2.StepInto
5.8.3.1.3.StepOver
5.8.3.1.4.StepReturn
5.8.3.1.5.Suspend
5.8.3.1.6.Terminate
5.8.3.1.7.Terminate/DisconnectAll
5.8.3.1.8.TerminateandRelaunch
5.8.3.1.9.TerminateandRemove
5.8.3.2.CopyStack
5.8.3.3.Disconnect
5.8.3.4.DroptoFrame
5.8.3.5.EditLaunchConfiguration
5.8.3.6.EditSourceLookup
5.8.3.7.EditStepFilters
5.8.3.8.FilterPackage
5.8.3.9.FilterType
5.8.3.10.Find...
5.8.3.11.LookupSource
5.8.3.12.OpenDeclaredType
5.8.3.13.OpenDeclaredTypeHierarchy
5.8.3.14.Properties
5.8.3.15.Relaunch
5.8.3.16.RemoveAllTerminated
5.8.3.17.ShowMonitors
5.8.3.18.ShowQualifiedNames
5.8.3.19.ShowSystemThreads
5.8.3.20.ShowThreadGroups
5.8.3.21.UseStepFilters
5.8.4.DisplayView
5.8.4.1.Clear
5.8.4.2.ContentAssist
5.8.4.3.CopySelectedStatements
5.8.4.4.CutSelectedStatements
5.8.4.5.Display
5.8.4.6.ExecuteSelectedStatement
5.8.4.7.Find/Replace
5.8.4.8.Inspect
5.8.4.9.Paste

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 4/322
12/10/2015 Javadevelopmentuserguide
5.8.4.10.SelectAll
5.8.5.ExpressionsView
5.8.5.1.DetailPane
5.8.5.1.1.AssignValue
5.8.5.1.2.ContentAssist
5.8.5.1.3.Cut
5.8.5.1.4.Copy
5.8.5.1.5.Display
5.8.5.1.6.Execute
5.8.5.1.7.Find/Replace
5.8.5.1.8.ForceReturn
5.8.5.1.9.Inspect
5.8.5.1.10.MaxLength
5.8.5.1.11.Paste
5.8.5.1.12.SelectAll
5.8.5.1.13.WrapText
5.8.5.2.ViewDisplayCommands
5.8.5.2.1.ShowContants
5.8.5.2.2.ShowLogical
5.8.5.2.3.ShowNull
5.8.5.2.4.ShowQualified
5.8.5.2.5.ShowReferences
5.8.5.2.6.ShowStatic
5.8.5.2.7.ShowTypeNames
5.8.5.3.ViewLayoutCommands
5.8.5.3.1.ShowColumns
5.8.5.3.2.SelectColumns
5.8.5.3.3.HorizontalLayout
5.8.5.3.4.VerticalLayout
5.8.5.3.5.ViewOnly
5.8.5.4.AddWatchExpression
5.8.5.5.AllInstances
5.8.5.6.AllReferences
5.8.5.7.ChangeVariableValue
5.8.5.8.CollapseAll
5.8.5.9.CopyExpressions
5.8.5.10.ConverttoWatchExpression
5.8.5.11.DisableSelectedWatchExpression
5.8.5.12.EditWatchExpression
5.8.5.13.EnableSelectedWatchExpression
5.8.5.14.Find...
5.8.5.15.InspectVariable
5.8.5.16.JavaPreferences
5.8.5.17.ReevaluateWatchExpression
5.8.5.18.RemoveSelectedExpressions
5.8.5.19.RemoveAllExpressions
5.8.5.20.SelectAll
5.8.5.21.ToggleWatchpoint
5.8.6.PackageExplorerview
5.8.6.1.JavaElementFiltersdialog
5.8.7.VariablesView
5.8.7.1.DetailPane
5.8.7.1.1.AssignValue
5.8.7.1.2.ContentAssist
5.8.7.1.3.Cut
5.8.7.1.4.Copy
5.8.7.1.5.Display
5.8.7.1.6.Execute
5.8.7.1.7.Find/Replace
5.8.7.1.8.ForceReturn
5.8.7.1.9.Inspect
5.8.7.1.10.MaxLength
5.8.7.1.11.Paste
5.8.7.1.12.SelectAll
5.8.7.1.13.WrapText
5.8.7.2.ViewDisplayCommands
5.8.7.2.1.ShowContants
5.8.7.2.2.ShowLogical
5.8.7.2.3.ShowNull
5.8.7.2.4.ShowQualified
5.8.7.2.5.ShowReferences
5.8.7.2.6.ShowStatic
5.8.7.2.7.ShowTypeNames
5.8.7.3.ViewLayoutCommands
5.8.7.3.1.ShowColumns
5.8.7.3.2.SelectColumns
5.8.7.3.3.HorizontalLayout
5.8.7.3.4.VerticalLayout
5.8.7.3.5.ViewOnly
5.8.7.4.AllInstances
5.8.7.5.AllReferences
5.8.7.6.ChangeVariableValue
5.8.7.7.CollapseAll
5.8.7.8.CopyVariables
5.8.7.9.CreateWatchExpression
5.8.7.10.Find...
5.8.7.11.InspectVariable
5.8.7.12.JavaPreferences
5.8.7.13.SelectAll
5.8.7.14.ToggleWatchpoint
5.8.8.JavaOutlineView
5.8.9.JavaScrapbookPage
5.8.10.TypeHierarchyView
5.8.11.CallHierarchyView

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 5/322
12/10/2015 Javadevelopmentuserguide
5.8.12.JUnitView
5.8.13.JavadocView
5.9.JavaEditor
5.9.1.JavaContentAssist
5.9.2.JavaFormatter
5.9.3.Quickfix
5.9.4.Quickassist
5.9.5.Suppresswarnings
5.10.WizardsandDialogs
5.10.1.CreateNewElements
5.10.1.1.NewJavaProjectWizard
5.10.1.1.1.JavaBuildPathPage
5.10.1.1.2.AttachingSourcetoJARFilesandVariables
5.10.1.2.NewJavaPackageWizard
5.10.1.3.NewJavaClassWizard
5.10.1.4.NewJavaEnumWizard
5.10.1.5.NewJavaInterfaceWizard
5.10.1.6.NewJavaAnnotationWizard
5.10.1.7.NewSourceFolderWizard
5.10.1.8.NewJavaScrapbookPageWizard
5.10.2.ExportBreakpoints
5.10.3.ExportLaunchConfigurations
5.10.4.ExternalizeStringswizard
5.10.5.ImportBreakpoints
5.10.6.ImportLaunchConfigurations
5.10.7.JARFileExporter
5.10.8.JavadocGeneration
5.10.9.RunnableJARFileExporter
5.10.10.JavaElementFilters
5.10.11.OpenTypeDialog
5.10.12.CreateGetterandSetter
5.10.13.GeneratetoString()
5.10.13.1.FormatTemplates
5.10.13.2.CodeStyles
5.10.13.3.ContentListing
5.10.14.OverrideMethods
5.11.FrequentlyAskedQuestions:JDT
5.12.Glossary
5.13.Icons
5.14.AvailableQuickAssists
5.15.AvailableQuickFixes
5.16.ListofJDTKeyBindings
6.Tipsandtricks
6.1.Editing
6.2.Refactoring
6.3.Searching
6.4.Navigation
6.5.Views
6.6.Miscellaneous
6.7.Debugging

1.Javadevelopmentoverview
TheJDTprojectprovidesthetoolpluginsthatimplementaJavaIDEsupportingthedevelopmentofanyJavaapplication,includingEclipseplugins.ItaddsaJavaprojectnature
andJavaperspectivetotheEclipseWorkbenchaswellasanumberofviews,editors,wizards,builders,andcodemergingandrefactoringtools.TheJDTprojectallowsEclipseto
beadevelopmentenvironmentforitself.
TrytheBasictutorialtogetafirstimpression.DiscovermoreintheTipsandTrickssectionandlearnaboutthelatestfeaturesinWhat'snew.

2.1.Basictutorial
ThistutorialprovidesastepbystepwalkthroughoftheJavadevelopmenttools.
NextSection:Preparingtheworkbench

2.1.1.PreparingEclipse
Inthissection,youwillverifythatEclipseisproperlysetupforJavadevelopment.
Thefollowingisassumed:
YouarestartingwithanewEclipseinstallationwithdefaultsettings.
YouarefamiliarwiththebasicEclipseworkbenchmechanisms,suchasviewsandperspectives.
Ifyou'renotfamiliarwiththebasicworkbenchmechanisms,pleaseseetheGettingStartedchapteroftheWorkbenchUserGuide.

VerifyingJREinstallationandclasspathvariables
1. IfyoustillseetheEclipseWelcomepage,clickthearrowicontobeginusingEclipse.
2. Selectthemenuitem Window>Preferences...toopentheworkbenchpreferences.
3. Selectthe Java>InstalledJREspreferencepagetodisplaytheinstalledJavaRuntimeEnvironments.ConfirmthataJREhasbeendetected.Bydefault,theJREused
toruntheworkbenchwillbeusedtobuildandrunJavaprograms.ItshouldappearwithacheckmarkinthelistofinstalledJREs.WerecommendthatyouuseaJavaSDK
insteadofaJRE.AnSDKisdesignedfordevelopmentandcontainsthesourcecodefortheJavalibrary,easingdebugging.AdditionalSDKscanbeaddedbysearchingthe
harddriveforinstalledSDKs.Todoso,simplyclicktheSearch...buttonandspecifyarootfolderforthesearch.
Ifyouworkwithcodethatdoesnotyetusegenerics(aswedointhistutorial),werecommendthatyouinstallaJavaSDK1.4aswell,butleavethemostrecentversion
checkedasdefault.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 6/322
12/10/2015 Javadevelopmentuserguide

4. Selectthe General>Workspacepreferencepage.ConfirmthattheBuildautomaticallyoptionischecked.

5. Selectthe Java>BuildPathpreferencepage.ConfirmthatSourceandoutputfolderissettoFolders.

6. Selectthe Java>Editorpreferencepage.ConfirmthatoptionReportproblemsasyoutypeischecked.

7. Selectthe Java>Compilerpreferencepage.ConfirmthatoptionCompilercompliancelevelmatchesyourdefaultJREversion(usually1.6).

8. ClickonOKtosavethepreferences.
NextSection:CreatingyourfirstJavaproject

Javaprojects
Classpathvariables
Buildclasspath

WorkingwithJREs

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 7/322
12/10/2015 Javadevelopmentuserguide
InstalledJREsPreferences
JavaEditorPreferences

2.1.2.CreatingyourfirstJavaproject
Inthissection,youwillcreateanewJavaproject.YouwillbeusingJUnitasyourexampleproject.JUnitisanopensourceunittestingframeworkforJava.

GettingtheSampleCode(JUnit)
FirstyouneedtodownloadtheJUnitsourcecode.
1. ClickheretodownloadtheJUnitsourcecode.
2. Savethearchive(donotextract)toadirectoryfromnowonreferencedas<Downloads>.

Creatingtheproject
1. InsideEclipseselectthemenuitemFile>New>Project....toopentheNewProjectwizard
2. SelectJavaProjectthenclickNexttostartthe NewJavaProjectwizard:

Onthispage,
type"JUnit"intheProjectnamefield,and
select"J2SE1.4"intheUseanexecutionenvironmentJREfield.
ThenclickFinish.
3. InthePackageExplorer,expandtheJUnitprojectandselectthesourcefoldersrc.
4. SelectthemenuitemFile>Import....
5. ExpandGeneral,selectArchivefile,andclickNext.
6. ClicktheBrowsebuttonnexttotheArchivefilefieldandbrowsetoselect
<Downloads>/junit381src.jar
Note:Thisstepassumesthatyoufollowedsteps1and2intheGettingtheSampleCodesectionabove.
7. IntheImportwizard,expandtherootnode,pressDeselectAllandselectonlythejunitnode.Youcanexpandandselectelementswithinthejunitdirectoryontheleftpane
toviewtheindividualresourcesthatyouareimportingontherightpane.Note:Donotdeselectanyoftheresourcesinthejunitdirectoryatthistime.Youwillneedallofthese
resourcesinthetutorial.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 8/322
12/10/2015 Javadevelopmentuserguide

8. MakesurethattheJUnitproject'ssourcefolderappearsinthedestinationIntofolderfield.ThenclickFinish.Intheimportprogressindicator,noticethattheimported
resourcesarecompiledastheyareimportedintotheworkbench.ThisisbecausetheBuildautomaticallyoptionischeckedontheWorkbenchpreferencespage.
9. InthePackageExplorerview,expandtheJUnitprojectandthesrcfoldertoviewtheJUnitpackages.

NextSection:BrowsingJavaelementsusingthepackageexplorer

Javaprojects
Javaviews

NewJavaProjectWizard
PackageExplorerView

2.1.3.BrowsingJavaelementsusingthepackageexplorer
Inthissection,youwillbrowseJavaelementswithintheJUnitproject.
1. InthePackageExplorerview,makesuretheJUnitprojectandthesourcefolderareexpandedsoyoucanseethepackages.
2. Expandthepackagejunit.frameworktoseetheJavafilescontainedinthepackage.
3. ExpandtheJavafileTestCase.java.NotethatthePackageExplorershowsJavaspecificsubelementsofthesourcecodefile.Thepublictypeanditsmembers(fieldsand
methods)appearinthetree.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 9/322
12/10/2015 Javadevelopmentuserguide

NextSection:OpeningaJavaeditor

Javaviews

PackageExplorerView

2.1.4.1.OpeningaJavaeditor
Inthissection,youwilllearnhowtoopenaneditorforJavafiles.YouwillalsolearnaboutsomeofthebasicJavaeditorfeatures.
1. Expandthepackagejunit.samplesandselectthefileVectorTest.java.YoucanopenVectorTest.javaintheJavaeditorbydoubleclickingonit.Ingeneralyoucanopena
JavaeditorforJavafiles,types,methodsandfieldsbysimplydoubleclickingonthem.Forexample,toopentheeditordirectlyonthemethodtestClonedefinedin
VectorTest.java,expandthefileinthePackageExploreranddoubleclickonthemethod.
2. Noticethesyntaxhighlighting.DifferentkindsofelementsintheJavasourcearerenderedinuniquecolors.ExamplesofJavasourceelementsthatarerendereddifferently
are:
Regularcomments
Javadoccomments
Keywords
Strings

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 10/322
12/10/2015 Javadevelopmentuserguide

3. LookattheOutlineview.ItdisplaysanoutlineoftheJavafileincludingthepackagedeclaration,importdeclarations,fields,typesandmethods.TheOutlineviewusesicons
toannotateJavaelements.Forexample,iconsindicatewhetheraJavaelementisstatic( ),abstract( ),orfinal( ).Differenticonsshowyouwhetheramethodoverridesa
methodfromabaseclass( )orwhenitimplementsamethodfromaninterface( ).

4. ToggletheHideFields,HideStaticMembers,andHideNonPublicMembersbuttonsintheOutlineviewtoolbartofiltertheview'sdisplay.Beforegoingtothenextstep
makesurethattheHideNonPublicMembersandHideStaticFieldsandMethodsbuttonsarenotpressed.

5. IntheOutlineview,selectdifferentelementsandnotethattheyareagaindisplayedinawholefileviewintheeditor.TheOutlineviewselectionnowcontainsarangeindicator
ontheverticalrulerontheleftborderoftheJavaeditorthatindicatestherangeoftheselectedelement.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 11/322
12/10/2015 Javadevelopmentuserguide

NextSection:Usingquickviews

Javaviews
Javaeditor
SortingelementsinJavaviews

JavaOutlineView
JavaEditorPreferences

2.1.4.2.Usingquickviews
Inthissection,youwillbeintroducedtothequickoutlineview.Quickviewsareinplaceviewswhichareshownontopoftheeditorareaandcaneasilybecontrolledusingthe
keyboard.AsecondquickviewwillbeintroducedintheTypeHierarchysection.

QuickOutline
TousethequickoutlineviewintheJavaeditor:
1. Openjunit.samples.VectorTest.javafileintheJavaeditorifyoudonotalreadyhaveitopen.
2. PressCtrl+OorselectNavigate>QuickOutlineandyouwillseeaninplaceoutlineofthecurrentsourcefile.

3. PressCtrl+Oasecondtimeandallinheritedfields,typesandmethodsareshownaswell(forthetypesmarkedwith ontheleft).Inheritedmembersareshowninblue.
4. Starttypingwhilethequickoutlineviewisshowntofilterthelistofdisplayedelements.Further,usethearrowkeystonavigateintheoutlineviewandpressEntertoreveal
theselectedelementintheJavaeditor.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 12/322
12/10/2015 Javadevelopmentuserguide

5. Clickthetriangleintheupperrightcornertoseethequickviewmenu:


Themenuitemscanbedividedinto3categories:
PositionAllowsyoutoresizeandmovethequickviewandtorememberthesesettings
FilterDefinefilterssothatnotallmembersareshowninthequickoutline.
SortSortthemembersbytheirdefiningtypeoralphabetically.
Note:Ctrl+OalwaysopenstheoutlineforthecurrentJavaeditor.PressCtrl+F3toopenthequickoutlineforthecurrentlyselectedtype.
NextSection:Addingnewmethods

2.1.4.3.Addingnewmethods
1. StartaddingamethodbytypingthefollowingattheendoftheVectorTest.javafile(butbeforetheclosingbraceofthetype)intheJavaeditor:
publicvoidtestSizeIsThree()
Assoonasyoutypethemethodnameintheeditorarea,thenewmethodappearsatthebottomoftheOutlineview.

Inaddition,
errorannotations(redboxes)appearintheoverviewrulerpositionedontherighthandsideoftheeditor,

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 13/322
12/10/2015 Javadevelopmentuserguide
erroriconsappearintheverticalrulerpositionedontheleftoftheeditor,
anerrorindicatorappearsinthetoprightcorneroftheeditor,
errorsaremarkedinthetext.
Theseerrorannotationsindicatethatthecompilationunitiscurrentlynotcorrect.Ifyouhoverovertheerrorinthetext,atooltipappears:Syntaxerrorontoken")",{expected
afterthistoken.Thisiscorrectsincethemethoddoesn'thaveabodyyet.Notethaterrorannotationsintheeditorareupdatedasyoutype.Thisbehaviorcanbecontrolledvia
theReportproblemsasyoutypeoptionlocatedonthe Java>Editorpreferencepage.

2. ClicktheSavebutton.ThecompilationunitiscompiledautomaticallyanderrorsappearinthePackageExplorerview,intheProblemsviewandontheverticalruler(lefthand
sideoftheeditor).InthePackageExplorerview,theerrorsarepropagateduptotheprojectofthecompilationunitcontainingtheerror.

3. Completethenewmethodbytypingthefollowing:
{
//TODO:Checksize
Notethattheclosingcurlybracehasbeeninsertedautomatically.
4. Savethefile.Noticethattheerrorindicatorsdisappearsincethemissingbracehasbeenadded.
NextSection:Usingcontentassist

Javaeditor

JavaEditorPreferences

2.1.4.4.Usingcontentassist
Inthissectionyouwillusecontentassisttofinishwritinganewmethod.Openthefilejunit.samples/VectorTest.javaintheJavaeditorifyoudonotalreadyhaveitopenandselect
thetestSizeIsThree()methodintheOutlineview.Ifthefiledoesn'tcontainsuchamethodseeAddingnewmethodsforinstructionsonhowtoaddthismethod.
1. ReplacetheTODOcommentwiththefollowinglines.
assertTrue(fFull.size()==3)
Vectorv=newVector()
for(inti=0i<3i++)
v.addElement(newObject())
assert
2. Withyourcursorattheendofthewordassert,pressCtrl+Spacetoactivatecontentassist.Thecontentassistwindowwithalistofproposalswillappear.Scrollthelistto
seetheavailablechoices.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 14/322
12/10/2015 Javadevelopmentuserguide

3. Withthecontentassistwindowstillactive,typetheletter't'inthesourcecodeafterassert(withnospaceinbetween).Thelistisnarrowedandonlyshowsentriesstarting
with'assert'.SingleclickvariousitemsinthelisttoviewanyavailableJavadochelpforeachitem.

4. SelectassertTrue(boolean)fromthelistandpressEnter.ThecodefortheassertTrue(boolean)methodisinserted.
5. Completethelinesothatitreadsasfollows:
assertTrue(v.size()==fFull.size())
6. Savethefile.
NextSection:Identifyingproblemsinyourcode

Javaeditor

JavaContentAssist
JavaEditorPreferences

2.1.4.5.Identifyingproblemsinyourcode
Inthissection,youwillreviewthedifferentindicatorsforidentifyingproblemsinyourcode.
BuildproblemsaredisplayedintheProblemsviewandannotatedintheverticalrulerofyoursourcecode.
1. Openjunit.framework/TestCase.javaintheeditorfromthePackageExplorerview.
2. Addasyntaxerrorbydeletingthesemicolonattheendofthepackagedeclarationinthesourcecode.

3. ClicktheSavebutton.Theprojectisrebuiltandtheproblemisindicatedinseveralways:
IntheProblemsview,theproblemsarelisted,
InthePackageExplorerview,theTypeHierarchyortheOutlineview,problemticksappearontheaffectedJavaelementsandtheirparentelements,
Intheeditor'sverticalruler,aproblemmarkerisdisplayedneartheaffectedline,
Squigglylinesappearunderthewordwhichmighthavecausedtheerror,and
Theeditortabisannotatedwithaproblemmarker.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 15/322
12/10/2015 Javadevelopmentuserguide

4. Youcanhoveroverthemarkedwordintheeditortoviewadescriptionoftheproblem.Youcanalsohoverovertheproblemmarkersintheverticaloroverviewrulers.

5. ClicktheClose("X")buttonontheeditor'stabtoclosetheeditor.
6. IntheProblemsview,selectaprobleminthelist.OpenitscontextmenuandselectGoTo.Thefileisopenedintheeditoratthelocationoftheproblem.

7. Correcttheproblemintheeditorbyaddingthesemicolon.ClicktheSavebutton.Theprojectisrebuiltandtheproblemindicatorsdisappear.
8. IntheOutlineview,selectthemethodgetName().Theeditorwillscrolltothismethod.
9. OnthefirstlineofthemethodchangethereturnedvariablefNametofTestName.Whileyoutype,aproblemhighlightunderlineappearsonfTestName,toindicateaproblem.
Hoveringoverthehighlightedproblemwilldisplayadescriptionoftheproblemandapplicablequickfixes.
10. Onthemarkerbaralightbulbmarkerappears.Thelightbulbsignalsthatcorrectionproposalsareavailableforthisproblem.

11. Clicktoplacethecursorontothehighlightederror,andchooseQuickFixfromtheEditmenubar.YoucanalsopressCtrl+1orleftclickthelightbulb.Aselectiondialog
appearswithpossiblecorrections.

12. Select'ChangetofName'tofixtheproblem.Theproblemhighlightlinewilldisappearasthecorrectionisapplied.
13. Closethefilewithoutsaving.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 16/322
12/10/2015 Javadevelopmentuserguide
14. Youcanconfigurehowproblemsareindicatedonthe General>Editors>TextEditors>Annotationspreferencepage.
NextSection:Usingcodetemplates

Javaeditor
Javaviews
Javabuilder

Editorpreferencepage
Quickfix

2.1.4.6.Usingcodetemplates
Inthissectionyouwillusecontentassisttofillinatemplateforacommonloopstructure.Openjunit.samples/VectorTest.javafileintheJavaeditorifyoudonotalreadyhaveit
open.
1. Startaddinganewmethodbytypingthefollowing:
publicvoidtestValues(){
Integer[]expected=newInteger[3]
for
2. Withthecursorattheendoffor,pressCtrl+Spacetoenablecontentassist.Youwillseealistofcommontemplatesfor"for"loops.Whenyousingleclickatemplate,or
selectitwiththeUporDownarrowkeys,you'llseethecodeforthetemplateinitshelpmessage.Notethatthelocalarraynameisguessedautomatically.

3. ChoosetheforiterateoverarrayentryandpressEntertoconfirmthetemplate.Thetemplatewillbeinsertedinyoursourcecode.

4. Nextwechangethenameoftheindexvariablefromitoe.Todososimplypresse,astheindexvariableisautomaticallyselected.Observethatthenameoftheindex
variablechangesatallplaces.Wheninsertingatemplateallreferencestothesamevariableareconnectedtoeachother.Sochangingonechangesalltheothervaluesas
well.

5. Pressingthetabkeymovesthecursortothenextvariableofthecodetemplate.Thisisthearrayexpected.

Sincewedon'twanttochangethename(itwasguessedrightbythetemplate)wepresstabagain,whichleavesthetemplatesincetherearen'tanyvariableslefttoedit.
6. Completetheforloopasfollows:
for(inte=0e<expected.lengthe++){
expected[e]=newInteger(e+1)
}
Integer[]actual=to
7. Withthecursorattheendofto,pressCtrl+Spacetoenablecontentassist.PicktoarrayconvertcollectiontoarrayandpressEntertoconfirmtheselection(or
doubleclicktheselection).

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 17/322
12/10/2015 Javadevelopmentuserguide
Thetemplateisinsertedintheeditorandtypeishighlightedandselected.

8. OverwritetheselectionbytypingInteger.Thetypeofarrayconstructorchangeswhenyouchangetheselection.
9. PressTabtomovetheselectiontocollectionandoverwriteitbytypingfFull.

10. Addasemicolonandthefollowinglinesofcodetocompletethemethod:
assertEquals(expected.length,actual.length)
for(inti=0i<actual.lengthi++)
assertEquals(expected[i],actual[i])
11. Savethefile.
NextSection:Organizingimportstatements

Javaeditor
Templates

TemplatesPreferences
JavaEditorPreferences

2.1.4.7.Organizingimportstatements
Inthissectionyouwillorganizetheimportdeclarationsinyoursourcecode.Openjunit.samples/VectorTest.javafileintheJavaeditorifyoudonotalreadyhaveitopen.
1. Bydefault,importdeclarationsarehiddenintheOutlineview.SelectViewMenu>Filters...anduncheckImportdeclarations.ClickOKtomakethemvisibleintheOutline
view.
2. DeletetheimportdeclarationsbyselectingthemintheOutlineviewandselectingDeletefromthecontextmenu.ConfirmtheresultingdialogwithYes.Youwillseenumerous
compilewarningsintheverticalrulersincethetypesusedinthemethodarenolongerimported.

3. Fromthecontextmenuintheeditor,selectSource>OrganizeImports.Therequiredimportstatementsareaddedtothebeginningofyourcodebelowthepackage
declaration.

YoucanalsochooseOrganizeImportsfromthecontextmenuoftheimportdeclarationsintheOutlineview.
Note:Youcanspecifytheorderoftheimportdeclarationsusingthe Java>CodeStyle>OrganizeImportspreferencepage.
4. Savethefile.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 18/322
12/10/2015 Javadevelopmentuserguide
NextSection:Usingthelocalhistory

Javaeditor

OrganizeImportsPreferences

2.1.4.8.Usingthelocalhistory
Inthissection,youwillusethelocalhistoryfeaturetoswitchtoapreviouslysavedversionofanindividualJavaelement.
1. Openjunit.samples/VectorTest.javafileintheJavaeditorandselectthemethodtestCapacity()intheOutlineview.
2. Changethecontentofthemethodsothatthe'for'statementsreadsas:
for(inti=0i<99i++)
SavethefilebypressingCtrl+S.
3. IntheOutlineview,selectthemethodtestCapacity(),andfromitscontextmenu,selectReplaceWith>ElementfromLocalHistory.
4. IntheReplaceJavaElementfromLocalHistorydialog,theLocalHistorylistshowsthevarioussavedstatesofthemethod.TheJavaSourceComparepaneshowsdetails
ofthedifferencesbetweentheselectedhistoryresourceandtheexistingworkbenchresource.

5. Inthetoppane,selectthepreviousversion,andclicktheReplacebutton.IntheJavaeditor,themethodisreplacedwiththeselectedhistoryversion.
6. Savethefile.
7. Besidereplacingamethod'sversionwithapreviousoneyoucanalsorestoreJavaelementsthatweredeleted.Again,selectthemethodtestCapacity()intheOutlineview,
andfromitscontextmenu,selectDelete.ConfirmtheresultingdialogwithYesandsavethefile.
8. NowselectthetypeVectorTestintheOutlineview,andfromitscontextmenu,selectRestorefromLocalHistory....SelectandcheckthemethodtestCapacity()inthe
AvailableJavaElementspane.Asbefore,theLocalHistorypaneshowstheversionssavedinthelocalhistory.

9. IntheLocalHistorypane,selecttheearlierworkingversionandthenclickRestore.
NextSection:Extractinganewmethod

Javaeditor

Usingthelocalhistory

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 19/322
12/10/2015 Javadevelopmentuserguide

2.1.4.9.Extractinganewmethod
Inthissection,youwillimprovethecodeoftheconstructorofjunit.framework.TestSuite.Tomaketheintentofthecodeclearer,youwillextractthecodethatcollectstestcases
frombaseclassesintoanewmethodcalledcollectInheritedTests.
1. Inthejunit.framework/TestSuite.javafile,selectthefollowingrangeofcodeinsidetheTestSuite(Class)constructor:
ClasssuperClass=theClass
Vectornames=newVector()
while(Test.class.isAssignableFrom(superClass)){
Method[]methods=superClass.getDeclaredMethods()
for(inti=0i<methods.lengthi++){
addTestMethod(methods[i],names,theClass)
}
superClass=superClass.getSuperclass()
}
2. Fromtheselection'scontextmenuintheeditor,selectRefactor>ExtractMethod....

3. IntheMethodNamefield,typecollectInheritedTests.

4. Topreviewthechanges,pressPreview>.Thepreviewpagedisplaysthechangesthatwillbemade.PressOKtoextractthemethod.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 20/322
12/10/2015 Javadevelopmentuserguide

5. GototheextractedmethodbyselectingitintheOutlineview.

NextSection:CreatingaJavaclass

Javaeditor
Refactoringsupport

JavaPreferences

2.1.5.CreatingaJavaclass
Inthissection,youwillcreateanewJavaclassandaddmethodsusingcodegenerationactions.
1. InthePackageExplorerview,selecttheJUnitproject.ClicktheNewJavaPackagebuttoninthetoolbar,orselectNew>Packagefromtheproject'scontextmenu.
2. IntheNamefield,typetestasthenameforthenewpackage.ThenclickFinish.
3. InthePackageExplorerview,selectthenewtestpackageandclicktheNewJavaClassbuttoninthetoolbar.
4. MakesurethatJUnitappearsintheSourceFolderfieldandthattestappearsinthePackagefield.IntheNamefield,typeMyTestCase.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 21/322
12/10/2015 Javadevelopmentuserguide

5. ClicktheBrowsebuttonnexttotheSuperclassfield.
6. IntheChooseatypefieldintheSuperclassSelectiondialog,typeTesttonarrowthelistofavailablesuperclasses.

7. SelecttheTestCaseclassandclickOK.
8. SelectthecheckboxforConstructorsfromsuperclass.
9. ClickFinishtocreatethenewclass.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 22/322
12/10/2015 Javadevelopmentuserguide

10. Thenewfileisopenedintheeditor.Itcontainsthenewclass,theconstructorandcomments.Youcanselectoptionsforthecreationandconfigurationofgenerated
commentsinthe Java>CodeStyle>CodeTemplatespreferencepage.
11. IntheOutlineviewselectthenewclassMyTestCase.OpenthecontextmenuandselectSource>Override/ImplementMethods....

12. IntheOverrideMethodsdialog,checksetUp()andtearDown()andclickOK.Twomethodsareaddedtotheclass.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 23/322
12/10/2015 Javadevelopmentuserguide

13. ChangethebodyofsetUp()tocontainer=newVector()
14. containerandVectorareunderlinedwithaproblemhighlightlineastheycannotberesolved.Alightbulbappearsonthemarkerbar.Movethemouseovertheunderlinedword
Vector.Ahoverappearsthatshowstheerrormessageandcontainsquickfixes.MovethemouseintothehoverandclickImport'Vector'(java.util).Thisaddsthemissing
importdeclaration.

Theblinkingcursorshouldstillbeonthelinethatcontainstheerror(ifnot,setittotheendoftheline).PressCtrl+1.Thisletsthecursorjumptothenearesterrorlocation
andopensthequickfixproposals.ChooseCreatefield'container'toaddthenewfield.

15. IntheOutlineview,selecttheclassMyTestCase.OpenthecontextmenuandselectSource>GenerateGettersandSetters....

16. TheGenerateGetterandSetterdialogsuggeststhatyoucreatethemethodsgetContainerandsetContainer.SelectbothandclickOK.Agetterandsettermethodforthefield
containerareadded.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 24/322
12/10/2015 Javadevelopmentuserguide

17. Savethefile.
18. Theformattingofgeneratedcodecanbeconfiguredinthe Java>CodeStyle>Formatterpreferencepage.Ifyouuseaprefixorsuffixforfieldnames(e.g.fContainer),
youcanspecifythisinthe Java>CodeStylepreferencepagesothatgeneratedgettersandsetterswillsuggestmethodnameswithouttheprefixorsuffix.
NextSection:RenamingJavaelements

Javaviews
Javaeditor

NewJavaClasswizard
Sourceactions
Quickfix
Overridemethodsdialog
GenerateGetterandSetterdialog
Codeformatterpreferencepage
Codestylepreferencepage
Codetemplatespreferencepage

2.1.6.RenamingJavaelements
Inthissection,youwillrenameaJavaelementusingrefactoring.Refactoringactionschangethestructureofyourcodewithoutchangingitssemantics(behavior).
1. InthePackageExplorerview,selectjunit.framework/TestCase.java.
2. Fromitscontextmenu,selectRefactor>Rename.
3. IntheNewNamefieldontheRenameCompilationUnitpage,type"TestCase2".

4. Topreviewthechangesthatwillbemadeasaresultofrenamingtheclass,pressNext.
5. Theworkbenchanalyzestheproposedchangeandpresentsyouwithapreviewofthechangesthatwouldtakeplaceifyourenamethisresource.
Sincerenamingacompilationunitwillaffecttheimportstatementsinothercompilationunits,thereareothercompilationunitsaffectedbythechange.Theseareshownina
listofchangesinthepreviewpane.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 25/322
12/10/2015 Javadevelopmentuserguide

6. OntheRefactoringpreviewpage,youcanscrollthroughtheproposedchangesandselectordeselectchanges,ifnecessary.Youwilltypicallyacceptalloftheproposed
changes.
7. ClickFinishtoacceptallproposedchanges.
Youhaveseenthatarefactoringactioncancausemanychangesindifferentcompilationunits.Thesechangescanbeundoneasagroup.
1. Inthemenubar,selectEdit>UndoRenameCompilationUnit.

2. Therefactoringchangesareundone,andtheworkbenchreturnstoitspreviousstate.Youcanundorefactoringactionsrightupuntilyouchangeandsaveacompilationunit,at
whichtimetherefactoringundobufferiscleared.
NextSection:MovingandcopyingJavaelements

Refactoringsupport

Refactoringactions
Refactoringwizard
Javapreferences

2.1.7.MovingandcopyingJavaelements
Inthissection,youwilluserefactoringtomovearesourcebetweenJavapackages.Refactoringactionschangethestructureofyourcodewithoutchangingitssemanticbehavior.
1. InthePackageExplorerview,selecttheMyTestCase.javafilefromthetestpackageanddragitintothejunit.samplespackage.Dragginganddroppingthefileissimilarto
selectingthefileandchoosingRefactor>Movefromthecontextmenu.
2. Youwillbepromptedtoselectwhetherornottoupdatereferencestothefileyouaremoving.Typically,youwillwanttodothistoavoidcompileerrors.Youcanpressthe
Previewbuttontoseethelistofchangesthatwillbemadeasaresultofthemove.
3. PressOK.Thefileismoved,anditspackagedeclarationchangestoreflectthenewlocation.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 26/322
12/10/2015 Javadevelopmentuserguide

4. UseEdit>UndoMovetoundothemove.
Thecontextmenuisanalternativetousingdraganddrop.Whenusingthemenu,youmustspecifyatargetpackageintheMovedialog,inadditiontoselectingtheupdate
referencesoptionsyou'vealreadyseen.
1. SelecttheMyTestCase.javafileandfromitscontextmenu,selectRefactor>Move.
2. IntheMovedialog,expandthehierarchytobrowsethepossiblenewlocationsfortheresource.Selectthejunit.samplespackage,thenclickOK.Theclassismoved,andits
packagedeclarationisupdatedtothenewlocation.

NextSection:NavigatetoaJavaelement'sdeclaration

Javaviews
Refactoringsupport

Refactoringactions
Refactoringwizard
Javapreferences

2.1.8.NavigatetoaJavaelement'sdeclaration
Inthissection,youwilllearnhowtoopenatypeintheJavaEditorandhowtonavigatetorelatedtypesandmembers.

1. OpentheOpenTypedialogbypressingCtrl+Shift+T,choosingNavigate>OpenType...,orclickingthetoolbaricon( ).TypeMoney,presstheArrowDownkeyafew
timestoselectMoneyTest,andthenpressEntertoopenthetypeintheJavaeditor.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 27/322
12/10/2015 Javadevelopmentuserguide

2. OnthefirstlineoftheMoneyTestclassdeclaration,selectthesuperclassTestCaseandeither
fromthemenubarselectNavigate>OpenDeclarationor
pressF3.

TheTestCaseclassopensintheeditorareaandisalsorepresentedintheOutlineview.
Note:Thiscommandalsoworksonmethodsandfields.

3. WiththeTestCase.javaeditoropenandtheclassdeclarationselected:
fromthemenubarselectNavigate>OpenTypeHierarchyor
pressF4.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 28/322
12/10/2015 Javadevelopmentuserguide

4. TheTypeHierarchyviewopenswiththeTestCaseclassdisplayed.

Note:YoucanalsoopeneditorsontypesandmethodsintheTypeHierarchyview.
NextSection:Viewingthetypehierarchy

Openinganeditorforaselectedelement

TypeHierarchyView

2.1.9.Viewingthetypehierarchy
Inthissection,youwilllearnaboutusingtheTypeHierarchyviewbyviewingclassesandmembersinavarietyofdifferentways.
1. InthePackageExplorerview,findjunit.framework/TestCase.java.Fromitscontextmenu,select OpenTypeHierarchy.Youcanalsoopentypehierarchyview:
fromthemenubarbyselectingNavigate>OpenTypeHierarchy.
fromthekeyboardbypressingF4afterselectingTestCase.java.

2. Thebuttonsintheviewtoolbarcontrolwhichpartofthehierarchyisshown.ClicktheShowtheTypeHierarchybuttontoseetheclasshierarchy,includingthebase

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 29/322
12/10/2015 Javadevelopmentuserguide
classesandsubclasses.ThesmallarrowontheleftsideofthetypeiconofTestCaseindicatesthatthehierarchywasopenedonthistype.

3. ClicktheShowtheSupertypeHierarchybuttontoseeahierarchyshowingthetype'sparentelementsincludingimplementedinterfaces.Thisviewshowstheresultsof
goingupthetypehierarchy.

Inthis"reversedhierarchy"view,youcanseethatTestCaseimplementstheTestinterface.
4. ClicktheShowtheSubtypeHierarchybuttonintheviewtoolbar.

5. ClicktheLockViewandShowMembersinHierarchybuttoninthetoolbarofthememberpane,thenselecttherunTest()methodinthememberpane.Theviewwillnow
showallthetypesimplementingrunTest().

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 30/322
12/10/2015 Javadevelopmentuserguide
6. IntheTypeHierarchyview,clicktheShowtheSupertypeHierarchybutton.Thenonthememberpane,selectcountTestCases()todisplaytheplaceswherethismethodis
declared.

7. IntheTypeHierarchyviewselecttheTestelementandselectFocusOn'Test'fromitscontextmenu.TestispresentedintheTypeHierarchyview.
8. ActivatethePackageExplorerviewandselectthepackagejunit.framework.UseOpenTypeHierarchyfromitscontextmenu.Ahierarchyisopenedcontainingallclassesof
thepackage.Forcompletionofthetree,thehierarchyalsoshowssomeclassesfromotherpackages.Thesetypesareshownbyatypeiconwithawhitefill.

9. UsePreviousTypeHierarchiestogobacktoapreviouslyopenedelement.Clickonthearrownexttothebuttontoseealistofelementsorclickonthebuttontoeditthe
historylist.

IfyouareworkingintheeditorandonlywanttodoaquicklookupforahierarchyyoucanusetheQuickTypeHierarchy:
1. Openjunit.framework.TestCase.javafileintheJavaeditorifyoudonotalreadyhaveitopen.
2. SelectthetypenameintheJavaeditor
3. PressCtrl+TorinvokeNavigate>QuickTypeHierarchyandtheinplacetypehierarchyviewisshown.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 31/322
12/10/2015 Javadevelopmentuserguide
4. PressingCtrl+Twhilethetypehierarchyviewisshownwilltogglebetweensupertypehierarchyandsubtypehierarchy.

Toseewhereavirtualmethodcallcanresolveto:
1. InthebodyofrunBare()selecttheinvocationofsetUp()
2. PressCtrl+TorinvokeNavigate>QuickTypeHierarchyandtheinplacetypehierarchyviewisshown.
3. YoucanseethatsetUp()isimplementedin3moreclasses.ObjectandAssertareonlyshownwithawhitefilledimagesasareonlyrequiredtocompletethehierarchybutdo
notimplementsetUp()
4. SelectatypetonavigatetoitsimplementationofsetUp()

NextSection:Searchingtheworkbench

Javaviews

TypeHierarchyview
JavaBasepreferencepage

2.1.10.Searchingtheworkbench
Inthissection,youwillsearchtheworkbenchforJavaelements.
IntheSearchdialog,youcanperformfile,textorJavasearches.Javasearchesoperateonthestructureofthecode.Filesearchesoperateonthefilesbynameand/ortextcontent.
Javasearchesarefaster,sincethereisanunderlyingindexingstructureforthecodestructure.Textsearchesallowyoutofindmatchesinsidecommentsandstrings.

PerformingaJavasearchfromtheworkbench
1. IntheJavaperspective,clicktheSearch( )buttonintheworkbenchtoolbaroruseSearch>Java...fromthemenubar.
2. Ifitisnotalreadyselected,selecttheJavaSearchtab.
3. IntheSearchstringfield,typerunTest.IntheSearchForarea,selectMethod,andintheLimitToarea,selectReferences.
VerifythattheScopeissettoWorkspace.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 32/322
12/10/2015 Javadevelopmentuserguide

ThenclickSearch.WhilesearchingyoumayclickCancelatanytimetostopthesearch.Partialresultswillbeshown.
4. IntheJavaperspective,theSearchviewshowsthesearchresults.

UsetheShowNextMatch( )andShowPreviousMatch( )buttonstonavigatetoeachmatch.Ifthefileinwhichthematchwasfoundisnotcurrentlyopen,itisopened


inaneditor.
5. WhenyounavigatetoasearchmatchusingtheSearchviewbuttons,thefileopensintheeditoratthepositionofthematch.Searchmatchesaretaggedwithasearchmarker
intherulers.

SearchingfromaJavaview
Javasearchescanalsobeperformedfromspecificviews,includingtheOutline,TypeHierarchyviewandthePackageExplorerview.
1. InthePackageExplorerview,doubleclickjunit.framework.Assert.javatoopenitinaneditor.
2. IntheOutlineview,selectthefail(String)method,andfromitscontextmenu,selectReferences>Workspace.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 33/322
12/10/2015 Javadevelopmentuserguide

Searchingfromaneditor
FromthePackageExplorerview,openjunit.framework.TestCase.java.Intheeditor,selecttheclassnameTestCaseandfromthecontextmenu,selectReferences>Workspace.

Continuingasearchfromthesearchview

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 34/322
12/10/2015 Javadevelopmentuserguide
TheSearchResultsviewshowstheresultsfortheTestCasesearch.Selectasearchresultandopenthecontextmenu.Youcancontinuesearchingtheselectedelement's
referencesanddeclarations.

Ifyouwanttofollowmultiplelevelsofmethodcalls,youcanalsouseNavigate>OpenCallHierarchy.

Performingafilesearch
1. IntheJavaperspective,clicktheSearchbuttonintheworkbenchtoolbarorselectSearch>Filefromthemenubar.
2. Ifitisnotalreadyselected,selecttheFileSearchtab.
3. IntheContainingtextfield,typeTestCase.MakesurethattheFilenamepatternsfieldissetto*.java.TheScopeshouldbesettoWorkspace.ThenclickSearch.

4. Tofindallfilesofagivenfilenamepattern,leavetheContainingTextfieldempty.

Viewingprevioussearchresults
IntheSearchResultsview,clickthearrownexttothePreviousSearchResultstoolbarbuttontoseeamenucontainingthelistofthemostrecentsearches.Youcanchooseitems
fromthismenutoviewprevioussearches.ThelistcanbeclearedbychoosingClearHistory.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 35/322
12/10/2015 Javadevelopmentuserguide

ThePreviousSearchResultsbuttonwilldisplayadialogwiththelistofallprevioussearchesfromthecurrentsession.

Selectingaprevioussearchfromthisdialogwillletyouviewthatsearch.
NextSection:Runningyourprograms

Javasearch

Refactoringactions
Refactoringwizard
Javapreferences

2.1.11.Runningyourprograms
Inthissection,youwilllearnmoreaboutrunningJavaprogramsintheworkbench.
1. InthePackageExplorerview,findjunit.textui/TestRunner.javaanddoubleclickittoopenitinaneditor.
2. IntheOutlineview,noticethattheTestRunnerclasshasaniconwhichindicatesthattheclassdefinesamainmethod.

3. RightclickonTestRunner.javainthePackageExplorerandselectRunAs>JavaApplication.ThiswilllaunchtheselectedclassasalocalJavaapplication.TheRunAs
contextmenuitemisalsoavailableinotherplaces,suchastheOutlineview.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 36/322
12/10/2015 Javadevelopmentuserguide

4. NoticethattheprogramhasfinishedrunningandthefollowingmessageappearsintheConsoleviewtellingyouthattheprogramneedsanexecutionargument.Running
classfromthePackageExplorerasaJavaApplicationusesthedefaultsettingsforlaunchingtheselectedclassanddoesnotallowyoutospecifyanyarguments.

5. Tospecifyarguments,usethedropdownRunmenuinthetoolbarandselectRunConfigurations....

YoucanalsoCtrl+Clickaconfigurationinthedropdownmenutostarteditingthatconfiguration.
6. Thistime,theLaunchConfigurationsdialogopenswiththeTestRunnerlaunchconfigurationselected.Alaunchconfigurationallowsyoutoconfigurehowaprogramis
launched,includingitsarguments,classpath,andotheroptions.(AdefaultlaunchconfigurationwascreatedforyouwhenyouchoseRun>JavaApplication).

7. SelecttheArgumentstabandtypejunit.samples.VectorTestintheProgramargumentsarea.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 37/322
12/10/2015 Javadevelopmentuserguide

8. ClickRun.Thistimetheprogramrunscorrectly,indicatingthenumberofteststhatwererun.

9. SwitchtotheDebugperspective.IntheDebugview,noticethataprocessforthelastprogramlaunchwasregisteredwhentheprogramwasrun.
Bydefault,theDebugviewautomaticallyremovesanyterminatedlauncheswhenanewlaunchiscreated.Thispreferencecanbeconfiguredonthe Run/Debug>
Launchingpreferencepage

Note:YoucanrelaunchaterminatedprocessbyselectingRelaunchfromitscontextmenu.
10. SelectthedropdownmenufromtheRunbuttonintheworkbenchtoolbar.Thislistcontainsthepreviouslylaunchedprograms.Theseprogramscanberelaunchedby
selectingtheminthehistorylist.

11. Bydefaultthecurrentlyselectedresourceoractiveeditorislaunchedwhentherunbuttonishit.Ifnoneoftheseislaunchablethecurrentprojectwillbelaunched.Youcan
configurethisbehaviorunder Run/Debug>Launching.

12. FromthecontextmenuintheDebugview(ortheequivalenttoolbarbutton),selectRemoveAllTerminatedtocleartheviewofterminatedlaunchprocesses.

NextSection:Debuggingyourprograms

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Runninganddebugging

Debugview
Runmenuactions
Runanddebugtoolbaractions

2.1.12.Debuggingyourprograms
Inthissection,youwilldebugaJavaprogram.
1. InthePackageExplorerviewintheJavaperspective,doubleclickjunit.samples/VectorTest.javatoopenitinaneditor.
2. PlaceyourcursorontheverticalruleralongtheleftedgeoftheeditorareaonthefollowinglineinthesetUp()method:
fFull.addElement(newInteger(1))
anddoubleclickontherulertosetabreakpoint.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 38/322
12/10/2015 Javadevelopmentuserguide

Thebreakpointiconindicatesthestatusofthebreakpoint.Theplainbluebreakpointiconindicatesthatthebreakpointhasbeenset,butnotyetinstalled.
Note:OncetheclassisloadedbytheJavaVM,thebreakpointwillbeinstalledandacheckmarkoverlaywillbedisplayedonthebreakpointicon.
3. InthePackageExplorerview,selectthejunit.samplespackageandselectDebugAs,andthenJavaApplication.Whenyourunaprogramfromapackage,youwillbe
promptedtochooseatypefromallclassesinthepackagethatdefineamainmethod.
4. SelecttheVectorTestiteminthedialog,thenclickOK.

Note:Youcanalsosimplyhitthedebugbutton whichwilllaunchthecurrentlyselectedresourceoractiveeditor.SelectJavaApplicationwhenyouare
promptedtoselectawaytodebugVectorTest.

5. Theprogramwillrununtilthebreakpointisreached.Whenthebreakpointishit,executionissuspended,andyouareaskedwhethertoopentheDebugperspective.Click
Yes.Noticethattheprocessisstillactive(notterminated)intheDebugview.Otherthreadsmightstillberunning.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 39/322
12/10/2015 Javadevelopmentuserguide

Note:Thebreakpointnowhasacheckmarkoverlay sincetheclassVectorTestwasloadedintheJavaVM.
6. IntheeditorintheDebugperspective,selectnewVector()fromthelineabovewherethebreakpointisset,andfromitscontextmenu,selectInspect.

7. Theexpressionisevaluatedinthecontextofthecurrentstackframe,andapopupappearswhichdisplaystheresults.YoucansendaresulttotheExpressionsviewby
pressingthekeybindingdisplayedinthepopup.
8. Expressionsthatyouevaluatewhiledebuggingaprogramwillbelistedinthisview.Todeleteanexpressionafterworkingwithit,selecttheexpressionandchooseRemove
fromitscontextmenu.
9. TheVariablesview(availableonatabalongwiththeExpressionsview)displaysthevaluesofthevariablesintheselectedstackframe.Expandthethis.fFulltreeinthe
VariablesviewuntilyoucanseeelementCount.
10. Thevariables(e.g.,elementCount)intheVariablesviewwillchangewhenyoustepthroughVectorTestintheDebugview.Tostepthroughthecode,clicktheStepOver( )
button.Executionwillcontinueatthenextlineinthesamemethod(or,ifyouareattheendofamethod,itwillcontinueinthemethodfromwhichthecurrentmethodwas

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 40/322
12/10/2015 Javadevelopmentuserguide
called).

11. Inthevariablesviewyoucanchoosetoseecertaintypesaslogicalstructures.Thishidestheimplementationdetailsofatypeandsimplyshowsitasarraysorfields.You
candefinelogicalstructuresbyyourselfinthepreferencepageJava>Debug>LogicalStructures.

12. Trysomeotherstepbuttons(StepInto ,StepReturn )tostepthroughthecode.Notethedifferencesinsteppingtechniques.


13. Youcanendadebuggingsessionbyallowingtheprogramtoruntocompletionorbyterminatingit.
YoucancontinuetostepoverthecodewiththeStepbuttonsuntiltheprogramcompletes.
YoucanclicktheResume( )buttontoallowtheprogramtorununtilthenextbreakpointisencounteredoruntiltheprogramiscompleted.
YoucanselectTerminatefromthecontextmenuoftheprogram'sprocessintheDebugviewtoterminatetheprogram.
NextSection:Evaluatingexpressions

Breakpoints
Remotedebugging
Localdebugging

Addingbreakpoints
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Suspendingthreads

Debugpreferences
Debugview
Runmenuactions
Runanddebugtoolbaractions
Breakpointsview
Consoleview
Displayview
Expressionsview
Variablesview

2.1.13.Evaluatingexpressions
Inthissection,youwillevaluateexpressionsinthecontextofyourrunningJavaprogram.
1. Debugjunit.samples.VectorTest.javatothebreakpointinthesetUp()methodandselectStepOvertwicetopopulatefFull.(SeetheDebuggingyourProgramssectionfor
fulldetails.)
2. OpentheDisplayviewbyselectingWindow>ShowView>Displayandtypethefollowinglineintheview:
fFull.size()
3. Selectthetextyoujusttyped,andfromitscontextmenu,selectDisplay.(YoucanalsochooseDisplayResultofEvaluatingSelectedText( )fromtheDisplayview
toolbar.)

4. TheexpressionisevaluatedandtheresultisdisplayedintheDisplayview.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 41/322
12/10/2015 Javadevelopmentuserguide

5. OnanewlineintheDisplayview,typethefollowingline:
fFull.toArray()
6. Selectthisline,andselectInspectfromthecontextmenu.(YoucanalsochooseInspectResultofEvaluatingSelectedText( )fromtheDisplayviewtoolbar.)
7. Alightweightwindowopenswiththevalueoftheevaluatedexpression.

NextSection:Evaluatingsnippets

Debugger

Evaluatingexpressions
Displayingtheresultofevaluatinganexpression
Inspectingtheresultofevaluatinganexpression

Expressionsview

2.1.14.Evaluatingsnippets
Inthissection,youwillevaluateJavaexpressionsusingtheJavascrapbook.JavascrapbookpagesallowyoutoexperimentwithJavacodefragmentsbeforeputtingtheminyour
program.
1. IntheFilemenuselectNew>Other>Java>JavaRun/Debug>ScrapbookPage.Youwillbepromptedforafolderdestinationforthepage.

2. IntheEnterorselectthefolderfield,typeorbrowsebelowtoselecttheJUnitprojectrootdirectory.
3. IntheFilenamefield,typeMyScrap.
4. ClickFinishwhenyouaredone.Ascrapbookpageresourceiscreatedforyouwiththejpagefileextension.(Thejpagefileextensionwillbeaddedautomaticallyifyoudo
notenterityourself.)Thescrapbookpageopensautomaticallyinaneditor.
5. Intheeditor,typeSystem.getandthenusecontentassist(Ctrl+Space)tocompletethesnippetasSystem.getProperties().

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 42/322
12/10/2015 Javadevelopmentuserguide

6. SelecttheentirelineyoujusttypedandselectDisplayfromthecontextmenu.YoucanalsoselectDisplayResultofEvaluatingSelectedTextfromthetoolbar.

7. Whentheevaluationcompletes,theresultoftheevaluationisdisplayedandhighlightedinthescrapbookpage.
8. YoucaninspecttheresultofanevaluationbyselectingtextandchoosingInspectfromthecontextmenu(orselectingInspectResultofEvaluatingSelectedTextfromthe
toolbar.)
9. Whenyouarefinishedevaluatingcodesnippetsinthescrapbookpage,youcanclosetheeditor.Savethechangesinthepageifyouwanttokeepthesnippetsforfuture
use.
NextSection:UsingtheJavabrowsingperspective

Debugger

CreatingaJavascrapbookpage
Displayingtheresultofevaluatinganexpression
Inspectingtheresultofevaluatinganexpression

NewJavaScrapbookPagewizard
Javascrapbookpage
Expressionsview

2.1.15.UsingtheJavabrowsingperspective
InthissectionyouwillusetheJavabrowsingperspectivetobrowseandmanipulateyourcode.BrowsingJavaelementswiththePackageExplorergivesanoverviewofusingthe
PackageExplorertobrowseelements.IncontrasttothePackageExplorer,whichorganizesallJavaelementsinatree,consistingofprojects,packages,compilationunits,types,
etc.,thebrowsingperspectiveusesdistinctviewstopresentthesameinformation.Selectinganelementinoneview,willshowitscontentinanotherview.
Toopenabrowsingperspectiveactivate Window>OpenPerspective>JavaBrowsingfromwithintheJavaperspectiveorusethecontextmenuoftheOpenaPerspective
toolbarbutton.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 43/322
12/10/2015 Javadevelopmentuserguide

Theviewsoftheperspectiveareconnectedtoeachotherinthefollowingways:
SelectinganelementintheProjectsviewsshowsitspackagesinthePackagesview.
TheTypesviewshowsthetypescontainedinthepackageselectedinthePackagesview.
TheMembersviewshowsthemembersofaselectedtype.Functionally,theMembersviewiscomparabletotheOutlineviewusedinthenormalJavaperspective.
SelectinganelementintheMembersviewrevealstheelementintheeditor.Ifthereisn'taneditoropenfortheelement,doubleclickingontheelementwillopena
correspondingeditor.
Allfourviewsarebydefaultlinkedtotheactiveeditor.Thismeansthattheviewswilladjusttheircontentandtheirselectionaccordingtothefilepresentedintheactiveeditor.The
followingstepsillustratethisbehavior:
1. Selectjunit.extensionsinthePackagesview.
2. OpentypeTestSetupintheeditorbydoubleclickingitintheTypesview.
3. NowgivebackfocustotheeditoropenedonfileTestCase.javabyclickingontheeditortab.ThePackages,TypesandMembersviewadjusttheircontentandselectionsto
reflecttheactiveeditor.ThePackagesview'sselectionissettojunit.frameworkandtheTypesviewshowsthecontentofthejunit.frameworkpackages.Inaddition,thetype
TestCaseisselected.
Functionally,theJavabrowsingperspectiveisfullycomparabletotheJavaperspective.Thecontextmenusforprojects,packages,types,etc.andtheglobalmenuandtoolbarare
thesame.ThereforeactivatingthesefunctionsisanalogoustoactivatingthemintheJavaperspective.
NextSection:WritingandrunningJUnittests

2.1.16.WritingandrunningJUnittests
Inthissection,youwillbeusingtheJUnittestingframeworktowriteandruntests.TogetstartedwithJUnityoucanrefertotheJUnitCookbook.

WritingTests
Createaproject"JUnitTest".Nowyoucanwriteyourfirsttest.YouimplementthetestinasubclassofTestCase.YoucandosoeitherusingthestandardClasswizardorthe
specializedTestCasewizard:
1. OpentheNewwizard(File>New>JUnitTestCase).
2. SelectNewJUnit3testandenter"TestFailure"asthenameofyourtestclass:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 44/322
12/10/2015 Javadevelopmentuserguide

Note:IfyouwanttouseJUnit4testsyouhavetomakesurethatyourcompilercomplianceissetto1.5.
3. Youwillseeawarningmessageaskingyoutoaddthejunitlibrarytothebuildpath.UsetheClickherelinktoaddthejunitlibraryautomatically.
4. ClickFinishtocreatethetestclass.
AddatestmethodthatfailstotheclassTestFailure.Aquickwaytoenteratestmethodiswiththetesttemplate.Todoso,placethecursorinsidetheclassdeclaration.Type"test"
followedbyCtrl+Spacetoactivatecodeassistandselectthe"test"template.ChangethenameofthecreatedmethodtotestFailureandinvokethefail()method.
publicvoidtestFailure()throwsException{
fail()
}

Nowyouarereadytorunyourfirsttest.

RunningTests
TorunTestFailurehittherunbuttoninthetoolbar.ItwillautomaticallyrunasJUnitTest.YoucaninspectthetestresultsintheJUnitview.Thisviewshowsyouthetestrun
progressandstatus:

Theviewisshowninthecurrentperspectivewheneveryoustartatestrun.AconvenientarrangementfortheJUnitviewistodockitasafastview.TheJUnitviewhastwotabs:
oneshowsyoualistoffailuresandtheothershowsyouthefulltestsuiteasatree.Youcannavigatefromafailuretothecorrespondingsourcebydoubleclickingthecorresponding
lineinthefailuretrace.
DocktheJUnitviewasafastview,removethefail()statementinthemethodtestFailure()sothatthetestpassesandrerunthetestagain.Youcanrerunatesteitherbyclickingthe
Rerunbuttonintheview'stoolbaroryoucanreruntheprogramthatwaslastlaunchedbyactivatingtheRundropdown.Thistimethetestshouldsucceed.Becausethetestwas
successful,theJUnitviewdoesn'tpopup,butthesuccessindicatorshowsontheJUnitviewiconandthestatuslineshowsthetestresult.Asaremindertorerunyourteststhe
viewiconisdecoratedbya"*"wheneveryouchangetheworkspacecontentsaftertherun.

Asuccessfultestrun

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 45/322
12/10/2015 Javadevelopmentuserguide

Asuccessfultestrun,buttheworkspacecontentshavechangedsincethelasttestrun.

Inadditiontorunningatestcaseasdescribedaboveyoucanalso:
Runalltestsinsideaproject,sourcefolder,orpackage
Selectaproject,packageorsourcefolderandrunalltheincludedtestswithRunas>JUnitTest.Thiscommandfindsalltestsinsideaproject,sourcefolderorpackageand
executesthem.
Runasingletestmethod
SelectatestmethodintheOutlineorPackageExplorerandwithRunas>JUnitTesttheselectedtestmethodwillberun.
Rerunasingletest
SelectatestintheJUnitviewandexecuteRunfromthecontextmenu.

CustomizingaTestConfiguration
WhenyouwanttopassparametersorcustomizethesettingsforatestrunyouopentheLaunchConfigurationDialog.SelectOpenRunDialog....intheRundropdownmenuinthe
toolbar:

Inthisdialogyoucanspecifythetesttoberun,itsarguments,itsruntimeclasspath,andtheJavaruntimeenvironment.

DebuggingaTestFailure
Inthecaseofatestfailureyoucanfollowthesestepstodebugit:
1. DoubleclickthefailureentryfromtheFailurestabintheJUnitviewtoopenthecorrespondingfileintheeditor.
2. Setabreakpointatthebeginningofthetestmethod.
3. SelectthetestcaseandexecuteDebugAs>JUnitTestfromtheDebugdropdown.
AJUnitlaunchconfigurationhasa"keepalive"option.IfyourJavavirtualmachinesupports"hotcodereplacement"youcanfixthecodeandrerunthetestwithoutrestartingthefull
testrun.ToenablethisoptionselecttheKeepJUnitrunningafteratestrunwhendebuggingcheckboxintheJUnitlaunchconfiguration.

CreatingaTestSuite
TheJUnitTestSuitewizardhelpsyouwiththecreationofatestsuite.Youcanselectthesetofclassesthatshouldbelongtoasuite.
1. OpentheNewwizard
2. SelectJava>JUnit>JUnitTestSuiteandclickNext.
3. Enteranameforyourtestsuiteclass(theconventionistouse"AllTests"whichappearsbydefault).

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 46/322
12/10/2015 Javadevelopmentuserguide

4. Selecttheclassesthatshouldbeincludedinthesuite.Wecurrentlyhaveasingletestclassonly,butyoucanaddtothesuitelater.
Youcanaddorremovetestclassesfromthetestsuiteintwoways:
Manuallybyeditingthetestsuitefile
Byrerunningthewizardandselectingthenewsetoftestclasses.
Note:thewizardputs2markers,//$JUnitBEGIN$and//$JUnitEND$,intothecreatedTestsuiteclass,whichallowsthewizardtoupdateexistingtestsuiteclasses.Editingcode
betweenthemarkersisnotrecommended.
NextSection:Projectconfigurationtutorial

2.2.Projectconfigurationtutorial
Inthissection,youwillcreateandconfigureanewJavaprojecttousesourcefoldersandtomatchsomeexistinglayoutonthefilesystem.Sometypicallayoutshavebeen
identified.Choosethesubsectionthatmatchesyourlayout.
NextSection:Detectingexistinglayout

Javaprojects
Javaviews

NewJavaProjectWizard
PackageExplorerView

2.2.1.Detectingexistinglayout
Layoutonfilesystem
Thesourcefilesforaproductarelaidoutinonedirectory"src".
Theclassfilesareinanotherdirectory"bin".

Stepsfordefiningacorrespondingproject
1. Click Window>OpenPerspective>Other...>JavatochangetotheJavaperspective.
2. Click File>New>Other...>JavaProjecttoopentheNewJavaProjectwizard.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 47/322
12/10/2015 Javadevelopmentuserguide
3. Type"Product"intheProjectnamefield.
4. InProjectlayoutgroup,changeselectiontoCreateseparatesourceandoutputfolders.
DeselectUsedefaultlocation.
ClickBrowse...andchoosetheProductdirectoryondriveD:.

5. ClickNext.
Ensurethatthesourceandoutputfoldersaredetected.

Warning:IftheScruboutputfolderswhencleaningprojectspreferenceintheOutputfoldersectionofthe Java>Compiler>Buildingpreferencepageischecked,

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 48/322
12/10/2015 Javadevelopmentuserguide
clickingFinishwillscrubthe"bin"directoryinthefilesystembeforegeneratingtheclassfiles.
6. ClickFinish.
7. YounowhaveaJavaprojectwitha"src"folderwhichcontainsthesourcesofthe"Product"directory.

Note:Thissolutioncreatesa".project"fileanda".classpath"fileinthe"Product"directory.Ifyoudonotwishtohavethesefilesinthe"Product"directory,youshoulduselinked
foldersasshownintheSiblingproductsinacommonsourcetreesection.
NextSection:Organizingsources

Javaprojects
Javaviews

NewJavaProjectWizard
PackageExplorerView

2.2.2.Organizingsources
Layoutonfilesystem
Inthissection,youwillcreateanewJavaprojectandorganizeyoursourcesinseparatefolders.Thiswillprepareyouforhandlingmorecomplexlayouts.
Let'sassumeyouwanttoputyoursourcesinonefolderandyourtestsinanotherfolder:

Stepsfordefiningacorrespondingproject
1. Click Window>OpenPerspective>Other...>JavatochangetotheJavaperspective.
2. Click File>New>Other...>JavaProjecttoopentheNewJavaProjectwizard.
3. Type"MyProject"intheProjectnamefield.
4. InProjectlayoutgroup,changeselectiontoCreateseparatesourceandoutputfoldersandeditConfiguredefault...tomodifySourcefoldernamefrom"src"to
"sources".

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 49/322
12/10/2015 Javadevelopmentuserguide

5. ClickOKtoreturnonNewJavaProjectwizardandthenclickNext.

6. Toaddanothersourcefoldertoyourproject,clickCreatenewsourcefolderlinkinDetailspaneorbutton inviewbar.
7. InNewSourceFolderdialog,type"tests"intheFoldernamefield.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 50/322
12/10/2015 Javadevelopmentuserguide

8. ClickFinishtovalidateandclosethedialog.
9. Yourprojectsetupnowlooksasfollows:

10. ClickFinish
11. YounowhaveaJavaprojectwithtwosourcefolders:sourcesandtests.Youcanstartaddingclassestothesefoldersoryoucancopythemusingdraganddrop.

NextSection:Siblingproductsinacommonsourcetree

Javaprojects
Javaviews

NewJavaProjectWizard
PackageExplorerView

2.2.3.Siblingproductsinacommonsourcetree
Layoutonfilesystem

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 51/322
12/10/2015 Javadevelopmentuserguide
ThesourcefilesforproductsarelaidoutinonebigdirectorythatisversionandconfigurationmanagedoutsideEclipse.
ThesourcedirectorycontainstwosiblingsdirectoriesProduct1andProduct2.

Stepsfordefiningcorrespondingprojects
1. Click Window>OpenPerspective>Other...>JavatochangetotheJavaperspective.
2. Click File>New>Other...>JavaProjecttoopentheNewJavaProjectwizard.
3. Type"Product1"intheProjectnamefield.ClickNext.

4. Onthenextpage,Select"Product1"sourcefolder.
ClickLinkadditionalsourcelinkinDetailspaneorbutton inviewbar.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 52/322
12/10/2015 Javadevelopmentuserguide

5. InLinkSourcedialogclickBrowse....andchoosetheD:\AllProducts\Product1\JavaSourceFilesdirectory.

6. ClickFinishtovalidateandclosethedialog.
7. Yourprojectsourcesetupnowlooksasfollows:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 53/322
12/10/2015 Javadevelopmentuserguide

8. ClickFinish.
9. Repeatsteps2to8for"Product2".
10. YounowhavetwoJavaprojectswhichrespectivelycontainthesourcesof"Product1"and"Product2".

NextSection:Overlappingproductsinacommonsourcetree

Javaprojects
Javaviews

NewJavaProjectWizard
PackageExplorerView

2.2.4.Overlappingproductsinacommonsourcetree
Layoutonfilesystem
TheJavasourcefilesforproductsareallheldinasinglemaindirectory.
ProductsareseparatedintofoursiblingspackagesProduct1,Product2,Product3andProduct4.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 54/322
12/10/2015 Javadevelopmentuserguide

Stepsfordefiningcorresponding"Product1"and"Product2"projects
1. Click Window>OpenPerspective>Other...>JavatochangetotheJavaperspective.
2. Click File>New>Other...>JavaProjecttoopentheNewJavaProjectwizard.
3. Type"Product1"intheProjectnamefield.ClickNext.

4. Onthenextpage,Select"Product1"sourcefolder.
ClickLinkadditionalsourcelinkinDetailspaneorbutton inviewbar.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 55/322
12/10/2015 Javadevelopmentuserguide

5. InLinkSourceclickBrowse....andchoosetheD:\AllJavaSourceFilesdirectory.
Type"src"inFoldername.

6. ClickFinishtovalidateandclosethedialog.
7. Expandthe"src"sourcefolder.SelectthethreelastpackagesandexcludethemfrombuildpathusingeitherExcludefrombuildpathlinkorExcludepopupmenuitem.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 56/322
12/10/2015 Javadevelopmentuserguide

8. Yourprojectsourcesetupnowlooksasfollows:

9. ClickFinish.
10. Copy"Product1"projectandpasteitas"Product2".
Edit"Product2"projectpropertiesandgoonJavaBuildPathpage.
InSourcetab,expand"Product2/src"sourcefolder,selectExcludedandclickEdit....

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 57/322
12/10/2015 Javadevelopmentuserguide

11. InInclusionandExclusionPatterns,select"com/xyz/product2"andclickEdit....

12. Change"com/xyz/product2"to"com/xyz/product1".

13. ClickOKtoenterthechange.
ClickFinishtovalidateandcloseInclusionandExclusionPatternsdialog.
ClickOKagaintovalidate"Product2"projectpropertieschanges.
14. YounowhavetwoJavaprojectswhichrespectivelycontainthesourcesof"product1","product2".

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 58/322
12/10/2015 Javadevelopmentuserguide

NextSection:Productwithnestedtests

Javaprojects
Javaviews

NewJavaProjectWizard
PackageExplorerView

2.2.5.Productwithnestedtests
Layoutonfilesystem
TheJavasourcefilesforaproductarelaidoutinapackagedirectory.
Sourcefilesoftestsarelaidoutinanestedpackagedirectory.

Stepsfordefiningacorrespondingproject
1. Click Window>OpenPerspective>Other...>JavatochangetotheJavaperspective.
2. Click File>New>Other...>JavaProjecttoopentheNewJavaProjectwizard.
3. Type"Product1"intheProjectnamefield.ClickNext.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 59/322
12/10/2015 Javadevelopmentuserguide

4. Onthenextpage,Select"Product1"sourcefolder.
ClickLinkadditionalsourcelinkinDetailspaneorbutton inviewbar.

5. InLinkSourceclickBrowse....andchoosetheD:\Product1\JavaSourceFilesdirectory.
Type"src"intheFoldernamefield.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 60/322
12/10/2015 Javadevelopmentuserguide

6. ClickFinishtovalidateandclosethedialog.
7. Expandthe"src"sourcefolder.Selecttheemptypackage"tests"andsetitassourcefolderusingeitherUseasSourceFolderpopupmenuitemorbutton inviewbar.

8. Yourprojectsourcesetupnowlooksasfollows:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 61/322
12/10/2015 Javadevelopmentuserguide

9. ClickFinish.
10. YounowhaveaJavaprojectwithtwosourcefolders:"src"and"src/tests"whichcontainrespectivelytheD:\Product1\JavaSourceFilesdirectoryandthe
D:\Product1\JavaSourceFiles\testsdirectory.

NextSection:Productssharingacommonsourceframework

Javaprojects
Javaviews

NewJavaProjectWizard
PackageExplorerView

2.2.6.Productssharingacommonsourceframework
Layoutonfilesystem
TheJavasourcefilesfortwoproductsrequireacommonframework.
Projectsandcommonframeworkareinseparatedirectorieswhichhavetheirownsourceandoutputfolders.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 62/322
12/10/2015 Javadevelopmentuserguide

Stepsfordefiningcorrespondingprojects
1. Click Window>OpenPerspective>Other...>JavatochangetotheJavaperspective.
2. Click File>New>Other...>JavaProjecttoopentheNewJavaProjectwizard.
3. Type"Product1"intheProjectnamefield.ClickNext.

4. Onthenextpage,Select"Product1"sourcefolder.
ClickLinkadditionalsourcelinkinDetailspaneorbutton inviewbar.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 63/322
12/10/2015 Javadevelopmentuserguide

5. InLinkSourceclickBrowse....andchoosetheD:\Product1\JavaSourceFilesdirectory.
Type"src"intheFoldernamefield.

6. ClickFinishtovalidateandclosethedialog.
7. Again,Select"Product1"andclickLinkadditionalsourcelinkinDetailspaneorbutton inviewbar.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 64/322
12/10/2015 Javadevelopmentuserguide

8. InLinkSourceclickBrowse....andchoosetheD:\Framework\JavaSourceFilesdirectory.
Type"srccommon"intheFoldernamefield.

9. ClickFinishtovalidateandclosethedialog.
Yourprojectsourcesetupnowlooksasfollows:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 65/322
12/10/2015 Javadevelopmentuserguide

10. ClickFinish.
11. Createproject"Product2"repeatingsteps2to5choosingD:\Product2\JavaSourceFilesdirectoryforsourcefolderinstead.
12. ClickonFinishtocreatetheprojectimmediately.
13. Now,we'llseehowtoaddalinkedsourcefolderwhenprojectisalreadycreatedinworkspace...
Editproject"Product2"propertiesandselectJavaBuilderPathpage.
OnSourcetab,clickLinkSource....

14. InLinkSourceclickBrowse....andchoosetheD:\Framework\JavaSourceFilesdirectory.
Type"srccommon"intheFoldernamefield.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 66/322
12/10/2015 Javadevelopmentuserguide

15. ClickFinishtovalidateandclosethedialog.
ClickOKtoapplyproject"Product2"propertieschanges.
16. YounowhavetwoJavaprojectswhichrespectivelycontainthesourcesof"Product1"and"Product2"andwhichareusingthesourcesof"Framework".

Note:Filesin"srccommon"areshared.Soediting"Common.java"in"Product1"willmodify"Common.java"in"Product2".Howevertheyarecompiledinthecontextoftheir
respectiveprojects.Two"Common.class"fileswillbegeneratedoneforeachproject.Ifthetwoprojectshavedifferentcompileroptions,thendifferenterrorscouldbereportedon
each"Common.java"file.
NextSection:Productnestingresourcesinoutputdirectory

Javaprojects
Javaviews

NewJavaProjectWizard
PackageExplorerView

2.2.7.Nestingresourcesinoutputdirectory
Layoutonfilesystem
TheJavasourcefilesforaproductarelaidoutbothinsourcesanddeliverablesdirectories.
AllJavaclassfilesarelaidoutindeliverablesdirectory.
Projectneedstousesomelibrarieslocatedindeliverables/librariesdirectory:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 67/322
12/10/2015 Javadevelopmentuserguide

Stepsfordefiningacorrespondingproject
1. Click Window>OpenPerspective>Other...>JavatochangetotheJavaperspective.
2. Click File>New>Other...>JavaProjecttoopentheNewJavaProjectwizard.
3. Type"Product"intheProjectnamefield.ClickNext.

4. Onthenextpage,Type"Product/deliverables"inDefaultoutputfolderfield.
Select"Product"sourcefolder.
ClickLinkadditionalsourcelinkinDetailspaneorbutton inviewbar.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 68/322
12/10/2015 Javadevelopmentuserguide

5. InLinkSourceclickBrowse....andchoosetheD:\Product\sourcesdirectory.

6. ClickFinishtovalidateandclosethedialog.
7. Again,Select"Product"andclickLinkadditionalsourcelinkinDetailspaneorbutton inviewbar.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 69/322
12/10/2015 Javadevelopmentuserguide

8. InLinkSourceclickBrowse....andchoosetheD:\Product\deliverablesdirectory.

9. Expandthe"Product/deliverables"sourcefolder.Selectthe"libraries"packageandexcludeitfrombuildpathusingeitherExclude'libraries'frombuildpathlinkorExclude
popupmenuitem.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 70/322
12/10/2015 Javadevelopmentuserguide

10. Yourprojectsourcesetupnowlooksasfollows:

11. SelectLibrariestab.
ClickonAddJARs....

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 71/322
12/10/2015 Javadevelopmentuserguide

12. Expand"Product"hierarchytoselectjarfilesin"libraries"directory
ClickOK.

13. ClickFinishtofinalizeprojectcreation.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 72/322
12/10/2015 Javadevelopmentuserguide

14. YounowhaveaJavaprojectwitha"sources"folderandanoutputfolderwhichcontainsnestedlibraryresources.

NextSection:Projectusingasourceframeworkwithrestrictedaccess

Javaprojects
Javaviews

NewJavaProjectWizard
PackageExplorerView

2.2.8.Projectusingasourceframeworkwithrestrictedaccess
Layoutonfilesystem
TheJavasourcefilesforaproductrequiresasourceframework.
"Product"and"Framework"areinseparatedirectorieswhichhavetheirownsourceandoutputfolders.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 73/322
12/10/2015 Javadevelopmentuserguide

Stepsfordefiningcorrespondingprojects
1. Click Window>OpenPerspective>Other...>JavatochangetotheJavaperspective.
2. Click File>New>Other...>JavaProjecttoopentheNewJavaProjectwizard.
3. Type"Framework"intheProjectnamefield.
4. DeselectUsedefaultlocation.
ClickBrowse...andchoosetheD:\Frameworkdirectory.

ClickNext.
5. Onthenextpage,verifythatdirectoryJavaSourceFileshasbeenautomaticallyaddedassourcefolder.
Expandittopreviewyourprojectsourcefoldercontents:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 74/322
12/10/2015 Javadevelopmentuserguide

6. ClickFinish.
7. InJavaperspective,typeCtrl+NtoopenNewwizardsdialog.
SelectJavaprojectinthelistofwizardsandclickNext.
8. Onthenextpage,type"Product"intheProjectnamefield.
9. DeselectUsedefaultlocation.
ClickBrowse...andchoosetheD:\Productdirectory.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 75/322
12/10/2015 Javadevelopmentuserguide

10. ClickNext.
11. Onthenextpage,verifythatdirectoryJavaSourceFileshasbeenautomaticallyaddedassourcefolder.
Expandittopreviewyourprojectsourcefoldercontents:

12. SelectProjectstab.
ClickAdd...toaddadependencytosourceframeworkproject...

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 76/322
12/10/2015 Javadevelopmentuserguide

13. InRequiredProjectSelection,check"Framework".

14. ClickOKtovalidateandclosedialog.
15. Now,let'sputaccessrulesonsourceframeworkcontenttoauthorize,discourageorforbidaccessto"Framework"sourcefolders,packageandclasses...
InProjectstab,select"Accessrules"of"Framework"dependingproject.
ClickEdit....

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 77/322
12/10/2015 Javadevelopmentuserguide

16. InTypeAccessRules,clickAdd....

17. InAddAccessRule,select"Forbidden"forResolution.
Type"**/forbidden/**"inRulePatternfield.

18. ClickOKtovalidateaccessruleandclosedialog.
19. Addanotheraccessrule:
Resolution:"Discouraged"andRulePattern:"**/internal/**".

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 78/322
12/10/2015 Javadevelopmentuserguide
20. Youraccessrulesnowlookasfollows:

21. ClickOKtovalidatethesenewrulesandclosedialog.
22. Dependentprojecthasnow2accessrulesset.

23. ClickFinish.
24. YounowhaveaJavaprojectwhichcontainsthesourceof"Product"andwhichisusingthesourceof"Framework".
Somepackagesoftheproject"Framework"arerestrictedandifyoutrytoimportthem,compilerdisplayseitherwarningsorerrorsdependingonyourrestrictionlevel:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 79/322
12/10/2015 Javadevelopmentuserguide

NextSection:EclipseandJ2SE5.0

Javaprojects

NewJavaProjectWizard
PackageExplorerView

2.3.EclipseandJ2SE5.0
Sincerelease3.1,EclipseincludesfullsupportforthenewJavalanguagefeaturesofJ2SE5.0.Oneofthemostimportantconsequencesofthissupportisthatyoumaynotnoticeit
atalleverythingyouexpecttoworkforJ2SE1.4,includingediting,compiling,debugging,quickfixes,refactorings,sourceactions,searching,etc.,willworkseamlesslywithJ2SE
5.0'snewtypesandsyntax.Inthisdocument,wewillintroducesomeofthemoreinterestingcapabilitiesEclipseuserswillfindwhenworkingwithJ2SE5.0.
Notethatbothversionnumbers'1.5'and'5.0'areusedtoidentifythereleaseoftheJava2PlatformStandardEdition.Version'5.0'istheproductversion,while'1.5'isthedeveloper
versionandisalsousedforthecompliancelevel.

Prerequisites
InordertodevelopcodecompliantwithJ2SE5.0,youwillneedaJ2SE5.0orJ2SE6.0JavaRuntimeEnvironment(JRE).IfyoustartEclipseforthefirsttimeusingaJ2SE5.0
JRE,thenitwilluseitbydefault.Otherwise,youwillneedtousethe Java>InstalledJREspreferencepagetoregisteritwithEclipse.
ThisdocumentintroducessomeofthenewlanguagefeaturesinJ2SE5.0verybriefly,butitisnotapropertutorialforthesefeatures.Seehereformoreinformation.

CompilerComplianceLevel
TousethenewJ2SE5.0features,youmustbeworkingonaprojectthathasa1.5compliancelevelenabledandhasa5.0JRE.Newprojectswillautomaticallyget1.5compliance
whenchoosinga5.0JREonthefirstpageofthe NewJavaProjectwizard:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 80/322
12/10/2015 Javadevelopmentuserguide

ToconvertanexistingJ2SE1.4projecttoJ2SE5.0,youcansimply:
1. MakesureyouhaveaJ2SE5.0JREinstalled.
2. Startusingthe5.0featuresinyourcode.
3. Whenacompileerrorisflagged,useQuickFixtoupdatetheproject'scompliancelevel:

4. Formorefinetunedcontrol,thecompilercompliancelevelcanbesetgloballyforaworkspace(withthe Java>Compilerpreferencepage)orindividuallyforeachproject
(fromtheproject'scontextmenu,chooseProperties>JavaCompiler).

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 81/322
12/10/2015 Javadevelopmentuserguide

Projectswithdifferentcompliancelevelscancoexistintheworkspace,anddependoneachother.Youcanalsofinetunethekindsofcompilewarningsanderrorsproducedforeach
projectusingProperties>JavaCompiler>Errors/Warnings.TheGenericTypesandtheAnnotationssectioncontainoptionsaddedforJ2SE5.0.

GenericTypes
Generictypesallowobjectsofthesameclasstosafelyoperateonobjectsofdifferenttypes.Forexample,theyallowcompiletimeassurancesthataList<String>alwayscontains
Strings,andaList<Integer>alwayscontainsIntegers.

AnywherethatEclipsehandlesanongenerictype,itcanhandleagenerictype:
Generictypescanbesafelyrenamed.
Typevariablescanbesafelyrenamed.
Genericmethodscanbesafelyextractedfrom/inlinedintogenericcode.
Codeassistcanautomaticallyinsertappropriatetypeparametersinparameterizedtypes.
Inaddition,anewrefactoringhasbeenadded:InferGenericTypeArgumentscaninfertypeparametersforeverytypereferenceinaclass,apackage,oranentireproject.

Invokingtherefactoringproduces:

Eclipseprovidesnewoptionswhensearchingforreferencestogenerictypes.Considerthisexample:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 82/322
12/10/2015 Javadevelopmentuserguide

SelectingthereferencetoList<Integer>andusingSearch>References>ProjectfromthecontextmenuwillhighlighttheListtypesonallfourlines:

UsingtheSearchViewmenu,theresultscanbefiltered:
FilterIncompatibleTypeArgumentsleavesonlyreferencestotypesthatareassignmentcompatiblewiththeselectedtype:

FilterInexactTypeArgumentsleavesonlytypereferenceswiththeexactsamesignature:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 83/322
12/10/2015 Javadevelopmentuserguide

Annotations
AnnotationsattachmetadataabouthowJavatypesandmethodsareusedanddocumentedtotheJavasourceandcanthenaffectcompilationorbequeriedatruntime.For
example,@Overridewilltriggeracompilewarningiftheannotatedmethoddoesnotoverrideamethodinasuperclass:

EverythingyoucandowithaJavatype,youcandowithanannotation:
CreatenewannotationsusingNew>Annotation
Refactor:rename,move,changesignaturesofmembers,etc.
Searchforoccurrences
Usecodeassisttofillinnamesandvalues
AveryusefulannotationwithfullsupportinEclipseis@SuppressWarnings.Forexample,consideraprivatemethodthatiscurrentlyunused,butyou'drathernotdelete:

Invokingquickfixonthewarningproposesaddinga@SuppressWarningsannotation:

Selectingthequickfixaddstheannotation.TheEclipsecompilerhonorstheannotationbyremovingthewarningonfoo:

Enumerations
Enumerationsaretypesthatareinstantiatedatruntimebyaknown,finitesetofobjects:

Again,anythingyoucandotoaJavaclasscanbedonetoanenumeration:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 84/322
12/10/2015 Javadevelopmentuserguide
CreatenewenumerationsusingNew>Enum
Refactor:rename,move,renameconstants,etc.
Searchforoccurrences
Usecodeassisttofillinconstants

Autoboxing
AutoboxingandautounboxingallowforelegantsyntaxwhenprimitivetypesareassignedtoorretrievedfromObjectreferences:

Eclipse'ssourcemanipulationfeatureshandleautoboxingseamlessly,givingthecorrecttypestonewlocalvariablesandcorrectcodeassists.Forcodeunderstanding,itisalso
possibletoflaginstancesofautoboxingorautounboxingconversions:
markthemascompilewarningsorerrors(BoxingandunboxingconversionsinthePotentialProgrammingProblemssectionofthe Java>Compiler>
Errors/Warningspreferencepage)
highlightthemusingsyntaxcoloring(viatheJava>Auto(un)boxedexpressionssectionofthe Java>Editor>SyntaxColoringpreferencepage):

Enhancedforloop
Forthecommoncaseofoperatingoneachelementofanarrayorcollectioninturn,J2SE5.0allowsanew,cleanersyntax.Eclipseprovidesa"foreach"codetemplatethatcan
automaticallyguessthecollectiontobeiterated:

Choosingthetemplateproduces:

Eclipsealsoprovidesa"Converttoenhancedforloop"quickassisttoupgrade1.4styleforloopswherepossible.

StaticImports
Staticimportsallowyoutousestaticfieldsandmethodsfromotherclasseswithoutqualification.
ContentassistintheJavaeditorcansuggestsuchstaticmembersandaddsastaticimportwhenrequired.Togetsuchproposals,configurethestaticimportfavoritesonthe
Java>Editor>ContentAssist>Favoritespreferencepage.

ConvertingJ2SE1.4codeto5.0
EclipseoffersthefollowingtoolstohelpyoubringJ2SE1.4codeto5.0:
CleanUpaction
Addmissing@Overrideand@Deprecatedannotations
Convertforloopstoenhanced
InferGenericTypeArgumentsrefactoring
Happycoding!

2.4.EclipseandJava7
Sincerelease3.7.1,EclipseincludesfullsupportforthenewJavalanguagefeaturesofJavaSE7.Oneofthemostimportantconsequencesofthissupportisthatyoumaynot
noticeitatalleverythingyouexpecttoworkforJava6,includingediting,compiling,debugging,quickfixes,refactorings,sourceactions,searching,etc.,willworkseamlesslywith
Java7'snewsyntax.Inthisdocument,wewillintroducesomeofthemoreinterestingcapabilitiesEclipseuserswillfindwhenworkingwithJava7.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 85/322
12/10/2015 Javadevelopmentuserguide
Notethatbothversionnumbers'1.7'and'7'areusedtoidentifythereleaseoftheJavaPlatformStandardEdition.Version'7'istheproductversion,while'1.7'isthedeveloper
versionandisalsousedforthecompilercompliancelevel.

Prerequisites
InordertodevelopcodecompliantwithJava7,youwillneedaJava7JavaRuntimeEnvironment(JRE).IfyoustartEclipseforthefirsttimeusingaJava7JRE,thenitwilluseit
bydefault.Otherwise,youwillneedtousethe Java>InstalledJREspreferencepagetoregisteritwithEclipse.
YoucanalsoconfigureaJava7executionenvironment,viathe Java>InstalledJREs>ExecutionEnvironmentspreferencepage:

ToconvertanexistingJavaprojecttoJava7,openthePropertiesoftheJRESystemLibraryandchooseExecutionenvironment:JavaSE1.7.

TheexecutionenvironmentAPIdescriptionforJava7isavailablefromthecorrespondingupdatesite.Afterinstallingit,onecandetectinvalidreferencestoJava7systemlibraries:

Java7languagefeatures
Java7comeswithasetofsmallenhancementstotheJavalanguage(akaProjectCoin),anewbytecodetodynamicallyinvokemethods,andmanyadditionstothelibraries.This
documentintroducessomeofthenewlanguagefeaturesinJava7verybriefly,butitisnotapropertutorialforthesefeatures.Seehereformoreinformation.
ImprovedTypeInferenceforGenericInstanceCreation(Diamond)
Multicatch
trywithresourcesstatement
SimplifiedVarargsMethodInvocation
Stringsinswitch
BinaryLiteralsandUnderscoresinNumericLiterals
PolymorphicMethods

ImprovedTypeInferenceforGenericInstanceCreation(Diamond)
Thislanguagechangeallowsexplicittypeargumentstoconstructorsofparameterizedclassestobeomittedinmanysituations.Thecompilerinferstheomittedtypearguments

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 86/322
12/10/2015 Javadevelopmentuserguide
basedontheexpectedtype.
Wherepossible,contentassistforconstructorinvocationsinsertsadiamondinsteadofexplicittypearguments.

Result:

Thecompilercanalsodetectredundantspecificationoftypearguments,whichyoucanremoveviatheRemovetypeargumentsquickfix.

Thisoptionisdisabledbydefaultbutcanbeenabledonthe Java>Compiler>Errors/Warningspreferencepage:

Inaddition,youcanalsoinsertinferredtypeargumentsofadiamondviaaquickassist.

Hint:Thisalsoworksasaquickfixin1.5and1.6code,wherethediamondisasyntaxerror.

Multicatch
InJava7youcancatchmultipleexceptiontypesusingasinglecatchblock.
MarkOccurrencesinJavaeditorcanbeusedtohighlightstatementswhichthrowaparticularexception.

TheSource>SurroundWith>Try/multicatchBlockactionallowsyoutosurroundselectedstatementswithatry/multicatchblock.ThisisalsoavailableasSurroundwith
try/multicatchquickfixincasetherearemultipleuncaughtexceptions.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 87/322
12/10/2015 Javadevelopmentuserguide

TheAddexceptionstoexistingcatchclausequickfixallowsyoutoadduncaughtexceptionstoanexistingcatchclause.

TheUseseparatecatchblocksquickassistallowsyoutoreplaceamulticatchclausewithindividualcatchblocks,oneforeachexceptioninthemulticatchclause.

TheMoveexceptionstoseparatecatchblockquickassistallowsyoutopickoutoneormoreselectedexceptionsfromamulticatchclause.

TheCombinecatchblocksquickassistallowsyoutocombineseparatecatchblocksintoasinglemulticatchblock.Thequickassistisofferedonlywhenbodiesofallthecatch
blocksaresame.

Thecompilerreportsanerrorifanexceptioninamulticatchclauseisalreadycaughtbyanalternativeexception.TheRemoveexceptionquickfixallowsyoutoremovethis
exception.

Inaddition,thereareLineWrappingoptionsintheformatterforthemulticatchsyntax.Thesecanbeconfiguredonthe Java>CodeStyle>Formatterpreferencepageunder
LineWrapping>Statements>'multicatch'.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 88/322
12/10/2015 Javadevelopmentuserguide
trywithresourcesstatement
Thetrywithresourcesstatementensuresthateachresourceajava.lang.AutoCloseableisclosedattheendofthestatement.
MarkOccurrencesintheJavaeditorunderstandsthetrywithresourcessyntax.Theclosing'}'ofatrywithresourcesstatementismarkedasamethodexitpointiftheimplicit
close()invocationthrowsanexception.Thecorrespondingresourcevariableisalsohighlighted.

Thecompilerdetectsunhandledexceptionsthrownbyautomaticclose()invocationonaresource.

Thecompilercansuggestusingtrywithresourcesstatementwhentheresourceshavebeenexplicitlyclosedbutnotdeclaredintrywithresourcesstatements.

Thisoptionisdisabledbydefaultbutcanbeenabledonthe Java>Compiler>Errors/Warningspreferencepage:

Inaddition,thereareLineWrappingandWhiteSpaceoptionsintheformatterforthetrywithresourcessyntax.Thesecanbeconfiguredonthe Java>CodeStyle>
FormatterpreferencepageunderLineWrapping>Statements>'trywithresources'andWhiteSpace>ControlStatements>'trywithresources'.

SimplifiedVarargsMethodInvocation
TheJava7compliergeneratesawarningatthedeclarationsiteofavarargsmethodorconstructorwithanonreifiablevarargsformalparameter.Thiswarningcanbesuppressed
usingthe@SafeVarargsannotation.
TheAdd@SafeVarargsquickfixisofferedforpotentialheappollutionwarningsonmethoddeclarations.

Thequickfixisalsoofferedfromcallsites.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 89/322
12/10/2015 Javadevelopmentuserguide
TheRemove@SafeVarargsquickfixisofferedforincorrectusageof@SafeVarargsannotation.

Stringsinswitch
YoucanuseaStringobjectintheexpressionofaswitchstatement.
TheConvert'switch'to'ifelse'quickassistworksforstringsinswitch.

NotethatthequickassistavoidsaNullPointerExceptionintheresultantcode.

BinaryLiteralsandUnderscoresinNumericLiterals
InJava7,theintegraltypes(byte,short,int,andlong)canalsobeexpressedusingthebinarynumbersystem.Inaddition,anynumberofunderscorecharacters(_)canappear
anywherebetweendigitsinanumericalliteral.
Thefeatureforchangingthevalueofavariablewhiledebuggingsupportsunderscoresinnumericliteralsandbinaryliterals:

PolymorphicMethods
Javadochoversforreferencestopolymorphicmethodsshowtheactuallyusedmethodsignature.

Happycoding!

3.1.JavaProjects
AJavaprojectcontainssourcecodeandrelatedfilesforbuildingaJavaprogram.IthasanassociatedJavabuilderthatcanincrementallycompileJavasourcefilesastheyare
changed.
AJavaprojectalsomaintainsamodelofitscontents.Thismodelincludesinformationaboutthetypehierarchy,referencesanddeclarationsofJavaelements.Thisinformationis
constantlyupdatedastheuserchangestheJavasourcecode.TheupdatingoftheinternalJavaprojectmodelisindependentoftheJavabuilderinparticular,whenperformingcode
modifications,ifautobuildisturnedoff,themodelwillstillreflectthepresentprojectcontents.
YoucanorganizeJavaprojectsintwodifferentways:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 90/322
12/10/2015 Javadevelopmentuserguide
Usingtheprojectasthesourcecontainer.Thisistherecommendedorganizationforsimpleprojects.
Usingsourcefoldersinsidetheprojectasthesourcecontainer.Thisistherecommendedorganizationformorecomplexprojects.Itallowsyoutosubdividepackagesinto
groups.

Javabuilder

NewJavaprojectwizard

3.2.JavaBuilder
TheJavabuilderbuildsJavaprogramsusingitsowncompiler(theEclipseCompilerforJava)thatimplementstheJavaLanguageSpecification.TheJavabuildercanbuildprograms
incrementallyasindividualJavafilesaresaved.NotethattheEclipseCompilerforJavacanalsobeinvokedusingAntasdescribedintheUsingtheantjavacadaptersection.
Problemsdetectedbythecompilerareclassifiedaseitherwarningsorerrors.Theexistenceofawarningdoesnotaffecttheexecutionoftheprogramthecodeexecutesasifit
werewrittencorrectly.Compiletimeerrors(asspecifiedbytheJavaLanguageSpecification)arealwaysreportedaserrorsbytheJavacompiler.Forsomeothertypesofproblems
youcan,however,specifyifyouwanttheJavacompilertoreportthemaswarnings,errorsortoignorethem.Tochangethedefaultsettings,usethe Java>Compiler>
Errors/Warningspreferencepage.
TheJavacompilercancreateCLASSfileseveninpresenceofcompilationerrors.However,inthecaseofseriouserrors(forexample,referencestoinconsistentbinaries,most
likelyrelatedtoaninvalidbuildpath),theJavabuilderdoesnotproduceanyCLASSfiles.

Buildclasspath

Usingthebatchcompiler
Usingtheantjavacadapter
ExcludingwarningsusingSuppressWarnings

Javabuildpathproperties
Javacompilerpreferences

3.2.1.BuildClasspath
ThebuildclasspathspecifieswhichJavasourcefilesandresourcefilesinaprojectareconsideredbytheJavabuilderandspecifieshowtofindtypesoutsideoftheproject.The
JavabuildercompilestheJavasourcefilesintotheoutputfolderandalsocopiestheresourcesintoit.Thebuildclasspathisspecifiedforeachproject.Intheprojectproperties,itis
referredtoastheJavaBuildPath

Javabuilder
Classpathvariables
Inclusionandexclusionpatterns
Accessrules

Classpathvariablespreferences
Javabuildpathproperties

3.2.1.1.InclusionandExclusionPatterns
InclusionandExclusionpatternscanbeconfiguredforsourcefolders.TheydefinewhichfilesareconsideredbytheJavabuilderandotherJavatooling.Thissetoffilesconsistsof
allfilesandfolderswherethepathrelativetothesourcefoldermatchesaninclusionpatternbutnotanexclusionpattern.
Bydefault,allfilesandfolderscontainedinasourcefolderareincluded.Bydefininganinclusionpattern,thesetofincludedresourceswillbelimitedtotheresourcesmatchingthe
inclusionpattern.Usingexclusionpatterns,someoftheseresourcescanbeexcludedagain.
Exclusionpatternsarerequiredwhennestingsourcefolders.Thenestedfoldermustbeexcludedfromtheoutersourcefolder.
ThepatternshavethesameformatasANTpatterns:
'*'matcheszeroormorecharacters,'?'matchesonecharacter.
'/'isusedtoseparatefolders:Thismeansthefirstsegmentinthepatternismatchedagainstthemostouterfoldernameinthepathtomatch,thesecondsegmentwiththe
second,andsoon.
'**'matchesanynumberoffolders

Javabuilder
Classpathvariables
Accessrules

JavaBuildPathproperties

3.2.1.2.AccessRules
Accessrulescanbeaddedtobuildclasspathentriestospecifywhichtypesinthegivenentrycanbeaccessedandwhichnot.Ifthecompilerdetectsatypeaccesstoatypethat
shouldnotbeaccessed,itwillcreateaproblemmarker.
Nonaccessiblerulesdefinetypesthatmustnotbereferenced.Thecompilertypicallycreatesanerrormarkerforaccessestothesetypes.
Discouragedrulesdefinetypesthatshouldnotbereferenced.Thecompilertypicallycreatesawarningmarkerforaccessestothesetypes.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 91/322
12/10/2015 Javadevelopmentuserguide
Accessiblerulesdefinetypesthatcanbereferenced.
Eachruleconsistofapattern(sameformatasANTpatterns)andoneoftheruletypeslistedabove.
Eachclasspathentrycanhaveanynumberofrulesdefined.Thecompilerwillprocessthelistintheorderdefinedandtakethefirstmatchingrule.

Theseverityoftheproblemmarkergeneratedforaccessesto'Nonaccessible'and'Discouraged'typecanbeconfiguredontheJavacompiler'sError/Warningspreferencepage.

CombineAccessRules
Javabuilder
Classpathvariable
Inclusionandexclusionpatterns

Javabuildpathproperties
Error/Warningspreferencepage

3.2.1.3.ClasspathVariables
ThebuildpathforaJavaprojectcanincludesourcecodefiles,otherJavaprojects,folderscontainingclassfilesandJARfiles.JARfilescanbespecifiedusingfilesystempaths,or
byusingvariablesthatrefertolocationsonthenetwork.
ClasspathvariablesallowyoutoavoidreferencestothelocationofaJARfileorfoldersonyourlocalfilesystem.Byusingaclasspathvariable,youcanspecifyaJARfileorfolder
usingonlyavariablename,suchasJRE_LIB,ratherthanspecifyingthelocationonyourworkstation.Inthisway,youcansharebuildpathsacrossteamsanddefinethevariables
torefertothecorrectlocationforyourparticularcomputer.

Javabuilder
Classpathvariable
Inclusionandexclusionpatterns
Accessrules

Classpathvariablespreferences
Javabuildpathproperties

3.3.JavaPerspectives
TheJavadevelopmenttoolscontributethefollowingperspectivestotheworkbench:

Java
AperspectivedesignedforworkingwithJavaprojects.Itconsistsofaneditorareaandthefollowingviews:
PackageExplorer
Outline
Problems
Javadoc
Declaration

JavaBrowsing
AperspectivedesignedforbrowsingthestructureofJavaprojects.Itconsistsofaneditorareaandthefollowingviews:
Projects
Packages
Types
Members

JavaTypeHierarchy
Aperspectivedesignedforexploringatypehierarchy.Itcanbeopenedontypes,compilationunits,packages,projectsorsourcefoldersandconsistsoftheTypeHierarchyviewand
aneditor.

Debug
AperspectivedesignedfordebuggingyourJavaprogram.Itincludesaneditorareaandthefollowingviews.
Debug
Breakpoints
Variables
Expressions
Outline
Console
Tasks

Javaviews

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 92/322
12/10/2015 Javadevelopmentuserguide
Breakpointsview
Consoleview
Debugview
Displayview
Expressionsview
Javaoutline
PackageExplorerview
TypeHierarchyview
Variablesview

3.4.JavaViews
TheJavadevelopmenttoolscontributethefollowingviewstotheworkbench:

Java

PackageExplorerView
ThePackageExplorerviewshowsaJavaspecificviewofresourcesinsideJavaprojectsinyourworkbench.TheJavaelementhierarchyisdefinedbytheproject'sbuildclass
pathsandconsistsofelementslike
sourcefoldersandlibraries
packages
sourceandclassfiles
types,methods,fieldsandinitializers

TypeHierarchyView
TheTypeHierarchyviewallowsyoutolookatthecompletehierarchyforatype,onlyitssubtypes,oronlyitssupertypes.Youcanalsoopenthehierarchyonaproject,source
folderorpackage.

CallHierarchyView
TheCallHierarchyviewallowsyoutolookatthecallersandcalleesforaselectedJavamember.

JavaOutlineView
TheJavaoutlineviewdisplaysanoutlineofthestructureofthecurrentlyactiveJavafileintheeditorarea.

JUnitView
TheJUnitviewshowsyoutheJUnittestrunprogressandstatus,andallowsyoutoreruntests.

JavadocView
TheJavadocviewshowstheJavadocoftheelementselectedintheJavaeditororinaJavaview.

DeclarationView
TheDeclarationviewshowsthesourceoftheelementselectedintheJavaeditororinaJavaview.

JavaBrowsing

ProjectsView
TheProjectsviewshowsJavaprojects,sourcefolders,externalandinternallibraries.
Note:sourcefoldersandlibraries(bothinternalandexternal)presentedinthisviewarenotexpandable.Whentheyareselected,theircontentsareshowninthePackages
view.

PackagesView
ThePackagesviewshowsalistofJavapackagesfromthecurrentlyselectedJavaprojects,sourcefoldersorlibraries.Typically,theProjectsviewisusedtomakethis
selection.

TypesView
TheTypesviewshowsalistofJavatypesfromthecurrentlyselectedpackages.Typically,thePackagesviewisusedtomakethisselection.

MembersView
TheMembersviewshowsthecontentofatype,compilationunitorCLASSfile.Typically,theTypesviewisusedtomakethisselection.

Debug

DebugView
TheDebugviewallowsyoutomanagethedebuggingorrunningofaprogramintheworkbench.Itdisplaysthestackframeforthesuspendedthreadsforeachtargetyouare
debugging.Eachthreadinyourprogramappearsasanodeinthetree.Itdisplaystheprocessforeachtargetyouarerunning.

BreakpointsView
TheBreakpointsviewlistsallthebreakpointsyoucurrentlyhavesetinyourworkspace.Youcanalsoenableordisablebreakpoints,deletethem,addnewones,groupthemby
workingset,orconfigureattributesofaselectedbreakpoint.

ExpressionsView
DatacanbeinspectedintheExpressionsview.Youcaninspectdatafromascrapbookpage,astackframeofasuspendedthread,andotherplaces.TheExpressionsView
opensautomaticallywhenanitemisaddedtotheview.EntriesintheExpressionsViewcanbeselectedtohavemoredetailedinformationbedisplayedintheDetailPane.
WhendebuggingaJavaprogram,datathatcontainsvariablescanbeexpandedtoshowthevariablesandthefieldsthevariablescontain.

VariablesView

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 93/322
12/10/2015 Javadevelopmentuserguide
TheVariablesviewdisplaysinformationaboutthevariablesassociatedwiththestackframeselectedintheDebugView.WhendebuggingaJavaprogram,variablescanbe
selectedtohavemoredetailedinformationbedisplayedintheDetailPane.Inaddition,Javaobjectscanbeexpandedtoshowthefieldsthatvariablecontains.

ConsoleView
TheConsoleviewdisplaysavarietyofconsoletypesdependingonthetypeofdevelopmentandthecurrentsetofusersettings.Theconsolesthatareprovidedbydefaultwith
theEclipsePlatformare:
TheProcessConsole
TheStacktraceConsole
TheCVSConsole
TheOSGiConsole

DisplayView
TheDisplayviewdisplaystheresultofevaluatinganexpressioninthecontextofthecurrentstackframe.Youcanevaluateanddisplayaselectioneitherfromtheeditoror
directlyfromtheDisplayView.

ViewCustomization
BoththeappearanceandbehavioroftheJavaviewscanbecustomized.
Filtering
Sorting
Javaelementdecorations
Presentationoptions

Javaperspectives

ChangingtheappearanceoftheConsoleview

Viewsandeditors

3.4.1.FilteringinJavaViews

ApplyingViewFilters
AllJavaviewsallowtofilterthedisplayedJavaelements.Thesetofavailablefiltersdependsontheview.
Tofilterelements:
1. Ontheviewtoolbar,clicktheMenubuttonandchooseFilters....
2. Selectorclearthefiltersthatyouwanttoapplytotheview(readFilterdescriptiontolearnabouttheselectedfilter'sfunctionality).
3. Optionally,youcanselectpatternsforfilteringtheview:
SelecttheNamefilterpatternscheckboxatthetopofthedialog.
Inthetextfieldbelow,specifythedesiredpatterns(namesmatchingoneofthepatternswillbehidden).

FilteringMembers
SeveralJavaviews(e.g.Outline,TypeHierarchy,Members)offerfilteringofmembers(fields,typesandmethods).Thefiltersareavailableastoolbarbuttonsorasviewmenu
items,dependingontheview.Thereare3memberfilters:
HideFields:whenactivated,thisfiltercausesallfieldstoberemovedfromtheview.
HideStaticFieldsandMethods:whenactivated,thisfiltercausesallstaticmemberstoberemovedfromtheview.
HideNonPublicMembers:whenactivated,thisfiltercausesallnonpublicmemberstoberemovedfromtheview.
Additionally,thePackageExplorerviewcandisplayorhideallelementsinsidecompilationunits.
ToshoworhidemembersinthePackageExplorerview,selectorcleartheShowmembersinPackageExplorercheckboxinthe Java>Appearancepreferencepage.

FilteringWorkingSets
SeveralJavaviews(e.g.PackageExplorer,TypeHierarchy)offertofilterbyoneormoreworkingsets.Thefiltersareavailableintheviewmenu.Onlytheelementsthatare
containedintheselectedworkingsetsareshownintheview.

Javaprojects
Workingsets

PackageExplorer

3.4.2.SortinginJavaViews
TheMembersandOutlineviewscanpresentmemberssortedorintheorderofdeclarationinthecompilationunit.
Tosortmembers:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 94/322
12/10/2015 Javadevelopmentuserguide
ToggleontheSorttoolbarbuttonintheviewtoolbar.
Thesortingordercanbeconfiguredontheonthe Java>Appearance>MembersSortOrderpreferencepage.
Aftertheabovesortingisperformed,membersineachgrouparesortedalphabetically.
Topresentmembersintheorderofdeclarationinthecompilationunit.
ToggleofftheSorttoolbarbuttonintheviewtoolbar.

Javatoolbaractions

3.4.3.JavaElementDecorations

OverrideIndicators
Javaviewscanshowspecialdecorationiconstoindicatemethodsthatoverrideorimplementmethodsfromsupertypes.
Toshoworhidetheoverrideindicators,selectorcleartheJavaMethodOverrideIndicatorcheckboxinthe General>Appearance>LabelDecorationspreferencepage.

JavaTypeIndicator
ThepackageexplorercanindicatethekindofJavatype(Enum,Interface,Annotation)containedinaJavafile.
Note:
IfaJavafilecontainsmorethanonetopleveltype,itisdecoratedaccordingtoitsprimarytype.
Nodecorationisshownforclasses,exceptforabstractclasses.
ToshoworhidetheJavatypeindicators,selectorcleartheJavaTypeIndicatorcheckboxinthe General>Appearance>LabelDecorationspreferencepage.

Appearancepreferencepage
PackageExplorer

3.4.4.PresentationOptionsforJavaViews

ShowingandHidingMethodReturnTypes
SeveralJavaviews(e.g.Outline,Members)presentmethodsandcanalsoshowtheirreturntypesandtypeparameters.
ToshowmethodreturntypesinJavaviewsselectorcleartheShowmethodreturntypesorShowmethodtypeparameterscheckboxinthe Java>Appearancepreference
page.

ShowingFullorCompressedPackageNames
ThePackageExplorerandPackagesviewscanshowfullorcompressedpackagenames.
Toshowfullpackagenames:
CleartheCompressallpackagenamesegments,exceptthefinalsegmentcheckboxonthe Java>Appearancepreferencepage.
Toshowcompressedpackagenames:
SelecttheCompressallpackagenamesegments,exceptthefinalsegmentcheckboxonthe Java>Appearancepreferencepage.
Compressionpatternscontrolhowmanycharactersofeachpackagenamesegmentaredisplayed.Thelastsegmentofapackagenameisalwaysdisplayed.
Acompressionpatternof"."indicatesthatonlytheseparatingperiodsareshowntorepresentasegment.Adigit(n)inacompressionpatternrepresentsthefirstncharactersof
apackagenamesegment.Examplesarethebestwaytounderstandcompressionpatterns.Thepackageorg.eclipse.jdtwouldbedisplayedasfollowsusingtheexample
compressionpatterns:
...jdt
0jdt
2~or~.ec~.jdt
3~org.ecl~.jdt

Javaappearancepreferencepage
PackageExplorer

3.5.JavaEditor
TheJavaeditorprovidesspecializedfeaturesforeditingJavacode.
AssociatedwiththeeditorisaJavaspecificOutlineview,whichshowsthestructureoftheactiveJavacompilationunit.Itisupdatedastheusereditsthecompilationunit.
Theeditorcanalsoshowabreadcrumbnavigationbar.Thebreadcrumbshowstheparentchainoftheelementatthecurrentcursorposition.Itisalsoupdatedwhentheuseredits
thecompilationunitorchangestheselection.
TheJavaeditorcanbeopenedonbinaryCLASSfiles.IfaJARfilecontainingtheCLASSfileshasasourceattachment,thentheeditorshowsthecorrespondingsource.
Theeditorincludesthefollowingfeatures:
Syntaxhighlighting
Content/codeassist
Codeformatting
Importassistance
Quickfix
Integrateddebuggingfeatures

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 95/322
12/10/2015 Javadevelopmentuserguide
TheJavaeditorcanbeconfiguredtoeithershowanentirecompilationunitorasingleJavaelementonly.Tochangethesetting,usethetoolbarbuttonShowSourceofSelected
ElementOnly.
ThemostcommonwaytoinvoketheJavaeditoristoopenaJavafilefromthePackageExplorerusingpopupmenusorbyclickingthefile(singleordoubleclickdependingonthe
userpreferences).YoucanalsoopentheeditorbyopeningJavaelements,suchastypes,methods,orfields,fromotherviews.

Quickfixandassist
Templates

Openinganeditorforaselectedelement
Viewingruntimeexceptions
Evaluatingexpressions

Quickassists
Quickfixes
Javaeditoractions
Javaeditorpreferences
Javaoutline
JavaEditorBreadcrumb
Viewsandeditors

3.6.QuickFixandQuickAssist
Formostproblemsunderlinedwithaproblemhighlightline,theJavaeditorcanoffercorrections.Thisisshownbythelightbulbshownintheeditormarkerbar.


ToseethecorrectionproposalsusetheQuickFixaction
Setthecursorinsideornearthehighlightrange,andselectQuickFixfromtheEditmenuorthecontextmenu.
Setthecursorinsideornearthehighlightrange,andpressCtrl+1
Clickonthelightbulb
QuickfixisalsoavailableonaproblementryintheProblemsview.TheQuickFixactionwillopenadialogtoselectthecorrection.

Notethatthelightbulbisonlyahint.Itispossiblethatevenwiththelightbulbshown,itturnsoutthatnocorrectionscanbeoffered.
AoverviewofquickfixesavailableintheJavaeditorcanbefoundhere.

QuickAssistsareproposalsavailableevenifthereisnoproblemorwarning.TheyusethesameshortcutandactionlikeQuickFix.Quickassistsareusedforlocalcode
manipulations.SeetheQuickassistreferenceformoreinformation.

Javaeditor

Quickassists
Quickfix
Javaeditorpreferences
Editmenu

3.7.EditorTemplates
Templatesareastructureddescriptionofcodingpatternsthatreoccurinsourcecode.TheJavaeditorsupportstheuseoftemplatestofillincommonlyusedsourcepatterns.
Templatesareinsertedusingcontentassist(Ctrl+Space).
Forexample,acommoncodingpatternistoiterateovertheelementsofanarrayusingaforloopthatindexesintothearray.Byusingatemplateforthispattern,youcanavoid
typinginthecompletecodefortheloop.Invokingcontentassistaftertypingthewordforwillpresentyouwithalistofpossibletemplatesforaforloop.Youcanchoosethe
appropriatetemplatebyname(iterateoverarray).Selectingthistemplatewillinsertthecodeintotheeditorandpositionyourcursorsothatyoucaneditthedetails.
Templatescancontaintemplatevariables.Variablesmarktheeditablelocations.Theycanberesolvedtoaconcretevaluewhenthetemplateisevaluatedinitscontext.Theycan
alsoprovidealistofalternativeproposalsvalidatthegivenlocation.
Manycommontemplatesarealreadydefined.Thesecanbeviewedwiththe Java>Editor>Templatespreferencepage.Youcanalsocreateyourowntemplatesoreditthe
existingones.

Templatespreferences
Templatevariables
Templateediting
Editmenu
Javacontentassist

3.7.1.JavaEditorTemplateVariables
GeneralTemplateVariables
JavaSpecificTemplateVariables

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 96/322
12/10/2015 Javadevelopmentuserguide
Templatevariablesmaybeusedinthetemplatepattern.Variablesareresolvedtotheirconcretevaluewhenthetemplateisevaluatedinitscontext.Variablesmaybespecified
usingsimpleorfullsyntax:
Simplevariablestakethefollowingform:
${array}
Thisdefinesavariablewithnamearraythatwillresolvetoanarray.Itcanbereferencedmultipletimesasis.
Fullvariablestakethefollowingform:
${it:var(java.util.Iterator)}
Thisdefinesavariablewithnameitthatwillresolvetoalocalvariableoftypejava.util.Iterator.Itcanbereferencedmultipletimesbysimplygivingitsnamewithoutthe
type:${it}.
Argumentstoafullvariablecanbewrittenverbatimiftheyarequalifiednamesorintegers.Ifanargumentincludesothercharactersorspaces,thenithastobeenclosedin
singlequotes''.
Ifthereareseveralpossiblematchesforavariable,theymaybepresentedasproposalstotheuser.

GeneralTemplateVariables
BothJavaandJavadoccontextdefinethefollowingvariables:

Variable Description
${cursor} Specifiesthecursorpositionwhenthetemplateeditmodeisleft.Thisisusefulwhenthecursorshouldjumptoanotherplacethantotheend
ofthetemplateonleavingtemplateeditmode.
${date} Evaluatestothecurrentdate.
${dollar} Evaluatestothedollarsymbol$.Alternatively,twodollarscanbeused:$$.
${enclosing_method} Evaluatestothenameoftheenclosingmethod.
${enclosing_method_arguments} Evaluatestoacommaseparatedlistofargumentnamesoftheenclosingmethod.Thisvariablecanbeusefulwhengeneratinglogstatements
formanymethods.
${enclosing_package} Evaluatestothenameoftheenclosingpackage.
${enclosing_project} Evaluatestothenameoftheenclosingproject.
${enclosing_type} Evaluatestothenameoftheenclosingtype.
${file} Evaluatestothenameofthefile.
${line_selection} Evaluatestocontentofallcurrentlyselectedlines.
${primary_type_name} Evaluatestothenameprimarytypeofthecurrentcompilationunit.
${return_type} Evaluatestothereturntypeoftheenclosingmethod.
${time} Evaluatestothecurrenttime.
${user} Evaluatestotheusername.
${word_selection} Evaluatestothecontentofthecurrenttextselection.
${year} Evaluatestothecurrentyear.

JavaSpecificTemplateVariables
TheJavacontextadditionallydefinesthefollowingvariables.Note:Inthetablebelow,idisauserchosennameofanewvariable.

Variable Description
${id:field(type[,type]*)} Evaluatestoafieldinthecurrentscopethatisasubtypeofanyofthegiventypes.Ifnotypeisspecified,anynonprimitive
fieldmatches.
Example:
${count:field(int)}

${id:var(type[,type]*)} Evaluatestoafield,localvariableorparametervisibleinthecurrentscopethatisasubtypeofanyofthegiventypes.Ifno
typeisspecified,anynonprimitivevariablematches.
Example:
${container:var(java.util.List,'java.lang.Object[]')}

${id:localVar(type[,type]*)} Evaluatestoalocalvariableorparametervisibleinthecurrentscopethatisasubtypeofanyofthegiventype.Ifnotypeis
specified,anynonprimitivelocalvariablematches.
${array}isashortcutfor${array:localVar('java.lang.Object[]')},butalsomatchesarraysofprimitivetypes.
${collection}isashortcutfor${collection:localVar(java.util.Collection)}.
${iterable}isashortcutfor${iterable:localVar(java.lang.Iterable)},butalsomatchesarrays.

${id:argType(variable,n)} Evaluatestothenthtypeargumentofthereferencedtemplatevariable.Thereferenceshouldbethenameofanother
templatevariable.Resolvestojava.lang.Objectifthereferencedvariablecannotbefoundorisnotaparameterizedtype.
Example:
${type:argType(vector,0)}${first:name(type)}=${vector:var(java.util.Vector)}.get(0)

${id:elemType(variable)} Evaluatestotheelementtypeofthereferencedtemplatevariable.Thereferenceshouldbethenameofanothertemplate
variablethatresolvestoanarrayoraninstanceofjava.lang.Iterable.TheelemTypevariabletypeissimilarto
${id:argType(reference,0)},thedifferencebeingthatitalsoresolvestheelementtypeofanarray.

${array_type}isashortcutfor${array_type:elemType(array)}.
${iterable_type}isashortcutfor${iterable_type:elemType(iterable)}.

${id:newName(reference)} Evaluatestoanonconflictingnameforanewlocalvariableofthetypespecifiedbythereference.Thereferencemayeither
beaJavatypenameorthenameofanothertemplatevariable.Thegeneratednamerespectsthecodestylesettings.
${index}isashortcutfor${index:newName(int)}.
${iterator}isashortcutfor${iterator:newName(java.util.Iterator)}.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 97/322
12/10/2015 Javadevelopmentuserguide
${array_element}isashortcutfor${array_element:newName(array)}.
${iterable_element}isashortcutfor${iterable_element:newName(iterable)}.

${id:newType(qualifiedTypeName)} EvaluatestoatypenamegiventhefullyqualifiedJavatypename.Evaluatestoasimpletypenameandanimportifno
conflictingtypeexists.Evaluatestoafullyqualifiedtypenameotherwise.
Example:
${type:newType(java.util.Iterator)}

${:import(type[,type]*)} Addsanimportstatementforeachtype.Doesnothingiftheimportalreadyexists.Doesnothingifaconflictingimport
exists.Evaluatestonothing.
Example:
${:import(java.util.List,java.util.Collection)}

${:importStatic([qualifiedName[,qualifiedName]*])} Addsastaticimportstatementforeachqualifiednamethatisnotalreadyimported.ThequalifiedNameisthefullyqualified
nameofastaticfieldormethod,oritisthequalifiednameofatypeplusa.*suffix,enclosedinsinglequotes''.Does
nothingifaconflictingimportexists.Evaluatestonothing.
Example:
${is:importStatic(java.util.Collections.EMPTY_SET,'java.lang.System.*')}

${id:link(proposal[,proposal]*)} Evaluatestoidifthelistofproposalsisempty,evaluatestothefirstproposalotherwise.Theevaluatedvalueisputinto
linkedmode.Aproposalwindowshowsallthegivenproposals.
Example:
java.util.Collections.${kind:link(EMPTY_SET,EMPTY_LIST,EMPTY_MAP)}

${array} Evaluatestoaproposalforanarrayvisibleinthecurrentscope.
${array_element} Evaluatestoanameforanewlocalvariableforanelementofthe${array}variablematch.
${array_type} Evaluatestotheelementtypeofthe${array}variablematch.
${collection} Evaluatestoaproposalforacollectionvisibleinthecurrentscope.
${exception_variable_name} Exceptionvariablenameincatchblocks.
${index} Evaluatestoaproposalforanundeclaredarrayindex.
${iterator} Evaluatestoanunusednameforanewlocalvariableoftypejava.util.Iterator.
${iterable} Evaluatestoaproposalforaniterableorarrayvisibleinthecurrentscope.
${iterable_element} Evaluatestoanameforanewlocalvariableforanelementofthe${iterable}variablematch.
${iterable_type} Evaluatestotheelementtypeofthe${iterable}variablematch.
${todo} Evaluatestoaproposalforthecurrentlyspecifieddefaulttasktag.

Templates

Editingtemplates
Templatespreferencepage
Javacontentassist
Tasktagpreferences
Codetemplatespreferences
Codestylepreferences

3.8.JavaSearch
TheJavasearchingsupportallowsyoutofinddeclarations,referencesandoccurrencesofJavaelements(packages,types,methods,fields).Searchingissupportedbyanindex
thatiskeptuptodateinthebackgroundastheresourcescorrespondingtoJavaelementsarechanged.TheJavasearchoperatesonworkspacesindependentoftheirbuildstate.
Forexample,searchescanbeconductedwhenautobuildisturnedoff.
ThefollowingsearchescanbeinitiatedfromthepopupmenusofJavaelementsorfromtheJavasearchdialog:

Command Description

References FindsallreferencestotheselectedJavaelement

Declarations FindsalldeclarationsoftheselectedJavaelement

Implementors FindsallimplementorsoftheselectedJavainterface

Readaccess FindsallreadaccessestotheselectedJavafield

Writeaccess FindsallwriteaccessestotheselectedJavafield

Matchlocationsfortypereferences Findsalltypereferencesatspecifiedlocations(incasts,asfieldtype,...)

OccurrencesinFile FindsalloccurrencesoftheselectedJavaelementinitsfile

Thescopeofthesearchisdefinedas:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 98/322
12/10/2015 Javadevelopmentuserguide
Workspaceallprojectsandfilesintheworkspaceareincludedinthissearch
EnclosingProjectstheprojectsenclosingthecurrentlyselectedelements
Hierarchyonlythetypehierarchyoftheselectedelementisincludedinthissearch
WorkingSetonlyresourcesthatbelongtothechosenworkingsetareincludedinthissearch

Searchactions
Javasearchtab

3.9.RefactoringSupport
ThegoalofJavaprogramrefactoringistomakesystemwidecodechangeswithoutaffectingthebehavioroftheprogram.TheJavatoolsprovideassistanceineasilyrefactoring
code.
TherefactoringtoolssupportanumberoftransformationsdescribedinMartinFowler'sbookRefactoring:ImprovingtheDesignofExistingCode,AddisonWesley1999,suchas
ExtractMethod,InlineLocalVariable,etc..
TogetanoverviewofallofferedrefactoringslookattheRefactormenu.Refactoringcommandsarealsoavailablefromthecontextmenusinmanyviewsorappearasquick
assists.
Whenperformingarefactoringoperation,youcanoptionallypreviewallofthechangesresultingfromarefactoringactionbeforeyouchoosetocarrythemout.Whenpreviewinga
refactoringoperation,youwillbenotifiedofpotentialproblemsandwillbepresentedwithalistofthechangestherefactoringactionwillperform.Ifyoudonotpreviewarefactoring
operation,thechangewillbemadeinitsentiretyandanyresultantproblemswillbeshown.Ifaproblemisdetectedthatdoesnotallowtherefactoringtocontinue,theoperationwill
behaltedandalistofproblemswillbedisplayed.
RefactoringcommandsareavailablefromthecontextmenusofseveralJavaviews(e.g.PackageExplorer,Outline)andeditors.Many"apparentlysimple"commands,suchas
MoveandRename,areactuallyrefactoringoperations,sincemovingandrenamingJavaelementsoftenrequirechangesindependentfiles.
Refactoringscannotonlybeperformedinteractively,butalsofromrefactoringscripts.MostrefactoringsavailableintheRefactormenuarestoredintheworkspacerefactoring
historyinordertobeusedinrefactoringscriptsafterwards.Therefactoringtoolssupportthecreationofrefactoringscriptsbasedonrefactoringsintheworkspacerefactoringhistory.
Refactoringscriptscanthenbeappliedtoanarbitraryworkspace.Applyingarefactoringscriptlaunchesarefactoringwizardwhichisabletoreplaytherefactoringsasiftheyhad
beeninitiatedbytheuserwhichoriginallyhadcreatedthem.
Relatedtorefactoringscripts,therefactoringtoolsofferarefactoringtomigrateaJARFiletoanewerversion,usingrefactoringinformationtoavoidbreakingchangesinyour
workspaceafterthemigration.

Refactoringactions
Refactoringwizard
Javapreferences

3.10.Debugger
TheJavadevelopmenttoolkit(JDT)includesadebuggerthatenablesyoutodetectanddiagnoseerrorsinyourprogramsrunningeitherlocallyorremotely.
Thedebuggerallowsyoutocontroltheexecutionofyourprogrambysettingbreakpoints,suspendinglaunchedprograms,steppingthroughyourcode,andexaminingthecontentsof
variables.
Thedebuggerhasaclient/serverdesignsoyoucandebugprogramsrunningremotelyonothersystemsinthenetworkaswellasprogramsrunninglocallyonyourworkstation.The
debugclientrunsinsidetheworkbenchonyourworkstation.Thedebuggerserverrunsonthesamesystemastheprogramyouwanttodebug.Thiscouldbeaprogramlaunchedon
yourworkstation(localdebugging)oraprogramstartedonacomputerthatisaccessiblethroughanetwork(remotedebugging).

Javadevelopmenttools(JDT)
Breakpoints
Remotedebugging
Localdebugging

Addingbreakpoints
Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
Evaluatingexpressions
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Suspendingthreads

Debugpreferences
Debugview
Runmenuactions
RunandDebugtoolbaractions

3.11.Scrapbook
TheJavadevelopmenttoolkit(JDT)contributesascrapbookfacilitythatcanbeusedtoexperimentandevaluateJavacodesnippetsbeforebuildingacompleteJavaprogram.
SnippetsareeditedandevaluatedintheScrapbookpageeditor,withresultantproblemsreportedintheeditor.
FromaJavascrapbookeditor,youcanselectacodesnippet,evaluateit,anddisplaytheresultasastring.Youcanalsoshowtheobjectthatresultsfromevaluatingacodesnippet
inthedebuggers'ExpressionsView.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 99/322
12/10/2015 Javadevelopmentuserguide
Javadevelopmenttools(JDT)
Debugger

CreatingaJavascrapbookpage
Displayingtheresultofevaluatinganexpression
Inspectingtheresultofevaluatinganexpression

NewJavaScrapbookPagewizard
JavaScrapbookpage
Expressionsview

3.12.LocalDebugging
TheJavadebuggerhasaclient/serverdesignsothatitcanbeusedtodebugprogramsthatrunlocally(onthesameworkstationasthedebugger)orremotely(onanothercomputer
onthenetwork).
Localdebuggingisthesimplestandmostcommonkindofdebugging.AfteryouhavefinishededitingandbuildingyourJavaprogram,youcanlaunchtheprogramonyour
workstationusingthe Run>DebugConfigurations...menuitemontheworkbench.Launchingtheprograminthiswaywillestablishaconnectionbetweenthedebuggerclient
andtheJavaprogramthatyouarelaunching.Youmaythenusebreakpoints,stepping,orexpressionevaluationtodebugyourprogram.

Breakpoints

Addingbreakpoints
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Suspendingthreads

Debugpreferences
Debugview
Runmenuactions
RunandDebugtoolbaractions

3.13.RemoteDebugging
Theclient/serverdesignoftheJavadebuggerallowsyoutolaunchaJavaprogramfromcomputeronyournetworkanddebugitfromtheworkstationrunningtheplatform.Thisis
particularlyusefulwhenyouaredevelopingaprogramforadevicethatcannothostthedevelopmentplatform.Itisalsousefulwhendebuggingprogramsondedicatedmachines
suchaswebservers.
Note:Touseremotedebugging,youmustbeusingaJavaVMthatsupportsthisfeature.
Todebugaprogramremotely,youmustbeabletolaunchtheprogramindebugmodeontheremotemachinesothatitwillwaitforaconnectionfromyourdebugger.Thespecific
techniqueforlaunchingtheprogramandconnectingthedebuggerareVMspecific.Thebasicstepsareasfollows:
1. EnsurethatyouarebuildingyourJavaprogramwithavailabledebuginformation.(Youcancontroltheseattributesfromthe Java>Compilerpreferencepage).
2. AfteryoubuildyourJavaprogram,installittothetargetcomputer.Thisinvolvescopyingthe.CLASSfilesor.JARfilestotheappropriatelocationontheremotecomputer.
3. InvoketheJavaprogramontheremotecomputerusingtheappropriateVMargumentstospecifydebugmodeandacommunicationportforthedebugger.
4. Startthedebuggerusingaremotelaunchconfigurationandspecifytheaddressandportoftheremotecomputer.
Whensettinguptheremotelaunchconfigurationthereareafewitemstotakenoteof:
Youmustensureyouenterthecorrecthostnamei.e.thenameoftheremotecomputerwhereyouarecurrentlyrunningyourcode.ThehostnamecanalsobetheIPaddressof
theremotemachine,forexampleusing127.0.0.1insteadoflocalhost.
Theportnumbermustbethenumberoftheportontheremotemachine.
CertainJavaVMssupportanotherwayofstartingaremotedebugsession.Inthisalternativeconnectiontype,thedebuggerislaunchedfirst.Thedebuggerthenwaitsandlistensfor
theVMtoconnecttoit.Todebugthisway,youmustproperlyconfigureandlauncharemotedebugsession,thenlaunchtheVM,specifyingthelocationofyourwaitingdebugger.
Formoreinformation,seeUsingtheremoteJavaapplicationlaunchconfiguration.

UsingtheremoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM

3.14.Breakpoints
Abreakpointsuspendstheexecutionofaprogramatthelocationwherethebreakpointisset.
BreakpointscanbeenabledanddisabledviathecontextmenuintheBreakpointsView,orviathecontextmenuintheJavaEditorruler.

Anenabledbreakpointcausesathreadtosuspendwheneverthebreakpointisencountered.Enabledbreakpointsaredrawnwithabluecircle[ ]andhaveacheckmark
overlayoncesuccessfullyinstalled.AbreakpointcanonlybeinstalledwhentheclassthebreakpointislocatedinhasbeenloadedbytheVM.
Adisabledbreakpointwillnotcausethreadstosuspend.Disabledbreakpointsaredrawnwithawhitecircle[ ].
BreakpointsaredisplayedintheverticaleditorrulerandintheBreakpointsview.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 100/322
12/10/2015 Javadevelopmentuserguide
Addingbreakpoints
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Suspendingthreads

Debugpreferences
Debugview
Runmenuactions
Runanddebugtoolbaractions
Breakpointsview

3.15.StringExternalization
TheJavatoolshelpyoutodevelopapplicationsthatcanberunoninternationalplatforms.Animportantfacetofdesigningaprogramforuseindifferentcountriesisthelocalization,
orexternalization,oftextthatisdisplayedbytheprogram.Byexternalizingstrings,thetextcanbetranslatedfordifferentcountriesandlanguageswithoutrebuildingtheJava
program.
TheJDTprovidesthefollowingsupportforinternationalizationandstringexternalization:
Acompileroptionletsyoumarknonexternalizedstringsascompiletimewarningsorerrors.
SeetheNonexternalizedstringsoptionintheCodestylesectionofthe Java>Compiler>Errors/Warningspreferencepage.
Toolsthatallowyoutofindstringsthathavenotbeenexternalized.
Awizardthatwillguideyouthroughexternalizingthestrings.
Toolsthathelpyoutofindunusedandincorrectlyusedkeysforstringslocatedinpropertyfiles.
Commentscanbeusedtodenotestringsthatshouldnotbeexternalizedandshouldnotresultincompiletimewarningsorerrors.Thesecommentsareofform//$NONNLSn$
wherenisthe1basedindexofthestringinalineofcode.
Additionalinformationaboutinternationalizedapplicationscanbefoundinthefollowingdocuments:
http://eclipse.org/articles/ArticleInternationalization/how2I18n.html
http://download.oracle.com/javase/tutorial/i18n/

Findingstringstoexternalize
Findingunusedandincorrectlyusedkeysinpropertyfiles

Sourcemenu
Externalizestringswizard
Javacompilerpreferences

4.1.1.Changingtheactiveperspectivewhenlaunching
Youcancontrolwhichperspectivebecomesactivewhenaprogramislaunchedandwhenitsuspends.Thesettingisconfigurableforeachlaunchconfigurationtype,foreachofthe
launchmodesitsupports.
Toactivateaparticularperspectivewhenaprogramislaunched,dothefollowing:
1. Openthe Run/Debug>Perspectivespreferencepage.
2. SelecttheAlwaysoptionfortheOpentheassociatedperspectivewhenlaunchingpreference.Thiswillcausetheperspectiveassociatedwithaprogramtobecomeactive
wheneveritislaunched.
Toactivateaparticularperspectivewhenaprogramissuspends,dothefollowing:
1. Openthe Run/Debug>Perspectivespreferencepage.
2. SelecttheAlwaysoptionfortheOpentheassociatedperspectivewhenanapplicationsuspendspreference.Thiswillcausetheperspectiveassociatedwithaprogramto
becomeactivewheneveraprogramsuspends.
Toassociateaparticularperspectivewithaprogram,dothefollowing:
1. Openthe Run/Debug>Perspectivespreferencepage.
2. Selectthetypeofapplicationthatyouwouldliketoassociateaperspectivewith(forexample,JavaApplication).
3. Foreachlaunchmode,selectthedesiredperspectiveusingthecombobox.Thiswillcausetheperspectiveyouchoosetobecomeactivebasedonyourpreferencesettings
(i.e.whenaprogramislaunchedand/orwhenitsuspends).
Ifthespecifiedperspectiveisnotopenatthetimeitneedstobeactivated,thatperspectiveiscreated.

Debugger
Remotedebugging
Localdebugging
Javaperspectives

Runninganddebugging
Settingexecutionarguments
LaunchingaJavaprogram

Consoleview
Debugpreferences
Debugview
RunMenu

4.1.2.Changingtheappearanceoftheconsoleview
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 101/322
12/10/2015 Javadevelopmentuserguide
Tosetthetypesofoutput(andtheircolors)intheConsoleview:
1. Openthe Run/Debug>Consolepreferencepage.
2. CheckingtheShowwhenprogramwritestostandardoutcheckboxwillmaketheConsoleviewvisibleeachtimenewoutputiswrittentotheconsolefromtheprogram's
standardoutputstream.IfthereisnoConsoleviewinthecurrentperspective,onewillbecreated.
3. CheckingtheShowwhenprogramwritestostandarderrcheckboxwillmaketheConsoleviewvisibleeachtimenewoutputiswrittentotheconsolefromtheprogram's
standarderrorstream.IfthereisnoConsoleviewinthecurrentperspective,onewillbecreated.
4. Clickanyofthecolorbuttonstochangethecolorforthecorrespondingtextstream.
TosetthefontsusedintheConsoleview:
1. Openthe General>Appearance>ColorsandFontspreferencepage.
2. SelectConsolefontfromtheDebugcategoryandusetheChange...buttontochangethefont.(TheDetailPaneTextFontcanbeusedtochangethefontofthe
debugger'sdefaultDetailPane).

Debugger
Javaviews

Consoleview
Viewsandeditors

4.2.CreatingJARFiles
YoucancreateandregenerateJARfilesintheworkbench.

CreatinganewJARfile
RegeneratingaJARfile
CreatinganewRunnableJARfile

JARfileexporter
RunnableJARfileexporter

4.2.1.CreatingaNewJARFile
TocreateanewJARfileintheworkbench:
1. InthePackageExplorer,youcanoptionallypreselectoneormoreJavaelementstoexport.(Thesewillbeautomaticallyselectedinthe JARPackageSpecification
wizardpage,describedinStep4.)
2. Eitherfromthecontextmenuorfromthemenubar'sFilemenu,selectExport.
3. ExpandtheJavanodeandselectJARfile.ClickNext.
4. IntheJARFileSpecificationpage,selecttheresourcesthatyouwanttoexportintheSelecttheresourcestoexportfield.
5. SelecttheappropriatecheckboxtospecifywhetheryouwanttoExportgeneratedclassfilesandresourcesorExportJavasourcefilesandresources.Note:Selected
resourcesareexportedinbothcases.
6. IntheSelecttheexportdestinationfield,eithertypeorclickBrowsetoselectalocationfortheJARfile.
7. SelectorcleartheCompressthecontentsoftheJARfilecheckbox.
8. SelectorcleartheOverwriteexistingfileswithoutwarningcheckbox.Ifyouclearthischeckbox,thenyouwillbepromptedtoconfirmthereplacementofeachfilethatwill
beoverwritten.
9. Note:TheoverwriteoptionisappliedwhenwritingtheJARfile,theJARdescription,andthemanifestfile.
10. Youhavetwooptions:
ClickFinishtocreatetheJARfileimmediately.
ClickNexttousetheJARPackagingOptionspagetosetadvancedoptions,createaJARdescription,orchangethedefaultmanifest.

Settingadvancedoptions
DefiningtheJARfile'smanifest
RegeneratingaJARfile

JARfileexporter
PackageExplorer

4.2.2.SettingAdvancedOptions
1. FollowtheprocedureforcreatingaJARfile,butclickNextinthelaststeptogototheJARPackagingOptionspage.
2. IfyouwanttosavetheJARfiledescription,selecttheSavethedescriptionofthisJARintheworkspacecheckbox.AJARfiledescriptioncanbeusedtoregeneratea
JARfilewithoutusingthewizard.
3. ThecompilerisabletogenerateCLASSfilesevenwhensourcecontainserrors.YouhavetheoptiontoexcludeCLASS(butnotsource)fileswithcompileerrors.Thesefiles
willbereportedattheend,ifreportingisenabled.
4. YoucanchoosetoexcludeCLASS(butnotsource)filesthathavecompilewarnings.Thesefileswillbereportedattheend.
Note:Thisoptiondoesnotautomaticallyexcludeclassfileswithcompileerrors.
5. YoucanchoosetoincludethesourcefolderpathbyselectingtheCreatesourcefolderstructurecheckbox.
6. SelecttheBuildprojectsifnotbuiltautomaticallycheckboxifyouwanttheexporttoperformabuildbeforecreatingtheJARfile.
7. ClickFinishtocreatetheJARfileimmediatelyorNextifyouwanttochangethedefaultmanifest.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 102/322
12/10/2015 Javadevelopmentuserguide
CreatinganewJARfile
DefiningtheJARfile'smanifest
RegeneratingaJARfile

JARfileexporter

4.2.3.DefiningtheJARFile'sManifest
YoucaneitherdefinetheimportantpartsoftheJARfilemanifestdirectlyinthewizardorchoosetouseamanifestfilethatalreadyexistsinyourworkbench.

Creatinganewmanifest
1. FollowtheprocedureforcreatingaJARfile,butclickNextinthelaststeptogototheJARPackagingOptionspage.
2. Setanyadvancedoptionsthatyouwanttoset,andthenclickNextagaintogototheJARManifestSpecificationpage.
3. Ifitisnotalreadyselected,clicktheGeneratethemanifestfilebutton.
4. Youcannowchoosetosavethemanifestintheworkbench.Thiswillsavethemanifestforlateruse.ClickSavethemanifestintheworkspace,thenclickBrowsenextto
theManifestfilefieldtospecifyapathandfilenameforthemanifest.
5. IfyoudecidedtosavethemanifestfileinthepreviousstepandyouchosetosavetheJARdescriptiononthepreviouswizardpage,thenyoucanchoosetoreuseitinthe
JARdescription(byselectingtheReuseandsavethemanifestintheworkspacecheckbox).ThismeansthatthesavedfilewillbeusedwhentheJARfileisrecreatedfrom
theJARdescription.ThisoptionisusefulifyouwanttomodifyorreplacethemanifestfilebeforerecreatingtheJARfilefromthedescription.
6. YoucanchoosetosealtheJARandoptionallyexcludesomepackagesfrombeingsealedorspecifyalistwithsealedpackages.Bydefault,nothingissealed.
7. ClicktheBrowsebuttonnexttotheMainclassfieldtospecifytheentrypointforyourapplications.
Note:Ifyourclassisnotinthelist,thenyouforgottoselectitatthebeginning.
8. ClickFinish.ThiswillcreatetheJAR,andoptionallyaJARdescriptionandamanifestfile.

Usinganexistingmanifest
Youcanuseanexistingmanifestfilethatalreadyexistsinyourworkbench.
1. FollowtheprocedureforcreatingaJARfile,butclickNextinthelaststeptogototheJARPackagingOptionspage.
2. Setanyadvancedoptionsthatyouwanttoset,andtheclickNextagaintogototheJARManifestSpecificationpage.
3. ClicktheUseexistingmanifestfromworkspaceradiobutton.
4. ClicktheBrowsebuttontochooseamanifestfilefromtheworkbench.
5. ClickFinish.ThiswillcreatetheJARandoptionallyaJARdescription.

CreatinganewJARfile
Settingadvancedoptions
RegeneratingaJARfile

JARfileexporter

4.2.4.RegeneratingaJARFile
YoucanuseaJARfiledescriptiontoregenerateapreviouslycreatedJARfile.
1. SelectoneormoreJARfiledescriptionsinyourworkbench.
2. Fromtheselection'spopupmenu,selectCreateJAR.TheJARfile(s)areregenerated.

CreatinganewJARfile
DefiningtheJARfile'smanifest

JARfileexporter

4.2.5.CreatingaNewRunnableJARFile
TocreateanewrunnableJARfileintheworkbench:
1. Fromthemenubar'sFilemenu,selectExport.
2. ExpandtheJavanodeandselectRunnableJARfile.ClickNext.
3. Inthe RunnableJARFileSpecificationpage,selecta'JavaApplication'launchconfigurationtousetocreatearunnableJAR.
4. IntheExportdestinationfield,eithertypeorclickBrowsetoselectalocationfortheJARfile.
5. Selectanappropriatelibraryhandlingstrategy.
6. Optionally,youcanalsocreateanANTscripttoquicklyregenerateapreviouslycreatedrunnableJARfile.

RunnableJARfileexporter

4.3.UsingtheLocalHistory
TheJDTextendstheworkbenchconceptofalocalhistoryinthreeways:
AfilecanbereplacedwithaneditionfromthelocalhistoryinthePackageExplorerview.
TheJDTallowsyoutocompareand/orreplaceindividualJavaelements(typesandtheirmembers)witheditionsfromthelocalhistory.
TheJDTallowsyoutorestoreJavaelements(andfiles)deletedfromtheworkbenchthathavebeenkeptinthelocalhistory.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 103/322
12/10/2015 Javadevelopmentuserguide
Note:FilesandJavaelementssuchastypesandtheirmemberschangeintime.A'snapshot'ofwhattheylooklikeapointintime(assavedinthelocalhistory)iscalledanedition.

Javadevelopmenttools(JDT)
Javaviews

ReplacingaJavaelementwithalocalhistoryedition
ComparingaJavaelementwithalocalhistoryedition
Restoringadeletedworkbenchelement

PackageExplorer

4.3.1.ComparingaJavaElementWithaLocalHistoryEdition
1. MakesurethataJavaviewisvisible.
2. OpenaJavaeditorfortheJavafileinwhichyouwanttocompareaJavaelementwithaneditionfromthelocalhistory.
3. Activatetheeditorbyclickingitstabintheeditorarea.TheOutlineviewalsodisplaystheJavafile.Note:ThePackageExplorercanbeconfiguredtoshowornotshowJava
elementsinfiles.UsetheShowMembersinPackageExplorercheckboxonthe Java>Appearancepreferencepagetosetyourpreference.
4. SelecttheelementthatyouwanttocompareintheOutlineorthePackageExplorer.
5. Fromtheelement'spopupmenu,selectCompareWith>ElementfromLocalHistory.
6. TheHistoryviewopensandshowsalleditionsoftheselectedelementavailableinthelocalhistory.
7. Selectaneditioninthehistoryviewtoseethedifferencesbetweentheselectededitionandtheeditionintheworkbenchinacomparisoneditor.
8. Ifyouaredonewiththecomparison,clickclosethecomparisoneditor.

Javaviews
Javaeditor

Usingthelocalhistory

Javaoutline

4.3.2.ReplacingaJavaElementWithaLocalHistoryEdition
1. MakesurethataJavaviewisvisible.
2. OpenaJavaeditorfortheJavafileinwhichyouwanttoreplaceaJavaelementwithaneditionfromthelocalhistory.
3. Activatetheeditorbyclickingitstabintheeditorarea.TheOutlineviewalsodisplaystheJavafile.Note:ThePackageExplorercanbeconfiguredtoshowornotshowJava
elementsinfiles.UsetheShowMembersinPackageExplorercheckboxonthe Java>Appearancepreferencepagetosetyourpreference.
4. SelecttheelementthatyouwanttoreplaceintheOutlineorthePackageExplorer.
5. Fromtheelement'spopupmenu,selectReplaceWith>ElementfromLocalHistory.
6. Intheupperpaneoftheresultingdialog,allavailableeditionsoftheselectedelementinthelocalhistoryaredisplayed.
7. Selectaneditionintheupperpanetoviewthedifferencesbetweentheselectededitionandtheeditionintheworkbench.
8. WhenyouhaveidentifiedtheeditionwithwhichyouwanttoreplacetheexistingJavaelement,clickReplace.
9. Thelocalhistoryeditionreplacesthecurrentoneintheeditor.Note:Thechangedcompilationunithasnotyetbeensavedatthispoint.

Javaviews
Javaeditor

Usingthelocalhistory

Javaoutline

4.3.3.RestoringaDeletedWorkbenchElement
1. EnsurethataJavaviewthatshowJavaelementsinsidefiles(suchastheOutlineview)isvisible.
2. OpenthecompilationunittowhichyouwanttoaddapreviouslyremovedJavaelementfromthelocalhistory.
3. Activatetheeditorbyclickingitstabintheeditorarea,andtheJavaviewshowsthecontentoftheJavafile.
4. IntheJavaview,selecttheelementtowhosecontainertypeyouwanttorestorethedeletedelement.
5. Fromthetype'spopupmenuintheJavaview,selectRestorefromLocalHistory.
6. Intheupperleftpaneoftheresultingdialog,allavailableeditionsoftheselectedelementinthelocalhistoryaredisplayed.
7. Intheleftpanecheckallelementsthatyouwanttoreplace.
8. Foreverycheckedelementselectaneditionintherighthandpaneandviewitscontentinthebottompane.
9. Whenyouhaveidentifiedtheeditionthatyouwanttorestore,pressRestore.Thelocalhistoryeditionsareloadedintotheeditor.

Javaeditor

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 104/322
12/10/2015 Javadevelopmentuserguide

Usingthelocalhistory

Javaoutline

4.4.ExternalizingStrings
Contents
Findingstringstoexternalize
Findingunusedandincorrectlyusedkeysinpropertyfiles

4.4.1.FindingStringstoExternalize
Tofindstringstoexternalize:
InaJavaview(e.g.PackageExplorer),selectasetofpackages,sourcefoldersorprojects.
Fromthemenubar,selectSource>ExternalizeStrings...
Adialogcomesupwithalistofallcompilationunitsthathavesomenonexternalizedstrings
Inthedialog,youcandoubleclickonalistedcompilationunitorpresstheExternalizebuttontoopentheExternalizeStringswizard

Stringexternalization

Findingunusedandincorrectlyusedkeysinpropertyfiles

Externalizestringswizard
Sourcemenu

4.4.2.FindingUnusedandIncorrectlyUsedKeysinPropertyFiles
Findingunusedandincorrectlyusedkeysinapropertyfile:
inaJavaview(e.g.PackageExplorer),selectasetofpackages,sourcefolders,projects,messagepropertyfiles,orresourcebundleaccessorclasses
fromthemenubar,selectSource>FindBrokenExternalizedStrings
Afterthesearchisfinished,theSearchResultviewdisplaysalistofunusedkeysinthepropertiesfilesandallincorrectreferencestononexistingkeys.

Stringexternalization

Externalizingstrings
Findingstringstoexternalize

Externalizestringswizard
Sourcemenu

4.5.1.OpeninganEditorforaSelectedElement
Youcanselectthenameofatype,method,orfieldintheJavasourceeditororinthescrapbookandopenaneditoronthedefinitionoftheelement.
1. IntheJavaeditor,selectthenameofatype,method,orfield.Youcanalsojustclickintothenameonce.
2. Dooneofthefollowing:
Fromthemenubar,selectNavigate>OpenDeclaration
Fromtheeditor'spopupmenu,selectOpenDeclaration
PressF3
or
1. HolddowntheCtrlkey.
2. IntheJavaeditor,movethemouseoverthenameofatype,method,orfielduntilthenamebecomesunderlined.
3. Clickthehyperlinkonce.
Iftherearemultipledefinitionsofthesamename,adialogisshown,andyoucanselectonedefinitionthatyouwanttoopen.Aneditoropenscontainingtheselectedelement.

Javaeditor

Navigatemenu
Viewsandeditors

4.5.2.ShowinganElementinthePackageExplorerView
Youcanrevealanelement'slocationinthePackageExplorerview
SelectaJavaelementoractivateaJavaeditor.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 105/322
12/10/2015 Javadevelopmentuserguide
Fromthemenubar,selectNavigate>ShowIn>PackageExplorer.IfthePackageExplorerisnotalreadyopen,thenitopensinthecurrentperspective.Theworkbench
navigatestotheselectedelement(ortheeditedcompilationunit).
FromtheJavaeditor'spopupmenu,selectShowIn>PackageExplorer.Thecurrentlyeditedcompilationunitwillberevealed.
Note:TheelementmightnotberevealedifPackageExplorerfiltersareactiveortheShowMembersinPackageExplorerpreferenceisclearedonthe Java>Appearance
preferencepage.

Javaviews

Settingexecutionarguments

Javapreferencepage
PackageExplorer

4.5.3.OpeningaTypeinthePackageExplorerView
YoucanopenthePackageExploreronanytypethatisincludedonaproject'sclasspath.
1. Fromthemenubar,selectNavigate>GoTo>Type.TheGotoTypedialogopens.
2. IntheChooseatypefield,begintypinganexpressiontonarrowthelistofavailabletypes,usingwildcardsasneeded.Asyoutype,thelistisfilteredtodisplayonlytypes
thatmatchthecurrentexpression.
3. IntheMatchingitemslist,selectatype.Hint:youcanpresstheDownkeytomovetothefirsttype.
4. ClickOKwhenyouaredone.TheselectedtypeisdisplayedinthePackageExplorer.
Note:TheGotoTypedialogmaintainsahistoryofrecentlyopenedtypes.Theseareshownwhenthedialogisopenedandstayaboveaseparatorlinewhenyoustarttotypeafilter
expression.
Note:RevealingmaynotbepossibleifPackageExplorerfiltersareapplied.

Javadevelopmenttools(JDT)

Showingatype'scompilationunitinthePackageExplorer

Navigateactions
PackageExplorer

4.5.4.OpeninganEditoronaType
Youcanopenaneditoronanytypeintheworkbench.
1. PressCtrl+Shift+Tor,selectNavigate>OpenTypefromthemenubar.TheOpenTypedialogopens.
2. IntheEntertypenameprefixorpatternfield,begintypinganexpressiontonarrowthelistofavailabletypes,usingwildcardsasneeded.Asyoutype,thelistisfilteredto
displayonlytypesthatmatchthecurrentexpression.CamelCasenotationisalsosupportedthatmeansyouonlyneedtoenterthecapitallettersofthetypename.
3. IntheMatchingitemslist,selectatype.Hint:youcanpresstheDownkeytomovetothefirsttype.
4. ClickOKwhenyouaredone.Aneditoropensontheselectedtype.
Note:TheOpenTypedialogmaintainsahistoryofrecentlyopenedtypes.Theseareshownwhenthedialogisopenedandstayaboveaseparatorlinewhenyoustarttotypeafilter
expression.
Note:IfyouopenatypefromaCLASSorJARfile,youwillseeaspecialeditorshowingonlymethodsignaturesunlessyouhaveattachedsourcetoit.

Javaeditor

Openinganeditorforaselectedelement

Opentypedialog
Navigateactions
Viewsandeditors

4.5.5.OpeningaPackage
TorevealapackageinthetreeofthePackageExplorer:
1. SelectNavigate>GoTo>Packagefromthemenubar.TheGotoPackagedialogopens.
2. TypeapackagenameintheChooseapackagefieldtonarrowthelistofavailablepackages,usingwildcardsasneeded.Asyoutype,thelistisfilteredtodisplayonly
packagesthatmatchthecurrentexpression.
3. Selectapackagefromthelist,thenclickOK.TheselectedpackageisdisplayedinthePackageExplorer.

Javaviews

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 106/322
12/10/2015 Javadevelopmentuserguide

Navigateactions
PackageExplorer

4.6.WorkingwithJREs
YoucaninstallasmanydifferentJavaRuntimeEnvironments(JREs)asyoulike.JREsareusedtorunanddebugjavaprograms.YourJREsaremanagedontheInstalledJREs
preferencepage.
AJREdefinitionconsistsof:
ThetypeoftheJRE(e.g.StandardVMorStandard1.x.xVM)
Aname
ThelocationwheretheJREisinstalled
ThesystemlibrariescontainingtheJavasystemclasses(likejava.lang.Object).Optionally,thesystemlibrariescanbeassociatedwith:
thesourcefilecontainingthesourcefortheclassesintheJRE'sCLASSfiles
ajavadoclocation(URL)
externalannotations.
OtherinformationneededbytheVMtobuild,runanddebugapplications.
YoucanswitchthedefaultJREfortheworkbench.ThedefaultJREisusedbydefaultwhenbuilding,running,anddebuggingapplications.Alternatively,projectsmayspecifya
specificJREthattheyshouldbebuiltandrunwith.

Javadevelopmenttools(JDT)

AddinganewJREdefinition
DeletingaJREdefinition
ChoosingadefaultJRE
ChoosingaJREforlaunchingaproject

InstalledJREspreferencepage

4.6.1.AssigningthedefaultJREfortheworkbench
ThedefaultJREisusedforcompilingandlaunchingJavaprogramsinallprojectsunlessyouspecificallyoverridethedefaultJREonaproject'sbuildpathoronalaunch
configuration.
HereishowyoucanchangethedefaultJRE:
1. Openthe Java>InstalledJREspreferencepage.
2. ChecktheboxonthelinefortheJREthatyouwanttoassignasthedefaultJREinyourworkbench.IftheJREyouwanttoassignasthedefaultdoesnotappearinthelist,
youmustaddit.
3. ClickOK.
Note:ChangingthedefaultJREmaycauseabuildtooccurifyouhaveautobuildenabled(Project>BuildAutomaticallyorinthe General>Workspacepreferencepage).

Javadevelopmenttools(JDT)

WorkingwithJREs
AddinganewJREdefinition
DeletingaJREdefinition
ChoosingaJREforlaunchingaproject

InstalledJREspreferencepage

4.6.2.AddinganewJREdefinition
InyourworkspaceyoucanhaveanynumberofJREdefinitions.YoucanalsoaddasmanyJREdefinitionsasyouwant.

ToaddanewJREdefinition:
1. Openthe Java>InstalledJREspreferencepage.
2. SelecttheAdd...button.TheAddJREwizardopens.
3. YouwillhavetoselectthetypeofJREyouwouldliketocreate:
StandardVMYouwillselectafolderwheretheJREisinstalled.ThedetailsoftheJREwillbedeterminedbyscanningthelocation.Youcanfurthercustomizethe
JREinstall,specifyingvmarguments,sourceattachments,etc.
StandardVM1.x.xSameoptionsasastandardVMinstall,buttheinstalliscustomizedtohandlethe1.x.xinstall
ExecutionEnvironmentDescriptionYouwillselectanexecutionenvironment(EE)filethatdescribesallthedetailsrequiredtosetuptheJRE.Youwillbeableto
customizesomeaspectsoftheinstall.

StandardVM:
1. IntheJREhomefield,clickBrowse...toselectapathtotherootdirectoryofaJREinstallation(usuallythedirectorycontainingthebinandlibdirectoriesfortheJRE).You

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 107/322
12/10/2015 Javadevelopmentuserguide
mayalsotypeafoldernameintothisfield.
2. IntheJREnamefield,typeanameforthenewJREdefinition.AllJREsofthesametypemusthaveauniquename.
3. IntheDefaultVMArgumentsfield,youcanadd/editthedefaultargumentsthatwillbepassedtotheVMwhenlaunching.
4. ThedefaultlibrariesappearfortheJREintheJREsystemlibrarieslist.Youcanmodifythelibrariesasdesired.
SourceandjavadoclocationscanbespecifiedforthereferencedJARs.TheJavadoclocationisusedbytheJavadocexportwizardasadefaultvalueandbythe'Open
ExternalJavadoc'action.
Jarscanbeadded,removed,andreordered.
5. ClickFinishwhenyouaredone.

Standard1.1.xVM:
FollowthesamestepsasforStandardVMJREs.

ExecutionEnvironmentFiles:
FormoreinformationonEEFilestructureseetheWikiPage.
1. IntheDefinitionhomedirectoryfield,clickFile...toselectaexecutionenvironmentdescriptionfiletoloadtheJREinstallationfrom.Youmayalsotypeafilepathintothis
field.
2. IntheJREnamefield,typeanameforthenewJREdefinition.AllJREsofthesametypemusthaveauniquename.
3. IntheDefaultVMArgumentsfield,youcanadd/editthedefaultargumentsthatwillbepassedtotheVMwhenlaunching.
4. ThedefaultlibrariesappearfortheJREintheJREsystemlibrarieslist.Youcanmodifythelibrariesasdesired.
SourceandjavadoclocationscanbespecifiedforthereferencedJARs.TheJavadoclocationisusedbytheJavadocexportwizardasadefaultvalueandbythe'Open
ExternalJavadoc'action.
Jarscanbeadded,removed,andreordered.
5. ClickFinishwhenyouaredone.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 108/322
12/10/2015 Javadevelopmentuserguide

Javadevelopmenttools(JDT)

WorkingwithJREs
DeletingaJREdefinition
ChoosingadefaultJRE
ChoosingaJREforlaunchingaproject

InstalledJREspreferencepage

4.6.3.ChoosingaJREforalaunchconfiguration
InsteadofusingthedefaultJREforrunninganddebuggingallJavaApplicationlaunchconfigurations,youcanspecificallyassignaJREforlaunchinganindividualconfiguration.
1. WithaJavaApplicationconfigurationselectedinthe LaunchConfigurationDialog,selecttheJREtab.
2. InthelistofavailableJREs,selecttheJREyouwanttousetolaunchthisconfigurationandclickApply,thenRunorDebug.
Note:ChangingtheJREusedforrunningdoesnotaffectthewayJavasourceiscompiled.Youcanadjustthebuildpathtocompileagainstcustomlibraries.

Javadevelopmenttools(JDT)

WorkingwithJREs
AddinganewJREdefinition
DeletingaJREdefinition
ChoosingadefaultJRE

InstalledJREspreferencepage

4.6.4.DeletingaJREdefinition
YoucandeleteJavaruntimeenvironmentdefinitionsthatareavailableforexecutingJavaprogramsintheworkbench.
1. Openthe Java>InstalledJREspreferencepage.
2. SelectthedefinitionyouwanttodeleteandclickRemove.
3. ChecktheboxforthedefinitionthatyouwanttouseasthedefaultJREfortheworkbench.

Javadevelopmenttools(JDT)

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 109/322
12/10/2015 Javadevelopmentuserguide

WorkingwithJREs
AddinganewJREdefinition
ChoosingadefaultJRE
ChoosingaJREforlaunchingaproject

InstalledJREspreferencepage

4.7.RunningandDebugging
YoumaylaunchyourJavaprogramsfromtheworkbench.Theprogramsmaybelaunchedineitherrunordebugmode.
Inrunmode,theprogramexecutes,buttheexecutionmaynotbesuspendedorexamined.
Indebugmode,executionmaybesuspendedandresumed,variablesmaybeinspected,andexpressionsmaybeevaluated.

Debugger
Remotedebugging
Localdebugging

Changingdebuggerlaunchoptions
ChoosingaJREforlaunchingaproject
CreatingaJavascrapbookpage
DisconnectingfromaVM
LaunchingaJavaprogram
Localdebugging
Preparingtodebug
Relaunchingaprogram
Remotedebugging
Resumingtheexecutionofsuspendedthreads
Settingexecutionarguments
Steppingthroughtheexecutionofaprogram
Suspendingthreads

RunMenu
Debugview
DebugPreferences
ConsolePreferences

4.7.1.1.AddingLineBreakpoints
Linebreakpointsaresetonanexecutablelineofaprogram.
1. Intheeditorarea,openthefilewhereyouwanttoaddthebreakpoint.
2. Directlytotheleftofthelinewhereyouwanttoaddthebreakpoint,openthemarkerbar(verticalruler)popupmenuandselectToggleBreakpoint.Youcanalsodouble
clickonthemarkerbarnexttothesourcecodeline.Anewbreakpointmarkerappearsonthemarkerbar,directlytotheleftofthelinewhereyouaddedthebreakpoint.
Also,thenewbreakpointappearsintheBreakpointsViewlist.
Whilethebreakpointisenabled,threadexecutionsuspendsbeforethatlineofcodeisexecuted.Thedebuggerselectsthethreadthathassuspendedanddisplaysthethread'sstack
frames.ThelinewherethebreakpointwassetishighlightedintheeditorintheDebugPerspective.

Debugger
Javaperspectives
Javaeditor

Applyinghitcounts
CatchingJavaexceptions
Removingbreakpoints
Enablinganddisablingbreakpoints
Managingconditionalbreakpoints
Settingmethodbreakpoints
Steppingthroughtheexecutionofaprogram

Breakpointsview

4.7.1.2.RemovingLineBreakpoints
Breakpointscanbeeasilyremovedwhenyounolongerneedthem.
1. Intheeditorarea,openthefilewhereyouwanttoremovethebreakpoint.
2. Directlytotheleftofthelinewhereyouwanttoremovethebreakpoint,openthemarkerbarpopupmenuandselectToggleBreakpoint.Thebreakpointisremovedfromthe
workbench.Youcanalsodoubleclickdirectlyonthebreakpointicontoremoveit.
BreakpointscanalsoberemovedintheBreakpointsView.Selectthebreakpoint(s)toberemovedandfromthecontextmenuselectRemove.
AllbreakpointscanberemovedfromtheworkbenchusingtheRemoveAllactioninthecontextmenuoftheBreakpointsView.
Ifyoufindyourselffrequentlyaddingandremovingabreakpointinthesameplace,considerdisablingthebreakpointwhenyoudon'tneedit(usingDisableBreakpointinthe
breakpointcontextmenuortheBreakpointsView)andenablingitwhenneededagain.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 110/322
12/10/2015 Javadevelopmentuserguide
Debugger
Javaperspectives
Javaeditor

Addingbreakpoints
Enablinganddisablingbreakpoints
Applyinghitcounts
CatchingJavaexceptions
Managingconditionalbreakpoints
Settingmethodbreakpoints
Steppingthroughtheexecutionofaprogram

Breakpointsview

4.7.1.3.Enablinganddisablingbreakpoints
Breakpointscanbeenabledanddisabledasneeded.Whenabreakpointisenabled,threadexecutionsuspendsbeforethatlineofcodeisexecuted.Whenabreakpointisdisabled,
threadexecutionisnotsuspendedbythepresenceofthebreakpoint.
TodisableabreakpointintheBreakpointsView:
1. Openthebreakpoint'scontextmenuandselectDisable,ordeselectthebreakpoint'scheckbox.
2. Thebreakpointimagewillchangetoawhitecircleanditscheckboxwillbeempty.
Todisableabreakpointinthemarkerbarofaneditor:
1. Openthebreakpoint'scontextmenuandselectDisableBreakpoint.
2. Thebreakpointimagewillchangetoawhitecircle.
ToenablethebreakpointintheBreakpointsView:
1. Openthebreakpoint'scontextmenuandselectEnable,orselectthebreakpoint'scheckbox.
2. Thebreakpointimagewillchangebacktoabluecircle,anditscheckboxwillbechecked.
Toenableabreakpointinthemarkerbarofaneditor:
1. Openthebreakpoint'scontextmenuandselectEnableBreakpoint.
2. Thebreakpointimagewillchangetoawhitecircle.

Debugger
Javaperspectives
Javaeditor

Applyinghitcounts
CatchingJavaexceptions
Removingbreakpoints
Settingmethodbreakpoints
Managingconditionalbreakpoints
Steppingthroughtheexecutionofaprogram

Breakpointsview

4.7.1.4.SettingMethodBreakpoints
Methodbreakpointsareusedwhenworkingwithtypesthathavenosourcecode(binarytypes).
1. OpentheclassintheOutlineView,andselectthemethodwhereyouwanttoaddamethodbreakpoint.
2. Fromthemethod'spopupmenu,selectToggleMethodBreakpoint.
3. AbreakpointappearsintheBreakpointsView.Ifsourceexistsfortheclass,thenabreakpointalsoappearsinthemarkerbarinthefile'seditorforthemethodthatwas
selected.
4. Whilethebreakpointisenabled,threadexecutionsuspendswhenthemethodisentered,beforeanylineinthemethodisexecuted.
Methodbreakpointscanalsobesetuptobreakonmethodexit.IntheBreakpointsview,selectthebreakpointandtoggletheExititeminitscontextmenu.
Methodbreakpointscanberemoved,enabled,anddisabledjustlikelinebreakpoints.

Breakpoints

Addingbreakpoints
Removingbreakpoints
Enablinganddisablingbreakpoints
Applyinghitcounts
CatchingJavaexceptions

Breakpointsview
Javaoutline

4.7.1.5.ApplyingHitCounts
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 111/322
12/10/2015 Javadevelopmentuserguide
Ahitcountcanbeappliedtolinebreakpoints,exceptionbreakpoints,watchpointsandmethodbreakpoints.Whenahitcountisappliedtoabreakpoint,thebreakpointsuspends
executionofathreadthenthtimeitishit,butneveragain,untilitisreenabledorthehitcountischangedordisabled.
Tosetahitcountonabreakpoint:
1. Selectthebreakpointtowhichahitcountistobeadded.
2. Fromthebreakpoint'spopupmenu,selectHitCount.
3. IntheEnterthenewhitcountforthebreakpointfield,typethenumberoftimesyouwanttohitthebreakpointbeforesuspendingexecution.

Note:Whenthebreakpointishitforthenthtime,thethreadthathitthebreakpointsuspends.Thebreakpointisdisableduntileitheritisreenabledoritshitcountischanged.

Breakpoints

Addingbreakpoints
Removingbreakpoints
Enablinganddisablingbreakpoints
Settingmethodbreakpoints

Breakpointsview

4.7.1.6.Managingconditionalbreakpoints
Aconditionalexpressioncanbeappliedtoalinebreakpointsuchthatthebreakpointsuspendsexecutionofathreadinoneofthesecases:
whentheresultoftheexpressionistrue
whentheresultoftheexpressionchanges
AconditionalexpressioncancontainarbitraryJavacodeandmaycontainmorethanonestatement,allowingbreakpointconditionstoimplementfeaturesliketracing.Forexample,a
conditioncanexecuteaprintstatementandthenreturnahardcodedvaluetoneversuspend("System.out.println(...)returnfalse").
Tosetaconditiononabreakpoint:
1. Findthebreakpointtowhichanenablingconditionistobeapplied(intheBreakpointsVieworintheeditormarkerbar).
2. Fromthebreakpoint'spopupmenu,selectBreakpointProperties....TheBreakpointpropertiesdialogwillopen.
3. Inthepropertiesdialog,checktheEnableConditioncheckbox.
4. IntheConditionfieldentertheexpressionforthebreakpointcondition.
5. Dooneofthefollowing:
Ifyouwantthebreakpointtostopeverytimetheconditionevaluatestotrue,selecttheconditionis'true'option.Theexpressionprovidedmustbeaboolean
expression.
Ifyouwantthebreakpointtostoponlywhentheresultoftheconditionchanges,selectthevalueofconditionchangesoption.
6. SelectOKtoclosethedialogandcommitthechanges.Whilethebreakpointisenabled,threadexecutionsuspendsbeforethatlineofcodeisexecutedifthebreakpoint
conditionevaluatestotrue.
Aconditionalbreakpointhasaquestionmarkoverlayonthebreakpointicon.


Debugger
Javaperspectives
Javaeditor


Addingbreakpoints
Applyinghitcounts
CatchingJavaexceptions
Removingbreakpoints
Settingmethodbreakpoints
Steppingthroughtheexecutionofaprogram

Breakpointsview

4.7.1.7.CatchingJavaExceptions
Itispossibletosuspendtheexecutionofthreadwhenanexceptionisthrownbyspecifyinganexceptionbreakpoint.Executioncanbesuspendedatlocationswheretheexceptionis
uncaught,caught,orboth.
1. ChooseAddJavaExceptionBreakpointfromtheBreakpointsViewortheworkbenchRunmenu.
2. Adialoglistingalloftheavailableexceptionsispresented(seethefollowingfigure).

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 112/322
12/10/2015 Javadevelopmentuserguide

3. Typethenameoftheexceptionyouwanttocatchorselectitfromthelist.
4. Atthebottomofthepage,usethecheckboxestospecifyhowyouwantexecutiontosuspendatlocationswheretheexceptionisthrown.
SelectCaughtifyouwantexecutiontosuspendatlocationswheretheexceptionisthrownandcaughtbyacatchclause.
SelectUncaughtifyouwantexecutiontosuspendatlocationswheretheexceptionisuncaught.
Note:Exceptionbreakpointscanbeenabledanddisabledandhavehitcountsjustlikeregularbreakpoints.

Javadevelopmenttools(JDT)
Breakpoints

CreatingExceptionBreakpointFilters
Suspendingthreads
Addingbreakpoints
Removingbreakpoints
Enablinganddisablingbreakpoints
Settingmethodbreakpoints

Breakpointsview
AddJavaexceptionbreakpoint

4.7.1.8.CreateExceptionBreakpointFiltering
TypenameandpackagenamefilteringcanbesetupforJavaexceptionbreakpoints.Thiscanbedonefromanexceptionbreakpoints'Filteringpropertiespage,asshowninthe
followingfigure.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 113/322
12/10/2015 Javadevelopmentuserguide

UsingtheFilteringpropertiespagetherearefourwaystoaddfilteringforaJavaexceptionbreakpoint:
1. Youcanselectspecificthreadstorestrictthebreakpointto(whichmustbedonewhileinadebugsession)
2. YoucanusetheAddClassbuttontoselectaclassviatheTypeSelectionDialog
3. YoucanusetheAddPackagebuttontoselectapackageusingafilteredTypeSelectionDialog
4. YoucanusetheAddbuttontodefineyourownpatterntomatchasaclassand/orpackagefilter

DefiningYourOwnFilterPattern
UsingtheAddbuttonmentionedabove,youcandefineyourownpatterntobeusedasafilterforaJavaexceptionbreakpoint.Oncepressed,youcanthen
enteranyexpressioninthenewspaceintheSelectedLocationslist,asshowninthefollowingfigure.

Therearesomerulestofollowwhencreatingyourownpattern.
1. Yourpatterncanonlycontaina'*'attheend
2. Yourpatternmustbefullyqualified,E.g.a.b.c.MyClass
3. Yourpatterncannothavespacesinit

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 114/322
12/10/2015 Javadevelopmentuserguide
Examples
a.b.c*wouldmatcheverythinginthepackagea.b.c
a.b.c.My*wouldmatchanythinginthea.b.cpackagethatstartedwith'My'
My*wouldmatchanythinginthedefaultpackagethatstartedwith'My'

4.7.2.1.PreparingtoDebug
Youcanmakeyourprogramseasiertodebugbyfollowingtheseguidelines:
Wherepossible,donotputmultiplestatementsonasingleline,becausesomedebuggerfeaturesoperateonalinebasis.Forexample,youcannotstepoverorsetline
breakpointsonmorethanonestatementonthesameline.
AttachsourcecodetoJARfilesifyouhavethesourcecode.

Debugger
Remotedebugging
Localdebugging

Changingdebuggerlaunchoptions
Runninganddebugging

Debugpreferences
Debugview
RunMenu

4.7.2.2.LaunchingaJavaprogramindebugmode
Launchingaprogramindebugmodeallowsyoutosuspendandresumetheprogram,inspectvariables,andevaluateexpressionsusingthedebugger.
TolaunchaJavaprogramindebugmode,
1. InthePackageExplorer,selecttheJavacompilationunitorclassfilewiththemainmethodyouwanttolaunch.
2. PresstheDebug[ ]buttonintheworkbenchtoolbarorselectRun>Debugfromtheworkbenchmenubar.AlternativelyyoucanselectRun>DebugAs>Java
Applicationfromtheworkbenchmenubar,orselectDebugAs>JavaApplicationinthePackageExplorerpopupmenuorinthedropdownmenuontheDebugtoolbar
button.
3. YourprogramisnowlaunchedandthelaunchedprocessappearsintheDebugview.
Ifyouwantyourprogramtostopinthemainmethodsothatyoucanstepthroughitscompleteexecution,createaJavaApplicationlaunchconfigurationandchecktheStopin
maincheckboxontheMaintab.
YoucanalsodebugaJavaprogrambyselectingaprojectinsteadofthecompilationunitorclassfile.Youwillbepromptedtoselectaclassfromthoseclassesthatdefineamain
method.(Ifonlyoneclasswithamainmethodisfoundintheproject,thatclassislaunchedasifyouselectedit.)

Javaviews
Javaeditor
Debugger

ConnectingtoaremoteVMwiththeJavaRemoteApplicationlauncher
Relaunchingaprogram
Runninganddebugging
Settingexecutionarguments
Steppingthroughtheexecutionofaprogram

Debugview
PackageExplorer

4.7.2.3.SuspendingThreads
Tosuspendanexecutingthread:
1. SelectthethreadintheDebugView.
2. ClicktheSuspendbutton[ ]intheviewtoolbar.
Thethreadsuspendsitsexecution.Thecurrentcallstackforthethreadisdisplayed,andthecurrentlineofexecutionishighlightedintheeditorintheDebugPerspective.
Whenathreadsuspends,thetopstackframeofthethreadisautomaticallyselected.TheVariablesViewshowsthestackframe'svariablesandtheirvalues.Complexvariables
canbefurtherexaminedbyexpandingthemtoshowthevaluesoftheirmembers.
WhenathreadissuspendedandthecursorishoveredoveravariableintheJavaeditor,thevalueofthatvariableisdisplayed.

Debugger
Javaeditor
Javaperspectives

CatchingJavaexceptions
Evaluatingexpressions
Resumingtheexecutionofsuspendedthreads
Steppingthroughtheexecutionofaprogram

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 115/322
12/10/2015 Javadevelopmentuserguide

Debugview
Resumecommand
Suspendcommand
Variablesview

4.7.2.4.Resumingtheexecutionofsuspendedthreads
Toresumetheexecutionofasuspendedthreads:
1. SelectthethreadoritsstackframeintheDebugView.
2. ClicktheResumebutton[ ]intheviewtoolbar(orpresstheF8key).
Thethreadresumesitsexecutionandstackframesarenolongerdisplayedforthethread.TheVariablesViewisalsocleared.

Debugger

Evaluatingexpressions
Steppingthroughtheexecutionofaprogram
Suspendingthreads

Debugview
Resumecommand
Suspendcommand
VariablesView

4.7.2.5.SteppingthroughtheexecutionofaJavaprogram
Whenathreadissuspended,thestepcontrolscanbeusedtostepthroughtheexecutionoftheprogramlinebyline.Ifabreakpointisencounteredwhileperformingastep
operation,theexecutionwillsuspendatthebreakpointandthestepoperationisended.

Stepover
1. SelectastackframeintheDebugView.ThecurrentlineofexecutioninthatstackframeishighlightedintheeditorintheDebugPerspective.
2. ClicktheStepOverbutton[ ]intheviewtoolbar,orpresstheF6key.Thecurrentlyselectedlineisexecutedandsuspendsonthenextexecutableline.

Stepinto
1. SelectastackframeintheDebugView.ThecurrentlineofexecutionintheselectedframeishighlightedintheeditorintheDebugPerspective.
2. ClicktheStepIntobutton[ ]intheviewtoolbar,orpresstheF5key.Thenextexpressiononthecurrentlyselectedlinetobeexecutedisinvoked,andexecution
suspendsatthenextexecutablelineinthemethodthatisinvoked.

StepintoSelection
1. SelectastackframeintheDebugView.ThecurrentlineofexecutionintheselectedframeishighlightedintheeditorintheDebugPerspective.
2. IntheJavaEditor,withinthecurrentlineofexecution,placethecursoronthenameofamethodthatyouwouldliketostepinto.
3. ClicktheStepintoSelectionactionintheRunmenuorJavaeditorcontextmenu,orpresstheCtrlF5key.Executionresumesuntiltheselectedmethodisinvoked.

Stepwithfilters
1. ToggletheUseStepFiltersbutton[ ]intheDebugviewtoolbar,oruseShift+F5.Whentheactionistoggledon,eachofthestepactions(over,into,return)willapplythe
setofstepfilterswhicharedefinedinthe Java>Debug>StepFilteringpreferencepage.Whenastepactionisinvoked,steppingwillcontinueuntilanunfilteredlocation
isreachedorabreakpointisencountered.

StepReturn
1. SelectastackframeintheDebugView.ThecurrentlineofexecutionintheselectedframeishighlightedintheeditorintheDebugPerspective.
2. ClicktheStepReturnbutton[ ]intheviewtoolbarorpresstheF7key.Executionresumesuntilthenextreturnstatementinthecurrentmethodisexecuted,and
executionsuspendsonthenextexecutableline.

Runtoline
Whenathreadissuspended,itispossibletoresumeexecutionuntilaspecifiedlineisexecuted.Thisisaconvenientwaytosuspendexecutionatalinewithoutsettinga
breakpoint.
1. Placeyourcursoronthelineatwhichyouwanttheprogramtorun.
2. SelecttheRuntoLinecommand[ ]fromthepopupmenuoruseCtrl+R.Programexecutionisresumedandsuspendsjustbeforethespecifiedlineistobeexecuted.
Itispossiblethatthelinewillneverbehitandthattheprogramwillnotsuspend.
Breakpointsandexceptionscancausethethreadtosuspendbeforereachingthespecifiedline.

Breakpoints
Javaperspectives

Addingbreakpoints
LaunchingaJavaprogram

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 116/322
12/10/2015 Javadevelopmentuserguide
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Settingexecutionarguments
Suspendingthreads

Debugview

4.7.2.6.Inspectingvalues
Whenastackframeisselected,youcanseethevisiblevariablesinthatstackframeintheVariablesView.
TheVariablesviewshowsthevalueofprimitivetypes.Complexvariablescanbeexaminedbyexpandingthemtoshowtheirmembers.

InspectingValuesintheExpressionsView
InspectingValuesintheVariablesView
InspectingValuesinotherviews

4.7.2.7.Evaluatingexpressions
WhentheVMsuspendsathread(duetohittingabreakpointorsteppingthroughcode),youcanevaluateexpressionsinthecontextofastackframe.
1. Selectthestackframeinwhichanevaluationistobeperformed.Theevaluationcontextwillbethecurrentlyselectedvariableintheview.Ifnovariableisselected,the
selectedstackframewillbethecontext.
2. Expressionscanbeenteredandevaluatedinthefollowingareas:
DisplayView
DetailPane(intheExpressionsViewandVariablesView)
JavaEditorwhenitisdisplayingsourceanditisnotreadonly
3. SelecttheexpressiontobeevaluatedandselectDisplay,InspectorExecutefromthecontextpopupmenu.TheresultofaDisplayorInspectevaluationisshownina
popupwindow.NotethatExecutedoesnotdisplayaresulttheexpressionisjustexecuted.
4. TheresultpopupwindowcanbedismissedbyclickingoutsideofthepopupwindoworbypressingEsc.TheresultcanbepersistedtotheDisplayview(ifDisplaywas
chosen)orExpressionsview(ifInspectwaschosen)bypressingthekeysequenceshownatthebottomofthepopupwindow.Forexample,tomovetheresultofanInspect
evaluationtotheExpressionsviewpressCtrlShiftI.NotethatwhentheDisplayactionisusedfromtheDisplayviewtheresultiswrittentotheDisplayviewratherthana
popup
Note:Evaluationscannotbeperformedinthreadsthathavebeenmanuallysuspended.

Debugger
Javaeditor

Suspendingthreads
Resumingtheexecutionofsuspendedthreads

DetailPane
Displayview
Expressionsview
Variablesview

4.7.3.1.UsingtheremoteJavaapplicationlaunchconfiguration
TheRemoteJavaApplicationlaunchconfigurationshouldbeusedwhendebugginganapplicationthatisrunningonaremoteVM.Sincetheapplicationisstartedontheremote
system,thelaunchconfigurationdoesnotspecifytheusualinformationabouttheJRE,programarguments,orVMarguments.Instead,informationaboutconnectingtothe
applicationissupplied.
TocreateaRemoteJavaApplicationlaunchconfiguration,dothefollowing:
1. Select Run>DebugConfigurations...fromtheworkbenchmenubar(orDebugConfigurations...fromthedropdownmenuontheDebugtoolbarbutton)toshowthe
launchconfigurationdialog.
2. SelecttheRemoteJavaApplicationinthelistofconfigurationtypesontheleft.
3. ClicktheNewtoolbarbutton.Anewremotelaunchconfigurationiscreatedandthreetabsareshown:Connect,Source,andCommon.
4. IntheProjectfieldoftheConnecttab,typeorbrowsetoselecttheprojecttouseasareferenceforthelaunch(forsourcelookup).Aprojectdoesnotneedtobespecified.
5. TheConnectionTypefieldoftheConnecttaballowsyoutochoosehowyouwillconnecttothevirtualmachine.Inmostcases,youwillbeattachingtothevmataspecific
location,inwhichcaseselectStandard(SocketAttach).therestoftheseinstructionsassumeyouhavechosenthisoption.TheStandard(SocketListen)connectiontype
createsalaunchthatwilllistenforincomingconnectionsfromaremoteVM.Youwillneedtospecifyaportthatthelaunchwilllistenat.
6. IntheHostfieldoftheConnecttab,typetheIPaddressordomainnameofthehostwheretheJavaprogramisrunning.
Iftheprogramisrunningonthesamemachineastheworkbench,typelocalhost.
7. InthePortfieldoftheConnecttab,typetheportwheretheremoteVMisacceptingconnections.Generally,thisportisspecifiedwhentheremoteVMislaunched.
8. TheAllowterminationofremoteVMflagisatogglethatdetermineswhethertheTerminatecommandisenabledinthedebugger.Selectthisoptionifyouwanttobeableto
terminatetheVMtowhichyouareconnecting.
9. ClickDebug.ThelaunchattemptstoconnecttoaVMatthespecifiedaddressandport,andtheresultisdisplayedintheDebugview.Ifthelauncherisunabletoconnectto
aVMatthespecifiedaddress,anerrormessageappears.
SpecificinstructionsforsettinguptheremoteVMshouldbeobtainedfromyourVMprovider.

Debugger
RemoteDebugging

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 117/322
12/10/2015 Javadevelopmentuserguide

LaunchingaJavaprogram
DisconnectingfromaVM
Settingexecutionarguments

Debugview

4.7.3.2.DisconnectingfromaVM
TodisconnectfromaVMthatwasconnectedtowithaRemoteJavaApplicationlaunchconfiguration:
1. IntheDebugView,selectthelaunch.
2. ClicktheDisconnectbutton[ ]intheviewtoolbar.
CommunicationwiththeVMisterminated,andallthreadsintheremoteVMareresumed.AlthoughtheremoteVMcontinuestoexecute,thedebugsessionisnowterminated.

Debugger

ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
Runninganddebugging

Debugview

4.7.4.CreatingaJavaapplicationlaunchconfiguration
WhenyouchooseRun>RunAs>JavaApplicationtolaunchyourclass,youarerunningyourclassusingagenericJavaApplicationlaunchconfigurationthatderivesmostofthe
launchparametersfromyourJavaprojectandyourworkbenchpreferences.Insomecases,youwillwanttooverridethederivedparametersorspecifyadditionalarguments.
YoudothisbycreatingyourownJavaApplicationlaunchconfiguration.
1. Select Run>RunConfigurations...or Run>DebugConfigurations...fromtheworkbenchmenubar.Thisopensadialogthatletsyoucreate,modify,anddelete
launchconfigurationsofdifferenttypes.
2. SelectJavaApplicationinthelefthandlistoflaunchconfigurationtypes,andpresstheNewbuttoninthetoolbar.ThiswillcreateanewlaunchconfigurationforaJava
application.Thetabsontherighthandsideallowyoucontrolspecificaspectsofthelaunch.

TheMaintabdefinestheclasstobelaunched.Enterthenameoftheprojectcontainingtheclasstolaunchintheprojectfield,andthefullyqualifiednameofthe
mainclassintheMainclassfield.ChecktheStopinmaincheckboxifyouwanttheprogramtostopinthemainmethodwhenevertheprogramislaunchedin
debugmode.
Note:Youdonothavetospecifyaproject,butdoingsoallowsadefaultclasspath,sourcelookuppath,andJREtobechosen.
TheArgumentstabdefinestheargumentstobepassedtotheapplicationandtothevirtualmachine(ifany).Youcanalsospecifytheworkingdirectorytobe
usedbythelaunchedapplication.
TheJREtabdefinestheJREusedtorunordebugtheapplication.YoucanselectaJREfromthealreadydefinedJREs,ordefineanewJRE.
TheClasspathtabdefinesthelocationofclassfilesusedwhenrunningordebugginganapplication.Bydefault,theuserandbootstrapclasslocationsarederived
fromtheassociatedproject'sbuildpath.Youmayoverridethesesettingshere.
TheSourcetabdefinesthelocationofsourcefilesusedtodisplaysourcewhendebuggingaJavaapplication.Bydefault,thesesettingsarederivedfromthe
associatedproject'sbuildpath.Youmayoverridethesesettingshere.
TheEnvironmenttabdefinestheenvironmentvariablevaluestousewhenrunningordebuggingaJavaapplication.Bydefault,theenvironmentisinheritedfrom
theEclipseruntime.Youmayoverrideorappendtotheinheritedenvironment.Variablesspecifiedinthetabalwaysreplacevaluesintheunderlyingnative
environment.However,when"Appendenvironmenttonativeenvironment"isselectedthelaunchedenvironmentisseededwiththenativeenvironment,after
whichvariablesinthetabreplace(existingvariables)oraugmentthesetofenvironmentvariables.When"Replacenativeenvironmentwithspecifiedenvironment"
isselected,thelaunchedenvironmentiscomprisedonlyofthevariablesspecifiedinthetab.
TheCommontabdefinesgeneralinformationaboutthelaunchconfiguration.Youmaychoosetostorethelaunchconfigurationinaspecificfileandspecify
whichperspectivesbecomeactivewhenthelaunchconfigurationislaunched.

Debugger
Localdebugging

ChoosingaJREforlaunchingaproject
LaunchingaJavaprogram
Settingexecutionarguments
Changingdebuggerlaunchoptions

Debugpreferences
Debugview
RunMenu

4.7.5.LaunchingaJavaProgram
ThesimplestwaytolaunchaJavaprogramistorunitusingaJavaApplicationlaunchconfiguration.Thislaunchconfigurationtypeusesinformationderivedfromtheworkbench
preferencesandyourprogram'sJavaprojecttolaunchtheprogram.
1. InthePackageExplorer,selecttheJavacompilationunitorclassfilewiththemainmethodyouwanttolaunch.
2. PresstheRun[ ]buttonintheworkbenchtoolbarorselectRun>Runfromtheworkbenchmenubar.Alternatively,selectRunAs>JavaApplicationinthePackage
Explorerpopupmenu,orselectRun>RunAs>JavaApplicationintheworkbenchmenubar,orselectRunAs>JavaApplicationinthedropdownmenuontheRun
toolbarbutton.
3. Yourprogramisnowlaunched,andtextoutputisshownintheConsoleView.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 118/322
12/10/2015 Javadevelopmentuserguide
YoucanalsolaunchaJavaprogrambyselectingaprojectinsteadofthecompilationunitorclassfile.Youwillbepromptedtoselectaclassfromthoseclassesthatdefineamain
method.(Ifonlyoneclasswithamainmethodisfoundintheproject,thatclassislaunchedasifyouselectedit.)

Javaviews
Javaeditor
Debugger

ConnectingtoaremoteVMwiththeJavaRemoteApplicationlauncher
Relaunchingaprogram
Runninganddebugging
Settingexecutionarguments
Steppingthroughtheexecutionofaprogram

ConsoleView
Debugview
PackageExplorer

4.7.6.LaunchingaJavaapplet
IfyourJavaprogramisstructuredasanapplet,youcanusetheJavaAppletlaunchconfiguration.Thislaunchconfigurationusesinformationderivedfromtheworkbench
preferencesandyourprogram'sJavaprojecttolaunchtheprogram.
1. InthePackageExplorer,selecttheJavacompilationunitorclassfilecontainingtheappletyouwanttolaunch.
2. PresstheRun[ ]buttonintheworkbenchtoolbarorselectRun>Runfromtheworkbenchmenu.Alternatively,selectRunAs>JavaAppletfromthePackage
Explorerpopupmenu,selectRun>RunAs>JavaAppletintheworkbenchmenubar,orselectRunAs>JavaAppletinthedropdownmenuontheRuntoolbar
button.
3. Yourprogramisnowlaunched.
YoucanalsolaunchaJavaappletbyselectingaprojectinsteadofthecompilationunitorclassfile.YouwillbepromptedtoselectaclassfromthoseclassesthatextendApplet.
(Ifonlyoneappletclassisfoundintheproject,thatclassislaunchedasifyouselectedit.)

Debugger

Relaunchingaprogram
Runninganddebugging
Steppingthroughtheexecutionofaprogram

Debugview
PackageExplorer

4.7.7.Settingexecutionarguments
Ifyouwanttospecifyexecutionargumentsforyourprogram,youmustdefinealaunchconfigurationthatspecifiesthearguments.
1. Select Run>RunConfigurations...or Run>DebugConfigurations...fromtheworkbenchRunmenutoopenthelistoflaunchconfigurations.Launch
configurationsforJavaprogramsareshownunderneathJavaApplicationinthislist.
2. SelectanexistingconfigurationorcreateanewlaunchconfigurationbypushingtheNewbuttonafterselectingJavaApplication.
3. OntheArgumentstabfortheconfiguration,youcanspecifythefollowingfieldsasnecessary:
ProgramArguments:Applicationspecificvaluesthatyourcodeisexpecting(ausernameoraURLforlocatinghelpfiles,forexample).
VMArguments:ValuesmeanttochangethebehavioroftheJavavirtualmachine(VM).Forexample,youmayneedtotelltheVMwhethertouseajustintime(JIT)
compiler,oryoumayneedtospecifythemaximumheapsizetheVMshoulduse.RefertoyourVM'sdocumentationformoreinformationabouttheavailableVM
arguments.
WorkingDirectory:Theworkingdirectoryusedforthelaunchedprocess.Tochangefromusingthedefaultworkingdirectory,selectOtherandspecifytheworkspaceor
localdirectorytousefortheworkingdirectoryofthelaunchedprocess.
4. ClickApplyorClosewhenyouaredone.Everytimeyoulaunchthisconfiguration,theseexecutionargumentswillbeused.

CreatingaJavaApplicationlaunchconfiguration
LaunchingaJavaprogram

4.7.8.Relaunchingaprogram
Theworkbenchkeepsahistoryofeachlaunchedanddebuggedprogram.Torelaunchaprogram,dooneofthefollowing:
SelectapreviouslaunchfromRunorDebugbuttonpulldownmenus.
Fromthemenubar,selectRun>RunHistoryorRun>DebugHistoryandselectapreviouslaunchfromthesesubmenus.
IntheDebugView,selectaprocessthatyouwanttorelaunch,andselectRelaunchfromtheprocess'spopupmenu.
Torelaunch,dooneofthefollowing:
ClicktheRunorDebugbuttons(withoutusingthebuttonpulldownmenu).
SelectRun>RunLastLaunched(Ctrl+F11),orRun>DebugLastLaunched(F11)fromtheworkbenchmenubar.
PreferencecanbesetintheLaunchOperationsectionunderWindow>Preferences>Run/Debug>Launchingtolaunchpreviouslylaunchedapplicationoractiveeditor.

LaunchingaJavaprogram
Runninganddebugging

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 119/322
12/10/2015 Javadevelopmentuserguide

Debugview
Relaunchcommand
TerminateandRelaunchcommand

4.7.9.InspectingmemoryintheMemoryview
WiththeMemoryview,youcanlookatthecontentsofmemoryataspecificaddress.Theaddresscanbeobtainedfromanexpressionthatreferencesavariableoraregister.When
youmonitormemory,youcansetthemonitortoberenderedinvariousdataformats.
TheMemoryviewiscomprisedoftwoportions:
TheMonitorspaneislocatedonthelefthandsideoftheview.Thisportionoftheviewcontainsalistofexpressions,variables,andregistersthatyouhaveaddedfor
monitoring.
TheRenderingspaneislocatedontherighthandsideoftheview(iftheviewissettohorizontalorientation).Youuseittosetthedataformat(orformats)thatyouwant
displayedformonitoredmemory.
WhenyoumonitoranaddressorexpressionfromtheMonitorspane,theRenderingspanebecomespopulatedwithasetofdefaultrenderingsprovidedbyyourdebugger.When
youmonitoranaddressorexpressionfromtheRenderingspane,thepanebecomespopulatedwithalistofrenderingsfromwhichyoucanchooseonetodisplay.
Youcanmonitormultiplevariables,expressions,andregistersintheMemoryviewandyoucanaddmultiplerenderingstotheRenderingspane.IntheMonitorspane,each
variable,expression,orregisterthatyouhaveaddedislisted.IntheRenderingspane,onlythememoryrendering(s)forthecurrentlyselectedmonitorintheMemoryviewis
displayed(multiplerenderingsareseparatedbytabsorasplitpane).
YoucansetthetwopanesintheMemoryviewtodisplayinahorizontalorientation(sidebyside)orinaverticalorientation(toptobottom).Tosetthelayoutoftheview,clickthe
MemoryviewdownarrowiconandselectLayoutfromthemenu.Thiswillopenasubmenu,fromwhichyoucanchoosetheorientationthatyouwanttodisplay.

4.7.9.1.Addingavariable,expression,orregistertotheMemoryview
Youcanaddaregister,variablename,orexpression(suchasarawaddress,forexample,0x00000234)toamemorymonitorfromtheMemoryview.
ToaddanewmemorymonitorfromtheMemoryview:

1. ClicktheMemoryviewAddMemoryMonitorpushbutton( ).ThisbuttonislocatedintheMonitorspane.
2. IntheMonitorMemorydialogbox,entertheaddressorexpressioninthefield(expressionsmustevaluatetoanaddress).Thisentrydoesnotneedtobecasesensitive.
Alternatively,ifyouhavepreviouslymonitoredtheaddressorexpressionwhendebuggingthisapplication,chooseitfromthepulldownlist.Dependingonthedebugengine
thatthedebuggeruserinterfaceisconnectedto,examplesofvalidexpressionsincluderegisternames,variables,andHEXaddresses.
Note:Whenaddingaregistertoamemorymonitor,theRegistersviewisaconvenientlocationtoseethenamesofallregistersinyourapplication.Youcanmakenoteofthe
nameofaregisterfromtheviewandthenuseitwhenaddingamemorymonitor.
3. ClickOK.
AfteraddingthenewmemorymonitoryoucanchoosethememoryformatthatyouwanttodisplayintheRenderingspane.
YoucanalsoaddanewmemorymonitorfromtheMemoryviewRenderingspane:

1. ClicktheMemoryviewAddRendering(s)pushbutton( ).ThisbuttonislocatedintheRenderingspane.
2. IntheAddMemoryRenderingdialogbox,selectanexistingmemorymonitorfromthepulldownlistoraddanewmemorymonitorbyclickingAddNew.Ifyouaddanew
memorymonitor,youwillbepromptedviatheMonitorMemorydialogboxtoenteranaddressorexpressiontomonitor.ClickOKtoreturntotheAddMemoryRenderingdialog
box.
3. Dooneofthefollowing:
SelectthememoryrenderingthatyouwanttodisplayforthememorymonitorandclickOK.
ClickCancelandthenchoosethememoryrenderingthatyouwanttodisplayrightfromtheRenderingspane.

4.7.9.2.Addingmultiplememoryrenderingsandremovingrenderings
Whenyouaddavariable,expression,orregistertotheMemoryview,youcandosomultipletimes,eachtimeaddinganew(orthesame)rendering.Alternatively,onceyouhave
addedamemorymonitorandrendering,youcangototheRenderingspaneandclicktheAddRendering(s)pushbutton( ).Thiswillpromptyouwithadialogtoselectthe
renderingthatyouwanttoaddtotheview.Inthisdialog,youcanselectmorethanonerenderingbyusingthekeyboardShiftorCtrlkeysdoingthiswillcausearenderingtobe
openedforeachrenderingformatthatisselected.Whenyouaddmultiplememoryrenderings,theyareseparatedbytabs.

YoucanalsosplittheMemoryRenderingspanebyselectingtheToggleSplitPanepushbutton( ).WhentheRenderingspaneissplit,youcanviewtworenderingssideby
side.
Whenyouhavemultiplememoryrenderingsforamemorymonitor,youcansettherenderingstobelinkedwithoneanother.Todothis,selecttheLinkMemoryRenderingPanes
pushbutton( ).Whenrenderingsarelinked,theyaresynchronizedwitheachother(forexample,ifyouchangethecolumnsizeinonerendering,thecolumnsizeintheother
renderingwillalsochangeorifyouscrollormovethecursorinonerendering,theotherrenderingwillscrollorfollowthesamecursormovement).Linkingmemoryrenderingsonly
appliestothecurrentMemoryview.IfyouhavemultipleMemoryviewsopen,theydonotlinktoeachother.

Toremovearendering,selectitintheRenderingspaneandclickRemoveRendering( ).Whenyouremoveallmemoryrenderingsforamonitoredexpression,variable,or
register,theRenderingspanewillbepopulatedwiththememoryrenderingselectionlist.Fromthislist,youcanselectthedataformatthatyouwanttouseforthememoryrendering
andthenclickAddRendering(s).

4.7.9.3.Workingwithmemorymonitors
ToviewthecontentsofmemoryfromtheMemoryview:
1. IntheMonitorspane,selectthememorymonitorthatcontainsthememorylocationthatyouwanttoview.MemorywillappearintheRenderingspane,whereyouwill
performallothersteps.Ifyouhaveaddedmultiplerenderings,selectthetabthatcontainstherenderingthatyouwanttoview.
2. Ifdesired,splittheRenderingspanebyselectingtheToggleSplitPanepushbutton( ).Bydefault,theMemoryviewonlydisplaysonerenderingpane.Whenyouclick
ToggleSplitPane,asecondrenderingopensanddisplaysasasplitpane.
3. Ifnecessary,usethescrollbarintherenderingtoviewmemorylocationsaboveorbelowthebaseaddressofthememorymonitorbeingshownbythecurrentrendering.
Alternatively,youcanrightclickintherenderingandchoosetheGotoAddresspopupmenuitemorhitCtrl+G.Thiswillopenasectionatthebottomoftherendering,in
whichyoucanperformthefollowingactions:
SelecttheGotoAddresspulldownmenuitemandthenenteranaddressthatyouwanttojumpto.Therenderingwillbepositionedsothattheaddressenteredis
visibleandselected.
SelecttheGotoOffsetpulldownmenuitemandthenentertheoffset.Therenderingwillbepositionedsothattheaddressoftheexpression(baseaddress),plusthe
offsetentered,isvisibleandselected.Anegativevaluewillpositiontherenderingbackfromthebaseaddress.
SelecttheJumpMemoryUnitspulldownmenuitem.Thisfunctiontakesthecurrentlyselectedaddressandaddsthenumberofmemoryunitsthatyouspecifytoit.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 120/322
12/10/2015 Javadevelopmentuserguide
Theresultingaddressisselected.Anegativevaluewillpositiontherenderingbackfromthecurrentaddress.
Foralloftheseentries,youcaninputthemasHEXbyselectingtheInputasHexcheckbox(ifthischeckboxisnotselected,inputwillbedecimal).Onceyouhavemade
theentryinthefield,hitEnterorclickOKtogotothelocationintherendering.Toclosethissection,clickCancelorhitCtrl+G.
Note:InputisalsotreatedasHEXifitisprefixedwith0x.
4. Ifyouwant,changethewidthofanycolumnbyclickingtheleftorrightsideofitsheadercellanddraggingittoalterthewidthofthecolumnorrightclickinsidetherendering
andselectResizetoFitfromthepopupmenusothatallcolumnsareresizedsothatalltextwithinthemcanbeviewed.Alternatively,youcanrightclickinsidetherendering
andselectFormatfromthepopupmenu.ThiswillopentheFormatdialogbox.Inthisdialogbox,youcansetthenumberofunitsperrowandthenumberofunitspercolumn.
Asyoumakethesesettings,aPreviewwindowinthedialogboxdisplaystherenderinglayoutthatyouaresetting.Tosavethesesettingsasthedefaultlayout,clickSaveas
Defaults.
5. YoucanalsohideelementsoftheMemoryviewforeasierviewing:
YoucanhidetheMonitorspanebydeselectingtheToggleMemoryMonitorsPanetoggle.
YoucanhidetheAddresscolumnbyrightclickinginsidetherenderingandselectingHideAddressColumn.Torestoreatheaddresscolumnwhenitishidden,right
clickinsidetherenderingandselectShowAddressColumnfromthepopupmenu.
Ifyouareinamemoryrenderingandmoveawayfromtheaddressthatyouoriginallysettomonitor,choosingtheResettoBaseAddresspopupmenuitemwillpositionthecursor
backtothebaseaddressofthememorymonitor.Alternatively,youcanresetallrenderingsforamemorymonitorbyrightclickingthemonitorandselectingReset(or,youcanselect
multiplemonitorsandchoosethisaction).Whenyouresetamonitor,bydefault,thevisiblerenderingswillberesettothebaseaddress.ToresetallrenderingsinthecurrentMemory
viewtothebaseaddress,modifytheMemoryviewpreferences.

4.7.9.4.Changingthecontentsofamemorylocation
TochangethecontentsofamemorylocationinamemorymonitorintheMemoryview:
1. IntheMonitorspane,selectthememorymonitorthatcontainsthememorylocationthatyouwanttoedit.MemorywillappearintheRenderingspane,whereyouwillperform
allothersteps.Ifyouhaveaddedmultiplerenderings,selectthetabthatcontainstherenderingthatyouwanttoedit.
2. Scrolldowntothememorylocationyouwanttochange.Alternatively,rightclickinthemonitorandchoosetheGotoAddresspopupmenuitem.ThiswillopenaGoTo
Addresssectionatthebottomoftherendering,inwhichyoucanenteranaddressthatyouwanttojumpto.
3. Selecttherowcontainingthevaluethatyouwanttochangeandthendoubleclickthevaluethatyouwanttochange.
Tip:Iftherenderingiscurrentlyinfocus,youdonotneedtodoubleclickthevaluethatyouwanttochangetobeabletoeditit.Rather,youcansimplystarttypingthechange
andtheeditorwillactivate.
4. Enteravalidvalueforthatmemorylocation.
5. PressEntertosubmitthechange.Thedebuggerchecksforavalidvalue.

4.7.9.5.Memoryviewpreferences
Youcansettablerendering,codepage,andpaddedstringpreferencesformemoryrenderings.Inaddition,youcanmodifythepreferredbehaviorforresettingmemoryrenderings.
MemoryviewpreferencedialogboxesareopenedfromtheMemoryviewdownarrowiconmenu.ToopentheMemoryviewPreferencesdialogbox,clicktheMemoryviewdown
arrowiconandselectPreferencesfromthemenu.ToopentheMemoryviewtablerenderingsPreferencesdialogbox,clicktheMemoryviewdownarrowiconandselectTable
RenderingsPreferencesfromthemenu.
Torestoreanychangesthatyoumakeinthepreferencestotheirdefaultsettings,clickRestoreDefaults.

Preferences:ResetMemoryMonitor
Youcanresetarenderingtothebaseaddressifyouhavemovedawayfromit.Whenyouresetarenderingtothebaseaddress,youcansetittoresetonlythevisiblerenderingsor
youcansetittoresetallrenderings.Ifyouchoosetoresetallrenderings,performanceoftheresetoperationcanbenegativelyimpacted.Tosetthispreference,openthe
PreferencesdialogboxandthenselecttheResetMemoryMonitornode.IntheResetMemoryMonitorpage,choosetheappropriateradiobutton.

Preferences:PaddedString
Thepaddedstringisthestringthatwillappearinmemorycontentswhenmemorycannotberetrieved.Tosetthepaddedstring,openthePreferencesdialogboxandselectthe
PaddedStringnode.InthePaddedStringpage,specifythestringthatyouwanttodisplaywhenmemorycontentscannotbedetermined.

Preferences:SelectCodepages
WhenmonitoringASCIIandEBCDICtextbasedrenderings(andmappedmemory,ifitisavailableintheproductthatyouinstalledthisdebuggerwith)intheRenderingspane,you
cansetthecodepageinwhichyouwanttherenderingtobedisplayed.
TosetthecodepageforrenderingmemorytoASCII/EBCDIC,openthePreferencesdialogboxandselecttheSelectCodepagesnode.IntheSelectCodepagespage,specifythe
codepageofthecharactersetthatyouwanttochange(forASCIIrenderings,EBCDICrenderings,orboth).

TableRenderingsPreferences
Tosetpreferencesformemoryrenderingsthataredisplayedinatable,clicktheMemoryviewdownarrowiconandselectTableRenderingsPreferences.Intheresulting
preferencesdialogbox,therearetwooptions:
Automaticradiobutton:SelectthisifyouwantthedebuggertoautomaticallypreloadabufferofmemorybeforeandafterthevisibleregionintheMemoryview.Whenyou
selectthissetting,youcaneasilyscrollawayfromthevisibleregionofmemorywithscrollandpageup/downactions.
Ifthebuffersizeislarge,theperformanceofrefreshingtheMemoryviewcanbenegativelyimpacted(theMemoryviewrefresheswhenthereisapotentialformemorychange
so,forexample,theMemoryviewrefresheswhenyoustep,suspendafterrunning,changeavariableorregister,ormodifymemory).Thisisbecausearequestformore
memorymustbemadefromthedebugengineforeachrefresh.Ontheotherhand,ifthebuffersizeistoosmall,theperformanceofscrollingcanbenegativelyimpacted.This
isbecausearequestformorememorymustbemadefromthedebugenginewhenthebufferisexhausted.Giventhisperformancetradeoff,youneedtosetthisoptiontosuit
yourneeds.
Manualradiobutton:Ifyouselectthissetting,thenthenumberoflinesperpagethatyouspecifywillbeloadedintotheRenderingspane.Whenusingthissetting,youhave
morecontrolinchoosingexactlywhatyouwanttomonitor,however,youwillnotbeabletoscrolloutsidethebufferdefinedbythispagesizesetting.Instead,toviewmemory
fromthenextpageorpreviouspage,youmustrightclicktousethePreviousPageandNextPageactionsfromthepopupmenu.
Ifthebuffersizeislarge,theperformanceofrefreshingtheMemoryviewcanbenegativelyimpacted(theMemoryviewrefresheswhenthereisapotentialformemorychange
so,forexample,theMemoryviewrefresheswhenyoustep,suspendafterrunning,changeavariableorregister,ormodifymemory).Thisisbecausearequestformore
memorymustbemadefromthedebugengineforeachrefresh.

4.7.9.6.WorkingwithmultipleMemoryviews
YoucanaddadditionalMemoryviewstotheworkbench.Todothis,clickNewMemoryView( ).WhenyouhavemultipleMemoryviewsopen,youcannotlinktheirrenderingsto
eachother.However,youcanpinthecontentsofaMemoryviewsothatmemoryrenderingsthatareaddedtooneviewdonotaffecttheotherview.Topinamemorymonitor,
ensurethatthePinMemoryMonitorbutton( )intheMemoryviewistoggledon.IfyouthengotoanotherMemoryviewandaddamemorymonitor,itwillshowupinboth

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 121/322
12/10/2015 Javadevelopmentuserguide
Memoryviews,however,thememoryrenderingthatiscurrentlydisplayedinthepinnedmonitorwillnotchange.
WhenyouaddanewMemoryview,itsRenderingspanewillbepopulatedwiththememoryrenderingselectionlist.Fromthislist,youcanselectthedataformatthatyouwantto
useforthememoryrenderingandthenclickAddRendering(s).

4.7.9.7.RemovingmemorymonitorsfromtheMemoryview
ToremoveamemorymonitorfromtheMemoryview:
1. Selectthememorymonitorthatyouwanttoremove(byselectingitinthelistintheMonitorspane).
2. ClicktheRemoveMemoryMonitorpushbutton( ).
Toremovemultiplememorymonitors,selectthemusingthekeyboardCtrlorShiftkeys,andthenclickRemoveMemoryMonitor.Toremoveallmemorymonitors,clickRemove
All.
Note:Ifyouhaveaddedmultiplerenderingsforamemorymonitor,allrenderingswillberemovedwhenyouchoosetoremovethemonitor.

4.8.1.CreatingaJavaScrapbookPage
ThescrapbookallowsJavaexpressions,toberun,inspected,anddisplayedunderthecontrolofthedebugger.Breakpointsandexceptionsbehaveastheydoinaregulardebug
session.
Codeiseditedonascrapbookpage.AVMislaunchedforeachscrapbookpageinwhichexpressionsarebeingevaluated.Thefirsttimeanexpressionisevaluatedinascrapbook
pageafteritisopened,aVMislaunched.TheVMforapagewillremainactiveuntilthepageisclosed,terminatedexplicitly(inthedebuggerorviatheStoptheEvaluationbuttonin
theeditortoolbar),orwhenaSystem.exit()isevaluated.
Thereareseveralwaystoopenthe NewJavaScrapbookPagewizard.
Createafilewitha.jpageextension
Fromthemenubar,selectFile>New>Other....ThenselectJava>JavaRun/Debug>ScrapbookPage.ThenclickNext.
Onceyou'veopenedtheNewJavaScrapbookPagewizard:.
1. IntheEnterorselectthefolderfield,typeorclickBrowsetoselectthecontainerforthenewpage.
2. IntheFilenamefield,typeanameforthenewpage.The.jpageextensionwillbeaddedautomaticallyifyoudonottypeityourself.
3. ClickFinishwhenyouaredone.Thenewscrapbookpageopensinaneditor.

Scrapbook
Javaprojects

Runninganddebugging

Javascrapbookpage

4.8.2.Inspectingtheresultofevaluatinganexpression
InspectingshowstheresultofevaluatinganexpressionintheExpressionsview.
1. Inthescrapbookpage,eithertypeanexpressionorhighlightanexistingexpressiontobeinspected.Forexample:System.getProperties()
2. ClicktheInspectbuttoninthetoolbar(orselectInspectfromtheselection'spopupmenu).
3. Theresultoftheinspectionappearsinapopup.
4. Theresultcanbeinspectedlikeavariableinthedebugger(forexample,childrenoftheresultcanbeexpanded).

Scrapbook

CreatingaJavascrapbookpage
Displayingtheresultofevaluatinganexpression
Executinganexpression
Viewingruntimeexceptions

Expressionsview
Javascrapbookpage

4.8.3.Displayingtheresultofevaluatinganexpression
Displayingshowstheresultofevaluatinganexpressioninthescrapbookeditor.
1. Inthescrapbookpage,eithertypeanexpressionorhighlightanexistingexpressiontobedisplayed.Forexample:System.getProperties()
2. ClicktheDisplaybuttoninthetoolbar(orselectDisplayfromtheselection'spopupmenu.)
3. Theresultoftheevaluationappearshighlightedinthescrapbookeditor.Theresultdisplayediseither
thevalueobtainedbysendingtoString()totheresultoftheevaluation,or
whenevaluatingaprimitivedatatype(e.g.,anint),theresultisthesimplevalueoftheresult.
Forexample:
Typeandhighlightnewjava.util.Date()intheeditor,andclickDisplay.Aresultsuchas(java.util.Date)TueJun1214:03:17CDT2001appearsintheeditor.
Asanotherexample,typeandhighlight3+4intheeditor,andpressDisplay.Theresult(int)7isdisplayedintheeditor.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 122/322
12/10/2015 Javadevelopmentuserguide
Scrapbook

Executinganexpression
Inspectingtheresultofevaluatinganexpression
Viewingruntimeexceptions

Javascrapbookpage

4.8.4.Executinganexpression
Executinganexpressionevaluatesanexpressionbutdoesnotdisplayaresult.
IfyouselecttheexpressiontoexecuteandclicktheExecutebuttoninthetoolbar,noresultisdisplayed,butthecodeisexecuted.
Forexample,ifyoutypeandhighlightSystem.out.println("HelloWorld"),andclicktheExecutebutton,HelloWorldappearsintheConsoleview,butnoresultisdisplayedin
thescrapbookeditorortheExpressionsview.

Javaviews

Displayingtheresultofevaluatinganexpression
Inspectingtheresultofevaluatinganexpression
Viewingruntimeexceptions

Expressionsview
Consoleview

4.8.5.Usingcodeassist
ThescrapbookeditorsupportscodeassistsimilarlytotheregularJavaeditor.
Forexample,typeTestCaseinthescrapbookeditorandpressCtrl+Space.Codeassistpromptsyouwithpossiblecompletions.

4.8.6.Scrapbookerrorreporting
Javascrapbookerrorsarereportedinthescrapbookpageeditor.

Viewingcompilationerrors
Viewingruntimeexceptions

4.8.6.1.Viewingcompilationerrors
Ifyoutrytoevaluateanexpressioncontainingacompilationerror,itwillbereportedinthescrapbookeditor.
Forexample,typeandselectthe(invalid)expressionSystem.println("hi")intheeditorandclickExecuteinthetoolbar.
TheerrormessageThemethodprintln(java.lang.String)isundefinedforthetypejava.lang.Systemappearsintheeditoratthepointoftheerror.

4.8.6.2.Viewingruntimeexceptions
Ifanexpressionyouevaluatecausesaruntimeexception,theexceptionwillbereportedintheeditor.Forexample:
TypeandselecttheexpressionObjectx=nullx.toString()intheeditorandclickDisplayinthetoolbar.
Theerrormessage:
Anexceptionoccurredduringevaluation:java.lang.NullPointerException
willbedisplayedintheeditor.

Javaeditor

Displayingtheresultofevaluatinganexpression
Inspectingtheresultofevaluatinganexpression
Executinganexpression

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 123/322
12/10/2015 Javadevelopmentuserguide
4.9.1.Usingthebatchcompiler

Findingthebatchcompiler
ThebatchcompilerclassislocatedintheJDTCoreplugin.Thenameoftheclassisorg.eclipse.jdt.compiler.batch.BatchCompiler.Itispackagedinto
plugins/org.eclipse.jdt.core_<version>.jar.Since3.2,itisalsoavailableasaseparatedownload.Thenameofthefileisecj.jar.Itscorrespondingsourceisalsoavailable.
Togetthem,gotothedownloadpageandsearchforthesectionJDTCoreBatchCompiler.Thisjarcontainsthebatchcompilerandthejavacantadapter.
Since3.3,thisjaralsocontainsthesupportforjsr199(CompilerAPI)andthesupportforjsr269(Annotationprocessing).Inordertousetheannotationsprocessingsupport,a1.6
VMisrequired.
SoitcanbeusedasastandaloneapplicationandinsideanAntbuildoutsideofEclipse.

Runningthebatchcompiler
Fromthecommandline.
javajarorg.eclipse.jdt.core_<version>.jarclasspathrt.jarA.java
or:
javajarecj.jarclasspathrt.jarA.java
Usingthestaticcompile(StringcommandLine,PrintWriteroutWriter,PrintWritererrWriter,CompilationProgressprogress)methodoftheclass
BatchCompiler.

org.eclipse.jdt.core.compiler.CompilationProgressprogress=null//instantiateyoursubclass
org.eclipse.jdt.core.compiler.batch.BatchCompiler.compile(
"classpathrt.jarA.java",
newPrintWriter(System.out),
newPrintWriter(System.err),
progress)

Youcancontrolhowprogressisreported,orhowthebatchcompileriscanceled,bysubclassingtheclassorg.eclipse.jdt.compiler.CompilationProgress.

Whichoptionsareavailable?
Therecommendedoptionshaveanorangebackground.
Whensomeoptionsarebeingsetmultipletimes,thebatchcompilerconsumesthemfromlefttoright.Whenthewarningoption(warn:....)isusedwithout'+'or'',thisoverridesthe
setofwarningspreviouslyspecified.Soyoushouldmakesurethatsuchanoptionisgivenbeforeanyotherusageofthewarnoption.
Sameappliesfortheerr:option.

Name Usage
Classpathoptions
bootclasspath<dir1><dir2>...<dirP> Thisisalistofdirectoriesorjarfilesusedtobootstraptheclassfilesusedbythecompiler.BydefaultthelibrariesoftherunningVM
areused.Entriesareseparatedbytheplatformpathseparator.
Eachdirectoryorfilecanspecifyaccessrulesfortypesbetween'['and']'.
Ifnobootclasspathisspecified,thecompilerwillinferitusingthefollowingsystempropertiessun.boot.class.path,
vm.boot.class.pathororg.apache.harmony.boot.class.pathinthisorderrespectively.

cp Thisisalistofdirectoriesorjarfilesusedtocompilethesourcefiles.Thedefaultvalueisthevalueoftheproperty"java.class.path".
classpath<dir1><dir2>...<dirP> Entriesareseparatedbytheplatformpathseparator.
Eachdirectoryorfilecanspecifyaccessrulesfortypesbetween'['and']'(e.g.[X]toforbidaccesstotypeX,[~X]todiscourage
accesstotypeX,[+p/X:p/*]toforbidaccesstoalltypesinpackagepbutallowaccesstop/X).
ThecompilerfollowstheClassPathclausesofjarfiles'manifestsrecursivelyandappendseachreferencedjarfiletotheendofthe
classpath,provideditisnotontheclasspathyet.

extdirs<dir1><dir2>...<dirP> Thisisalistofdirectoriesusedtospecifythelocationofextensionzip/jarfiles.Entriesareseparatedbytheplatformpathseparator.

endorseddirs<dir1><dir2>...<dirP> Thisisalistofdirectoriesusedtospecifythelocationofendorsedzip/jarfiles.Entriesareseparatedbytheplatformpathseparator.

sourcepath<dir1><dir2>...<dirP> Thisisalistofdirectoriesusedtospecifythesourcefiles.Entriesareseparatedbytheplatformpathseparator.
Eachdirectorycanspecifyaccessrulesfortypesbetween'['and']'.

d<dir1>|none Thisisusedtospecifyinwhichdirectorythegenerated.classfilesshouldbedumped.Ifitisomitted,nopackagedirectorystructure
iscreated.
Ifyouwanttogenerateno.classfileatall,usednone.

encoding<encodingname> Specifydefaultencodingforallsourcefiles.Customencodingcanalsobespecifiedonaperfilebasisbysuffixingeachinputsource
file/foldernamewith[<encodingname>].ForexampleX.java[UTF8]wouldspecifytheUTF8encodingforthecompilationunitX.java
locatedinthecurrentuserdirectory.
Ifmultipledefaultsourcefileencodingsarespecified,thelastonewillbeused.
Forexample:
...encodingUTF8X.java[Cp1252]Y.java[UTF16]Z.java....
MostsourcefileswillbereadusingUTF8encoding(thisincludesZ.java).X.javawillbereadusingCp1252encodingand
Y.javawillbereadusingUTF16encoding.
...encodingUTF8encodingUTF16....
AllsourcefileswillbereadusingUTF16encoding.TheencodingoptionforUTF8isignored.
...encodingCp1252/foo/bar/X.java[UTF16]/foo/bar[UTF8]....
AllsourcefileswillbereadusingCp1252encoding.X.javaistheonlyfileinsidethe/foo/bardirectorytobereadusingthe
encodingUTF16.AllotherfilesinthatdirectorywilluseUTF8encoding.

Complianceoptions
target1.1to1.8(or8,8.0,etc.) Thisspecifiesthe.classfiletargetsetting.Thepossiblevalueare:
1.1(majorversion:45minor:3)
1.2(majorversion:46minor:0)
1.3(majorversion:47minor:0)
1.4(majorversion:48minor:0)

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 124/322
12/10/2015 Javadevelopmentuserguide
1.5,5or5.0(majorversion:49minor:0)
1.6,6or6.0(majorversion:50minor:0)
1.7,7or7.0(majorversion:51minor:0)
1.8,8or8.0(majorversion:52minor:0)
Defaultsare:
1.1in1.3mode
1.2in1.4mode
1.5in1.5mode
1.6in1.6mode
1.7in1.7mode
1.8in1.8mode
clcd1.1canbeusedtogeneratetheStackMapattribute.

1.3 Setcompliancelevelto1.3.Implicitsource1.3target1.1.

1.4 Setcompliancelevelto1.4(default).Implicitsource1.3target1.2.

1.5 Setcompliancelevelto1.5.Implicitsource1.5target1.5.

1.6 Setcompliancelevelto1.6.Implicitsource1.6target1.6.

1.7 Setcompliancelevelto1.7.Implicitsource1.7target1.7.

1.8 Setcompliancelevelto1.8.Implicitsource1.8target1.8.

source1.1to1.8(or8,8.0,etc.) Thisisusedtospecifythesourcelevelexpectedbythecompiler.
Thepossiblevalueare:
1.3
1.4
1.5,5or5.0
1.6,6or6.0
1.7,7or7.0
1.8,8or8.0
Defaultsare:
1.3in1.3mode
1.3in1.4mode
1.5in1.5mode
1.6in1.6mode
1.7in1.7mode
1.8in1.8mode
In1.4,assertistreatedasakeyword.In1.5and1.6,enumandassertaretreatedaskeywords.
Warningoptions
?:warnhelp:warn Displayadvancedwarningoptions

warn:... Specifythesetofenabledwarnings.
warn:none disableallwarnings
warn:<warningtokensseparatedby,> enableexactlythelistedwarnings
warn:+<warningtokensseparatedby,> enableadditionalwarnings
warn:<warningtokensseparatedby,> disablespecificwarnings

Examples:
warn:unusedLocal,deprecationenablesonlythegiventwowarningoptionsanddisablesalltheotheroptions
warn:unusedLocal,deprecation,+fallthroughdisablesunusedLocalanddeprecation,enablesfallthrough,andleavestheother
warningoptionsuntouched
InthecolumnDefaultbelow,amark"+/"indicatesthatanoptioncoversseveralfinegrainedwarningvariants,someofwhichare
enabledbydefault,othersdisabled.Thismeansthatspecifyingthegivenoptionwith"+"willenablemorewarningsthanthedefault,
andspecifying""disablessomethatareenabledbydefault.
Default Tokenname Description
+/ allDeadCode deadcodeincludingtrivialif(DEBUG)check

+/ allDeprecation deprecationeveninsidedeprecatedcode

allJavadoc invalidormissingJavadoc

allOverann allmissing@Overrideannotations(superclassandsuperinterfaces)

allstaticmethod allmethodcanbedeclaredasstaticwarnings

+ assertIdentifier occurrenceofassertusedasidentifier

boxing autoboxingconversion

+ charConcat whenachararrayisusedinastringconcatenationwithoutbeing
convertedexplicitlytoastring

+ compareIdentical comparingidenticalexpressions

conditionAssign possibleaccidentalbooleanassignment

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 125/322
12/10/2015 Javadevelopmentuserguide
+ constructorName methodwithconstructorname

+ deadCode deadcodeexcludingtrivialif(DEBUG)check

depann missing@Deprecatedannotation

+/ deprecation usageofdeprecatedtypeormemberoutsidedeprecatedcode

+ discouraged useoftypesmatchingadiscouragedaccessrule

emptyBlock undocumentedemptyblock

+ enumIdentifier occurrenceofenumusedasidentifier

+ enumSwitch incompleteenumswitch

enumSwitchPedantic reportmissingenumswitchcaseseveninthepresenceofadefaultcase

fallthrough possiblefallthroughcase

fieldHiding fieldhidinganothervariable

+ finalBound typeparameterwithfinalbound

+ finally finallyblocknotcompletingnormally

+ forbidden useoftypesmatchingaforbiddenaccessrule

hashCode missinghashCode()methodwhenoverridingequals()

+/ hiding macroforfieldHiding,localHiding,maskedCatchBlock,andtypeHiding

includeAssertNull raisenullwarningsforvariablesthatgottaintedinanassertexpression

indirectStatic indirectreferencetostaticmember

inheritNullAnnot considernullannotationsasbeinginheritedfromanoverriddenmethodto
anyoverridingmethods

+ intfAnnotation annotationtypeusedassuperinterface

+ intfNonInherited interfacenoninheritedmethodcompatibility

intfRedundant findredundantsuperinterfaces

invalidJavadoc macrototogglethe'malformedJavadoccomments'optionandallitssub
optionslistedbelow

invalidJavadocTag reportinvalidJavadoctagsinJavadoccomments.

invalidJavadocTagDep reportinvaliddeprecatedreferencesinJavadoctagarguments

invalidJavadocTagNotVisible reportinvalidnonvisiblereferencesinJavadoctagarguments

invalidJavadocVisibility(<visibility>) specifyvisibilitymodifier("public","protected"or"private")formalformed
Javadoctagwarnings.Usageexample:invalidJavadocVisibility(public)

javadoc invalidJavadoc

localHiding localvariablehidinganothervariable

+ maskedCatchBlock hiddencatchblock

missingJavadocTags macrototogglethe'missingJavadoctags'optionandallitssuboptions
listedbelow

missingJavadocTagsMethod reportmissingJavadoctagsforamethod'stypeparameters

missingJavadocTagsOverriding reportmissingJavadoctagsinoverridingmethods

missingJavadocTagsVisibility(<visibility>) specifyvisibilitymodifier("public","protected"or"private")formissing
Javadoctagswarnings.Usageexample:
missingJavadocTagsVisibility(public)

missingJavadocComments macrototogglethe'missingJavadoccomments'optionandallitssub
optionslistedbelow

missingJavadocCommentsOverriding reportmissingJavadoccommentsinoverridingmethods

missingJavadocCommentsVisibility(<visibility>) specifyvisibilitymodifier("public","protected"or"private")formissing
Javadoccommentswarnings.Usageexample:
missingJavadocCommentsVisibility(public)

nls nonnlsstringliterals(lackingoftags//$NONNLS<n>)

+ noEffectAssign assignmentwithnoeffect

+ nonnullNotRepeated nonnullparameterannotationfromoverriddenmethodisnotrepeatedinan
overridingmethod.IseffectiveonlywiththenullAnnotoptionenabled.

+/ null potentialmissingorredundantnullcheck

nullAnnot enableannotationbasednullanalysis.
Ifdesired,theannotationtypestobeinterpretedbythecompilercanbe
specifiedbyappending(nullable|nonnull|nonnullbydefault),whereeach
annotationtypeisspecifiedusingitsfullyqualifiedname.
Usageexample:nullAnnot(p.Nullable|p.NonNull|p.NonNullByDefault)
Enablingthisoptionenablesallnullannotationrelatedsuboptions.These
canbeindividuallycontrolledusingoptionslistedbelow

nullAnnotConflict reportconflictsbetweennullannotationspecifiedandnullnessinferred.Is
effectiveonlywiththenullAnnotoptionenabled.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 126/322
12/10/2015 Javadevelopmentuserguide
nullAnnotRedundant reportredundantspecificationofnullannotation.Iseffectiveonlywiththe
nullAnnotoptionenabled.

nullDereference missingnullcheck

nullUncheckedConversion reportuncheckedconversionfromunannotatedtypeto@NonNulltype.Is
effectiveonlywiththenullAnnotoptionenabled.

overann missing@Overrideannotation(superclassonly)

paramAssign assignmenttoaparameter

+ pkgDefaultMethod attempttooverridepackagedefaultmethod

+ raw usageaofrawtype(insteadofaparameterizedtype)

+/ resource (potentially)unsafeusageofresourceoftypeCloseable

semicolon unnecessarysemicolonoremptystatement

+ serial missingserialVersionUID

specialParamHiding constructororsetterparameterhidinganotherfield

+/ staticaccess macroforindirectStaticandstaticReceiver

staticmethod aninstancemethodthatcouldbeasastaticmethod

+ staticReceiver ifanonstaticreceiverisusedtogetastaticfieldorcallastaticmethod

super overridingamethodwithoutmakingasuperinvocation

+ suppress enable@SuppressWarnings

switchDefault switchstatementlackingadefaultcase

syncOverride missingsynchronizedinsynchronizedmethodoverride

syntacticAnalysis performsyntaxbasednullanalysisforfields

syntheticAccess whenperformingsyntheticaccessforinnerclass

tasks enablesupportfortaskstagsinsourcecode

+ typeHiding typeparameterhidinganothertype

+ unavoidableGenericProblems reportevenunavoidabletypesafetyproblemsduetorawAPIs

+ unchecked uncheckedtypeoperation

unnecessaryElse unnecessaryelseclause

unqualifiedField unqualifiedreferencetofield

+/ unused macroforunusedImport,unusedLabel,unusedLocal,unusedPrivate,
unusedThrown,unusedTypeArgs,andunusedTypeParameter

unusedAllocation allocatinganobjectthatisnotused

unusedArgument unusedmethodparameter(deprecatedoptionuseunusedParaminstead)

+ unusedImport unusedimportreference

+ unusedLabel unusedlabel

+ unusedLocal unusedlocalvariable

+ unusedParam unusedmethodparameter

+ unusedParamImplementing unusedparameterforimplementingmethod

+ unusedParamIncludeDoc unusedparameterdocumentedinaJavadoccommenttag

+ unusedParamOverriding unusedparameterforoverridingmethod

+ unusedPrivate unusedprivatememberdeclaration

unusedThrown unuseddeclaredthrownexception

unusedThrownIncludeDocComment unuseddeclaredthrownexceptiondocumentedinaJavadoccomment
tag

unusedThrownExemptExceptionThrowable reportunuseddeclaredthrownexceptionbutexemptExceptionand
Throwable

unusedThrownWhenOverriding unuseddeclaredthrownexceptioninoverridingmethod

+ unusedTypeArgs unusedtypeargumentsformethodandconstructor

+ unusedTypeParameter unusedtypeparameter

uselessTypeCheck unnecessarycast/instanceofoperation

+ varargsCast varargsargumentneedexplicitcast

+/ warningToken unhandledorunusedwarningtokenin@SuppressWarnings

nowarn Nowarning(equivalenttowarn:none)

err:... Specifythesetofenabledwarningsthatareconvertedtoerrors.
e.g.err:unusedLocal,deprecation
unusedLocalanddeprecationwarningswillbeconvertedtoerrors.Allotherwarningsarestillreportedaswarnings.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 127/322
12/10/2015 Javadevelopmentuserguide
err:<warningtokensseparatedby,> convertexactlythelistedwarningstoerrors
err:+<warningtokensseparatedby,> convertadditionalwarningstoerrors
err:<warningtokensseparatedby,> removespecificwarningsfrombeingconvertedtoerrors

deprecation Equivalenttowarn:+deprecation.

properties<file> Setwarnings/errorsoptionbasedonthepropertiesfilecontents.Thisoptioncanbeusedwithnowarn,err:..orwarn:..options,but
thelastoneonthecommandlinesetstheoptionstobeused.
Thepropertiesfilecontentscanbegeneratedbysettingprojectspecificsettingsonanexistingjavaprojectandusingthefilein
.settings/org.eclipse.jdt.core.prefsfileasapropertiesfile,orasimpletextfilethatisdefinedentry/valuepairsusingthe
constantsdefinedintheorg.eclipse.jdt.core.JavaCoreclass.Ofthoseconstantsdeclaredinthisclass,alloptionsstartingwith
"org.eclipse.jdt.core.compiler."areinterpretedbythebatchcompiler.

...
org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning
org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
...

ToensurethatapropertyfilehasthesameeffectwhenusedintheIDEandforthebatchcompiler,useofthepropertiesoption
willchangethedefaultsforafewoptions:

g defaultchangedtoallenabled
preserveAllLocals defaultchangedtoenabled
enableJavadoc defaultchangedtoenabled
error/warningforbidden defaultchangedtoerror

Debugoptions
g[:none|:lines,vars,source] Setthedebugattributeslevel
g Alldebuginfo(equivalenttog:lines,vars,source)
g:none Nodebuginfo
g:[lines,vars,source] Selectivedebuginfo
Notspecifyingthisoptionisequivalenttosettingg:lines,source.

preserveAllLocals Explicitlyrequestthecompilertopreservealllocalvariables(fordebugpurpose).Ifomitted,thecompilerwillremoveunusedlocals.

parameters Explicitlyrequestthecompilertopreserveinformationabouttheformalparametersofamethod(suchastheirnames)tobeaccessed
fromreflectionlibraries,annotationprocessing,codeweaving,andinthedebugger.Thisoptionissupportedfromtargetlevel1.8and
later.
Annotationprocessingoptions(requirea1.6VMoraboveandareusedonlyifthecomplianceis1.6)
Akey[=value] Annotationprocessorsoptionsthatarepassedtoannotationprocessors.keyismadeofidentifiersseparatedbydots

proc:[only|none] Ifproc:onlyisspecified,theannotationprocessorswillrunbutnocompilationwillbeperformed.Ifproc:noneisspecified,
annotationprocessorswillnotbediscoveredorruncompilationwillproceedasifnoannotationprocessorswerefound.Bydefaultthe
compilermustsearchtheclasspathforannotationprocessors,sospecifyingproc:nonemayspeedcompilationifannotation
processingisnotrequired.

processor<class1[,class2,...]> Qualifiedclassnamesofannotationprocessorstorun.Ifspecified,thenormalprocessordiscoveryprocesswillbeskipped.

processorpath<dir1><dir2>...<dirP> Alistofdirectoriesorjarfileswhichwillbesearchedforannotationprocessors.Entriesareseparatedbytheplatformpathseparator.
Ifnotspecified,theclasspathwillbesearchedinstead.

s<dir> Thedirectorywheregeneratedsourcefileswillbecreated.

XprintProcessorInfo Printinformationaboutwhichannotationsandwhichelementsaprocessorisaskedtoprocess

XprintRounds Printinformationaboutannotationprocessingrounds

classNames<class1[,class2,...]> Qualifiednamesofbinarytypesthatneedtobeprocessed
Ignoredoptions(forcompatibilitywithjavacoptions)
J<option> Passoptiontothevirtualmachine

X<option> Specifynonstandardoption.Xemacsisnotignored.

X Printnonstandardoptionsandexit

O Optimizeforexecutiontime
Advancedoptions
@<file> Readcommandlineargumentsfromfile

maxProblems<n> Maxnumberofproblemspercompilationunit(100bydefault)

log<filename> Specifyalogfileinwhichalloutputfromthecompilerwillbedumped.Thisisreallyusefulifyouwanttodebugthebatchcompileror
getafilewhichcontainsallerrorsandwarningsfromabatchbuild.Iftheextensionis.xml,thegeneratedlogwillbeanxmlfile.

genericsignature Explicitlyrequestthecompilertopreserveinformationaboutgenericsignatureoflambdaexpressions.

Xemacs Useemacsstyletopresenterrorsandwarningslocationsintotheconsoleandregulartextlogs.XMLlogsareunaffectedbythis
option.Withthisoptionactive,themessage:
2.WARNINGin/workspace/X.java
(atline8)...
ispresentedas:
/workspace/X.java:8:warning:Themethod...

proceedOnError[:Fatal] Keepcompilinginspiteoferrors,dumpingclassfileswithproblemmethodsorproblemtypes.Thisisrecommendedonlyifyouwant
tobeabletorunyourapplicationevenifyouhaveremainingerrors.
With":Fatal",alloptionalerrorsaretreatedasfatalandthisleadstocodethatwillabortifanerrorisreachedatruntime.Without

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 128/322
12/10/2015 Javadevelopmentuserguide
":Fatal",optionalerrorsdon'tpreventthepropercodegenerationandtheproduced.classfilescanberunwithoutaproblem.

verbose Printaccessed/processedcompilationunitsintheconsoleorthelogfileifspecified.

referenceInfo Computereferenceinfo.Thisisusefulonlyifconnectedtothebuilder.Thereferenceinfosareuselessotherwise.

progress Showprogress(onlyinlogmode).

time Displayspeedinformation.

noExit DonotcallSystem.exit(n)atendofcompilation(n=0ifnoerror).

repeat<n> Repeatcompilationprocess<n>times(perfanalysis).

inlineJSR InlineJSRbytecode(implicitiftarget>=1.5).

enableJavadoc ConsiderreferencesinsideJavadoc.TheJavadocoptionsareeffectiveonlywhenthisoptionisenabled.

missingNullDefault Whenannotationbasednullanalysisisenabled(using"nullAnnot",above),thisoptionwillraiseawarningwheneverthereisno
defaultannotationonapackageoratype.

annotationpath Whenannotationbasednullanalysisisenabled(using"nullAnnot",above),thisoptiondefineslocationswheretofindexternal
annotationstosupportannotationbasednullanalysis.
Thevalueofthisoptionsisalistofdirectoriesorzipfiles.Entriesareseparatedbytheplatformpathseparator.
ThespecialnameCLASSPATHwillcauselookupofexternalannotationsfromtheclasspathandsourcepath.
Helpingoptions
?help Displaythehelpmessage.

vversion Displaythebuildnumberofthecompiler.Thisisveryusefultoreportabug.

showversion Displaythebuildnumberofthecompilerandcontinue.Thisisveryusefultoreportabug.

Examples
d:\tempclasspath Itcompilesallsourcefilesind:\tempanditssubfolders.Theclasspathissimplyrt.jar.Itgeneratesalldebugattributesandallgenerated.classfiles
rt.jartimegd aredumpedind:\tmp.Thespeedofthecompilerwillbedisplayedoncethebatchprocessiscompleted.
d:/tmp

d:\temp\Test.java ItcompilesonlyTest.javaanditsdependantfilesifany,retrievingdependantfilesfromd:\temp.Theclasspathisd:\tempfollowedbyrt.jar,which
classpath meansthatallnecessaryclassesaresearchedfirstind:\tempandtheninrt.jar.Itgeneratesnodebugattributesandallgenerated.classfilesare
d:\temprt.jarg:none dumpedind:\temp.

4.9.2.Usingtheantjavacadapter
TheEclipsecompilercanbeusedinsideanAntbuildfileusingthejavacadapter.InordertousetheEclipsecompiler,yousimplyneedtodefinethebuild.compilerpropertyinyour
buildfile.
Inordertogetthebatchcompilerworkinginanantbuildfile,theantruntimeclasspathneedstocontaintheEclipsebatchcompiler.Whenyourunyourantbuildfile:
1. outsideofEclipse:theeasiestwaytosetuptheantruntimeclasspathistoaddtheecj.jarfileusingthelibargumentordumpingitinsidetheANT_HOMElocation.
2. insideEclipseusingthesameJREthanEclipse:theEclipsebatchcompilerisimplicitlyaddedtotheantruntimeclasspath.
3. insideEclipseusingthedifferentJRE:theEclipsebatchcompilermustbeexplicitlyaddedtotheantruntimeclasspath.Thiscanbedoneusingtheecj.jarfileorusingthe
org.eclipse.jdt.corejarfileandthejdtCompilerAdapter.jarfilelocatedinsidetheorg.eclipse.jdt.corejarfile(thisjarfileneedstobeextractedfirst).
Hereisasmallexample:

<?xmlversion="1.0"encoding="UTF8"?>
<projectname="compile"default="main"basedir="../.">

<propertyname="build.compiler"value="org.eclipse.jdt.core.JDTCompilerAdapter"/>

<propertyname="root"value="${basedir}/src"/>

<propertyname="destdir"value="d:/temp/bin"/>

<targetname="main">
<javacsrcdir="${root}"destdir="${destdir}"debug="on"nowarn="on"extdirs="d:/extdirs"source="1.4">
<classpath>
<pathelementlocation="${basedir}/../org.eclipse.jdt.core/bin"/>

</classpath>
</javac>
</target>
</project>

ThesyntaxusedforthejavacAnttaskcanbefoundintheAntjavactaskdocumentation.ThecurrentadaptersupportstheJavacAnttask1.4.1upto1.6.5versions.
Ifyouareusingaversionabove1.5.0,youcanusethenestedcompilerargumentelement(<compilerarg>)tospecifycompilerspecificoptions.

...
<javacsrcdir="${root}"destdir="${destdir}"debug="on"nowarn="on"extdirs="d:/extdirs"source="1.4">
<classpath>
<pathelementlocation="${basedir}/../org.eclipse.jdt.core/bin"/>
</classpath>

<compilerargcompiler="org.eclipse.jdt.core.JDTCompilerAdapter"line="1.5warn:+boxing"/>
</javac>
...

Note:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 129/322
12/10/2015 Javadevelopmentuserguide
1. Topreventcompilerdependantbuildfiles,westronglyadviseyoutousea<compilerarg>whose"compiler"attributevalueisorg.eclipse.jdt.core.JDTCompilerAdapter.
Ifthisisnotset,thebuildfilecanonlybeusedwiththeEclipsecompiler.Ifset,thenestedcompilerargumentisignoredifthenameisdifferentfromthecompilername
specifiedbythebuild.compilerproperty.
2. <compilerarg>shouldnotbeusedtosetvaluesliketargetvalue,sourcevalue,debugoptions,oranyoptionsthatcouldbesetusingthedefinedattributesofthejavacant
task.Itsusagemustbereservedtopasscompilerspecificoptionslikewarningoptions.Whenacommandlineargumentisspecifiedmorethanonce,theEclipsebatch
compilercanreporterrorslike:

duplicatetargetcompliancesettingspecification:1.5

4.9.3.Excludingwarningsusing@SuppressWarnings
SinceJava5.0,youcandisablecompilationwarningsrelativetoasubsetofacompilationunitusingthejava.lang.SuppressWarningannotation.

@SuppressWarning("unused")publicvoidfoo(){
Strings
}

Withouttheannotation,thecompilerwouldcomplainthatthelocalvariablesisneverused.Withtheannotation,thecompilersilentlyignoresthiswarninglocallytothefoomethod.
Thisenablestokeepthewarningsinotherlocationsofthesamecompilationunitorthesameproject.
ThelistoftokensthatcanbeusedinsideaSuppressWarningsannotationis:
alltosuppressallwarnings
boxingtosuppresswarningsrelativetoboxing/unboxingoperations
casttosuppresswarningsrelativetocastoperations
depanntosuppresswarningsrelativetodeprecatedannotation
deprecationtosuppresswarningsrelativetodeprecation
fallthroughtosuppresswarningsrelativetomissingbreaksinswitchstatements
finallytosuppresswarningsrelativetofinallyblockthatdon'treturn
hidingtosuppresswarningsrelativetolocalsthathidevariable
incompleteswitchtosuppresswarningsrelativetomissingentriesinaswitchstatement(enumcase)
javadoctosuppresswarningsrelativetojavadocwarnings
nlstosuppresswarningsrelativetononnlsstringliterals
nulltosuppresswarningsrelativetonullanalysis
rawtypestosuppresswarningsrelativetousageofrawtypes
resourcetosuppresswarningsrelativetousageofresourcesoftypeCloseable
restrictiontosuppresswarningsrelativetousageofdiscouragedorforbiddenreferences
serialtosuppresswarningsrelativetomissingserialVersionUIDfieldforaserializableclass
staticaccesstosuppresswarningsrelativetoincorrectstaticaccess
staticmethodtosuppresswarningsrelativetomethodsthatcouldbedeclaredasstatic
supertosuppresswarningsrelativetooverridingamethodwithoutsuperinvocations
syntheticaccesstosuppresswarningsrelativetounoptimizedaccessfrominnerclasses
syncoverridetosuppresswarningsbecauseofmissingsynchronizewhenoverridingasynchronizedmethod
uncheckedtosuppresswarningsrelativetouncheckedoperations
unqualifiedfieldaccesstosuppresswarningsrelativetofieldaccessunqualified
unusedtosuppresswarningsrelativetounusedcodeanddeadcode

4.10.ImprovingJavacodequality
TheEclipseJavacompilerperformsmorechecksandanalysesthanaremandatedbytheJavaLanguageSpecification.Thisisdoneinordertohelpyoutoimprovethequalityof
yourJavacode.Sincedifferentusershavedifferentviewsofwhichwarningsareinteresting,thisbehaviorishighlyconfigurable.SeeJavaCompileErrors/WarningsPreferencesfor
availableoptions.
Somewarningsanderrorsshouldbeobviousandgenerallyvalidforeverybody.Insomecasesyoumaywanttoconfigurethecompilertomatchyourcodestyleandalsoyourquality
goals.Someanalysesaremosthelpfulifyoutosomedegreeadjustyourcodestyletomakeitbetteranalyzablebythecompiler.
Thepageslistedbelowgivesomebackgroundoncertainanalysesandhintsonhowtomakethebestuseofthem:
Usingnullannotations
Avoidingresourceleaks
Ensuringcompletenessofswitchstatements

4.10.1.Usingnullannotations
NullPointerExceptionisoneofthemostcommoncausesforfailureofJavaprograms.Inthesimplestcasesthecompilercandirectlywarnyouwhenitseescodelikethis:

Objecto=null
Strings=o.toString()

Withbranching/loopingandthrowingexceptionsquitesophisticatedflowanalysisbecomesnecessaryinordertofigureoutifavariablebeingdereferencedhasbeenassigneda
null/nonnullvalueonsomeorallpathsthroughtheprogram.
Duetotheinherentcomplexity,flowanalysisisbestperformedinsmallchunks.Analyzingonemethodatatimecanbedonewithgoodtoolperformancewhereaswholesystem
analysisisoutofscopefortheEclipseJavacompiler.Theadvantageis:analysisisfastandcanbedoneincrementallysuchthatthecompilercanwarnyoudirectlyasyoutype.
Thedownside:theanalysiscannot"see"whichvalues(nullornonnull)areflowingbetweenmethods(asparametersandreturnvalues).

Interproceduralnullanalysis
Thisiswherenullannotationscomeintoplay.Byspecifyingamethodparameteras@NonNullyoucantellthecompilerthatyoudon'twantanullvalueinthisposition.

Stringcapitalize(@NonNullStringin){
returnin.toUpperCase()//nonullcheckrequired
}
voidcaller(Strings){
if(s!=null)
System.out.println(capitalize(s))//precedingnullcheckisrequired

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 130/322
12/10/2015 Javadevelopmentuserguide
}

IntheveinofDesignbyContractthishastwosides:
1. It'sthecaller'sresponsibilitytoneverpassanullvalue,whichistobeensured,e.g.,byanexplicitnullcheck.
2. TheimplementorofmethodcapitalizeenjoystheguaranteethattheargumentinshallnotbenullandthusdereferencingwithoutanullcheckisOKhere.
Formethodreturnvaluesthesituationissymmetric:

@NonNullStringgetString(StringmaybeString){
if(maybeString!=null)
returnmaybeString//theabovenullcheckisrequired
else
return"<n/a>"
}
voidcaller(Strings){
System.out.println(getString(s).toUpperCase())//nonullcheckrequired
}

1. Nowtheimplementormustensurethatnullisneverreturned.
2. ConverselythecallernowenjoystheguaranteethatdereferencingthemethodresultwithoutcheckingisOK.

Availableannotations
TheEclipseJavacompilercanbeconfiguredtousethreedistinctannotationtypesforitsenhancednullanalysis(whichisdisabledbydefault):
@NonNull:nullisnotalegalvalue
@Nullable:nullvalueisallowedandmustbeexpected
@NonNullByDefault:typesinmethodsignaturesthatlackanullannotationareregardedasnonnull.

Annotations@NonNulland@Nullablearesupportedintheselocations:
Methodparameter
Methodreturn(syntacticallyamethodannotationisusedhere)
Localvariables
Fields
InJava8,morelocationscanbeannotatedwithnulltypeannotations
@NonNullByDefaultissupportedfor

Methodstoaffectalltypesinthismethod'ssignature
Types(classes,interfaces,enums)toaffectallmethodsinthetypebody
Package(viaafilepackageinfo.java)toaffectalltypesinthepackage
Note,thateventheactualqualifiednamesoftheseannotationsareconfigurable,butbydefaulttheonesgivenaboveareused(fromthepackageorg.eclipse.jdt.annotation).
Whenusing3rdpartynullannotations,pleaseensurethatthoseareproperlydefinedusingatleasta@Targetmetaannotation,becauseotherwisethecompilercannotdistinguish
betweendeclarationannotations(Java5)andtypeannotations(Java8).

Setupofthebuildpath
AJARwiththedefaultnullannotationsisshippedwithEclipseineclipse/plugins/org.eclipse.jdt.annotation_*.jar.ThisJARneedstobeonthebuildpathatcompiletimebutitisnot
necessaryatruntime(soyoudon'thavetoshipthistousersofyourcompiledcode).
StartingwithEclipseLuna,twoversionsofthisjarexist,onewithdeclarationannotationsforuseinJava7orbelow(version1.1.x)andonewithnulltypeannotationsforuseinJava
8(version2.0.x).
ForplainJavaprojectsthereisalsoaquickfixonunresolvedreferencesto@NonNull,@Nullable,or@NonNullByDefaultthataddsthesuitableversionoftheJARtothebuild
path:

ForOSGibundles/pluginspleaseaddoneofthefollowingentriestoyourMANIFEST.MF:
WhenusingnullannotationsinaJava7projectorbelow:

RequireBundle:...,
org.eclipse.jdt.annotationbundleversion="[1.1.0,2.0.0)"resolution:=optional

FornulltypeannotationsinaJava8projectpleaseuse:

RequireBundle:...,
org.eclipse.jdt.annotationbundleversion="[2.0.0,3.0.0)"resolution:=optional

Seealsothediscussioninthecorrespondingsectiononcompatibility.

Interpretationofnullannotations
ItshouldbeclearnowthatnullannotationsaddmoreinformationtoyourJavaprogram(whichcanthenbeusedbythecompilertogivebetterwarnings).Butwhatexactlydowe
wanttheseannotationstosay?Fromapragmaticpointofviewthereareatleastthreelevelsofwhatwemightwanttoexpresswithnullannotations:
1. Sporadichintstothereader(humanandcompiler)
2. Designbycontract:APIspecificationforsomeorallmethods
3. Fullspecificationusinganextendedtypesystem

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 131/322
12/10/2015 Javadevelopmentuserguide
For(1)youmaystartusingnullannotationsrightawayandwithoutreadingfurther,butyoushouldn'texpectmorethanalittlehinteverynowandthen.Theotherlevelsdeservesome
moreexplaining.

Designbycontract:APIspecification
AtfirstsightusingnullannotationsforAPIspecificationsintheveinofDesignbyContractonlymeansthatthesignaturesofallAPImethodsshouldbefullyannotated,i.e.,except
forprimitivetypeslikeinteachparameterandeachmethodreturntypeshouldbemarkedaseither@NonNullor@Nullable.Sincethiswouldmeantoinsertverymanynull
annotations,itisgoodtoknowthatinwelldesignedcode(especiallyAPImethods),@NonNullissignificantlymorefrequentthan@Nullable.Thusthenumberofannotationscanbe
reducedbydeclaring@NonNullasthedefault,usinga@NonNullByDefaultannotationatthepackagelevel.
Notethesignificantdifferencebetween@Nullableandomittinganullannotation:ThisannotationexplicitlystatesthatnullisOKandmustbeexpected.Bycontrast,noannotation
simplymeans,wedon'tknowwhat'stheintention.Thisistheoldsituationwheresometimesbothsides(callerandcallee)redundantlycheckfornull,andsometimesbothsides
wronglyassumethattheothersidewilldothecheck.ThisiswhereNullPointerExceptionsoriginatefrom.Withoutanannotationthecompilerwillnotgivespecificadvice,butwitha
@Nullableannotationeveryuncheckeddereferencewillbeflagged.

Withthesebasicswecandirectlymapallparameterannotationstopreconditionsandinterpretreturnannotationsaspostconditionsofthemethod.

Subtypingandoverriding
InobjectorientedprogrammingtheconceptofDesignbyContractneedstoaddressonemoredimension:subtypingandoverriding(inthesequeltheterm"override"willbeusedin
thesenseofthe@OverrideannotationinJava6:methodsoverridingorimplementinganothermethodfromasupertype).Aclientinvokingamethodlikethisone:

@NonNullStringcheckedString(@NullableStringin)

shouldbeallowedtoassumethatallimplementationsofthismethodfulfillthecontract.SowhenthemethoddeclarationisfoundinaninterfaceI1,wemustruleoutthatanyclass
CnimplementingI1providesanincompatibleimplementation.Specifically,itisillegalifanyCntriestooverridethismethodwithanimplementationthatdeclarestheparameteras
@NonNull.Ifwewouldallowthis,aclientmoduleprogrammedagainstI1couldlegallypassnullastheargumentbuttheimplementationwouldassumeanonnullvalueunchecked
dereferenceinsidethemethodimplementationwouldbeallowedbutblowupatruntime.Hence,a@Nullableparameterspecificationobligesalloverridestoadmitnullasan
expected,legalvalue.
Conversely,a@NonNullreturnspecificationobligesalloverridestoensurethatnullwillneverbereturned.
Therefore,thecompilerhastocheckthatnooverrideaddsa@NonNullparameterannotation(ora@Nullablereturnannotation)thatdidn'texistinthesupertype.
Interestingly,thereverseredefinitionsarelegal:addinga@Nullableparameterannotationora@NonNullreturnannotation(youmayconsidertheseas"improvements"ofthe
method,itacceptsmorevaluesandproducesamorespecificreturnvalue).
Byforcingsubclassestorepeatnullannotationsinanyoverridingmethods,thenullcontractofeachmethodcanbeunderstoodwithoutsearchingtheinheritancehierarchy.
However,insituationswhereaninheritancehierarchymixescodeofdifferentprovenanceitmaynotbepossibletoaddnullannotationstoallclassesatonce.Inthesesituationsthe
compilercanbetoldtotreatmethodswithmissingnullannotationsasifannotationsfromanoverriddenmethodwereinherited.Thisisenabledusingthecompileroptioninheritnull
annotations.Itispossiblethatamethodoverridestwomethodswithdifferentnullcontracts.Alsoanullnessdefaultcanbeapplicableatamethodwhichisinconflictwithan
inheritednullannotation.Thesecasesareflaggedasanerrorandtheoverridingmethodmustuseanexplicitnullannotationtoresolvetheconflict.

Relaxinga@NonNullparametertounspecified?
Ifinheritanceofnullannotationsisnotenabled,oneparticularsituationissafefromatypetheorypointofview,butmaystillindicateaproblem:Givenasupermethodthatdeclaresa
parameteras@NonNullandanoverridingmethodthatdoesnotconstrainthecorrespondingparameter(neitherbyanexplicitnullannotation,norbyanapplicable
@NonNullByDefault).
Thisissafebecauseclientsseeingthesuperdeclarationwillbeforcedtoavoidnullwhereasthetheoverridingimplementationsimplycannotleveragethisguaranteeduetothelack
ofaspecificationinthisspecificmethod.
Stillthismayleadtomisconceptionsbecauseitmaybeintendedthatthedeclarationinthesupertypeshouldapplyalsotoalloverrides.
Forthisreasonsthecompilerprovidesanoption'@NonNull'parameternotannotatedinoverridingmethod:
Enablingthiswarning/errorisusefulforforcingdeveloperstobeexplicitaboutthecontractofoverridingmethods.Ifnullshouldindeedbeacceptableitisgoodpracticetoadd
a@Nullableannotationtooverridethe@NonNullfromthesupermethod.
Disablingthiswarning/errorisusefulinscenariiofmixedcodeownership:itfacilitatestheuseoflegacyimplementations(withoutnullannotations)incombinationwithsuper
typesthathaveadoptedtheapproachofnullannotations.

Legacysupertypes
Thepreviousconsiderationsaddadifficultywhenannotatedcodeiswrittenasasubtypeofa"legacy"(i.e.,unannotated)type(whichmaybefroma3rdpartylibrary,thuscannot
bechanged).Ifyoureadthelastsectionverycarefullyyoumighthavenoticedthatwecannotadmitthata"legacy"methodisoverriddenbyamethodwitha@NonNullparameter
(sinceclientsusingthesupertypedon't"see"the@NonNullobligation).
Inthissituationyouwillbeforcedtoomitnullannotations(plansexisttosupportaddingannotationstolibrariesafterthefact,butnopromisecanbemadeyet,ifandwhensucha
featurewillbeavailable).

Cancelinganullnessdefault
Thesituationwillgettricky,ifasubtypeofa"legacy"typeresidesinapackageforwhich@NonNullByDefaulthasbeenspecified.Nowatypewithanunannotatedsupertype
wouldneedtomarkallparametersinoverridingmethodsas@Nullable:evenomittingparameterannotationsisn'tallowedbecausethatwouldbeinterpretedlikea@NonNull
parameter,whichisprohibitedinthatposition.That'swhytheEclipseJavacompilersupportscancellationofanullnessdefault:byannotatingamethodortypewith
@NonNullByDefault(false)anapplicabledefaultwillbecanceledforthiselement,andunannotatedparametersareagaininterpretedasunspecified.Now,subtypingislegalagain
withoutaddingunwanted@Nullableannotations:

classLegacyClass{
Stringenhance(Stringin){//clientsarenotforcedtopassnonnull.
returnin.toUpperCase()
}
}

@NonNullByDefault
classMyClassextendsLegacyClass{

//...methodswith@NonNulldefault...

@Override
@NonNullByDefault(false)
Stringenhance(Stringin){//wouldnotbevalidif@NonNullByDefaultwereeffectivehere
returnsuper.enhance(in)
}
}

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 132/322
12/10/2015 Javadevelopmentuserguide
Thecaseoffields
Nullannotationsworkbestwhenappliedinmethodsignatures(localvariablestypicallydon'tevenneedthese,butmayalsoleveragenullannotationsforbridgingbetween
annotatedcodeand"legacy"code).Insuchusagenullannotationsconnectthechunksofintraproceduralanalysisastoachievestatementsaboutglobaldataflows.Startingwith
EclipseKeplernullannotationscanalsobeappliedtofields,butherethesituationisslightlydifferent.
Considerafieldmarkedwith@NonNull:thisobviouslyrequiresthatanyassignmenttothefieldprovidesavaluethatisknownnottobenull.Additionally,thecompilermustbeable
toverifythatanonnullfieldcanneverbeaccessedinitsuninitializedstate(inwhichitstillhasthevaluenull).Ifitcanbeverifiedthateveryconstructorcompliestothisrule
(similarlyastaticfieldmusthaveaninitializer),theprogrambenefitsfromthesafetythatdereferencingthefieldcannevercauseaNullPointerException.
Thesituationismoredelicatewhenconsideringafieldmarked@Nullable.Suchafieldshouldalwaysbeconsideredasdangerousandtherecommendedwayofworkingwith
nullablefieldsis:alwaysassignthevaluetoalocalvariablebeforeworkingwithit.Usingalocalvariabletheflowanalysiscantellexactly,whetheradereferenceissufficiently
protectedbyanullcheck.Whenfollowingthisgeneralruleworkingwithnullablefieldsposesnoproblems.
Thingsgetmoreinvolvedwhenthecodedirectlydereferencesthevalueofanullablefield.Theproblemisthatanynullchecksthatthecodemayperformbeforethedereferencecan
easilybeinvalidatedbyoneofthese:
effectsviaaliasedreferences
sideeffectsofanothermethod
concurrency
Onecaneasilyseethatwithoutalsoanalyzingthreadsynchronization(whichisbeyondthecompiler'scapabilities)nonullcheckagainstanullablefieldwillevergrant100%safety
forasubsequentdereference.Soifconcurrentaccesstoanullablefieldispossible,thefield'svalueshouldneverbedirectlydereferenced,alwaysalocalvariableshouldbeused
instead.Evenifnoconcurrencyisinvolved,theremainingissuesposeachallengetoacompleteanalysisthatisharderthanwhatacompilercantypicallyhandle.

Flowanalysisvs.syntacticanalysis
Giventhecompilercannotfullyanalyzetheeffectsofaliasing,sideeffectsandconcurrency,theEclipsecompilerdoesnotperformanyflowanalysisforfields(otherthan
regardingtheirinitialization).Sincemanydeveloperswillconsiderthislimitationastoorestrictiverequiringtheuseoflocalvariableswheredevelopersfeelthattheircodeshould
actuallybesafeanewoptionhasbeenintroducedasatentativecompromise:
Thecompilercanbeconfiguredtoperformsomesyntacticanalysis.Thiswilldetectthemostobviouspatternslikethis:

@NullableObjectf
voidprintChecked(){
if(this.f!=null)
System.out.println(this.f.toString())
}

Withthegivenoptionenabledtheabovecodewillnotbeflaggedbythecompiler.Itisimportanttoseethatthissyntacticanalysisisnot"smart"inanyway.Ifanycodeappears
betweenthecheckandthedereferencethecompilerwillcowardly"forget"theinformationofthepreviousnullcheck,withouteventryingtoseeiftheintermediatecodecouldperhaps
beharmlessaccordingtosomecriteria.Thuspleasebeadvised:wheneverthecompilerflagsadereferenceofanullablefieldasunsafealthoughthehumaneyemayseethatnull
shouldnotoccur,pleaseeitherrewriteyourcodetocloselyfollowtherecognizedpatternshownabove,or,evenbetter:usealocalvariabletoleverageallthesophisticationofflow
analysis,whichsyntacticanalysiswillneverattain.

BenefitsofDesignbyContract
UsingnullannotationsinthestyleofDesignbyContractasoutlinedabove,helpstoimprovethequalityofyourJavacodeinseveralways:Attheinterfacebetweenmethodsitis
madeexplicit,whichparameters/returnstolerateanullvalueandwhichonesdon't.Thiscapturesdesigndecisions,whicharehighlyrelevanttothedevelopers,inawaythatisalso
checkablebythecompiler.
Additionally,basedonthisinterfacespecificationtheintraproceduralflowanalysiscanpickupavailableinformationandgivemuchmorepreciseerrors/warnings.Without
annotationsanyvalueflowingintooroutofamethodhasunknownnullnessandthereforenullanalysisremainssilentabouttheirusage.WithAPIlevelnullannotationsthenullness
ofmostvaluesisactuallyknown,andsignificantlyfewerNPEswillgounnoticedbythecompiler.However,youshouldbeawarethatstillsomeloopholesexist,whereunspecified
valuesflowintotheanalysis,preventingacompletestatementwhetherNPEscanoccuratruntime.

Completespecificationusinganextendedtypesystem
Thesupportfornullannotationshadbeendesignedinawaythatshouldbecompatibletoafutureextension.ThisextensionhasbecomepartoftheJavalanguageastype
annotations(JSR308),whichhavebeenintroducedinJava8.JDTsupportstoleveragethenewconceptfornulltypeannotations.

Compilermessagesexplained
Semanticdetailsofannotationbasednullanalysisarepresentedhere,byexplainingtherulesthatthecompilerchecksandthemessagesitissuesuponviolationofarule.
Onthecorrespondingpreferencepagetheindividualrulescheckedbythecompileraregroupedunderthefollowingheadings:

Violationofnullspecification
Asspecificationviolationwehandleanysituationwhereanullannotationmakesaclaimthatisviolatedbytheactualimplementation.Thetypicalsituationresultsfromspecifyinga
value(local,argument,methodreturn)as@NonNullwhereastheimplementationactuallyprovidesanullablevalue.Hereanexpressionisconsideredasnullableifeitheritis
staticallyknowntoevaluatetothevaluenull,orifitisdeclaredwitha@Nullableannotation.
Secondly,thisgroupalsocontainstherulesformethodoverridingasdiscussedabove.Hereasupermethodestablishesaclaim(e.g.,thatnullisalegalargument)whileanoverride
triestoevadethisclaim(byassumingthatnullisnotalegalargument).Asmentionedevenspecializinganargumentfromunannotatedto@NonNullisaspecificationviolation,
becauseitintroducesacontractthatshouldbindtheclient(tonotpassnull),butaclientusingthesupertypewon'tevenseethiscontract,sohedoesn'tevenknowwhatis
expectedofhim.
Thefulllistofsituationsregardedasspecificationviolationsisgivenhere.Itisimportanttounderstandthaterrorsinthisgroupshouldneverbeignored,becauseotherwisethe
entirenullanalysiswillbeperformedbasedonfalseassumptions.Specifically,wheneverthecompilerseesavaluewitha@NonNullannotationittakesitforgrantedthatnullwillnot
occuratruntime.It'stherulesaboutspecificationviolationswhichensurethatthisreasoningissound.Thereforeitisstronglyrecommendedtoleavethiskindofproblemconfigured
aserrors.

Conflictbetweennullannotationsandnullinference
Alsothisgroupofruleswatchesovertheadherencetonullspecifications.However,herewedealwithvaluesthatarenotdeclaredas@Nullable(northevaluenullitself),butvalues
wheretheintraproceduralflowanalysisinfersthatnullcanpossiblyoccuronsomeexecutionpath.
Thissituationarisesfromthefactthatforunannotatedlocalvariablesthecompilerwillinferwhethernullispossibleusingitsflowanalysis.Assumingthatthisanalysisisaccurate,
ifitseesaproblemthisproblemhasthesameseverityasdirectviolationsofanullspecification.Therefore,itisagainstronglyrecommendedtoleavetheseproblemsconfiguredas
errorsandnottoignorethesemessages.
Creatingaseparategroupfortheseproblemsservestwopurposes:todocumentthatagivenproblemwasraisedwiththehelpoftheflowanalysis,and:toaccountforthefactthat
thisflowanalysiscouldbeatfault(becauseofabugintheimplementation).ForthecaseofanacknowledgedimplementationbugitcouldinexceptionalsituationsbeOKto
suppressanerrormessageofthiskind.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 133/322
12/10/2015 Javadevelopmentuserguide
Giventhenatureofanystaticanalysis,theflowanalysismayfailtoseethatacertaincombinationofexecutionpathsandvaluesisnotpossible.Asanexampleconsidervariable
correlation:

Stringflatten(String[]inputs1,String[]inputs2){
StringBuffersb1=null,sb2=null
intlen=Math.min(inputs1.length,inputs2.length)
for(inti=0i<leni++){
if(sb1==null){
sb1=newStringBuffer()
sb2=newStringBuffer()
}
sb1.append(inputs1[i])
sb2.append(inputs2[i])//warninghere
}
if(sb1!=null)returnsb1.append(sb2).toString()
return""
}

Thecompilerwillreportapotentialnullpointeraccessattheinvocationofsb2.append(..).Thehumanreadercanseethatthereisnoactualdangerbecausesb1andsb2actually
correlateinawaythateitherbothvariablesarenullorbotharenotnull.Atthelineinquestionweknowthatsb1isnotnull,hencealsosb2isnotnull.Withoutgoingintothedetails
whysuchcorrelationanalysisisbeyondthecapabilityoftheEclipseJavacompiler,pleasejustkeepinmindthatthisanalysisdoesn'thavethepowerofafulltheoremproverand
thereforepessimisticallyreportssomeproblemswhichamorecapableanalysiscouldpossiblyidentifyasfalsealarms.
Ifyouwanttobenefitfromflowanalysis,youareadvisedtogivealittlehelptothecompilersoitcan"see"yourconclusions.Thishelpcanbeassimpleassplittingtheif(sb1==
null)intotwoseparateifs,oneforeachlocalvariable,whichisaverysmallpricetopayforthegainthatnowthecompilercanexactlyseewhathappensandcheckyourcode
accordingly.Morediscussiononthistopicwillfollowbelow.

Uncheckedconversionfromnonannotatedtypeto@NonNulltype
Thisgroupofproblemsisbasedonthefollowinganalogy:inaprogramusingJava5genericsanycallstopreJava5librariesmayexposerawtypes,i.e.,applicationsofageneric
typewhichfailtospecifyconcretetypearguments.Tofitsuchvaluesintoaprogramusinggenericsthecompilercanaddanimplicitconversionbyassumingthattypearguments
werespecifiedinthewayexpectedbytheclientpartofthecode.Thecompilerwillissueawarningabouttheuseofsuchaconversionandproceeditstypecheckingassumingthe
library"doestherightthing".Inexactlythesameway,anunannotatedreturntypeofalibrarymethodcanbeconsideredasa"raw"or"legacy"type.Againanimplicitconversioncan
optimisticallyassumetheexpectedspecification.Againawarningisissuedandanalysiscontinuesassumingthatthelibrary"doestherightthing".
Theoreticallyspeaking,alsotheneedforsuchimplicitconversionsindicatesaspecificationviolation.However,inthiscaseitmaybe3rdpartycodethatviolatesthespecification
whichourcodeexpects.Or,maybe(aswehaveconvincedourselvesof)some3rdpartycodedoesfulfillthecontract,butonlyfailstodeclareso(becauseitdoesn'tusenull
annotations).Insuchsituationswemaynotbeabletoexactlyfixtheproblemfororganizationalreasons.

@SuppressWarnings("null")
@NonNullFoofoo=Library.getFoo()//implicitconversion
foo.bar()

TheabovecodesnippetassumesthatLibrary.getFoo()returnsaFoowithoutspecifyinganullannotation.Wecanintegratethereturnvalueintoourannotatedprogramby
assignmenttoa@NonNulllocalvariable,whichtriggersawarningregardinganuncheckedconversion.ByaddingacorrespondingSuppressWarnings("null")tothisdeclarationwe
acknowledgetheinherentdangerandaccepttheresponsibilityofhavingverifiedthatthelibraryactuallybehavesasdesired.

Tipsformakingcodebetteranalyzable
Ifflowanalysiscannotseethatavalueisindeednotnull,thesimpleststrategyisalwaystoaddanewscopedlocalvariableannotatedwith@NonNull.Then,ifyouareconvinced
thatthevalueassignedtothislocalwillneverbenullatruntimeyoucanuseahelpermethodslikethis:

static@NonNull<T>TassertNonNull(@NullableTvalue,@NullableStringmsg){
if(value==null)thrownewAssertionError(msg)
returnvalue
}
@NonNullMyTypefoo(){
if(isInitialized()){
MyTypecouldBeNull=getObjectOrNull()
@NonNullMyTypetheValue=assertNonNull(couldBeNull,
"valueshouldnotbenullbecauseapplication"+
"isfullyinitializedatthispoint.")
returntheValue
}
returnnewMyTypeImpl()
}

NotethatbyusingtheaboveassertNonNull()methodyouareacceptingtheresponsibilitythatthisassertionwillalwaysholdatruntime.Ifthatisnotwhatyouwant,annotated
localvariableswillstillhelptonarrowdownwhereandwhytheanalysisseesapotentialfornullflowingintoacertainlocation.

Tipsforadoptingnullannotations
AtthetimeofreleasingtheJDTversion3.8.0,collectingadviceforadoptingnullannotationsisstillworkinprogress.Forthatreasonthisinformationiscurrentlymaintainedinthe
Eclipsewiki.

4.10.2.Usingnulltypeannotations
StartingwithJava8,nullannotationscanbeusedinanewandmorepowerfulway,becausethenewconceptof"typeannotations"(JSR308)supportstheuseofannotationsasan
extensiontothetypesystem.
Technically,thisisdeterminedbytwonewelementsintheenumjava.lang.annotation.ElementType:TYPE_USEandTYPE_PARAMETER.Notably,whensaying
@Target(ElementType.TYPE_USE)theannotationthusmarkedcanbeattachedbasicallytoallusagesofatype.

ByinterpretingnullannotationsaspartofthetypesystemweinterpreteachclassorinterfaceCninthesystemasintroducingtwodistincttypes:"@NonNullCn"and"@Nullable
Cn".TheformertypecontainsallinstancesofCnwhereasthelattertypeadditionallycontainsthevaluenull.Thisimpliesthat@NonNullCnisasubtypeof@NullableCnwithall
regularconsequencesregardingassignability.Soideallyforeveryvalueinaprogramwewillknowifitcanbenull(andmustbecheckedbeforedereference)ornot.Theunannotated
typewillbeconsideredalegacytypejustlikerawtypesarelegacytypessincetheintroductionofgenerics:awayforinterfacingwitholdcode,tobeflaggedwithwarningsabout
uncheckedconversions.Ifwesystematicallyavoidsuchlegacytypes,thenthecompilercanrigorouslyflageveryunsafeusage.
Inordertoachievecompletenessofnullanalysis,checksregardingnulltypeannotationshavebeenintegratedwithalltypecheckingtasksofthecompiler(activeifnullannotations
areenabled).
UsersmigratingfromnullannotationsinpreviousversionstoJava8stylenulltypeannotationsareadvisedtocheckthesectionaboutcompatibility.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 134/322
12/10/2015 Javadevelopmentuserguide
Generics
Perhapsthemainadvantageoftypeannotationsfornullanalysisistheabilitytoannotatetheparametersandargumentsofgenericclassesandinterfaces.Programmersonlyusing
genericclassesmaydirectlyskiptothesectionontypeargumentsbutdesignersofgenericclassesshouldtakethetimetounderstandthedifferentimplicationsofannotatingthese
elements:
typeparameters
typevariables
typearguments

Typeparameters
Agenericclass,interfaceormethodmaydeclareoneormoretypeparameters.Technicallythesearedeclarations,andhenceitwasamereoversightthatthesecannotbeannotated
inJava5.InJava8anannotationcandeclare@Target(ElementType.TYPE_PARAMETER)tobeapplicableinthisposition.JDT'snulltypeannotations@NonNulland@Nullableare
declaredwith@Target({TYPE_USE}),whichincludesusageontypeparameterdeclarations.
Withrespecttonulltypeannotations,eachtypeparametercanbespecifiedatoneoftheselevels:
unconstrained
thetypeparameterdoesnotimposeanynullnessconstraintsontheargumentsthataclientmysubstituteforthetypeparameter.
constrainedbyanupperbound
thetypeparameterhasanextendsclausethatspecifiesminimalnullnessrequirementsontypeargumentsprovidedbyclients
exactlyspecified
thetypeparameterrestrictsusagetotypesofexactlyoneparticularnullness
Constrainingatypeparameterviaanupperboundreliesonthefactthateachtype' @NonNullCn'isasubtypeofthecorrespondingtype' @NullableCn'.Hence,a@Nullable
upperbounddoesnotimposeanyrestriction,whereasa@NonNullupperboundprohibitsthesubstitutionbya@Nullabletypeargument:

//declarations:
classC0<T0extends@NullableObject>{}//meaningless,noconstraintimposed
classC1<T1extends@NonNullObject>{}
...
//usage:
C1<@NonNullString>c1String//legal
C1<@NullableString>c1String//illegal

Forexactspecificationanullannotationmaybeattachedtothetypeparameterdeclarationitself,whichisinterpretedasdefiningbothanupperandalowerbound.Inotherwords,
onlytypeswiththeexactsamenulltypeannotationarelegalastypearguments:

//declaration:
classC2<@NullableT2>{}
...
//usage:
C2<@NonNullString>c2String//illegal
C2<@NullableString>c2String//legal

Giventheasymmetry,thatinJavaatypeparametermaydeclareonlyupperboundsbutnolowerbounds,thefollowingthreestylescanberecommended:
Usea@NonNullupperboundforconstrainingtypeargumentstononnulltypes.
Directlyspecifyatypeparameteras@Nullableforconstrainingtypeargumentstonullabletypes.
Useanunconstrainedtypeparametertosupporttypeargumentsofeithernullness.

Typevariables
Withinthescopeofagenericdeclaration(class,interfaceormethod),thenameofatypeparametercanbeusedasatypevariable,i.e.,aplaceholderforatypethatisnotknownat
thispoint.
Atypevariablewilltypicallybeusedwithout(further)nullannotations,whichimpliesthattheannotationsfromthetypeparameterdeclarationwillapplyasdetailedbelow.Insome
situations,however,itisusefultoannotateanindividualuseofatypevariable.Asanexampleconsiderthelibrarymethodjava.util.Map.get(Object),whichshouldactuallybe
annotatedlikethis:

@NullableVget(Objectkey)

BythisdeclarationwewouldindicatethatthereturntypeisthenullablevariantofwhatevertypeVmayrepresent.Inotherwords,anullannotationontheuseofatypevariable
overridesanyothernullinformationthatwouldotherwiseapplytothistype.Inparticularanynullannotationonthecorrespondingtypeparameterdeclaration(oritsbound)is
overriddenbyanullannotationinthisposition.
Ontheotherhand,whenusingatypevariablewithoutimmediatenullannotationsthefollowingrulesapplydependingonthedeclarationofthecorrespondingtypeparameter:
Atypevariablecorrespondingtoatypeparameterwitha@NonNullupperbounddenotesatypethatisknowntobenonnull.

classC1<T1extends@NonNullNumber>{
intconsume(T1t){
returnt.intValue()//OKsinceT1isknowntobenonnull
}
T1provide(){
returnnull//NOTOKsinceT1requiresnonnull
}
}

Atypevariablecorrespondingtoatypeparameterspecifiedas@Nullabledenotesatypethatisknowntobenullable.

classC2<@NullableT2extendsNumber>{
intconsume(T2t){
returnt.intValue()//NOTOKsinceT2isknowntobenullable
}
T2provide(){
returnnull//OK:returningnullislegal
}
}

Atypevariablecorrespondingtoanunconstrainedtypeparameterrequirespessimisticcheckinginordertoguaranteesafetywithalllegalsubstitutions:thistypecanneitherbe
assumedtobenullablenornonnull.

classC<TextendsNumber>{
intconsume(Tt){

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 135/322
12/10/2015 Javadevelopmentuserguide
returnt.intValue()//NOTOKsinceTcouldbenullable
}
Tprovide(){
returnnull//NOTOKsinceTcouldrequirenonnull
}
}

Thelastpointmaylooksurprisingatfirst,butpleaseseethatanunconstrainedtypeparameterimpliesthatwemaynotassumeanythingaboutthenullnessofthetyperepresented
bythecorrespondingtypevariable.Evenmore:wemustactivelysupportnullableandnonnulltypes.Ontheotherhandthissimplyextendstheexistingrulethattheonlytypebeing
compatiblewithanunboundedtypevariableisthetypevariableitself.Toexplainthissituationinthecontextofnullanalysis,thecompilerwillraisethefollowingerroragainstthe
returninprovide():

Nulltypemismatch(typeannotations):'null'isnotcompatibletothefreetypevariable'T'

Byenforcingthisdefensivestrategyregardingunconstrainedtypeparametersweobtainthebenefitofallowingclientstofreelychoosetherulesforaparticulargenericinstantiation,
aswillbeshownnext.

Typearguments
Wheninstantiatingagenerictypeorwheninvokingagenericmethod,theconstraintsputforwardbythetypeparametermustbeobserved.Hence,whenaproviderofagenerictype
ormethodspecifiedtherequirednullness,thismustbeobeyedandthecompilerwillflaganyviolations.
When,ontheotherhand,atypeparameterdoesnotimposeanyrestrictions,aclientmayfreelychoosethenullnessofhistypearguments:

intprocessWithoutNulls(@NonNullList<@NonNullInteger>ints){
intresult=0
for(inti=0i<ints.size()i++){
Integerelement=ints.get(i)
result+=element.intValue()//OK:listelementisknowntobenonnull
ints.set(i,null)//NOTOK:listdoesnotacceptnullvalue
}
returnresult
}
intprocessWithNulls(@NonNullList<@NullableInteger>ints){
intresult=0
for(inti=0i<ints.size()i++){
Integerelement=ints.get(i)
result+=element.intValue()//NOTOK:listelementcanbenull
ints.set(i,null)//OK:listacceptsnullvalue
}
returnresult
}

Inference
Withnulltypeannotationsaffectingtypearguments,thelanguagefeaturesonemorelocationamenabletoinference:duringtypeinferencefortheinvocationofagenericmethod
(lambdaexpressionetc.),typeinferenceshylyattemptstoalsoinfertheappropriatenulltypeannotations.Example:

<T>Tcheck(Tin){returnin}
voidtest(@NonNullList<@NullableString>someStrings){
@NonNullList<@NullableString>checked
checked=check(someStrings)//inferringtypesforthisinvocation
...
}

Inthistrivialexample,inferencewillindeedinstantiatethegenericparameter<T>to@NonNullList<@NullableString>.Morecomplexscenariosareinferred,too,butnoguarantee
ismade,thatapossiblesolutionwillalwaysbefound.Incaseinferencefailstoinfersuitablenulltypeannotations,usersareadvisedtoreverttoexplicitlyspecifytypearguments
evenofagenericmethodinvocation.

Morelocations

Castandinstanceof
Syntactically,typeannotationscanbeusedalsoincastsandinstanceofexpressions.Fornullannotations,however,thishaslimitedvalue.
Castingtoanullannotatedtypeisalwaysanuncheckedcastbecausethecompilerisnotallowedtoinsertruntimechecksthatwouldmakethecastmeaningful.Ifaruntimecheck
isdesired,pleaseconsiderusingasmallhelperfunctionlike:

static@NonNull<T>TcastToNonNull(@NullableTvalue,@NullableStringmsg){
if(value==null)thrownewNullPointerException(msg)
returnvalue
}

Castsaffectingthetypeargumentsofagenerictypewillalwaysbeuncheckedcastsduetoerasure.
instanceofcheckswithnulltypeannotationsarenotmeaningful.Hencethecompilerflagsthisasillegalusageofanulltypeannotation.

Locationsthatarenonnullbydefinition
Syntactically,typeannotationscanalsobeusedfor
allocationexpressions
methodreceiver(pseudoargumentbythenameofthis)
catchparameter
Ineachoftheseconstructs,thetypeisnonnullbydefinition.Henceanulltypeannotationinoneofthesepositionsisflaggedasillegaluse.Thisdoesn't,however,restricttheuseof
nulltypeannotationsontypeargumentsofthegiventype.

Compatibility
Migratingfromdeclarationannotationstotypeannotationshasafewunavoidableimplications,regardingthesyntax,regardingprojectconfigurationandregardingthesemantics.

Syntax

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 136/322
12/10/2015 Javadevelopmentuserguide
FortwoconstructstheJLSintroducesasyntacticchange:

DeclarationAnnotations(Java7orbelow) TypeAnnotation(Java8)
@NonNullString[] String@NonNull[]

@NonNulljava.lang.String java.lang.@NonNullString

Inbothcasesthenewsyntaxhasbeenintroducedtoprovidemoreoptions.
Forarraysatypeannotationbeforetheleafelementtypewillnowdenoteanarraywhoseindividualcellshavethegivennullnesshere:cellscannotbenull.InJava7andbelowthe
samesyntaxexpressedapropertyofthecorrespondingvariableandhencecapturedthenullnessofthearrayitself.ToexpressthesameusingJava8typeannotations,viz.thatthe
arrayitselfcanorcannotbenull,thetypeannotationisplacedbeforethesquarebracketsdenotingthearraydimensions.Thisimpliesthattheoldsyntaxisstillvalid,butitsmeaning
haschanged:

//annotatedleaftype:
@NonNullObject[]o1
o1=null//OK
o1=newObject[1]
o1[0]=null//NOTOK
...
//annotatedarraytype:
Object@NonNull[]o2
o2=null//NOTOK
o2=newObject[1]
o2[0]=null//OK
...
//multidimensionalarray:
Object@NonNull[]@Nullable[]o3
o3=null//NOTOK,outerarrayisnonnull
o3=newObject[1]@Nullable[]
o3[0]=null//OK,innerarrayisnullable

Unfortunately,checkingproperinitializationofanarraywithnonnullcontentisbeyondthecapabilitiesofJDT'sstaticanalysis.
Forqualifiedtypenamesthetypeannotationmustbeplaceddirectlyprecedingtheactualtypename.Thiswayitispossibletogivedifferenttypeannotationsforinnerclassesand
theirenclosinglikeinorg.project.@ImmutableOuter.@NullableInner.Thisdistinction,however,isnotusefulfornullannotations,becausetheenclosingofanonstaticinner
classisbydefinitionalwaysnonnull.Usersofnulltypeannotationsonlyneedtounderstandthattheoldsyntaxforthiscaseisillegalfortypeannotationsandhowtoconvertthis
intolegalJava8code(seethetableabove).

Projectconfiguration
Properlydesignedannotationtypescanbedistinguishedbylookingattheir@Targetdeclaration(theuseofnullannotationslackinga@Targetdeclarationisdiscouraged).Tosupport
bothstylesofannotations,JDThaspublishedamajorupdateoftheannotationbundleorg.eclipse.jdt.annotation:Versions1.1.xareoldstyledeclarationannotationsversions
2.0.0andonwardaretypeannotations.Byincreasingthemajorversionanincompatibilityissignaled.Usersareadvisedtoreferencethislibrarywithanexplicitversionrange,either
[1.1.0,2.0.0)fordeclarationannotationsor[2.0.0,3.0.0)fortypeannotations.

Theexactconfigurationdependsofcourseontheflavorofproject:
PlainJava
JDTcontinuestoofferaquickfixforcopyingtheannotationlibraryintotheproject.Theversionwillbedeterminedbythecompliancesettingsoftheproject.
Maven
Bothversionsoftheannotationbundlewillbepublishedtorepo.eclipse.org,fromwheretheycanbeconsumedusingtheregularmavenmechanisms:besuretospecify
thecorrectversionspecifying<scope>compile</scope>isrecommendedforthisdependency.
OSGi/Eclipse
WhendevelopingOSGibundles/Eclipsepluginstheversionrangeshouldbespecifiedasmentionedabove.Unfortunately,OSGidoesn'tsupportaconceptofcompiletime
dependencies.ThePDEspecificmechanisminfilebuild.propertiesisproblematicbecauseitdoesn'tsupportspecifyingaversionrange.Thusthebestapproximationof
thedesiredsemanticsistouseaRequireBundledependency.qualifiedwithresolution:=optionalinordertoavoidforcingthisdependencyontheruntime:

RequireBundle:...,
org.eclipse.jdt.annotationbundleversion="[2.0.0,3.0.0)"resolution:=optional

SemanticsNonNullByDefault
Whilethefundamentalsemanticsofnullannotationremainsunchanged,theannotation@NonNullByDefaulthasbeenchangedslightly:
Thisannotationcannowaffectmorelocations.
Thelocationstobeaffectedcanbefinetunedusingthevaluepropertyoftheannotation(seealsotheenumDefaultLocation).
Asaconsequence,thenotationforcancelingadefaultfromanouterscopehasbeenchanged,too:
DeclarationAnnotations(Java7orbelow) TypeAnnotation(Java8)
@NonNullByDefault(false) @NonNullByDefault({})

AlthoughtheJava8variantof@NonNullByDefaultaffectsmorelocations,twonoteworthyexceptionsexist(asspecifiedinDefaultLocation):

Wildcardsandtheuseoftypevariablesarealwaysexcludedfrom@NonNullByDefault.

Bythisrule,typevariablesandwildcardsretaintheirintendedpropertiesas"unknowns"alsointermsofnullness,evenwhentheyappearinthecontextof@NonNullByDefault.

Compilermessagesexplained
Inadditiontocompilermessagesofthepreviousversionthefollowingmessagesmaybeissued,ifnulltypeannotationsareenabledforanalysis:

Generalnulltypemismatch
Nulltypemismatch(typeannotations):required'X'butthisexpressionhastype'Y'
Inanassignmentcontextnulltypeannotationsdon'tmatch.Notethatthemismatchmayrelatetoanydetailofthetype(typeargument,arrayelement),notnecessarilytothe
maintype.
Allmismatchesdetectedbasedontypeannotationsareprefixedwith"Nulltypemismatch(typeannotations)".

Variousexpressions

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 137/322
12/10/2015 Javadevelopmentuserguide
Potentialnullpointeraccess:arrayelementmaybenull
Anarrayelementisdereferenced,wherethearraytypedeclaresitselementsas@Nullable.
Potentialnullpointeraccess:thisexpressionhasa'@Nullable'type
Anyexpressionatthelefthandsideofadothasatypethatisdeclaredtobenullable.
Redundantnullcheck:comparing'@NonNullX'againstnull
Anarbitraryexpressionknowntohavea@NonNulltypeisunnecessarilybeingcomparedagainstnull.

Uncheckedconversions
Nulltypesafety(typeannotations):Theexpressionoftype'X'needsuncheckedconversiontoconformto'@NonNullX'
Avalueofanunannotatedtypeisbeingassignedtoavariableofanannotatedtype.Notethatthemismatchmayrelatetoanydetailofthetype(typeargument,array
element),notnecessarilytothemaintype.
Nulltypesafety:UncheckedcastfromXto'@NY'
Avalueiscastedtoanullannotatedtype,wherethenullnessisnotcheckedatruntimebythecast.

Problemsspecifictogenerics
Nullconstraintmismatch:Thetype'X'isnotavalidsubstituteforthetypeparameter'T'
Herethetypeparameter<T>hasaconstraintinoneoftheformsmentionedabove.TheactualtypeargumentX,however,doesn'tconformtothisconstraint.
Thisnullnessannotationconflictswitha'@N'annotationwhichiseffectiveonthesametypeparameter
Anullannotationonaboundofatypeparameterconflictswithanothernullannotationonanotherboundoronthetypeparameteritself.
Nulltypemismatch(typeannotations):''null''isnotcompatibletothefreetypevariable'T'
Anattemptismadetoassingnulltoavariabletypedtoanunconstrainedtypevariable,seethesectionontypevariables
Nulltypemismatch(typeannotations):required'T'butthisexpressionhastype'@NullableT',where'T'isafreetypevariable
Anattemptismadetoassignavalueofanullabletypetoavariabletypedtoanunconstrainedtypevariabled,seethesectionontypevariables
Contradictorynullannotations:methodwasinferredas'Tfoo(X)',butonlyoneof'@NonNull'and'@Nullable'canbeeffectiveatanylocation
Typeinferenceforagenericmethodinvocationhasproducedasignatureinwhichcontradictorynullannotationsclashonthesameelement.

Lambdaexpressionsandmethodreferences
Foranymismatchesinnullannotationsaffectinglambdaexpressionsormethodreferencesthecorresponding"descriptor"ismentioned(thesingleabstractmethodbeing
implementedbythelambda/methodreference).Thisisusefullforfindingtheoriginofanullannotationthatisnotexplicitatthecurrentexpression.

4.10.3.Usingexternalnullannotations
Nullannotations,orevenbetter,nulltypeannotationscansignificantlyreduce(ideally:eliminate)thedangerofNullPointerExceptionthrownatprogramruntime.Unfortunately,the
APIofmanylibrariesdoesnotyetconsistentlyspecifywherenullisallowedandwhereitisn't.Thiscanbeamajorsourceofincompletenessinthisendeavor.Inordertofillthis
gap,startingwithEclipse4.5(Mars),JDTsupportstheconceptofexternalannotations,whichmeansthatnullannotationscanbespecifiedinseparatefileswithoutmodifyingthe
originallibrary.Ifyouattachsuchexternalnullannotationstoagivenlibrary,JDTwillthenconsidertheseannotationsforitsstaticnullanalysis.
Thishelppagedescribes
thestructureofexternalannotations
configuringaprojecttouseexternalannotations
interactivelycreatingexternalannotations
inspectingexternalannotations
differencesbetweendeclarationannotationsandtypeannotations

Structureofexternalannotations
Externalannotationscanbeprovidedasadirectorytree,whoseleavesaretextfileswithextension.eea("EclipseExternalAnnotations").Inthisstructure,eachdirectory
correspondstoaJavapackage,andeach.eeafilecorrespondstoaJavatype(class,interfaceetc.).
Optionally,theabovestructurecanbepackedinasinglezipfilewithextension.zipor.jar.
Theexactformatof.eeatextfileshasbeendesignedwithslightbiastowardsprocessingbytools.Still,thesefilesareamenabletostoring,comparingandmergingusingany
versioncontrolsystem.Theformatisbasedonsignaturesasdefinedin JVMS4.7.9.1.

Configuringaprojecttouseexternalannotations
Caveat:Whendifferentprojectsreferringtothesamelibraryhavedifferentconfigurationswithrespecttoexternalannotations,theUIsupportdescribedbelow
(commandAnnotateandJavadochovers)caneasilygetconfused:Whenlookingatagivenlibraryclass,JDTmaynotknowwhichprojecttheuseriscurrentlyworking
on,producingunexpectedresults.Whilehopefullythiswillbeimprovedinafutureversion,forthetimebeingusersareadvisedtousethesameexternalannotation
locationforallprojectsreferringtothesamelibrary.Ashared("common")baseprojectwilltypicallybeagoodchoiceforhostingexternalannotations.

JavaRuntimeEnvironments
ExternalannotationscanbedirectlyattachedtoeachJREconfiguredinthecurrentworkspace.Forthispurpose,pleaseusetheInstalledJREspreferencepageandclickEditfor
detailsoftheselectedJRE.AfterselectingoneormoreJarfilescontributedbythegivenJREinstallation,clickExternalAnnotationstoopenanewdialog,whereeitheradirectory
orazipfilecanbeselectedastheexternalannotationlocationfortheselectedjar(s).
Alternatively,youmayselectthepropertiesofaspecificJREboundintheJavaBuildPathofaspecificproject.Pleasenote,thatattachingexternalannotationstoindividualjarsofa
JREalwaysaffectstheworkspacepreference,evenifaccessedviatheproject'sbuildpath.Theonlywaytodefineaprojectspecificlocationforexternalannotationlocationfora
JREisviathedirectchildExternalannotations:ofthetoplevelnodecalledJRESystemLibrary,butnote,thatprojectspecificlocationsarenotrecommended,seethe"Caveat"
above.

OtherClasspathContainers
Dependingonthebuildtechnologyinuse,projectsmayhaveadditionalclasspathcontainerslikePluginDependenciesorMavenDependencies.Forthesecontainers,theonly
optioncurrentlyistospecifytheexternalannotationlocationviaeachprojectsbuildpath.Inthiscaseusersareadvisedtomanuallyensurethatthesamelocationisusedforall
projectsoftheworkspace,seethe"Caveat"above.

OtherLibraries
Foranyotherlibraries(jars)explicitlyreferencedfromtheJavaBuildPathofaproject,externalannotationscanbeattachedseparatelyintheLibrariespageoftheproject'sbuild
path.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 138/322
12/10/2015 Javadevelopmentuserguide
Creatingexternalannotations
Prerequisites:Externalannotationsrequirealibrarywithsourceattachment.Additionally,annotationbasednullanalysismustbeenabledforthecurrentproject,anexternal
annotationlocationmustbedefinedforthelibraryandthatlocationmustbeadirectory(notazipfile)withintheworkspace.
Afternavigatingtothedesiredclass,youmayselectthetype(methodparameterormethodreturntype)thatshouldbeaffectedbyanannotation,andinvokethenewcommand
Annotate(availableviacontextmenuandbydefaultboundtoCtrl1).SimilartoquickassistsinaJavasourcecodeeditor,thiscommandwillofferproposalsapplicableatthe
currentlocation.Forexternalannotations,thethreeoptionsare:
Annotateas'@NonNullSomeType'
Annotateas'@NullableSomeType'
Removenullnessannotationfromtype'SomeType'
Forobviousreasons,exactly2ofthesethreeproposalsareofferedatanysuitablelocation.Behindthescenesthiscommandwillcreateand/orupdatean.eeafilecorrespondingto
thecurrentclass.Thenewannotationwillthenberespectedbythecompiler:ErrorsandwarningsinanopeneditorwillbeupdatedimmediatelyTheProblemsviewwillbeupdated
whenaffectedclassesarerecompiled.

Becareful:Whenattachingexternalannotationstoalibrary,keepinmindthatyouaredefininganewcontract,thatwillthenbeusedtocheckyourprogramagainst.
Thecompilerwill,however,notcheckthelibrary,whetheritactuallyconformstothiscontract.Bycarelesslymarking,e.g.,areturntypeas@NonNullyouletthe
compileradviseyoutoremovenullchecksagainstreturnvaluesfromthegivenmethod.Ifthelibrarydoesreturnnullinanysituation,thisnullwillhityouunguarded.
Beforeaddinganannotation,makesureitisbackedbyfacts,like,e.g.:
explicitmentioninJavadoc,e.g.,whena@returnspecificationsays:"...ornullwhen...".
anexplicitnullcheckofamethodparameter,whichdoesnotthrowanexception(implyingthatnullisaccepted@Nullableparameter)
uncheckdereferenceofamethodparameter(implyingthatnullisnotaccepted@NonNullparameter)
anexplicitnullreturn(implyinga@Nullablereturntype)
explicitlycreatedreturnvaluesateachreturnstatement(implyinga@NonNullreturntype).

Inspectingexternalannotations
Theimmediateeffectofexternalannotationscanbeobservedviachangesincompilererrors/warnings.Forfulltransparency,annotatedlibrarysignaturescanbeinspectedusingthe
JavadochoverorJavadocview.
Duetoanimplementationlimitation,thisfeaturecurrentlyonlyworksfortypeannotations(Java8).

Declarationannotationsvstypeannotations
Generally,supportforexternalannotationshasbeendevelopedwithregardtofullysupportingalllocationsofnulltypeannotations(Java8).Thismeans,youmayrefertoanydetail
ofatypeinamethodsignatureandannotate,e.g.,atypeparameter,atypeboundoranarraydimension.Whenusingdeclarationannotations,therelevantsubsetoflocationshares
thesamemechanismsforexternalannotations.
Inonesituationthedesignfortypeannotationsshinesthroughevenwhenusingdeclarationannotations:annotatinganarraytypeisbasedonthenewsyntaxoftypeannotations
(seealsoCompatibility>Syntax).ForillustrationconsiderthefollowingmethodintypeCollection:

Object[]toArray()

EvenwhenaprojectusesJava7orbelow,thereturntypeofthismethodisannotatedbyplacingthecursorbeforethearraybrackets.InvokingAnnotatewillcreateanexternal
annotationthatisinternallyinterpretedasanannotationonthemethod(butstillthemeaningis:describingthereturnofthismethod).
Otherthanthisoneexception,externalannotationscloselymimichowannotationsdirectlywithinasourcefilewouldbehandled,withareducedsetoflocationsfordeclaration
annotations,andthefullsetoflocationsfortypeannotations.

4.10.4.Avoidingresourceleaks
Classesimplementingtheinterfacejava.io.Closeable(sinceJDK1.5)andjava.lang.AutoCloseable(sinceJDK1.7)areconsideredtorepresentexternalresources,which
shouldbeclosedusingmethodclose(),whentheyarenolongerneeded.
TheEclipseJavacompilerisabletoanalyzewhethercodeusingsuchtypesadherestothispolicy.E.g.,thefollowingsnippetrepresentsanobviousresourceleak:

intlen(Filef)throwsIOException{
InputStreamstream=newFileInputStream(f)
returnstream.available()
}

Thecompilerwillflagthiswith"Resourceleak:'stream'isneverclosed".

Basicflowanalysisforresourceleaks
Flowanalysisdetectsthefollowingsituations:
Aresourceisdefinitelynotclosed
Aresourceisnotclosedonallcontrolflows(flaggedas"maynotbeclosed")
Aresourceisnotclosedatamethodexitpoint(returnstatementorwhenanexceptionisraised)(definitelyoronsomecontrolflow)
InaJava7programaresourceisclosedbutthecodecouldstillbeimprovedbyusingatrywithresourcesstatement.
Additionally,flowanalysistriestofollowresourcevaluesthroughvariableassignments.However,ifdifferentresourcesmaybeassignedtothesamevariable(ondifferentcontrol
flowsorinsequence),theanalysiscanbecomelessaccurate.
Notalltheanalysisisenabledbydefault.Pleaseconsultthecompilerpreferencesregardingtheindividualconfigurationoptions.
Hints:Codewillgenerallybeeasiertoanalyze(andeasiertounderstandbyhumanreaders)ifresourcetypevariablesarenotreusedfordifferentpurposes.Ideally,inJava7
programsallresourcesshouldbemanagedwithatrywithresourcesstatement.

Ownership/responsibility
Theabovediagnosticsbasicallyassumethatamethodthatcreatesaninstanceofaresourcetypeisalsoresponsibleforclosingthisresource.However,someresourceswillbe
sharedamongseveralmethods.Heretheanalysismakesthefollowingassumptions:
Ifamethodreturnsaresourcetoitscaller,itisnotresponsibleforclosingnoproblemisreported.
Ifaresourceisstoredinafield,nosinglemethodisconsideredasresponsibleforclosingnoproblemisreported.
Ifamethodobtainsaresourceviaamethodcallratherthanbyanewexpression,itmayormaynotberesponsibleanyproblemsareonlyflaggedaspotentialresourceleaks.
Ifaresourceispassedasanargumentinamethodcallorconstructorcall,thecurrentmethodmayormaynotberesponsibleanyproblemsareonlyflaggedaspotential

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 139/322
12/10/2015 Javadevelopmentuserguide
resourceleaks.

Resourcewrappersandresourcefreecloseables
TheJDKdefinesafewclasseswhichimplementCloseablebutdonotdirectlyrepresentaresourceattheleveloftheoperatingsystem.
java.io.StringReaderisanexampleofacloseablethatdoesn'trequirecallingclose()becausenooperatingsystemresourcesareheldthatwouldrequirecleanup.The
analysisusesanexplicitwhitelisttodetectclassesfromjava.iothatfallinthiscategory.Noresourceleakwarningsareissuedregardingtheseclasses.
Instancesofclasseslikejava.io.BufferedInputStreamarewrappersaroundanotherresource(wherewrapperscanbeappliedatmultiplelevels).Alsotheseobjectsdonot
directlyrepresentanoperatingsystemresource.Ifthewrappedresourceisclosed,thewrapperdoesn'tneedclosing.Conversely,ifawrapperisclosedthiswillincludeclosingof
thewrappedresource.Theanalysishasasecondwhitelistfordetectingwrapperresources,andwillrecognizewhethertheunderlyingactualresourcewillbecloseddirectlyor
indirectlyviathewrapper.Eitheronesufficestosilencewarningsregardingresourceleaks.Thewhitelistcontainsclassesfromjava.io,java.util.zip,java.security,
java.beansandjava.sound.sampled.

Hint:Itisgenerallypreferable/safesttoclosetheoutermostwrapper,notawrappedresource.

4.10.5.Ensuringcompletenessofswitchstatements
Itisgoodpracticetoensurethateachswitchstatementshouldbecompleteinthesensethateachexecutionatruntimewillfindasuitablebranch.Thisisactuallyanontrivialtask
whentakingallofthefollowingintoconsideration:
Differentrulesapplyforswitchesoveranenumvaluevs.intorevenString.
Dependingonthecontext,usingadefaultlabelmayappearundesirableorgoodpracticeorevenmandatory.
Insomecontextsprogramevolutionshouldbesafeguardedbyflagginginconsistentextensionasanerror,whileinothercontextsamoreforgivingstrategyisdesirable.
Additionally,theJLSmandatesaflowanalysisforenumswitchstatementswhichcanleadtounexpectedcompiletimeerrors:

enumColors{RED,GREEN,BLUE}
StringcolorString(Colorc){
switch(c){
caseRED:return"red"
caseGREEN:return"green"
caseBLUE:return"blue"
}
}

Thecompilerwillanswer:

"ThismethodmustreturnaresultoftypeString.Notethataproblemregardingmissing'default:'on'switch'hasbeensuppressed,whichisperhapsrelatedtothis
problem".

Thismessagehasbeendesignedtoalertusersofthedifferentnotionsofcompleteness:theflowanalysismandatedbytheJLSconsiderseachenumswitchstatementwithouta
defaultcaseasincomplete,evenifitlistsall(currentlyknown)enumconstants.Thisconcernsreturnstatementsaswellasdefiniteassignmentoflocalvariablesorblankfinalfields.
However,ifyoufollowallrecommendationsbelow,theaboveerrormessagewillneveroccur.
Pleaseconsultthecompilerpreferencesregardingtheindividualconfigurationoptionsforreportingvariouslevelsofincompleteness.Inthesequelwediscussdifferentdesigngoals
andpoliciesandhowtheycanbecheckedusingtheEclipseJavacompiler.

Onusing"default:"
Optimally,eachswitchstatementshouldhaveameaningfuldefaultbranch,whichhandlesallcasesthatarenotexplicitlylistedusingan"alwaysreasonable"strategy.Obviously,
suchastrategyisdifficultorevenimpossibletofindinmanycases,butifyoucanfindameaningfuldefaultimplementation,that'scertainlythebestsolution.

Recommendation:Bylettingthecompilerwarnyouabouteachswitchstatementlackingadefaultcaseyouareremindedtosearchforagooddefaultimplementationfor
everyswitchstatement.

Ifthecompilerwarnsyouaboutamissingdefaultcase,butthereasonablethingtodobydefaultisjustdonothing,thismightaswellbeworthdocumenting.

Recommendation:If"donothing"isareasonabledefaultstrategyyoushouldaddadefault:labelwhoseactionisonlyacommentexplainingthat(andwhy)doingnothingis
OKinthisswitch.Bydoingsoyoualsotellthecompilerthatyoudidnotsimplyforgetaboutadefaultcase.

Ifdefinitelynoreasonabledefaultimplementationcanbefound,asalastresortyoumaywanttopreventanunexpectedvaluetobetherootcauseforothererrorsfurther
downstream,i.e.,youmaywanttofailearlyatruntime.

Recommendation:Ifneitherareasonabledefaultimplementationcanbefoundnor"donothing"appearstobeagoodstrategy,addadefault:casethatthrowsanexception
and/orlogstheproblem.

Eachswitchstatementshouldbeassignabletooneofthethreeabovecategories.Thismeanslettingthecompilerwarnyouabouteachmissingdefaultcaseisauniversallyvalid
strategy.

Handlingallenumconstants
Whenperformingaswitchoveranenumvalue,itmaybedesirabletoexplicitlycovereachenumconstantbyacorrespondingcasestatement.

Recommendation:Ifyouwanttobewarnedaboutenumswitchstatementsthatlackacasestatementforanyoftheenumconstants,pleaseconsiderenablingtheoption
Signalevenif'default'caseexists.

Ifyoudon'tliketheoptionthatallenumswitchesshouldmentionallenumconstants,butstillwanttogetthewarningaboutmissingcaselabelsforsomeenumswitchstatements,
you'llneedtoselectthestrategyforeachindividualenumswitchstatement.

Recommendation:Iftheabovewarningisdesirableforsomeswitchstatements,considertogloballyenablethewarning,andidentifythoseswitchstatementswhereitisOK
toomitcasesforsomeenumconstants,becausethosearesuitablyhandledbythedefaultcase.Fortheseswitchstatementsusethe'//$CASESOMITTED$'tagcomment
todocumentyourdecision:

StringcolorString2(Colorc){
switch(c){
caseRED:return"red"
caseGREEN:return"green"
//$CASESOMITTED$

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 140/322
12/10/2015 Javadevelopmentuserguide
default:
return"unknowncolor"
}
}

Hint:Ifthecompilerreportssomethinglike"TheenumconstantBLUEshouldhaveacorrespondingcaselabelinthisenumswitchonColor"aquickfixwillbeofferedforinserting
thetagcomment.

Summary
Theaboveconsiderationshaveshownthatyougetmosthelpfromthecompilerifyouenablealloptionalwarningsregardingincompleteswitchstatements,anduseempty
documenteddefaultcasesplus//$CASESOMITTED$tagcommentstomarkthoseswitchstatementswhereincompletenessisOKbydesign.Ifyoufollowtheserecommendations,
youwillgetallrelevantwarnings(orerrorsifyoulike)whenbranchesareaccidentallyomitted,includingthesituationoflateadditionofoneormoreenumconstants.Allexceptions
fromthismaximumcompletenesswillbedocumentedinthecodeandnolongerflaggedwithawarning.
Stillthecompilercannotpreventtheuseofinconsistentclassversionsatruntime,soaclassmaybecompiledagainstanoldversionofanenumtype,butintherunningapplication
theenumtypemayhavemoreenumconstants.Fortheseandsimilarsituationsanappropriate"catchall"defaultimplementationscanraiseruntimeexceptionstoalertofthis
inconsistencyandpreventtheerrorfrompropagatingfurtherintotheapplication.
Asanaddedvalueofthestrictcompilersettingsrecommendedabove,thedubiouserrormessageaboutamissingreturnstatementshownabove(orsimilarmessagesabout
uninitializedvariables)willnolongeroccur.

4.11.UsingtheFormatterApplication
TheJDThasacommandlineEclipseapplicationthatallowsuserstoformatJavasourcecodeeitherwiththeEclipsedefaultcodeformatteroptionsorwithcustomoptions.

Runningtheformatterapplication

CodeFormatter

4.11.1.RunningtheFormatterApplication
Runningtheformatterapplicationisassimpleasrunningtheorg.eclipse.jdt.core.JavaCodeFormatterapplicationfromthecommandline:

eclipsevm<pathtovirtualmachine>applicationorg.eclipse.jdt.core.JavaCodeFormatter[OPTIONS]<files>

WheninvokedonMacOS,thepathstopointtotheconfigurationfileorthesourcefilescanberelative,buttheywillbecomputedfromthelocationoftheeclipse.inifile.Thisisa
limitationoftheEclipselauncheronMacOS.Onallotherplatforms,therelativepathsarecomputedrelativetothecurrentuserdirectory.

Javasourcefilesand/ordirectoriestoformat.Onlyfilesendingwith.java
<files>
willbeformattedinthegivendirectory.

OPTIONS Description

config<file> Usetheformattingstylefromthespecifiedpropertiesfile.Referto
Generatingaconfigfilefortheformatterapplicationfordetails.

help Displaythehelpmessage.

quiet Onlyprinterrormessages.

verbose Beverboseabouttheformattingjob.

Codeformatter

4.11.2.GeneratingaConfigFilefortheFormatterApplication
GeneratingaconfigfilefortheformatterapplicationinvolvesmodifyingthecodeformattersettingsforaJavaprojectandcopyingorg.eclipse.jdt.core.prefsoutofthe.settings
directoryforthatproject.
1. SelectaJavaproject,openthepopupmenuandchooseProperties.
2. SelecttheJavaCodeStyle>FormatterpageandcheckEnableprojectspecificsettings.
3. Selectoreditaprofileasexplainedabove.
4. ClickOKwhenyouaredone.
5. Useeitherafilemanagerorthecommandlinetocopyworkspace/YourJavaProject/.settings/org.eclipse.jdt.core.prefstoanewlocation.
6. Ifthefilesyouwanttoformatareusing1.5constructs,youmustaddthefollowinglinesinsidethepreferencefileyoujustcreated:

org.eclipse.jdt.core.compiler.compliance=1.5
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
org.eclipse.jdt.core.compiler.source=1.5

Codeformatter

5.1.1.BreakpointEnableCondition

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 141/322
12/10/2015 Javadevelopmentuserguide
SelecttheConditionaloptiontoenabletheabilitytoprovideacustomconditionforthebreakpoint.
Eachbreakpointcanhaveauniqueconditionthatdetermineswhenthebreakpointwillbehit.
Aconditionforabreakpointcanbeanylogicalexpressionthatevaluatestoeithertrueorfalse.Theexpressionisevaluatedinthescopeofthebreakpointlocation,meaningyou
cannotmakereferencetoaclass,etc.,outsidethescopeofthebreakpointlocationwhencomposingyourexpression.
Considerthefollowingexample:

publicclassPerson{

Stringname=""
intage=0

publicPerson(Stringname,intage){
this.name=name
this.age=age //breakpointhere
}
}

Ifwetaketheaboveexample,placeabreakpointwhereindicatedandgotothebreakpointpropertieswecanaddourcondition.Inthiscasewearelimitedonlytothemembersofthe
classthebreakpointiscontainedinandthoseprovidedbyObject.
Forexampleavalidconditioncouldbe:

age==56

meaningthebreakpointwouldonlysuspendwhenagewasequalto56.
ConditionscanbeaddedtobreakpointsintheBreakpointsViewdetailpaneorwiththeBreakpointsProperties...shownbelow.

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

EnabledOption
HitCount
SuspendPolicy
MethodEntry
MethodExit

5.1.2.BreakpointEnabled
SelecttheEnabledoptiontoenableordisableabreakpoint.
ThisoptioncanbechangedintheBreakpointsViewdetailpane,withtheBreakpointProperties...,byrightclickingabreakpoint,orbyselectingthebreakpointoritsgroupingin
theBreakpointsView.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 142/322
12/10/2015 Javadevelopmentuserguide

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

HitCount
SuspendPolicy

5.1.3.ExceptionBreakpointCaughtException
SelecttheCaughtlocationsoptiontosuspendexecutionwhenanexceptionofthesametypeasthebreakpointisthrowninacaughtlocation.
ThisoptioncanbechangedintheBreakpointsViewdetailpane,withtheBreakpointProperties...,orbyrightclickinganexceptionbreakpoint.

Breakpoints

Catchingexceptions
CreatingExceptionBreakpointFilters
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

AddJavaexceptionbreakpoint
EnabledOption
HitCount
SuspendPolicy

5.1.4.ExceptionBreakpointSuspendonSubclassofthisException
SelecttheSubclassesofthisexceptionoptiontosuspendexecutionwhensubclassesoftheexceptiontypeareencountered.
Forexample,ifanexceptionbreakpointforRuntimeExceptionisconfiguredtosuspendonsubclasses,itwillalsobetriggeredbyaNullPointerException.
ThisoptioncanbechangedintheBreakpointsViewdetailpane,withtheBreakpointProperties...,orbyrightclickingabreakpoint.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 143/322
12/10/2015 Javadevelopmentuserguide

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

AddJavaexceptionbreakpoint
EnabledOption
HitCount
SuspendPolicy
CaughtOption
UncaughtOption

5.1.5.ExceptionBreakpointUncaughtException
SelecttheUncaughtlocationsoptiontosuspendexecutionwhenanexceptionofthesametypeasthebreakpointisthrowninanuncaughtlocation.
ThisoptioncanbechangedintheBreakpointsViewdetailpane,withtheBreakpointProperties...,orbyrightclickinganexceptionbreakpoint.

Breakpoints

Catchingexceptions
CreatingExceptionBreakpointFilters
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

AddJavaexceptionbreakpoint

5.1.6.BreakpointHitCount
SelecttheHitCountoptiontodefineahitcountfortheselectedbreakpoint.
TheHitCountoptionisusedtodeterminewhenyourprogramshouldsuspendonthatbreakpoint.
IfabreakpointhasahitcountofN,executionwillsuspendwhenthebreakpointisencounteredfortheNthtime.Afterbeinghit,thebreakpointisdisableduntileitheritisreenabled
oritshitcountischanged.

ThisoptioncanbechangedintheBreakpointsViewdetailpane,withtheBreakpointProperties...,orbyrightclickingabreakpoint.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 144/322
12/10/2015 Javadevelopmentuserguide

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

EnabledOption
SuspendPolicy

5.1.7.BreakpointMethodEntry
SelecttheEntryoptiontosuspendexecutionwhenthemethodassociatedwiththebreakpointisentered.
ThisoptioncanbechangedintheBreakpointsViewdetailpane,withtheBreakpointProperties...,orbyrightclickingamethodbreakpoint.

Breakpoints

Settingmethodbreakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

EnabledOption
HitCount
SuspendPolicy
MethodExit
BreakpointConditions

5.1.8.BreakpointMethodExit
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 145/322
12/10/2015 Javadevelopmentuserguide
SelecttheExitoptiontosuspendexecutionwhenthemethodassociatedwiththebreakpointisexited.
ThisoptioncanbechangedintheBreakpointsViewdetailpane,withtheBreakpointProperties...,orbyrightclickingamethodbreakpoint.

Breakpoints

Settingmethodbreakpoints
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

EnabledOption
HitCount
SuspendPolicy
MethodExit
BreakpointConditions

5.1.9.BreakpointSuspendPolicy
Abreapoint'ssuspendpolicydetermineswhatshouldbesuspendedwhenabreakpointishit.
TherearetwooptionsforJavabreakpoints:
Suspendthreadsuspendsonlythethreadthatencounteredthebreakpoint
SuspendVMsuspendstheentireVMwhenthebreakpointisencountered
ThisoptioncanbechangedintheBreakpointsViewdetailpane,withtheBreakpointProperties...,orbyrightclickingabreakpoint.

Youcanalsochangethedefaultsettingforthesuspendpolicyforallnewlycreatedbreakpoints.
Todothisgotothe Java>Debugpreferencepageandchangeitthere.

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 146/322
12/10/2015 Javadevelopmentuserguide

EnabledOption
HitCount

5.1.10.WatchpointFieldModification
SelecttheModificationoptiontosuspendexecutionwhentheassociatedfieldismodified(written).
ThisoptioncanbechangedintheBreakpointsViewdetailpane,withtheBreakpointProperties...,orbyrightclickingawatchpoint.

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

OpeningtheBreakpointPropertiesDialog
WatchpointModificationContextAction
EnabledOption
HitCount
SuspendPolicy

5.1.11.WatchpointFieldAccess
SelecttheAccessoptiontosuspendexecutionwhentheassociatedfieldisaccessed(read).
ThisoptioncanbechangedintheBreakpointsViewdetailpane,withtheBreakpointProperties...,orbyrightclickingawatchpoint.

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

OpeningtheBreakpointPropertiesDialog
WatchpointAccessContextAction
EnabledOption
HitCount
SuspendPolicy

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 147/322
12/10/2015 Javadevelopmentuserguide
5.2.JDTActions
JDTactionsareavailablefrom
Menubar
Toolbar
Contextmenusinviews

Javadevelopmenttools(JDT)

FrequentlyaskedquestionsonJDT
JDTglossary
Filemenuactions
Editmenuactions
Sourcemenuactions
Refactormenuactions
Navigatemenuactions
Searchmenuactions
Projectmenuactions
Runmenuactions
Javatoolbaractions
Runanddebugtoolbaractions
Javaeditoractions

5.2.1.Fileactions
Filemenucommands:

Keyboard
Name Function
Shortcut

Alt+Shift
New CreateaJavaelementoranewresource.ConfigurewhichelementsareshowninthesubmenuinWindow>CustomizePerspective.InaJava +N
perspective,bydefaultactionforcreatingaproject,package,class,interface,enum,annotation,sourcefolder,Javaworkingset,JUnittest,fileand
folderareavailable.


OpenFile Opensafilefromthefilesysteminaneditor.

Close Closethecurrenteditor.Iftheeditorcontainsunsaveddata,asaverequestdialogwillbeshown. Ctrl+W

Ctrl+
CloseAll Closealleditors.Ifeditorscontainsunsaveddata,asaverequestdialogwillbeshown.
Shift+W

Save Savethecontentofthecurrenteditor.Disablediftheeditordoesnotcontainunsavedchanges. Ctrl+S

SaveAs Savethecontentofthecurrenteditorunderanewname.

Ctrl+
SaveAll Savethecontentofalleditorswithunsavedchanges.Disabledifnoeditorcontainsunsavedchanges.
Shift+S
Revert Revertthecontentofthecurrenteditorbacktothecontentofthesavedfile.Disablediftheeditordoesnotcontainunsavedchanges.
Move Movearesource.DisabledonJavaElements.TomoveJavaelementsuseRefactor>Move(withupdatingallreferencestothefile)orEdit>Cut/
Paste(noupdatingofreferences).
Rename Renamesaresource.DisabledonJavaElements.TorenameJavaelementsuseRefactor>Rename(withupdatingallreferencestothefile).
Refresh Refreshesthecontentoftheselectedelementwiththelocalfilesystem.Whenlaunchedfromnospecificselection,thiscommandrefreshesallprojects. F5
Convert
Line
Convertthelinedelimitersofallthetextfilesintheselectiontotheselecteddelimiterkind.
Delimiters
To
Print Printsthecontentofthecurrenteditor.Enabledwhenaneditorhasthefocus. Ctrl+P
Switch
Switchtoanotherworkspace.
Workspace
Restart Restartstheapplication.
Import Openstheimportwizarddialog.JDTdoesnotcontributeanyimportwizards.
Export Openstheexportwizarddialog.JDTcontributestheJARfileexportwizardandtheJavadocgenerationwizard.
Properties Opensthepropertypagesoftheselectelements.OpenedonJavaprojectstheJavaBuildPathpageandtheJavadocLocationpageareavailable.For Alt+
JARarchives,configuretheJAR'sSourceAttachmentandJavadocLocationhere. Enter
Exit ExitEclipse

Javadevelopmenttools(JDT)

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 148/322
12/10/2015 Javadevelopmentuserguide
CreatingJARfiles

NewJavaprojectwizard
NewJavapackagewizard
NewJavaclasswizard
NewJavaenumwizard
NewJavainterfacewizard
NewJavaannotationwizard
JARfileexporter
Javadocgeneration
Javadoclocationproperties
Javabuildpathproperties
Sourceattachmentproperties

5.2.2.Editactions
EditmenucommandsshownwhenaJavaeditorisvisible:

Keyboard
Name Function
Shortcut

Ctrl+Z
Undo Revertthelastchangeintheeditor

Redo Revertanundonechange Ctrl+Y

Cut Copiesthecurrentlyselectedtextorelementtotheclipboardandremovestheelement.Onelements,theremoveisnotperformedbeforethe
Ctrl+X
clipboardispasted.

Copy Copiesthecurrentlyselectedtextorelementstotheclipboard Ctrl+C

CopyQualified Copiesthefullyqualifiednameofthecurrentlyselectedelementtotheclipboard

Name

Paste Pastethecurrentcontentastexttotheeditor,orasasiblingorchildelementtotheacurrentlyselectedelement. Ctrl+V

Delete Deletethecurrenttextorelementselection. Delete


SelectAll Selectalltheeditorcontent. Ctrl+A
ExpandSelection Alt+Shift+
To EnclosingElement:Selectstheenclosingexpression,block,ormethodinthecode.ThisactionisawareoftheJavasyntax.Itmaynot ArrowKeys
functionproperlywhenthecodehassyntaxerrors.(ArrowUp)
NextElement:Selectsthecurrentandnextelements.(ArrowRight)
PreviousElement:Selectsthecurrentandpreviouselements.(ArrowLeft)
RestoreLastSelection:RestoresthepreviousselectionafteraninvocationofExpandSelectionTo.(ArrowDown)

Find/Replace OpentheFind/Replacedialog.Editoronly. Ctrl+F


FindNext Findsthenextoccurrenceofthecurrentlyselectedtext.Editoronly. Ctrl+K
FindPrevious Findsthepreviousoccurrenceofthecurrentlyselectedtext.Editoronly. Ctrl+Shift+K
IncrementalFind
Startstheincrementalfindmode.Afterinvocation,enterthesearchtextasinstructedinthestatusbar.Editoronly. Ctrl+J
Next
IncrementalFind
Startstheincrementalfindmode.Afterinvocation,enterthesearchtextasinstructedinthestatusbar.Editoronly. Ctrl+Shift+J
Previous
AddBookmark Addabookmarktothecurrenttextselectionorselectedelement.
AddTask Addauserdefinedtasktothecurrenttextselectionorselectedelement.
SmartInsert Ctrl+Shift+
TogglestheInsertMode.Whensmartinsertmodeisdisabled,typingaidslikeautomaticindentation,closingofbracketsetc.aredisabled.
Mode Insert
ShowTooltip
Showsthevalueofahoverthatwouldappearatthecurrentcursorlocation.Thedialogshownisscrollableanddoesnotshortendescriptions. F2
Description
Opensacontentassistdialogatthecurrentcursorposition.Bydefaultcontentassistsupportsfivedifferentcategoriesofproposals.
1. Defaultunionallofproposals
2. TypeProposals(e.g.java.lang.String,List)
3. OtherJavaProposals(e.g.methodorfieldnames)
ContentAssist Ctrl+Space
4. TemplateProposals(e.g.'iterateoverarray'template)
5. WordProposals(Proposeswordswhichhavebeentypedalready)
SeetheJavaEditorpreferencepageforconfiguringthebehaviorofcodeassistandthecontentsoftheDefaultproposalcategory.
SeetheTemplatespreferencepageforavailabletemplates.

WordCompletion Proposeswordcompletionsforthecurrentstringbasedonallwordsfoundinanyopeneditor.Worksinalltextbasededitors. Alt+/


QuickFix Opensadialogwithpossiblesolutionsifthecursorislocatednearaproblemindication. Ctrl+1
SetEncoding Togglestheencodingofthecurrentlyshowntextcontent.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 149/322
12/10/2015 Javadevelopmentuserguide
Javaeditor
Javadevelopmenttools(JDT)

Javaeditor
Javaeditorpreferences
Javaoutline
Viewsandeditors

5.2.3.SourceActions
Sourcemenucommands:

Keyboard
Name Function
Shortcut

Ctrl+/
ToggleComment Commentoruncommentalllinescontainingthecurrentselection.

Ctrl+
AddBlock Addsablockcommentaroundalllinescontainingthecurrentselection. Shift+/
Comment

RemoveBlock Removesablockcommentfromalllinescontainingthecurrentselection. Ctrl+


Comment Shift+\

GenerateElement Addsacommenttotheselectedelement.SeetheCodetemplatespreferencepagetospecifytheformatofthegeneratedcomments.Available Alt+Shift


Comment ontypes,fields,constructors,andmethods. +J

ShiftRight Incrementsthelevelofindentationofthecurrentlyselectlines.Onlyactivatedwhentheselectioncoversmultiplelinesorasinglewholeline.

ShiftLeft Decrementsthelevelofindentationofthecurrentlyselectlines.Onlyactivatedwhentheselectioncoversmultiplelinesorasinglewholeline.

CorrectIndentation Correctstheindentationofthelinesdenotedbythecurrenttextselection. Ctrl+I

Ctrl+
Format Usesthecodeformattertoformatthecurrenttextselection.TheformattingoptionsareconfiguredontheCodeFormatterpreferencepage.
Shift+F

FormatElement UsesthecodeformattertoformattheJavaelementcomprisingthecurrenttextselection.TheFormatElementactionworksonmethodandtype

level.TheformattingoptionsareconfiguredontheCodeFormatterpreferencepage.

AddImport Createsanimportdeclarationforatypereferencecurrentlyselected.Ifthetypereferenceifqualified,thequalificationwillberemovedifpossible. Ctrl+


Ifthereferencedtypenamecannotbemappeduniquelytoatypeofthecurrentprojectyouwillbepromptedtospecifythecorrecttype.Add Shift+M
ImporttriestofollowtheimportorderasspecifiedintheOrganizeImportpreferencepage
Organizestheimportdeclarationsinthecompilationunitcurrentlyopenorselected.Unnecessaryimportdeclarationsareremoved,andrequired
importdeclarationsareorderedasspecifiedintheOrganizeImportspreferencepage.Organizeimportscanbeexecutedonincompletesourceand Ctrl+
OrganizeImports
willpromptyouwhenareferencedtypenamecannotbemappeduniquelytoatypeinthecurrentproject. Shift+O
Youcanalsoorganizemultiplecompilationunitsbyinvokingtheactiononapackageorselectingasetofcompilationunits.

SortMembers SortsthemembersofatypeaccordingtothesortingorderspecifiedintheMemberSortOrderpreferencepage

CleanUp PerformsvariouschangesinordertocleanupyourcodeaccordingtothesettingsspecifiedintheCleanUppreferencepage

Override/Implement OpenstheOverrideMethoddialogthatallowsyoutooverrideorimplementamethodinthecurrenttype.Availableontypesoronatextselection
Methods insideatype.
GenerateGetter OpenstheGenerateGettersandSettersdialogthatallowsyoutocreateGettersandSettersforfieldsinthecurrenttype.Availableonfieldsand
andSetter typesoronatextselectioninsideatype.
GenerateDelegate OpenstheGenerateDelegateMethodsdialogthatallowsyoutocreatemethoddelegatesforfieldsinthecurrenttype.Availableonfieldsand
Methods typeswithfields.
Generate OpenstheGenerateHashCodeandEqualsdialogthatallowsyoutostartandcontrolthegenerationofhashCodeandequalsmethodsinthe
hashCode()and currenttype.
equals()
GeneratetoString() OpenstheGeneratetoString()dialogthatallowsyoutostartandcontrolthegenerationofatoString()methodinthecurrenttype.
Generate
Constructorusing Addsconstructorswhichinitializefieldsforthecurrentlyselectedtypes.Availableontypes,fieldsoronatextselectioninsideatype.
Fields
AddConstructor
Addsconstructorsasdefinedinthesuperclassforthecurrentlyselectedtypes.Availableontypesoronatextselectioninsideatype.
fromSuperclass
Surroundtheselectedstatementswithacodetemplate.CreateyourowntemplatesontheTemplatepreferencepage.Further,youcan Alt+Shift
SurroundWith
useExpandSelectiontofromtheEditmenutogetavalidselectionrange. +Z
ExternalizeStrings OpenstheExternalizestringswizard.Thiswizardsallowsyoutoreplaceallstringsinthecodebystatementsaccessingapropertyfile.
FindBroken Searchesforbrokenexternalizedstringsinaselectedpropertyfile,package,projectorsetofprojects.
Externalized
Strings

Javaeditor
Stringexternalization

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 150/322
12/10/2015 Javadevelopmentuserguide
Javadevelopmenttools(JDT)

Externalizingstrings

Javaeditor
Javaeditorpreferences
Javaoutline
Viewsandeditors

5.2.4.RefactorActions
Refactormenucommands:

Name Description

Renamestheselectedelementand(ifenabled)correctsallreferencestotheelements(alsoinotherfiles).
Rename
Available: Methods,methodparameters,fields,localvariables,types,typeparameters,enumconstants,compilationunits,packages,sourcefolders,
projectsandonatextselectionresolvingtooneoftheseelementtypes
Shortcut: Alt+Shift+R
Options: Renamingatypedoesallowtorenamesimilarlynamedvariablesandmethods.Enable'Updatesimilarlynamedvariablesandmethods'inthe
RenameTypedialog.Select'Configure...'toconfigurethestrategyformatchingtypenames.

Renamingapackagedoesallowtorenameitssubpackages.Enable'Renamesubpackages'intheRenamePackagedialog.

Enable'Keeporiginalmethodasdelegatetochangedmethod'tokeeptheoriginalmethod.Optionallyyoucandeprecatetheoldmethod.

Movestheselectedelementsand(ifenabled)correctsallreferencestotheelements(alsoinotherfiles).
Move
Available: Instancemethod(whichcanbemovedtoacomponent),oneormorestaticmethods,staticfields,types,compilationunits,packages,source
foldersandprojectsandonatextselectionresolvingtooneoftheseelementtypes
Shortcut: Alt+Shift+V
Options: YoucanuseDrag&DropinthePackageExplorertostartthisrefactoring.

ChangeMethod Changesparameternames,parametertypes,parameterorderandupdatesallreferencestothecorrespondingmethod.Additionally,parametersandthrown
Signature exceptionscanberemovedoraddedandmethodreturntypeandmethodvisibilitycanbechanged.
Available: Methodsorontextselectionresolvingtoamethod
Shortcut: Alt+Shift+C
Options: Enable'Keeporiginalmethodasdelegatetochangedmethod'intheChangeMethodSignaturedialogtokeeptheoriginalmethod.

ExtractMethod Createsanewmethodcontainingthestatementsorexpressioncurrentlyselectedandreplacestheselectionwithareferencetothenewmethod.This
featureisusefulforcleaninguplengthy,cluttered,oroverlycomplicatedmethods.
Available: YoucanuseExpandSelectiontofromtheEditmenutogetavalidselectionrange.
Thisrefactoringisalsoavailableasquickassistonstatementsandexpressionsselectedintheeditor.
Shortcut: Alt+Shift+M

ExtractLocal Createsanewvariableassignedtotheexpressioncurrentlyselectedandreplacestheselectionwithareferencetothenewvariable.
Variable Available: Textselectionsthatresolvetolocalvariables.YoucanuseExpandSelectiontofromtheEditmenutogetavalidselectionrange.
Thisrefactoringisalsoavailableasquickassistonexpressionsselectedintheeditor.
Shortcut: Alt+Shift+L

ExtractConstant Createsastaticfinalfieldfromtheselectedexpressionandsubstitutesafieldreference,andoptionallyrewritesotherplaceswherethesameexpression
occurs.
Available: Constantexpressionsortextselectionswhichresolvetoconstantexpressions
Thisrefactoringisalsoavailableasquickassistonexpressionsselectedintheeditor.

Inline Inlinelocalvariables,methodsorconstants.
Available: Methods,staticfinalfieldsandtextselectionsthatresolvetomethods,staticfinalfieldsorlocalvariables
Thisrefactoringisalsoavailableasquickassistonlocalvariablesselectedintheeditor.
Shortcut: Alt+Shift+I

ConvertAnonymous Convertsananonymousinnerclasstoamemberclass.
ClasstoNested Available: Anonymousinnerclasses

MoveTypetoNew CreatesanewJavacompilationunitfortheselectedmembertypeortheselectedsecondarytype,updatingallreferencesasneeded.Fornonstatic
File membertypes,afieldisaddedtoallowaccesstotheformerenclosinginstance,ifnecessary.
Available: Membertypes,secondarytypes,ortextresolvingtoamembertypeorasecondarytype.

ConvertLocal Turnalocalvariableintoafield.Ifthevariableisinitializedoncreation,thentheoperationmovestheinitializationtothenewfield'sdeclarationortothe
VariabletoField class'sconstructors.
Available: Textselectionsthatresolvetolocalvariables.
Thisrefactoringisalsoavailableasquickassistonlocalvariablesselectedintheeditor.

ExtractSuperclass Extractsacommonsuperclassfromasetofsiblingtypes.Theselectedsiblingtypesbecomedirectsubclassesoftheextractedsuperclassafterapplying
therefactoring.
Available: Types
Options: Enable'Usetheextractedclasswherepossible'tousethenewlycreatedclasswhereverpossible.SeeUseSupertypeWherePossible.

ExtractInterface Createsanewinterfacewithasetofmethodsandmakestheselectedclassimplementtheinterface.
Available: Types

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 151/322
12/10/2015 Javadevelopmentuserguide
Options: Enable'Usetheextractedinterfacetypewherepossible'tousethenewlycreatedinterfacewhereverpossible.SeeUseSupertypeWhere
Possible.

UseSupertype Replacesoccurrencesofatypewithoneofitssupertypesafteridentifyingallplaceswherethisreplacementispossible.
WherePossible Available: Types

PushDown Movesasetofmethodsandfieldsfromaclasstoitssubclasses.
Available: Oneormoremethodsandfieldsdeclaredinthesametypeoronatextselectioninsideafieldormethod

PullUp Movesafieldormethodtoasuperclassofitsdeclaringclassor(inthecaseofmethods)declaresthemethodasabstractinthesuperclass.
Available: Oneormoremethods,fieldsandmembertypesdeclaredinthesametypeoronatextselectioninsideafield,methodormembertype

ExtractClass Replacesasetoffieldswithnewcontainerobject.Allreferencestothefieldsareupdatedtoaccessthenewcontainerobject.
Available: Thesetoffieldsoratypecontainingfields
Options: Enable'CreateGetterandSetters'toaddaccessormethodstothenewtype

IntroduceParameter Replacesasetofparameterswithanewclass,andupdatesallcallersofthemethodtopassaninstanceofthenewclassasthevaluetotheintroduce
Object parameter.
Available: Methodsorontextselectionresolvingtoamethod
Options: Enable'Keeporiginalmethodasdelegatetochangedmethod'intheIntroduceParameterObjectdialogtokeeptheoriginalmethod.

IntroduceIndirection Createsastaticindirectionmethoddelegatingtotheselectedmethod.
Available: Methodsorontextselectionresolvingtoamethod
Options: Enable'Redirectallmethodinvocations'toreplaceallcallstotheoriginalmethodbycallstotheindirectionmethod.

IntroduceFactory Createsanewfactorymethod,whichwillcallaselectedconstructorandreturnthecreatedobject.Allreferencestotheconstructorwillbereplacedbycalls
tothenewfactorymethod.
Available: Constructordeclarations

IntroduceParameter Replacesanexpressionwithareferencetoanewmethodparameter,andupdatesallcallersofthemethodtopasstheexpressionasthevalueofthat
parameter.
Available: Textselectionsthatresolvetoexpressions

EncapsulateField Replacesallreferencestoafieldwithgetterandsettermethods.
Available: Fieldoratextselectionresolvingtoafield.
Thisrefactoringisalsoavailableasquickassistonfielddeclarationsandreferencesselectedintheeditor.

GeneralizeDeclared Allowstheusertochooseasupertypeofthereference'scurrenttype.Ifthereferencecanbesafelychangedtothenewtype,itis.
Type Available: Typereferencesanddeclarationsoffields,localvariables,andparameterswithreferencetypes

InferGenericType Replacesrawtypeoccurrencesofgenerictypesbyparameterizedtypesafteridentifyingallplaceswherethisreplacementispossible.
Arguments Available: Projects,packages,andtypes
Options: 'Assumeclone()returnsaninstanceofthereceivertype'.Wellbehavedclassesgenerallyrespectthisrule,butifyouknowthatyourcode
violatesit,uncheckthebox.

'Leaveunconstrainedtypeargumentsraw(ratherthaninferring<?>)'.Iftherearenoconstraintsontheelementsofe.g.ArrayLista,uncheck
thisboxwillcauseEclipsetostillprovideawildcardparameter,replacingthereferencewithArrayList<?>.

MigrateJARFile MigratesaJARFileonthebuildpathofaprojectinyourworkspacetoanewerversion,possiblyusingrefactoringinformationstoredinthenewJARFileto
avoidbreakingchanges.
Available: JARFilesonbuildpath

CreateScript Createsascriptoftherefactoringsthathavebeenappliedintheworkspace.Refactoringscriptscaneitherbesavedtoafileorcopiedtotheclipboard.See
ApplyScript.
Available: Always

ApplyScript Appliesarefactoringscripttoprojectsinyourworkspace.Refactoringscriptscaneitherbeloadedfromafileorfromtheclipboard.SeeCreateScript.
Available: Always

History Browsestheworkspacerefactoringhistoryandofferstheoptiontodeleterefactoringsfromtherefactoringhistory.
Available: Always

RefactoringcommandsarealsoavailablefromthecontextmenusinmanyviewsandtheJavaeditor.

Refactoringsupport

Refactoringdialogs
Javapreferences

5.2.5.NavigateActions
Navigatemenucommands:

Keyboard
Name Function
Shortcut


GoInto Setstheviewinputtothecurrentlyselectedelement.SupportedbythePackageExplorerview.

GoTo Back:Setstheviewinputtotheinputbackinhistory:Onlyenabledwhenahistoryexists(GoIntowasused)

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 152/322
12/10/2015 Javadevelopmentuserguide
Forward:Setstheviewinputtotheinputforwardinhistory:Onlyenabledwhenahistoryexists(GoInto,GoTo>Backwereused)
UpOneLevel:Setstheinputofthecurrentviewtoitsinput'sparentelement

Type:Browseforatypeandrevealitinthecurrentview.SupportedbythePackageExplorerview
Package:Browseforapackageandrevealitinthecurrentview.SupportedbythePackageExplorerview
Resource:Browseforaresourceandrevealitinthecurrentview.

Open Triestoresolvetheelementreferencedatthecurrentcodeselectionandopensthefiledeclaringthereference.
F3
Declaration

OpenType TriestoresolvetheelementreferencedatthecurrentcodeselectionandopenstheelementintheTypeHierarchyview.Invokedonelements,
F4
Hierarchy opensthetypehierarchyoftheelement.SupportedintheJavaeditorandviewsshowingJavaelements.

OpenCall TriestoresolvethemethodreferencedatthecurrentcodeselectionandopenstheelementintheCallHierarchyview.
Ctrl+Alt+H
Hierarchy

Open Openstheimplementationofthecurrentlyselectedmethodifthere'sonlyoneimplementor,elseopenstheQuickTypeHierarchyonthatmethod.

Implementation

OpenSuper Openaneditorforthesuperimplementationofthecurrentlyselectedmethodormethodsurroundingthecurrentcursorposition.Noeditorisopened

Implementation ifnomethodisselectedorthemethodhasnosuperimplementation.

OpenstheJavadocdocumentationofthecurrentlyselectedelementortextselection.ThelocationoftheJavadocofaJARoraprojectisspecified
OpenAttached
intheJavadoclocationpropertypageonprojectsorJARs.NotethatthisattachedJavadocdocumentationmaynotbeuptodatewiththeJavadoc Shift+F2
Javadoc
specifiedinthecurrentcode.YoucancreateJavadocdocumentationforsourcefilesinaJavaprojectusingtheJavadocexportwizard.
TriestoopenthematchingJavaelementintheeditoriftheclipboardcontainsasingleline.OtherwiseitopensthecontentsintheJavaStackTrace
Console.Examples:
java.lang.String
String
String#getBytes
Openfrom String.getBytes
Clipboard
java.lang.String.getBytes(String)
String.java:123
atjava.lang.String.matches(String.java:1550)
java.lang.String.valueOf(char)line:1456
currentTimeMillis()

OpenType BringsuptheOpenTypedialogtoopenatypeintheeditor.TheOpenTypeselectiondialogshowsalltypesexistingintheworkspace. Ctrl+Shift+T


OpenTypeIn BringsuptheOpenTypedialogtoopenatypeintheeditorandtheTypeHierarchyview.TheOpenTypeselectiondialogshowsalltypesthatexist Ctrl+Shift+H
Hierarchy intheworkspace.

Open OpenstheOpenResourcedialogtoopenanyresourceinyourworkspace.
Ctrl+Shift+R
Resource

ShowsthecurrentlyselectedelementinthebreadcrubbaroftheJavaeditor.
ShowIn
Ctrl+Shift+B
Breadcrumb

ShowIn Choosetoshowthecurrentlyselectedelementin Alt+Shift+W


PackageExplorer
History
Navigator
Outline

QuickOutline Opensthelightweightoutlinerforthecurrentlyselectedtype. Ctrl+O


PressingCtrl+Oasecondtimewillshowallinheritedfields,typesandmethodsaswell(forthetypesmarkedwith ontheleft).Inheritedmembers
areshowninblue.

QuickType Opensthelightweighthierarchyviewerforthecurrentlyselectedtype. Ctrl+T


Hierarchy
PressingCtrl+Twhilethetypehierarchyviewisshownwilltogglebetweensupertypehierarchyandsubtypehierarchy.

LastEdit
Revealsthelocationwherethelasteditoccurred. Ctrl+Q
Location
GotoLine Opensadialogwhichallowsenteringthelinenumbertowhichtheeditorshouldjumpto.Editoronly. Ctrl+L
Back Revealsthepreviouseditorlocationinthelocationhistory. Alt+Left
Forward Revealsthenexteditorlocationinthelocationhistory. Alt+Right

Javaviews
Javadevelopmenttools(JDT)

Openinganeditorforaselectedelement

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 153/322
12/10/2015 Javadevelopmentuserguide
Showinganelementinthepackageexplorer
Openingatypeinthepackageexplorer
Openinganeditoronatype
Openingapackage

PackageExplorerview
TypeHierarchyview
Javadoclocationproperties
Javadocexportwizard

5.2.6.SearchActions
Searchmenucommands:

Name Function

Search... Opensthesearchdialog(Ctrl+H)

File... OpensthesearchdialogontheFilesearchpage

Java... OpensthesearchdialogontheJavasearchpage

Text Searchesfortheselectedtextinthechosenscope:
Workspace(Ctrl+Alt+G)
Project
Hierarchy
WorkingSet

References FindsallreferencestotheselectedJavaelementinthechosenscope:
Workspace(Ctrl+Shift+G):
Project
Hierarchy
WorkingSet

Declarations FindsalldeclarationsoftheselectedJavaelementinthechosenscope:
Workspace(Ctrl+G)
Project
Hierarchy
WorkingSet
Note:Astrictdeclarationsearchwouldonlyeverreturnasingledeclaration.Sincethat'snotinteresting,declarationsearchesarerelaxedasfollows:
Methoddeclarations:Hierarchysearchfindsoverridingandoverriddenmethodsinthehierarchy.Othersearchesfindmethodswiththesamenameand
signature,butignoringdeclaringtypeandreturntype.
Fielddeclarations:Ignorethedeclaringtypeandthefield'stype.

Implementors Findsallimplementorsoftheselectedinterfaceinthechosenscope:
Workspace
Project
WorkingSet

ReadAccess
Findsallreadaccessestotheselectedfieldinthechosenscope:
Workspace
Project
Hierarchy
WorkingSet

WriteAccess
Findsallwriteaccessestotheselectedfieldinthechosenscope:
Workspace
Project
Hierarchy
WorkingSet

Occurrences FindsalloccurrencesoftheselectedJavaelementinitsfile(Ctrl+Shift+U)
inFile
Identifier:Occurrencesofallidentifiersresolvingtotheselectedelement
ImplementingMethods:Allmethodsimplementedbytheselectedsuperinterfacedeclaration
ThrowingExceptions:Allstatementsthatpossiblethrowtheselecteddeclaredexception
MethodExits:Allstatementsthatcanexitthemethodoftheselectedreturntype
Break/ContinueTarget:Thetargetsoftheselectedbreakandcontinuestatement

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 154/322
12/10/2015 Javadevelopmentuserguide

Referring FindsallJUnitteststhatrefertothecurrentlyselectedtype
Tests

Searchscopessubmenu:

Scope Availability Description

Workspace allelements Searchesinthefullworkspace

Project allelements Searchesintheprojectenclosingtheselectedelement

Hierarchy typesandmembers Searchesinthetype'shierarchy

WorkingSet allelements Searchesinaworkingset

Customscopescanbeconfiguredusingtheworkingsetdialog.ExistingworkingsetsareshownintheSearchscopesubmenusafterthey'vebeenusedinasearch.
AJavasearchcanalsobeconductedviathecontextmenuofallJavaviews.ThesearchcontextmenuisalsoavailableintheJavaeditor.Thesearchisonlyperformedifthe
currentlyselectedtextcanberesolvedtoaJavaelement.
ThetypeoftheselectedJavaelementdefineswhichsearchcontextmenusareavailable.TheJavaeditordoesnotconstrainthelistofavailableJavasearchesbasedonthe
selection.

Javasearch

Javasearchtab

5.2.7.ProjectActions
Projectmenucommands:

Keyboard
Name Function
Shortcut


OpenProject Showsadialogthatcanbeusedtoselectaclosedprojectandopenit

CloseProject Closesthecurrentlyselectedprojects

BuildAll Buildsallprojectsintheworkspace.Thisisanincrementalbuild,meaningthatthebuilderanalyzesthechangessincethelasttimeofbuildand
Ctrl+B
minimizesthenumberofchangedfiles.

BuildProject Buildsthecurrentlyselectedproject.Thisisanincrementalbuild,meaningthatthebuilderanalyzesthechangessincethelasttimeofbuildand

minimizesthenumberofchangedfiles.

Build Buildstheprojectscontainedinthecurrentlyselectedworkingset.Thisisanincrementalbuild,meaningthatthebuilderanalyzesthechangessince

WorkingSet thelasttimeofbuildandminimizesthenumberofchangedfiles.

Clean... Showsadialogwheretheprojectstobecleanedcanbeselected.

Build Ifselected,allmodifiedfilesareautomaticallyrebuiltifsaved.Thisisanincrementalbuild,meaningthatthebuilderanalyzesthechangessincethe

Automatically lasttimeofbuildandminimizesthenumberofchangedfiles.
Generate
OpenstheGenerateJavadocwizardonthecurrentlyselectedproject.
Javadoc...
Properties Opensthepropertypagesonthecurrentlyselectedproject.

Javaprojects
Javabuilder

5.2.8.RunMenuActions
TheRunMenu,foundonthemainmenuoftheEclipseworkbenchcontainsalloftheactionsrequiredrun,debug,stepthroughcodeandworkwithbreakpoints.Differentpartsofthe
menuarevisibleatdifferenttimes,aseachperspectivecanbecustomizedtoshowonlyspecificcapabilities.
TheRunMenucommands.
RunMenuCommands

Command Name Description Shortcut

AddJavaException OpenstheAddJavaExceptiondialogtoselecttheexceptionbreakpointtypetocreate

Breakpoint

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 155/322
12/10/2015 Javadevelopmentuserguide
AddClassLoadBreakpoint OpenstheSelectTypedialogtoselecttheJavatypetoaddaclassloadbreakpointto

AllInstances... DisplaysalloftheinstancesoftheselectedtypeinthecurrentVMinapopup(onlyavailablewithaJava1.6
Ctrl+Shift+N
VM)
AllReferences... DisplaysallofthereferencesoftheselectedtypeinthecurrentVMinapopup(onlyavailablewithaJava1.6

VM)

DebugAs Presentsasubmenuofregistereddebuglaunchshortcuts.Launchshortcutsprovidesupportforworkbenchor
activeeditorselectionsensitivelaunching.

DebugHistory Presentsasubmenuoftherecenthistoryoflaunchconfigurationslaunchedindebugmode

DebugLastLaunched/ Allowsyoutoquicklyrepeatthemostrecentlaunchindebugmodeortodebugthecurrentselection,ifthatmode F11


Debug issupported(basedonyourcurrentlaunchsettings).

Display UsestheDisplayviewtoshowtheresultofevaluatingtheselectedexpressioninthecontextofastackframeor Ctrl+Shift+D


variableinthatthread.IfthecurrentactivepartisaJavaSnippetEditor,theresultisdisplayedthere.

Execute WithinthecontextoftheJavasnippeteditor,thiscommandallowsyoutoevaluateanexpressionbutdoesnot Ctrl+E


displayaresult.

ForceReturn Forcesthecurrentmethodtoreturnwiththespecifiedvalue Alt+Shift+F

Inspect UsestheExpressionsviewtoshowtheresultofinspectingtheselectedexpressionorvariableinthecontextof Ctrl+Shift+I


astackframeorvariableinthatthread.


OpenDebugDialog... Thiscommandopensthelaunchconfigurationdialogtomanagedebugmodelaunchconfigurations.


OpenRunDialog... Opensthelaunchconfigurationdialogtomanagerunmodelaunchconfigurations.

RemoveAllBreakpoints Removesallofthebreakpointsfromthecurrentworkspace

Resume Resumesasuspendedthread. F8


RunAs Presentsasubmenuofregisteredrunlaunchshortcuts.Launchshortcutsprovidesupportforworkbenchor
activeeditorselectionsensitivelaunching.


RunHistory Presentsasubmenuoftherecenthistoryoflaunchconfigurationslaunchedinrunmode

RunLastLaunched/Run Allowsyoutoquicklyrepeatthemostrecentlaunchinrunmodeorquicklyruntheselectedresource,ifthat Ctrl+F11


modeissupported(basedonyourcurrentlaunchsettings).

RunToLine Executestheprogramtothecurrentlyselectedlineintheeditor Ctrl+R

StepInto Stepsintothecurrentstatement. F5

StepIntoSelection Stepsintotheselectedstatementintheeditor Ctrl+F5

StepOver Stepsoverthehighlightedstatement.Executionwillcontinueatthenextlineeitherinthesamemethodor(ifyou
areattheendofamethod)itwillcontinueinthemethodfromwhichthecurrentmethodwascalled. F6
Thecursorjumpstothedeclarationofthemethodandselectsthisline.

StepReturn Stepsoutofthecurrentmethod.Thisoptionstopsexecutionafterexitingthecurrentmethod. F7

Suspend Suspendstheselectedthreadofatargetsothatyoucanbrowseormodifycode,inspectdata,step,andsoon.

Terminate Terminatestheselecteddebugtarget. Ctrl+F2

ToggleBreakpoint Togglestheappropriatetypeofbreakpointbasedonwhatiscurrentlyselected Ctrl+Shift+B

ToggleLineBreakpoint Togglesalinebreakpointonthecurrentexecutablelineofcode

ToggleMethodBreakpoint Togglesamethodbreakpointonthecurrentlyselectedmethoddeclaration

ToggleWatchpoint Togglesawatchpointonthecurrentlyselectedfield

UseStepFilters Togglesstepfilterson/off.Whenon,allstepfunctionsapplystepfilters. Shift+F5


Watch Usedtocreateawatchitem.AwatchitemisanexpressionintheExpressionsviewwhosevalueisupdatedas
youdebug.

Debugger
Javadevelopmenttools(JDT)
LocalDebugging

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 156/322
12/10/2015 Javadevelopmentuserguide
RemoteDebugging

RunningandDebugging
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
AddingLinebreakpoints
Settingmethodbreakpoints
Catchingexceptions

DebugPreferences
RunandDebugtoolbaractions

5.2.9.JavaToolbarActions

JavaActions

Toolbar
Command Description
Button

CreateaJava ThiscommandhelpsyoucreateanewJavaproject.
Project
SeenewJavaprojectwizard

CreateaJava ThiscommandhelpsyoucreateanewJavapackage.
Package
SeenewJavapackagewizard

CreateaJava ThiscommandhelpsyoucreateanewJavaclass.
Class
SeenewJavaclasswizard

CreateaJava ThiscommandhelpsyoucreateanewJavaenum.
enum
SeenewJavaenumwizard

CreateaJava ThiscommandhelpsyoucreateanewJavainterface.
Interface
SeenewJavainterfacewizard

CreateaJava ThiscommandhelpsyoucreateanewJavaannotation.
annotation
SeenewJavaannotationwizard

CreateaJUnit ThiscommandhelpsyoucreateanewJUnittestcase.
testcase

OpenType ThiscommandallowsyoutobrowsetheworkspaceforatypetoopeninthedefineddefaultJavaeditor.Youcanoptionallychoosetodisplaythe
typesimultaneouslyintheTypeHierarchyview.SeeOpenTypedialog.

Javadevelopmenttools(JDT)

Openinganeditoronatype

NewJavaprojectwizard
NewJavapackagewizard
NewJavaclasswizard
NewJavaenumwizard
NewJavainterfacewizard
NewJavaannotationwizard
NewJavascrapbookpagewizard
Viewsandeditors

5.2.10.RunandDebugtoolbaractions
RunandDebugtoolbaractions

Toolbar
Command Description
Button

Run Thiscommandrelaunchesthemostrecentlylaunchedapplication,orlaunchestheselectedresourceoractiveeditordependingonthelaunchoperation
preferencesettingsfoundontheRun/Debug>Launchingpreferencepage

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 157/322
12/10/2015 Javadevelopmentuserguide

Debug Thiscommandrelaunchesthemostrecentlylaunchedapplicationunderdebuggercontrol,orlaunchestheselectedresourceoractiveeditordependingon
thelaunchoperationpreferencesettingsfoundontheRun/Debug>Launchingpreferencepage

Debugger
LocalDebugging
RemoteDebugging

RunningandDebugging
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
Linebreakpoints
Settingmethodbreakpoints
Catchingexceptions

DebugView
DebugPreferences
LaunchingPreferences
Runmenuactions

5.2.11.Javaeditor

Toolbaractions
Toolbar
Command Description
Button

ToggleJavaEditor ThisbuttonenablestheJavaeditorbreadcrumb.
Breadcrumb
Theenablementisrememberedforeachperspectiveseparately.

ToggleMarkOccurrences TurnsmarkoccurrencesonandoffintheJavaeditor.

ToggleBlockSelection Thisbuttonenablesblock(akacolumn)selectionmodeintheeditor.
Mode

ShowWhitespace Thisbuttonenablesthedisplayofwhitespacecharactersinaneditor.
Characters

ShowSourceofSelected Thisbuttonenableddisplayofasegmentedviewofthesourceofacompilationunit.
ElementOnly
ThisbuttonisonlyshownifyoucustomizeyourperspectivetoshowtheEditorPresentationactions.
Forexample,ifamethodisselectedintheOutlineview,theShowSourceOfSelectedElementOnlyoptioncausesonlythatmethod
tobedisplayedintheeditor,asopposedtotheentireclass.
Off:Theentirecompilationunitisdisplayedintheeditor,withtheselectedJavaelementhighlightedinthemarkerbarwitharange
indicator.
On:OnlytheselectedJavaelementisdisplayedintheeditor,whichislinkedtotheselectionintheOutlineorTypeHierarchyview.

GotoNextProblem Thiscommandnavigatestothenextproblemmarkerintheactiveeditor.

GotoPreviousProblem Thiscommandnavigatestothepreviousproblemmarkerintheactiveeditor.

Keybindingactions
Thefollowingactionscanonlybereachedthroughkeybindings.TheKeybindingsfieldinWindow>Preferences>General>Keysmustbesetto'Emacs'.

Keybinding Description

Alt+0Ctrl+K,Esc0Ctrl+K Deletesfromthecursorpositiontothebeginningoftheline.

Ctrl+K Deletesfromthecursorpositiontotheendoftheline.

Ctrl+Space,Ctrl+2 Setsamarkatthecurrentcursorposition.

Ctrl+XCtrl+X Swapsthecursorandmarkpositionifany.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 158/322
12/10/2015 Javadevelopmentuserguide
Javaeditor

Openinganeditorforaselectedelement

Javaoutline
Javaeditorpreferences
JDTactions
Viewsandeditors

5.3.1.JavaPreferences
ThefollowingJavapreferencescanbesetonthe Javapreferencepageanditssubpages.
Appearance
BuildPath
CodeStyle
Compiler
Debug
Editor
InstalledJREs
JUnit
PropertiesFileEditor

Option Description Default

Actionondoubleclickin Expandtheselectedelement
thePackageExplorer Gointotheselectedelement
Whenyoudoubleclickacontainer,aGoIntocommandisexecuted.
SeeGoIntofromtheNavigatemenu.
Expandtheselectedelement
Whenyoudoubleclickacontainer,itisexpandedanditschildrenarerevealed.

WhenopeningaType ShowtheTypeHierarchyView
Hierarchy OpenanewTypeHierarchyPerspective inthecurrentperspective
OpensanewTypeHierarchyperspectivewheneveraTypeHierarchyviewisopened.
ShowtheTypeHierarchyViewinthecurrentperspective
TheTypeHierarchyviewisdisplayedinthecurrentperspective.
Note:OntheWorkbenchpreferencespage,youcanchoosewhethernewperspectivesopeninanewwindow,inthe
currentwindow,orasareplacementforthecurrentperspective.
RefactoringJavacode Off
Saveallmodifiedresourcesautomaticallypriortorefactoring
Ifthisoptionisturnedoff,refactoringsmayprompttosavemodifiedfilesifrequired.Ifitisturnedon,all
modifiedfilesaresavedwithoutpromptingpriortoopeningarefactoringwizard.

On
Renameineditorwithoutdialog
Ifthisoptionisturnedon,thentherenamerefactoringwillnotshowadialogifinvokedinsideaJavaeditor.
Insteadthenewnamefortheelementtorenamecanbetypedintotheeditorrightaway.

Search On
Usereducedsearchmenu
Ifthisoptionisturnedon,thesearchcontextmenusshowonlythemostfrequentlyusedsearchactions.

Javadialogs Button
Clearall'donotshowagain'settingsandshowallhiddendialogsagain
Ifpressed,all'donotshow'settingsarecleared.

Javaviews

PackageExplorerview
TypeHierarchyview

5.3.1.1.JavaAppearancePreferences
TheappearanceofJavaelementsinviewscanbeconfiguredonthe Java>Appearancepreferencepageandonitssubpages:
Membersortorder
Typefilters
Theoptionsare:

Option Description Default

Showmethodreturntypes Ifenabled,methodsdisplayedinviewsshowthereturntype. Off

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 159/322
12/10/2015 Javadevelopmentuserguide

Showmethodtypeparameters Ifenabled,methodsdisplayedinviewsshowtheirtypeparameters. On

Showcategories Ifenabled,method,fieldandtypelabelscontainthecategoriesspecifiedintheirJavadoccomment. On

ShowmembersinPackageExplorer Ifenabled,JavaelementsbelowthelevelofJavafilesandClassfilesaredisplayedaswell. On

Foldemptypackagesinhierarchicallayout Ifenabled,emptypackageswhichdonotcontainresourcesorotherchildelementsarefolded. On

Compresspackagenamesegments Ifenabled,packagenames,exceptforthefinalsegment,arecompressedaccordingtothecompressionpattern. Off

Abbreviatepackagenames Ifenabled,packagenamesareabbreviatedaccordingtothespecifiedabbreviationrules. Off

StackviewsverticallyintheJavaBrowsingperspective Ifenabled,viewsinJavaBrowsingperspectivewillbestackedvertically,ratherthanhorizontally. Off

Note:TheColoredLabelssettingsisnowavailableonthe General>Appearancepreferencepage.

Javaviews

PackageExplorerview

5.3.1.1.1.MemberSortOrderPreferences
IndicateyourpreferencesfortheMemberSortOrdersettingsonthe Java>Appearance>MemberSortOrderpreferencepage.
ThissettingsareusedbyJavaviewsaswellasbytheSortMembersAction.

Option Description Default

Choosetheorderinwhichmemberswill Types,StaticFields,StaticInitializers,StaticMethods,Fields,
bedisplayed. Up Initializers,Constructors,Methods
Movemembersofselectedcategoryclosertothe
beginningofatype.
Down
Movemembersofselectedcategoryclosertotheend
ofatype.

Sortmembersinsamecategoryby Ifenabled,membersofsamecategoryaresortedbyvisibility Off


visibility withinthecategory.
Public,Private,Protected,Package
Up
Movemembersofselectedvisibilityclosertothe
beginningofacategory.
Down
Movemembersofselectedvisibilityclosertotheend
ofacategory.

Javaviews

PackageExplorerview
SourceActions

5.3.1.1.2.TypeFiltersPreferences
IndicateyourpreferencesfortheTypeFilterssettingsonthe Java>Appearance>TypeFilterspreferencepage.
Specifytypesandpackagestohideinthe'OpenType'dialogandcontentassistorquickfixproposalsonthispreferencepage.Ifaqualifiedtypenameorapackagematchoneof
thecheckedentriesinthelist,theywillbehidden.
Thedefaultistohidenothingbutforbiddenreferences.

Option Description

Add Addsanewentrytothelist.Entrieswillbecomparedagainstqualifiedtypename(usingdotsaspackagenameseparators)andcanusewildcards('*'and'?')
AddPackages Addsanewentrytothelistfromthelistofexistingpackagescurrentlyintheworkspace.
Edit Editsthecurrentlyselectedentry
Remove Removesthecurrentlyselectedentries
CheckAll Setsthecheckmarkonallentries
UncheckAll Removesthecheckmarkonallentries

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 160/322
12/10/2015 Javadevelopmentuserguide
AccessRestrictions
Option Description Default

Hideforbiddenreferences Ifenabled,referencestoJavaelementsforbiddenbyaccessrulesarenotdisplayed. On
Hidediscouragedreferences Ifenabled,referencestoJavaelementsdiscouragedbyaccessrulesarenotdisplayed. Off

Quickfix
AccessRules

Opentype
Content/Codeassist

5.3.1.2.JavaBuildPathPreferences
IndicateyourpreferencesfortheBuildPathsettingsonthe Java>BuildPathpreferencepageanditssubpages:
ClasspathVariables
UserLibraries
Theoptionsare:

Option Description Default

Sourceandoutputfolder Folders
Project SourceFolder:src
UsetheprojectrootfolderasthefolderwhereJavasourcefilesandthegeneratedclassfilesarestoredbydefault. OutputFolder:bin
Folders
SpecifyseparatesourceandoutputfolderstostoretheJavasourcefilesseparatedfromthegeneratedclassfiles.

AsJRElibraryuse SelectwhatkindofJRElibraryshouldbeusedfornewlycreatedJavaprojects. JREcontainer

Classpathvariables

NewJavaprojectwizard

5.3.1.2.1.ClasspathVariablesPreferences

Configurablevariables
ClasspathvariablescanbeusedinaJavaBuildPathtoavoidareferencetothelocalfilesystem.Usingavariableentry,theclasspathonlycontainsavariableandthebuildpath
canbesharedinateam.Thevalueofsuchvariablesisconfiguredonthe Java>BuildPath>ClasspathVariablespreferencepage.

Command Description

New... Addsanewvariableentry.Intheresultingdialog,specifyanameandpathforthenewvariable.YoucanclicktheFileorFolderbuttonstobrowseforapath.

Edit... Allowsyoutoedittheselectedvariableentry.Intheresultingdialog,editthenameand/orpathforthevariable.YoucanclicktheFileorFolderbuttonstobrowsefor
apath.

Remove Removestheselectedvariableentry.

Reservedclasspathvariables
CertainclasspathvariablesaresetinternallyandcannotbechangedintheClasspathvariablespreferences:
JRE_LIB:ThearchivewiththeruntimeJARfileforthecurrentlyusedJRE.
JRE_SRC:ThesourcearchiveforthecurrentlyusedJRE.
JRE_SRCROOT:TherootpathinthesourcearchiveforthecurrentlyusedJRE.
Thesevariablesaredeprecatedandshouldnotbeusedanymore.InsteaduseaJRESystemLibrary.

Classpathvariables

InstalledJREs

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 161/322
12/10/2015 Javadevelopmentuserguide
5.3.1.2.2.UserLibrariesPreferences
IndicateyourpreferencesfortheUserLibrariessettingsonthe Java>BuildPath>UserLibrariespreferencepage.
AuserlibraryisasetofJARfiles.Auserlibrarycanbeaddedtoaprojectsbuildpaththroughthebuildpathpropertiespage.TheUserLibrariespreferencepageallowstodefine,
edit,import,export,orremoveuserlibraries.

Option Description

New... Createsanewuserlibrary
Edit... Editsthecurrentlyselectedlibrary,JARorJARattribute
Add AddsoneormoreJARstothecurrentlyselecteduserlibrary
JARs...
Remove.. RemovesthecurrentlyselecteduserlibraryorJAR
Up MovesthecurrentlyselectedJARupinthelistofJARsofauserlibrary.TheordercanbeimportantifmorethanoneJARcontainatypewiththesamequalified
name.
Down MovesthecurrentlyselectedJARdowninthelistofJARsofauserlibrary.TheordercanbeimportantifmorethanoneJARcontainatypewiththesamequalified
name.
Import... Addsnewlibrariesfromanimportfile
Export... Exportslibrariestoanimportfile

JavaBuildPathpage

5.3.1.3.JavaCodeStylePreferences
The Java>CodeStylepreferencepageallowstoconfigurenamingconventions,stylerulesandcommentsettings.Thesepreferencesareusedwhennewcodehastobe
generated.
Subpagesoffermorecodestylesettings:
CleanUp
CodeTemplates
Formatter
OrganizeImports
Theoptionsare:

NamingConventions
Thelistdefinesthenamingconventionsforfields(staticandnonstatic),parametersandlocalvariables.Foreachvariabletypeitispossibletoconfigurealistofprefixorsuffixor
both.
Namingconventionsareusedbyallactionsand'QuickFix'proposalsthatcreatefields,parametersandlocalvariables,inparticulartheSourceactions.

Action Description

Edit... Opensadialogtoeditthelistofprefixandsuffixesforthecurrently
selectedvariabletype

CodeConventions
Thefollowingsettingsspecifyhownewlygeneratedcodeshouldlooklike.Thenamesofgettermethodscanbespecifiedaswellastheformatoffieldaccesses,methodcomments,
annotationsandexceptionvariables.

Action Description Default

Qualifyallgenerated Ifselected,fieldaccessesarealwaysprefixedwith'this', Off


fieldaccesseswith regardlesswhetherthenameofthefieldisuniqueinthescopeof
'this.' thefieldaccessornot.

Use'is'prefixfor Ifselected,thenamesofgettermethodsofbooleantypeare On
gettersthatreturn prefixedwith'is'ratherthan'get'.
boolean

Add'@Override' Ifselected,methodswhichoverrideanalreadyimplemented On
annotationforoverriding methodareannotatedwithan'@Override'annotation.Seethe
methods Compilerpreferencepageforsettingsrelatedtoannotations.

Exceptionvariable Specifythenameoftheexceptionvariabledeclaredincatch e
nameincatchblocks blocks.

Sourceactions
Javaeditor

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 162/322
12/10/2015 Javadevelopmentuserguide
Javaeditorpreferences
Javacompilerpreferences
Codetemplatespreferences

5.3.1.3.1.CleanUpPreferences
The Java>CodeStyle>CleanUppreferencepageletsyoumanageyourcodecleanupprofilesfortheJavacodecleanup.

Action Description

Activeprofile Selectstheprofileactivefortheworkspaceorcurrentproject.

Edit... Showsadialogwhichdisplaysthesettingsstoredintheactiveprofile.
Onlyuserdefinedprofilescanbemodified.

Remove Removestheselectedprofile.Thisactionisonlyavailableonuserdefined
profiles.

New... Showsthedialogtocreateanewprofile.Thedialogrequiresyoutoentera
nameforthenewprofile.Additionally,youmayselectabuiltinoruser
definedexistingprofiletobaseyournewprofileon.

Import... Importsprofilesfromthefilesystem.

ExportAll... Exportsalltheprofilestothefilesystem.

Details Displaysasummaryoftheenabledoptionsoftheactiveprofile

DisableShowprofileselectiondialogforthe'Source>CleanUp'actiontoapplytheactiveprofilewhenyouinvokeSource>CleanUpwithoutbeingdisturbedbyadialog.

Javaeditor
Javaeditorpreferences

5.3.1.3.2.CodeTemplatesPreferences
The Java>CodeStyle>CodeTemplatespreferencepageletsyouconfiguretheformatofnewlygeneratedcodeandcomments.

CodeandComments
Thecodeandcommentpagecontainscodetemplatesthatareusedbyactionsthatgeneratecode.Templatescontainvariablesthataresubstitutedwhenthetemplateisapplied.
Somevariablesareavailableinalltemplates,somearespecifictotemplates.

Action Description Default

n/a
Edit... OpenstheCodeTemplatedialogtoeditthecurrentlyselected
codetemplate.

n/a
Import... Importscodetemplatesfromthefilesystem.

n/a
Export... Exportsallselectedcodetemplatestothefilesystem.

n/a
ExportAll... Exportsallcodetemplatestothefilesystem.

Automaticallyadd Ifselected,newlygeneratedmethodsandtypesareautomatically Off


commentsfornew generatedwithcommentswhereappropriate.Theformatsofthe
methodsandtypes generatedcommentsaredefinedbytheCommentTemplates.

CommentTemplates
Commenttemplatescancontainthevariable${tags}thatwillbesubstitutedbythestandardJavadoctags(@param,@return..)forthecommentedelement.The'Overridingmethod'
commentcanadditionallycontainthetemplate${see_to_overridden}

TemplateName Specifies

Files Headercommentfornewfiles.
Notethatthistemplatecanbereferencedinthe'NewJavaFile'template
with${filecomment}.

Types Thecommentfornewtypes.
Notethatthistemplatecanbereferencedinthe'NewJavaFile'template

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 163/322
12/10/2015 Javadevelopmentuserguide
with${typecomment}.

Fields Thecommentfornewfields.

Constructors Thecommentfornewconstructors.

Methods Thecommentfornewmethodsthatdonotoverrideanmethodinabase
classandthatdonotdelegatetoanyothermethod.

Overridingmethods Thecommentfornewmethodsthatoverrideanmethodinabaseclass.
BydefaultthecommentisdefinedasanonJavadoccomment(Javadoc
willreplacethiscommentwiththecommentoftheoverriddenmethod).You
canchangethistoarealJavadoccommentifyouwant

Delegatingmethods Thecommentfornewmethodswhichdelegatetoexistingmethods.
SuchmethodscanbecreatedwiththeSource>GenerateDelegate
Methods...action.

Getters Thecommentforgettermethods.

Setters Thecommentforsettermethods.

CodeTemplates
TemplateName Description

NewJavafiles UsedbytheNewTypewizardswhenanewJavafileiscreated.
Thetemplatecanspecifywherecommentsareadded.Notethatthe
templatecancontainthevariable${typecomment}and${filecomment}
thatwillbesubstitutedbytheevaluationoftheTypesrespectivelyFiles
commenttemplate.

Classbody UsedbytheNewClasswizardswhenanewJavaclassiscreated.

Interfacebody UsedbytheNewInterfacewizardswhenanewJavainterfaceiscreated.

Enumbody UsedbytheNewEnumwizardswhenanewJavaenumiscreated.

Annotationbody UsedbytheNewAnnotationwizardswhenanewJavaannotationis
created.

Methodbody The'Methodbody'templatesareusedwhennewmethodwithabodyis
createdthatstillneedssomecodetocompleteitsfunctionality.
Itcontainsthevariable${body_statement}thatresolvestoareturn
statementor/andasupercall.

Constructorbody The'Constructorbody'templatesareusedwhennewmethodor
constructorwithbodyiscreated.
Itcontainsthevariable${body_statement}thatresolvesasupercall.

Getterbody The'Getterbody'templatesareusedwhennewgettermethodiscreated.
Itcontainsthevariable${body_statement}thatresolvestotheappropriate
returnstatement.

Setterbody The'Setterbody'templatesareusedwhennewsettermethodiscreated.
Itcontainsthevariable${body_statement}thatresolvestotheappropriate
assignmentstatement.

Catchblockbody The'Catchblockbody'templateisusedwhenacatchblockbodyis
created.
Itcanusethevariables${exception_type}and${exception_var}.

CodeTemplatedialog
Thefollowingfieldsandbuttonsappearinthedialog:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 164/322
12/10/2015 Javadevelopmentuserguide
Action Description

Description Adescriptionofthetemplate

Pattern Thetemplatepattern.

InsertVariables... Displaysalistofpredefinedtemplatespecificvariables.

Templatevariables

Sourceactions
Javaeditor
Javaeditorpreferences
Templatespreferences

5.3.1.3.3.CodeFormatterPreferences
The Java>CodeStyle>FormatterpreferencepageletsyoumanageyourcodeformatterprofilesfortheJavacodeformatter.

Action Description

Activeprofile Selectstheprofileactivefortheworkspaceorcurrentproject.

Edit... Showsadialogwhichdisplaysthesettingsstoredintheactiveprofile.
Onlyuserdefinedprofilescanbemodified.

Remove Removestheselectedprofile.Thisactionisonlyavailableonuserdefined
profiles.

New... Showsthedialogtocreateanewprofile.Thedialogrequiresyoutoentera
nameforthenewprofile.Additionally,youmayselectabuiltinoruser
definedexistingprofiletobaseyournewprofileon.

Import... Importsprofilesfromthefilesystem.

ExportAll... Exportsalltheprofilestothefilesystem.

Details DisplaysasamplehowtheactiveprofileformatsaJavacodesnippet

Tochangeyourformatteroptionsyoucaneitherselectoneofthebuiltinprofilesorcreateanewprofile.TocreateanewprofileselectNew....Youcantheneditthenewprofileby
selectingEdit....
Ifyourprojectisshared,e.g.throughCVS,andusesaformatterprofilewhichisnotmanagedbyyourself(youhavenotcreatedtheprofile)thentheprofilewillbemarkedas
UnmanagedProfile.Youarenotallowedtochangesuchaprofile,onlythecreator(manager)oftheprofilecanchangeit.

Javaeditor
Javaeditorpreferences

5.3.1.3.4.OrganizeImportsPreferences
The Java>CodeStyle>OrganizeImportspreferencepagedefineshowtheOrganizeImportscommandgeneratestheimportstatementsinacompilationunit.

Option Description Default

Importorderlist ThislistofprefixesshowsthesequentialorderforpackagesimportedintoaJavacompilationunit.Eachentrydefinesa java


block.Differentblocksareseparatedbyaspacerline. javax
org
com

New... Addsapackagenameprefixtotheimportorderlist.Intheresultingdialog,typeapackagenameorpackagenameprefix. n/a

NewStatic... Addsapackagenameprefixtotheimportorderlist.Intheresultingdialog,typeapackagenameorpackagenameprefix. n/a

Edit... Editsthecurrentlyselectedentryintheimportorderlist.Intheresultingdialog,typeapackagenameorpackagename n/a


prefix.

Remove Removesthecurrentlyselectedentryfromtheimportorderlist. n/a

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 165/322
12/10/2015 Javadevelopmentuserguide
Up Movestheselectedpackagenameprefixupintheimportorderlist. n/a

Down Movestheselectedpackagenameprefixdownintheimportorderlist. n/a

Import... Loadsalistofpackagenameprefixesfromafile. n/a

Export... Savesthelistofpackagenameprefixestoafile. n/a

Numberofimportsneededfor.* Thenumberofimportstatementsthatareallowedfortypesinthesamepackagebefore<package>.*isused. 99

Numberofstaticimportsneededfor.* Thenumberofstaticimportstatementsthatareallowedforstaticmembersofthesametypebeforetypeisused. 99

Donotcreateimportsfortypesstartingwith Ifenabled,typesstartingwithalowercaseletterarenotimported. On
alowercaseletter

Sourceactions

5.3.1.4.JavaCompilerPreferences
The Java>CompilerpreferencepageletsyouconfigurethevarioussettingsrelatedtocompilingofJavasourcecodeandclassfilegeneration.
AnEclipsebasedproductmaychangethecompilerdefaults,sotheymaybedifferentthantheonesindicatedhere.
Subpagesoffermorecompilersettings:
Building
Error/Warnings
Javadoc
TaskTags
Theoptionsare:

JDKCompliance

Option Description Default

Compilercompliancelevel Specifiesthecompilercompliancelevel. Dependsondefault


JRE

Usedefaultcompliance Ifenabled,thedefaultcompliancesettingsforthecompilercompliancelevelareapplied. On
settings

Generatedclassfiles Specifiesthegeneratedclassfilecompatibility. Dependsondefault


compatibility JRE

Sourcecompatibility Specifiesthecompatibilityoftheacceptedsourcecode. Dependsondefault


JRE

Disallowidentifierscalled Whenenabled,thecompilerwillissueanerrororawarningwhenever'assert'isusedasanidentifier(reservedkeywordin Warning


'assert' J2SE1.4).

Disallowidentifierscalled Whenenabled,thecompilerwillissueanerrororawarningwhenever'enum'isusedasanidentifier(reservedkeywordin Warning


'enum' J2SE1.5).

Classfilegeneration

Addvariableattributesto Ifenabled,variableattributesareaddedtotheclassfile.Thiswillenablelocalvariablenamestobedisplayedinthedebugger(inplaces On
generatedclassfiles wherevariablesaredefinitelyassigned)Theresulting.classfileisthenbigger.

Addlinenumberattributesto Ifenabled,linenumberinformationisaddedtotheclassfile.Thiswillenablesourcecodehighlightinginthedebugger. On
generatedclassfiles

Addsourcefilenameto Ifenabled,thesourcefilenameisaddedtotheclassfile.Thiswillenablethedebuggertopresentthecorrespondingsourcecode. On
generatedclassfile

Preserveunusedlocalvariables Ifenabled,unusedlocalvariables(i.e.neverread)arenotstrippedfromtheclassfile.Ifstrippedthispotentiallyaltersdebugging. On

Inlinefinallyblocks Ifenabled,finallyblocksareinlinedinthegeneratedclassfiles.Thispositivelyaffectsperformance,butmayresultinlargerclassfiles. Off

Storeinformationaboutmethod Ifenabled,informationaboutmethodparametersisstoredinthegeneratedclassfiles. Off

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 166/322
12/10/2015 Javadevelopmentuserguide
parameters

Javabuilder

WorkingwithJREs

Classpathvariablespreferences
Javabuildpathproperties
Buildingpreferencepage
Errors/Warningspreferencepage
Javadocpreferencepage
Tasktagspreferencepage

5.3.1.4.1.JavaBuildingPreferences
IndicateyourpreferencesfortheBuildingsettingsonthe Java>Compiler>Buildingpreferencepage.

General

Option Description Default

Maximumnumberofreportedproblemsper Specifieshowmanyproblemsshouldbereportedforacompilationunit. 100


compilationunit

Enableuseofexclusionpatternsinsource Whendisabled,noentryonaprojectclasspathcanbeassociatedwithanexclusionpattern. On
folders

Enableuseofmultipleoutputlocationsfor Whendisabled,noentryonaprojectclasspathcanbeassociatedwithaspecificoutputlocation,preventingthususage On
sourcefolders ofmultipleoutputlocations.

Buildpathproblems

Abortbuildwhenbuild Allowtotogglethebuildertoabortiftheclasspathisinvalid. On
patherrorsoccur

Incompletebuildpath Indicatetheseverityoftheproblemreportedwhenanentryontheclasspathdoesnotexist,isnotlegitimateorisnotvisible(e.g.areference Error


projectisclosed).

Circulardependencies Indicatetheseverityoftheproblemreportedwhenaprojectisinvolvedinacycle. Error

Incompatiblerequired IndicatetheseverityoftheproblemreportedwhenaprojectrequiresanotherprojectorlibrarywithanincompatibletargetJDKlevel(e.g.a Ignore


binaries projectusing1.4compilercompliance,butcompiledagainst1.5systemlibrariesonthebuildpath).

Outputlocationoverlaps Indicatedtheseverityoftheproblemreportedwhenasourceentry'soutputlocationoverlapsanothersourceentry. Error


sourcelocation

Nostrictlycompatible Indicatetheseverityoftheproblemreportedwhenproject'sbuildpathcontainsanexecutionenvironmentforwhichthereisnostrictly Ignore


JREforexecution compatibleJREavailableintheworkspace(e.g.aprojectusingexecutionenvironmentJavaSE1.6asJRESystemLibrary,buttheonly
environmentavailable InstalledJREsavailableinthepreferencesare1.7and1.8.

Outputfolder

Duplicatedresources Indicatetheseverityoftheproblemreportedwhenmorethanoneoccurrenceofaresourceistobecopiedintotheoutput Warning


location.

Scruboutputfolderswhencleaning IndicatewhethertheJavaBuilderisallowedtocleantheoutputfolderswhenperformingfullbuildoperations. On
projects

Rebuildclassfilesmodifiedbyothers Indicatewhetherclassfileswhichhavebeenmodifiedbyothersshouldberebuilttoundothemodification. Off

Filteredresources Acommaseparatedlistoffilepatternswhicharenotcopiedtotheoutputfolder. Empty

Javabuilder
Inclusionandexclusionpatterns
Buildclasspath

5.3.1.4.2.JavaCompileErrors/WarningsPreferences
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 167/322
12/10/2015 Javadevelopmentuserguide
IndicateyourpreferencesfortheErrors/Warningssettingsonthe Java>Compiler>Errors/Warningspreferencepage.

Codestyle

Option Description Default

Nonstaticaccesstoastatic Whenenabled,thecompilerwillissueanerrororawarningwheneverastaticfieldormethodisaccessedwithanexpressionreceiver.A Warning


member referencetoastaticmembershouldbequalifiedwithatypename.

Indirectaccesstoastatic Whenenabled,thecompilerwillissueanerrororawarningwheneverastaticfieldormethodisindirectlyaccessed.Astaticfieldofan Ignore


member interfaceshouldbequalifiedwiththedeclaringtypename.

Unqualifiedaccessto Whenenabled,thecompilerwillissueanerrororawarningwheneveritencountersafieldaccesswhichisnotqualified(e.g.missesa Ignore


instancefield 'this').

Accesstoanonaccessible Whenenabled,thecompilerwillissueanerrororawarningwheneveritemulatesaccesstoanonaccessiblememberofanenclosing Ignore


memberofanenclosingtype type.Suchaccessescanhaveperformanceimplications.

Parameterassignment Assigningavaluetoaparameterisgenerallyconsideredpoorstyleprogramming.Whenthisoptionisenabled,thecompilerwillsignal Ignore


suchscenarioeitherasanerrororawarning.

Nonexternalizedstrings Whenenabled,thecompilerwillissueanerrororawarningfornonexternalizedStringliteral(i.e.nontaggedwith//$NONNLS<n>$)orfor Ignore


nonexternalizedStringtagswhichdonotbelongtoaString.

Undocumentedemptyblock Whenenabled,thecompilerwillissueanerrororawarningwheneveritencountersanemptyblockstatementwithnoexplainingcomment. Ignore

Resourcenotmanagedvia Whenenabled,thecompilerwillissueanerrororawarningifalocalvariableholdsavalueoftype'java.lang.AutoCloseable',andifthe Ignore


trywithresource(1.7or method'close()'isexplicitlyinvokedonthatresource,buttheresourceisnotmanagedbyatrywithresourcesblock.
higher)

Methodwithaconstructor Namingamethodwithaconstructornameisgenerallyconsideredpoorstyleprogramming.Whenthisoptionisenabled,thecompilerwill Warning


name signalsuchscenarioeitherasanerrororawarning.

Methodcanbestatic Whenenabled,thecompilerwillissueanerrororawarningformethodswhichareprivateorfinalandwhichreferonlytostaticmembers. Ignore

Methodcanpotentiallybe Whenenabled,thecompilerwillissueanerrororawarningformethodswhicharenotprivateorfinalandwhichreferonlytostatic Ignore


static members.Notethatmethodscanbeoverriddeninasubclass,soifyoumakea"potentiallystatic"methodstatic,thismaybreakexisting
clients.

Potentialprogrammingproblems

Comparingidentical Whenenabled,thecompilerwillissueanerrororawarningifacomparisonisinvolvingidenticaloperands(e.g'x==x'). Warning


values('x==x')

Assignmenthasno Whenenabled,thecompilerwillissueanerrororawarningwheneveranassignmenthasnoeffect(e.g.'x=x'). Warning


effect(e.g.'x=x')

Possibleaccidental Whenenabled,thecompilerwillissueanerrororawarningwheneveritencountersapossibleaccidentalbooleanassignment(e.g.'if(a=b)'). Ignore


booleanassignment
(e.g.'if(a=b)')

Boxingandunboxing Whenenabled,thecompilerwillissueanerrororawarningwheneveritencountersaboxingorunboxingconversion.Autoboxingmayaffects Ignore


conversions performancenegatively.

Usingachararrayin Whenenabled,thecompilerwillissueanerrororawarningwheneverachar[]expressionisusedinStringconcatenations, Warning


stringconcatenation
"hello"+newchar[]{'w','o','r','l','d'}

Inexacttypematchfor Whenenabled,thecompilerwillissueanerrororawarningwheneveritencountersaninexacttypematchforvarargarguments. Warning


varargarguments

Emptystatement Whenenabled,thecompilerwillissueanerrororawarningwheneveritencountersanemptystatement(e.g.asuperfluoussemicolon). Ignore

Unusedobjectallocation Whenenabled,thecompilerwillissueanerrororawarningwhenitencountersanallocatedobjectwhichisnotused,e.g. Ignore


if(name==null)
newIllegalArgumentException()

Incomplete'switch' Whenenabled,thecompilerwillissueanerrororawarningwheneveritencountersa'switch'statementwhichdoesnotcontaina'default' Warning


casesonenum casenorcasestatementsforeveryenumconstantofthereferencedenum.
ThiswarningisrecommendedbytheJavaLanguageSpecification14.11.Ithelpstoensurethat'switch'statementscoverallpossibleenum
values.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 168/322
12/10/2015 Javadevelopmentuserguide
Signalevenif Whenenabled,thecompileradditionallywillissueanerrororawarningifanenumconstantisnotcoveredbyacase,evenifa'default'case Off
'default'caseexists exists.
Thisoptionhelpstocatchmissingcasestatementswhenanewenumconstantisadded.

'switch'ismissing Whenenabled,thecompilerwillissueanerrororawarningifa'switch'statementlacksa'default'case.Consequently,amissing'default'will Ignore


'default'case beflaggedevenifallpossiblevaluesareotherwisecoveredby'case'statements.
Thisoptionhelpstoensurethatnew'switch'expressionvaluesarehandledexplicitly,ratherthanbeingskipped.Itcanalsohelptoexplain
compileerrorsforuninitializedvariablesaftera'switch'statement:Thesetoflegalvaluescangrowinthefuture,sothevariablealsoneedsto
beinitializedinthe'default'case.

'switch'casefallthrough Whenenabled,thecompilerwillissueanerrororawarningwhenacasemaybeenteredbyfallingthroughapreceding,nonemptycase. Ignore

Hiddencatchblock Locallytoatrystatement,somecatchblocksmayhideothers,e.g. Warning


try{thrownewjava.io.CharConversionException()
}catch(java.io.CharConversionExceptione){
}catch(java.io.IOExceptione){}

Whenenabled,thecompilerwillissueanerrororawarningforhiddencatchblockscorrespondingtocheckedexceptions.

'finally'doesnot Whenenabled,thecompilerwillissueanerrororawarningwhenevera'finally'statementdoesnotcompletenormally(e.g.containsareturn Warning


completenormally statement).

Deadcode(e.g.'if Whenenabled,thecompilerwillissueanerrororawarningwhenitencountersdeadcode(e.g'if(false)'). Warning


(false)')

Resourceleak Whenenabled,thecompilerwillissueanerrororawarningifalocalvariableholdsavalueoftype'java.lang.AutoCloseable'(compliance>= Warning


1.7)oravalueoftype'java.io.Closeable'(compliance<=1.6)andifflowanalysisshowsthatthemethod'close()'isnotinvokedlocallyonthat
value.

Potentialresourceleak Whenenabled,thecompilerwillissueanerrororawarningifalocalvariableholdsavalueoftype'java.lang.AutoCloseable'(compliance>= Ignore


1.7)oravalueoftype'java.io.Closeable'(compliance<=1.6)andifflowanalysisshowsthatthemethod'close()'isnotinvokedlocallyonthat
valueforallexecutionpaths.

Serializableclass Whenenabled,thecompilerwillissueanerrororawarningwheneveratypeimplementing'java.io.Serializable'doesnotcontaina Warning


withoutserialVersionUID serialVersionUIDfield.

Missingsynchronized Whenenabled,thecompilerwillissueanerrororawarningwhenitencountersaninheritedmethodwhichismissingthesynchronized Ignore


modifieroninherited modifier.
method

Classoverrides Whenenabled,thecompilerwillissueanerrororawarningwhenitencountersaclasswhichoverrides'equals()'butnot'hashCode()'. Ignore


'equals()'butnot
'hashCode()'

Nameshadowingandconflicts

Fielddeclarationhidesanother Whenenabled,thecompilerwillissueanerrororawarningifafielddeclarationhidesanotherinheritedfield. Ignore


fieldorvariable

Localvariabledeclarationhides Whenenabled,thecompilerwillissueanerrororawarningifalocalvariabledeclarationhidesanotherfieldorvariable. Ignore


anotherfieldorvariable

Includeconstructororsetter Whenenabled,thecompileradditionallywillissueanerrororawarningifaconstructororsettermethodparameterhidesanotherfield Off


methodparameters orvariable.

Typeparameterhidesanother Whenenabled,thecompilerwillissueanerrororawarningifi.e.atypeparameterofaninnerclasshidesanoutertype. Warning


type

Methoddoesnotoverride Apackagedefaultmethodisnotvisibleinadifferentpackage,andthuscannotbeoverridden.Whenthisoptionisenabled,the Warning


packagevisiblemethod compilerwillsignalsuchscenarioeitherasanerrororawarning.

Interfacemethodconflictswith Whenenabled,thecompilerwillissueanerrororawarningwheneveraninterfacedefinesamethodincompatiblewithanoninherited Warning


protected'Object'method Objectmethod.Untilthisconflictisresolved,suchaninterfacecannotbeimplemented,e.g.
interfaceI{
intclone()
}

DeprecatedandrestrictedAPI

DeprecatedAPI Whenenabled,thecompilerwillsignaluseofdeprecatedAPIeitherasanerrororawarning. Warning

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 169/322
12/10/2015 Javadevelopmentuserguide
SignaluseofdeprecatedAPIinside Whenenabled,thecompilerwillsignaluseofdeprecatedAPIinsidedeprecatedcode.Theseverityoftheproblemis Off
deprecatedcode controlledwithoption"DeprecatedAPI".

Signaloverridingorimplementing Whenenabled,thecompilerwillsignaloverridingorimplementingadeprecatedmethodTheseverityoftheproblemis Off


deprecatedmethod controlledwithoption"DeprecatedAPI".

Forbiddenreference(accessrules) Whenenabled,thecompilerwillsignalaforbiddenreferencespecifiedintheaccessrules. Error

Discouragedreference(accessrules) Whenenabled,thecompilerwillsignaladiscouragedreferencespecifiedintheaccessrules. Warning

Unnecessarycode

Valueoflocalvariableisnotused Whenenabled,thecompilerwillissueanerrororawarningwheneveralocalvariableisdeclaredbutitsvalueisnever Warning


usedwithinitsscope.

Valueofmethodparameterisnotused Whenenabled,thecompilerwillissueanerrororawarningwheneveramethodparameterisdeclaredbutitsvalueisnever Ignore


usedwithinitsscope.

Ignoreinoverridingandimplementing Whenenabled,thecompilerwillnotissueanerrororawarningwheneveraparameterisdeclaredbutneverusedwithinits On
methods scopeinamethodthatoverridesorimplementsanothermethod.

Unusedtypeparameter Whenenabled,thecompilerwillissueanerrororawarningforunusedtypeparameter. Ignore

Ignoreparametersdocumentedwith Whenenabled,thecompilerwillnotissueanerrororawarningwheneveranunreadparameterisdocumentedwithan On
'@param'tag '@param'tag.

Valueofexceptionparameterisnotused Whenenabled,thecompilerwillissueanerrororawarningforunusedexceptionparameter. Ignore

Unusedimport Whenenabled,thecompilerwillissueanerrororawarningforunusedimportreference. Warning

Unusedprivatemember Whenenabled,thecompilerwillissueanerrororawarningwheneveraprivatememberisdeclaredbutneverusedwithin Warning


thesameunit.

Unnecessary'else'statement Whenenabled,thecompilerwillissueanerrororawarningwheneveritencountersanunnecessaryelsestatement(e.g.if Ignore


(condition)returnelsedoSomething()).

Unnecessarycastor'instanceof'operation Whenenabled,thecompilerwillissueanerrororawarningwheneveritencountersanunnecessarycastor'instanceof' Ignore


operation(e.g.if(objectinstanceofObject)return).

Unnecessarydeclarationofthrown Whenenabled,thecompilerwillissueanerrororawarningwheneveritencountersanunnecessarydeclarationofathrown Ignore


exception exception.

Ignoreinoverridingandimplementing Whenenabled,thecompilerwillnotissueanerrororawarningwheneveritencountersanunnecessarydeclarationofa On
methods thrownexceptioninamethodthatoverridesorimplementsanothermethod.

Ignoreexceptionsdocumentedwith Whenenabled,thecompilerwillnotissueanerrororawarningwheneveranunnecessarydeclarationofathrownexception On
'@throws'or'@exception'tags isdocumentedwithan'@throws'or'@exception'tag.

Ignore'Exception'and'Throwable' Whenenabled,thecompilerwillnotissueanerrororawarningwheneveritencountersanunnecessarydeclarationof On
'Exception'and'Throwable'exception

Unused'break'or'continue'label Whenenabled,thecompilerwillissueanerrororawarningwheneveritencountersanunused'break'or'continue'label. Warning

Redundantsuperinterface Whenenabled,thecompilerwillissueanerrororawarningwheneveritencountersatypewhichexplicitlyimplementsan Ignore


interfacethatisalreadyimplementedbyanyofitssupertypes.

Generictypes

Uncheckedgeneric Whenenabled,thecompilerwillissueanerrororawarningwheneveritencountersanuncheckedgenerictypeoperation. Warning


typeoperation

Usageofarawtype Whenenabled,thecompilerwillissueanerrororawarningwheneveritencountersausageofarawtype(e.g.ListinsteadofList<String>). Warning

Generictype Whenenabled,thecompilerwillissueanerrororawarningwheneveritencountersatypeboundinvolvingafinaltype. Warning


parameterdeclared
withafinaltype
bound

Ignoreunavoidable Whenenabled,thecompilerwillignoregenericsrelatedtypeproblemsthatcouldnothavebeenavoidedbytheprogrammer,becauseareferenced Off


generictypeproblems APIalreadycontainsrawtypes.Asanexample,atypemaybeforcedtouserawtypesinitsmethodsignaturesandreturntypesbecausethe

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 170/322
12/10/2015 Javadevelopmentuserguide
duetorawAPIs methodsitoverridesfromasupertypearedeclaredtouserawtypesinthefirstplace.
WhentheoldAPIiseventuallygenerified,thenmostoftheseproblemseithergoaway,oryouwillseeacompileerrorbecausethetype
argumentsyouusedarenotcorrect.Forrawreferencesinmethodsignatures,therawtypeproblemwillreappear.

Annotations

Missing'@Override'annotation Whenenabled,thecompilerwillissueanerrororawarningwheneveritencountersamethodoverridinganotherimplemented Ignore


method,andthe'@Override'annotationismissing.

Includeimplementationsofinterface Whenenabled,thecompilerwillalsoissueanerrororawarningwheneveritencountersamethodoverridingorimplementinga On
methods(1.6orhigher) methoddeclaredinaninterface,andthe'@Override'annotationismissing.
Notethat'@Override'isonlyallowedonsuchmethodsifthecompilercompliancelevelis1.6orhigher,sothiserrororwarning
willneverappearin1.5code.

Missing'@Deprecated'annotation Whenenabled,thecompilerwillissueanerrororawarningwheneveritencountersadeprecatedtypewithoutadditional Ignore


'@Deprecated'annotation.

Annotationisusedassuperinterface Whenenabled,thecompilerwillissueanerrororawarningwheneveritencountersatypeimplementinganannotation. Warning


Althoughpossible,thisisconsideredbadpractice.

Unhandledtokenin Whenenabled,thecompilerwillissueanerrororawarningwheneveritencountersanunknowntokenina Warning


'@SuppressWarnings' '@SuppressWarnings'annotation.

Enable'@SuppressWarnings' Whenenabled,thecompilerwillprocess'@SuppressWarnings'annotations.Whendisabled,itwillactasifall On
annotations '@SuppressWarnings'annotationswereremoved.

Unused'@SuppressWarnings' Whenenabled,thecompilerwillissueanerrororawarningwheneveritencountersanunusedtokenina'@SuppressWarnings' Warning


token annotation.

Suppressoptionalerrorswith Whenenabled,the'@SuppressWarnings'annotationwillalsosuppressoptionalcompileerrors,i.e.optionssetto"Error"here. Off


'@SuppressWarnings' Mandatorycompileerrorscannotbesuppressed.

Nullanalysis

Nullpointeraccess Whenenabled,thecompilerwillissueanerrororawarningwhenitencountersthatalocalvariablewhichiscertainlynullis Warning


dereferenced.Notethattheanalysiscannotfindallnullpointeraccesses,seePotentialnullpointeraccess.

Potentialnullpointeraccess Whenenabled,thecompilerwillissueanerrororawarningwhenitencountersthatalocalvariablewhichmaybenullisdereferenced. Ignore


Notethattheanalysisisfairlyconservative,itonlyconsiderscaseswherethereissomethingsuspicious.
Thequalityoftheanalysiscanbeimprovedbyusingnullannotations,whichcanbeenabledusingtheoptionEnableannotationbased
nullanalysis

Redundantnullcheck Whenenabled,thecompilerwillissueanerrororawarningwheneveralocalvariablewhichcannotbenullistestedfornull. Ignore

Include'assert'innullanalysis Whenenabled,thecompilerwillhonor'assert'statementwhendoingthenullanalysis. Off

Enableannotationbasednull Whenenabled,thecompilerwillinterpretannotations@Nullable,@NonNull,and@NonNullByDefaultasspecifyingwhetherornota Off


analysis giventypeincludesthevalue'null'.
Theeffectoftheseanalysesisfurthercontrolledbythefollowingsuboptions.
SeealsoUsingnullannotations.

Violationofnull Dependingonthisoption,thecompilerwillissueeitheranerrororawarningwheneveroneofthefollowingsituationsisdetected: Error


specification
1. Amethoddeclaredwithanonnullannotationreturnsanullableexpression.
2. Anullableexpressionispassedasanargumentinamethodcallwherethecorrespondingparameterofthecalledmethodis
declaredwithanonnullannotation.
3. Anullableexpressionisassignedtoalocalvariablethatisdeclaredwithanonnullannotation.
4. Amethodthatoverridesaninheritedmethoddeclaredwithanonnullannotationtriestorelaxthatcontractbyspecifyinganullable
annotation(prohibitionofcontravariantreturn).
5. Amethodthatoverridesaninheritedmethodwhichhasanullabledeclarationforatleastoneofitsparameters,triestotightenthat
nullcontractbyspecifyinganonnullannotationforitscorrespondingparameter(prohibitionofcovariantparameters).
Intheaboveanexpressionisconsideredasnullableifeitheritisstaticallyknowntoevaluatetothevaluenull,orifitisdeclaredwitha
nullableannotation.

Conflictbetweennull Dependingonthisoption,thecompilerwillissueeitheranerrororawarningwheneveroneofthefollowingsituationsisdetected: Error


annotationsandnull
inference 1. Amethoddeclaredwithanonnullannotationreturnsanexpressionthatisstaticallyknowntoevaluatetoanullvalueonsome
flow.
2. Anexpressionthatisstaticallyknowntoevaluatetoanullvalueonsomeflowispassedasanargumentinamethodcallwhere
thecorrespondingparameterofthecalledmethodisdeclaredwithanonnullannotation.
3. Anexpressionthatisstaticallyknowntoevaluatetoanullvalueonsomeflowisassignedtoalocalvariablethatisdeclaredwith
anonnullannotation.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 171/322
12/10/2015 Javadevelopmentuserguide
Uncheckedconversion Dependingonthisoption,thecompilerwillissueeitheranerrororawarningwheneveroneofthefollowingsituationsisdetected: Warning
fromnonannotatedtypeto
@NonNulltype 1. Amethoddeclaredwithanonnullannotationreturnsanexpressionforwhichinsufficientnullnessinformationisavailablefor
staticallyprovingthatnoflowwillpassanullvalueatruntime.
2. Anexpressionforwhichinsufficientnullnessinformationisavailableforstaticallyprovingthatitwillneverevaluatetoanullvalue
atruntimeispassedasanargumentinamethodcallwherethecorrespondingparameterofthecalledmethodisdeclaredwitha
nonnullannotation.
3. Anexpressionforwhichinsufficientnullnessinformationisavailableforstaticallyprovingthatitwillneverevaluatetoanullvalue
atruntimeisassignedtoalocalvariablethatisdeclaredwithanonnullannotation.
Uncheckedconversionisusuallyaconsequenceofusingotherunannotatedvariablesormethods.

Redundnantnull Whenenabled,thecompilerwillissueanerrororawarningwhenanonnullannotationisappliedalthoughthesameeffectisalready Warning


annotation achievedbyadefaultapplicableatthecurrentlocation.Suchadefaultmaybesetbyusingthe@NonNullByDefaultannotation.

'@NonNull'parameternot Whenenabled,thecompilerwillissueanerrororawarningagainstaparameterofamethodthatoverridesaninheritedmethodifallof Warning


annotatedinoverriding thefollowinghold:
method
Theoverriddenmethoddeclaresthecorrespondingparameterasnonnull.
Theparameterintheoverridingmethodhasnonullannotation.
Theoverridingmethodisnotaffectedbyanullnessdefault.
Inheritanceofnullannotationsisdisabled.

Missing Whenenabled,thecompilerwillissueanerrororawarninginthefollowingcases: Ignore


'@NonNullByDefault'
annotationonpackage 1. Whenapackagedoesnotcontainadefaultnullnessannotation,asaresultofmissingpackageinfo.javaormissingdefault
nullnessannotationinpackageinfo.java.
2. Whenatypeinsideadefaultpackagedoesnotcontainadefaultnullnessannotation.

Usedefaultannotationsfor Whenenabled,thecompilerwillusethedefaultsetofannotationsfornullspecifications.TheseannotationsareincludedintheEclipse On
nullspecifications SDKintheorg.eclipse.jdt.annotationbundle.
Youcanspecifydifferentannotationnamestouseinyourprojects,butbeawarethattheEclipsecompileronlysupportsthesemantics
specifiedinthedefaultannotations:
org.eclipse.jdt.annotation.Nullable:AfullyqualifiednameofaJavaannotationtype,whichwhenappliedtoatypeinamethod
signature,variabledeclarationorfielddeclaration,willbeinterpretedasaspecificationthatnullisalegalvalueinthatposition.
Currentlysupportedpositionsare:methodparameters,methodreturntype,localvariablesandfields.
org.eclipse.jdt.annotation.NonNull:AfullyqualifiednameofaJavaannotationtype,whichwhenappliedtoatypeinamethod
signature,variabledeclarationorfielddeclaration,willbeinterpretedasaspecificationthatnullisnotalegalvalueinthatposition.
Currentlysupportedpositionsare:methodparameters,methodreturntype,localvariablesandfields.
org.eclipse.jdt.annotation.NonNullByDefault:AfullyqualifiednameofaJavaannotationtype.Whenappliedtoanelement
withoutanannotationargument,allunannotatedtypesinmethodsignatureswithintheannotatedelementwillbetreatedasifthey
werespecifiedwiththenonnullannotation.
Onthecontrary,whentheannotationisappliedwiththeconstant'false'asitsargument,allcorrespondingdefaultsatouterscopes
willbecanceledfortheannotatedelement.

Inheritnullannotations Whenenabled,thecompilerwillcheckforeachmethodwithoutanyexplicitnullannotations:Ifitoverridesamethodwhichhasnull Off


annotations,itwilltreatthecurrentmethodasifithadthesameannotationsastheoverriddenmethod.
Annotationinheritancewillusetheeffectivenullnessoftheoverriddenmethodaftertransitivelyapplyinginheritanceandafterapplying
anydefaultnullnessatthesiteoftheoverriddenmethod.
Ifdifferentimplicitnullannotations(fromanonnulldefaultand/oroverriddenmethods)areapplicabletothesametypeinamethod
signature,thisisflaggedasanerrorandanexplicitnullannotationmustbeusedtodisambiguate.

Enablesyntacticnull Whenenabled,thecompilerwilldetectcertainsyntacticconstellationswhereanullrelatedwarningagainstafieldreferencewould Off


analysisforfields normallyberaisedbutcanbesuppressedatlowriskgiventhatthesamefieldreferencewasknowntobenonnullimmediatelybefore.
Whenusingthisoptionpleaseseethesehints.

WhenTreataboveerrorslikefatalcompileerrorsisenabled,allgeneratederrors,fatalorconfigurable,leadtononexecutablecode.Ifdisabled,thenyourcodecanbeexecuted
aslongasithasnofatalerror(syntaxerror,typeerror,oranyerroraccordingtotheJavaLanguageSpecification).

ProblemsView
QuickFix
Javabuilder

5.3.1.4.3.JavaCompilerJavadocPreferences
IndicateyourpreferencesfortheJavadocsettingsonthe Java>Compiler>Javadocpreferencepage.

Option Description Default

ProcessJavadoccomments(includes ThebuilderdetectsproblemsinJavadoccommentsifthisoptionisenabled.Forsearchandrefactoringtoworkon On
searchandrefactoring) Javadoccommentsitisalsorequiredtoenablethisoption.

MalformedJavadoccomments Whenenabled,thecompilerwillissueanerrororwarningwheneveritencountersamalformedJavadoccomment. Ignore

Onlyconsidermembersasvisibleas Thecompileronlychecksmemberswiththespecifiedorabroadervisibility. Public

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 172/322
12/10/2015 Javadevelopmentuserguide
Validatetagarguments(@param, Whenenabled,thecompilerwillissueanerrororwarningwheneveritencountersanerrorinaJavadoccommenttag Off
@throws,@exception,@see,@link) argumentfor@param,@throws,@exception,@seeor@link.

Reportnonvisiblereferences Whenenabled,thecompilerwillissueanerrororwarningwheneveritencountersareferencetoanonvisible Off


element.

Reportdeprecatedreferences Whenenabled,thecompilerwillissueanerrororwarningwheneveritencountersareferencetoadeprecated Off


element.

Missingtagdescriptions Choosebetween'Validateallstandardtags','Validate@returntags'and'Ignore'.Whenenabled,thecompilerwill 'Validate


issueanerrororwarningwheneveritencountersamissingtagdescription @returntags'

MissingJavadoctags Whenenabled,thecompilerwillissueanerrororwarningwheneveritencountersamissingJavadoctag(i.e.missing Ignore


@paramtagforaparameter).

Onlyconsidermembersasvisibleas Thecompileronlychecksmemberswiththespecifiedorabroadervisibility. Public

Ignoreinoverridingandimplementing Whenenabled,methodsthatoverrideorimplementanothermethodarenotcheckedformissingJavadoctags. On
methods

Ignoremethodtypeparameters Whenenabled,missingJavadoctagsarenotreportedformethodtypeparameters. On

MissingJavadoccomments Whenenabled,thecompilerwillissueanerrororwarningwheneveritencountersamissingJavadoccommentfora Ignore


Javamember.

Onlyconsidermembersasvisibleas Thecompileronlychecksmemberswiththespecifiedorabroadervisibility. Public

Ignoreinoverridingandimplementing Whenenabled,methodsthatoverrideorimplementanothermethodarenotcheckedformissingJavadoccomments. On
methods

5.3.1.4.4.JavaTaskTagsPreferences
Tasktagscanbeconfiguredonthe Java>Compiler>TaskTagspreferencepage.Whenthetaglistisnotempty,thecompilerwillissueataskmarkerwheneveritencounters
oneofthecorrespondingtaginsideanycommentinJavasourcecode.Generatedtaskmessageswillincludethetag,rangeuntilthenextlineseparator,commentendingornon
emptytag,andwillbetrimmed.Ifthesamelineofcodecarriesmultipletags,theywillbereportedseparately.
SeetheCompilerpreferencepageforinformationonhowtoenabletasktagsinyoursourcecode.

Action Description

New... Addsanewtasktag.Intheresultingdialog,specifyanameandpriorityforthenewtasktag.

Remove Removestheselectedtasktag.

Edit... Allowsyoutoedittheselectedtasktag.Intheresultingdialog,editthenameand/orpriorityforthetasktag.

Default Setsthecurrentlyselectedtasktagasthedefaulttasktag.ThedefaulttasktagistheonethatisusedinthecodetemplatesasspecifiedontheCodeTemplates
preferencepage.Thedefaulttasktagisdisplayedinboldfont.

CasesensitivityofthetasktagscanbespecifiedatthebottomofthepreferencepageusingtheoptionCasesensitivetasktagnames.

Javacompilerpreferences
Codetemplatepreferences

5.3.1.5.JavaDebugPreferences
Thefollowingpreferencescanbesetusingthe Java>Debugpreferencepage.
Theseoptionsapplytojavaspecificdebuggersandhavetodowithsuspendingoptionsandhotcodereplace.

Option Description Default

Suspendexecutiononuncaught On
exceptions Thisoptioncontrolsifaprogramwillsuspendifanuncaughtexceptionisthrown.
ForexampleifyoutrytocallamethodonanullobjectandaNullPointerExceptionisthrown,withthisoptiononyourprogramwill
suspendatthelocationtheexceptionwasthrown

Suspendexecutiononcompilation Thisoptioncontrolsifaprogramwillsuspendwhenacompilationerrorisencountered On
errors
Suspendforbreakpointsduring Thisoptionscontrolsifbreakpointswillsuspendduringanevaluationofcodecontainingabreakpoint.Formoreinformationabout On
evaluations evaluationsgohere

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 173/322
12/10/2015 Javadevelopmentuserguide
Openpopupwhensuspendedon Thisoptioncontrolsifapopupwindowwillbedisplayedwhenexecutionofaprogramstopsonanexception.Theexceptionthe Off
exception programsuspendedonismadeavailableforinspectioninthepopup
Defaultsuspendpolicyfornew Thisoptionallowsthedefaultsuspendpolicytobesetfornewbreakpoints.Thesuspendpolicyisusedbybreakpointstotellthe Suspend
breakpoints VMwhattosuspend,inthiscaseeitherthethreadthebreakpointisactiveinortheentirerunningVM Thread
Defaultsuspendpolicyfornew Thisoptionallowsthedefaultsuspendpolicytobesetfornewwatchpoints.Thesuspendpolicyisusedbywatchpointstotellthe Suspend
watchpoints VMwhatkindoffieldactionstosuspendoninthiscaseeitheraccessandmodification(both),accessonlyormodificationonly Thread
Showerrorwhenhotcodereplace Thisoptioncontrolsiftheuserwillbepresentedwithanerrordialogwhenahotcodereplacefails On
fails
Showerrorwhenhotcodereplace Thisoptioncontrolsiftheuserwillbepresentedwithanerrordialogwhenhotcodereplaceisnotsupported,andtheuserhas On
isnotsupported madeandsavedchangestocurrentlyrunningcode
Showerrorwhenobsoletemethods Thisoptioncontrolsiftheuserwillbepresentedwithanerrordialogwhenahotcodereplacecompleted,buttherewereobsolete On
remainafterhotcodereplace methodsleftover
Replaceclassfilescontaining Thisoptioncontrolsisclassfilescontainingcompilationerrorswillbereplaced On
compilationerrors
Debuggertimeout Thisoptiondescribesthelengthoftime(inmilliseconds)thedebuggerwillwaittryingtocommunicatewitharunningVMbefore 3000
givingupanddisconnecting
Launchtimeout Thisoptiondescribesthelengthoftime(inmilliseconds)thatalaunchwillwaittocompletethelaunchingprocessbeforegivingup 20000
andterminating.Thisoptionhasnobearingonthelengthoftimeaprogramwillrun,onlyhowlongtheprocessoftryingtoruna
programwillwait
Warnwhenunabletoinstall Thisoptioncontrolsiftheuserwillbenotifiediftheytrytosetalinebreakpointonalinethathasinvalidlineinformation On
breakpointduetomissingline
numberattributes
Promptforconfirmationwhen Thisoptioncontrolsifclientsshouldbepromptedwhentryingtoremoveabreakpointwithaconditionfromtheeditor On
deletingaconditrionalbreakpoint
fromtheeditor
Onlyincludeexportedclasspath Thisoptioncontrolsifonlyclasspathentriesmarkedasexportedshouldbeincludedintheclasspathusedforlaunching Off
entrieswhenlaunching

Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging

LaunchingaJavaprogram
Runninganddebugging

DetailFormattersPreferences
HeapWalkingPreferences
InstalledJREsPreferences
LogicalStructuresPreferences
PrimitiveDisplayPreferences
Run/DebugPreferences
StepFilteringPreferences

5.3.1.5.1.DetailFormattersPreferences
Thefollowingpreferencescanbesetusingthe Java>Debug>DetailFormatterspreferencepage.
Thesepreferencesareusedtocreateandmanagedetailformatters,whichareusedinthedetailspanesofvariablesviews,orforvariablelabelsthemselves.

Option Description Default

Typeswithdetailformatters Thelistingoftypesthatcurrentlyhavedetailformatters(thelistitself),andtheenabledstateofthedetailformatter,i.e.ifitisonuse
(thecheckedstateofalistitem)
Addbutton Usedtoaddanewdetailformattertothecurrentlisting
Editbutton Usedtoedittheselecteddetailformatter
Removebutton Usedtoremovetheselecteddetailformatter
Detailformattercodesnippetfor Displaysthecurrentcodesnippetinuseforthedetailformatteroftheselectedtype.Thisfieldisnoteditable,theonlywaytoedita
selectedtype detailformatteristousetheEdit...button
Showvariablesdetails
Thisoptioncontrolswhereyouwanttoseethedetailformatterappear,youhaveoneofthreechoices:
Asalabelforvariableswithdetailformatterswillappearastheprimarydisplaylabelonlyforassociatedvariablesthehave
detailformatters
Asalabelforallvariableswillappearforallassociatedvariables,regardlessofthemhavingdetailformattersalready
Indetailpaneonlywillonlyappearinvariablesviewdetailspanesandnowhereelse

Debugger
Javaperspectives
Javaviews
Localdebugging

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 174/322
12/10/2015 Javadevelopmentuserguide
Remotedebugging

LaunchingaJavaprogram
Runninganddebugging

HeapWalkingPreferences
InstalledJREsPreferences
JavaDebugPreferences
LogicalStructuresPreferences
PrimitiveDisplayPreferences
Run/DebugPreferences
StepFilteringPreferences

5.3.1.5.2.HeapWalkingPreferences
Thefollowingpreferencescanbesetusingthe Java>Debug>HeapWalkingpreferencepage.
ThesepreferencesallowcountsettingsforJava1.6heapwalkingfeaturestobechanged.

Option Description Default

Maximuminstancesto Themaximumnumberoftypeinstancestodisplayusingtheallinstancescommand.Enteringzerowillalwaysshowalloftheinstancesofthe 100


display selectedtypeinthecurrentVM
Maximumreferencesto Themaximumnumberoftypereferencestodisplayusingtheallreferencescommand.Enteringzerowillalwaysshowallofthereferencesto 100
display theselectedtypeinthecurrentVM

Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging

LaunchingaJavaprogram
Runninganddebugging

DetailFormattersPreferences
InstalledJREsPreferences
JavaDebugPreferences
LogicalStructuresPreferences
PrimitiveDisplayPreferences
Run/DebugPreferences
StepFilteringPreferences

5.3.1.5.3.LogicalStructuresPreferences
Thefollowingpreferencescanbesetusingthe Java>Debug>LogicalStructurespreferencepage.
Thesepreferencesareusedtoadd,editandremovelogicalstructures,whichareusedtodisplaycollectiontypeobjects

Option Description Default

LogicalStructures Showsalistingofallofthecurrentlogicalstructuresavailable.Notethatlogicalstructureswithayellowbackgroundcannotbeeditedorremoved
Addbutton Usedtoaddanewlogicalstructuretothelisting
Editbutton Usedtoedittheselectedlogicalstructure
Removebutton Usedtoremovetheselectedlogicalstructure
Preview Showsthecodesnippettotheselectedlogicalstructure.Thispreviewisnoteditable,youmustusetheEdit...buttontoeditalogicalstructure

Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging

LaunchingaJavaprogram
Runninganddebugging

DetailFormattersPreferences
HeapWalkingPreferences
InstalledJREsPreferences

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 175/322
12/10/2015 Javadevelopmentuserguide
JavaDebugPreferences
PrimitiveDisplayPreferences
Run/DebugPreferences
StepFilteringPreferences

5.3.1.5.4.PrimitiveDisplayOptionsPreferences
Thefollowingpreferencescanbesetusingthe Java>Debug>PrimitiveDisplayOptionspreferencepage.
Thesepreferencesaffecthowprimitivevaluesaredisplayed(int,double,etc).

Option Description Default

Displayhexadecimalvalues(byte,short,char,int, Thisoptioncontrolswhetherhexadecimalvalueswillbedisplayedfortheprimitivetypesbyte,short,char,intand Off


long) long
DisplayASCIIcharvalue(byte,short,int,long) ThisoptioncontrolswhetherASCIIcharvalueswillbedisplayedfortheprimitivetypesbyte,short,intandlong Off
Displayunsignedvalues(byte) Thisoptioncontrolswhetherunsignedvalueswillbedisplayedforbytes Off

Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging

LaunchingaJavaprogram
Runninganddebugging

DetailFormattersPreferences
HeapWalkingPreferences
InstalledJREsPreferences
JavaDebugPreferences
LogicalStructuresPreferences
Run/DebugPreferences
StepFilteringPreferences

5.3.1.5.5.StepFilteringPreferences
Thefollowingpreferencescanbesetusingthe Java>Debug>StepFilteringpreferencepage.
Thesepreferencesareusedtoconfigurestepfiltersandstepfilteringoptions.

Option Description Default

Usestep Thisoptioncontrolsisstepfilteringshouldbeenabledornot.SeealsothestepfilteringcommandintheDebugView On
filters
Defined Thisisalistingofallofthedefinedstepfilters(thelistingitself)andwhetherthestepfiltersareinuseornot(thecheckedstateofstepfilter)
stepfilters
AddFilter Usedtoaddanewstepfilterthatisbasedonaregularexpression
button
AddClass UsedtoaddanewJavaclasstothelistingofstepfilters
button
Add UsedtoaddnewJavapackagestothelistingofstepfilters
Packages
button
Remove Usedtoremovetheselectedstepfilter(s)
button
SelectAll Usedtosetalldefinedstepfiltersasenabled(orchecked)
button
DeselectAll Usedtosetalldefinedstepfiltersasdisabled(orunchecked)
button
Filter Thisoptioncontrolsifsyntheticmethodshouldalwaysbefilteredornotwhilestepping.ThisoptionrequiresthattheVMusedsupportsyntheticmethods Off
synthetic
methods
Filterstatic Thisoptioncontrolsifstaticinitializersshouldalwaysbefilteredornotwhilestepping Off
initializers
Filtersimple ThisoptioncontrolsifsimpleJavabeanstylegettersshouldalwaysbefilteredornotwhilestepping Off
getters
Filtersimple ThisoptioncontrolsifsimpleJavabeanstylesettersshouldalwaysbefilteredornotwhilestepping Off
setters
Filter Thisoptioncontrolsifconstructorsshouldalwaysbefilteredornotwhilestepping Off
constructors
Step On
through Thisoptioncontrolsstepfilterstoalwaysreturnfromafilteredlocationorstepthroughtoanonfilteredlocation.
filters Forexample,ifjava.utilisafilteredlocation,steppingintocodeinHashMapcouldresultinacallbacktoyourapplicationcodetochecktheequalityofan

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 176/322
12/10/2015 Javadevelopmentuserguide
object.IfyouchoosetoStepthroughfiltersastepintowouldendupinyourapplicationcode.However,whentheStepthroughfiltersoptionisdisabled,
astepintoHashMapwouldbehavelikeastepover.

Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging

LaunchingaJavaprogram
Runninganddebugging

DetailFormattersPreferences
HeapWalkingPreferences
InstalledJREsPreferences
JavaDebugPreferences
LogicalStructuresPreferences
PrimitiveDisplayPreferences
Run/DebugPreferences

5.3.1.6.JavaEditorPreferences
ThefollowingJavaeditorpreferencescanbesetonthe Java>Editorpreferencepageanditssubpages.
ContentAssist
Advanced
Favorites
Folding
Hovers
MarkOccurrences
SaveActions
SyntaxColoring
Templates
Typing
Notethatsomeoptionsthataregenerallyapplicabletotexteditorscanbeconfiguredonthetexteditorpreferencepage.

Option Description Default


SmartcaretpositioninginJavanames(overrides
platformbehavior) Ifenabled,thereareadditionalwordboundariesinside|Camel|Case|Javanames. On

Reportproblemsasyoutype
Ifenabled,theeditormarkserrorsandwarningsasyoutype,evenifyoudonotsavetheeditorcontents.The On
problemsareupdatedafterashortdelay.

Brackethighlighting
Ifenabled,theJavaeditorhighlightsparenthesis,bracketorcurlybraces,basedonwhichsuboptionisselected. On
ThecolorofthebrackethighlightisspecifiedwithAppearancecoloroptions.

Matchingbracket
Ifenabled,wheneverthecursorisnexttoabracket,itsopeningorclosingcounterpartishighlighted. On

Matchingbracketandcaretlocation
Ifenabled,wheneverthecursorisnexttoabracket,boththebracketanditsopeningorclosingcounterpartare Off
highlighted.

Enclosingbrackets
Ifenabled,theJavaeditorhighlightstheclosestbracketpairenclosingthecursor. Off

Lightbulbforquickassists
Ifenabled,a showsupintheverticalrulerwheneveraquickassistisavailable.Seethequickassistsection Off
foralistoftheavailableassists.

OnlyshowtheselectedJavaelement
Ifenabled,theJavaeditorwillonlyshowtheselectedJavaelementwhichiscurrentlyselected(i.e.intheOutline Off
VieworthePackageExplorer).

Appearancecoloroptions
ThecolorsofvariousJavaeditorappearancefeaturesarespecifiedhere. default
colors
Matchingbracketshighlight
Thecolorofbracketshighlight.
Parameterhintsbackground
Thebackgroundcoloroftheparameterhintwindow
Parameterhintsforeground
Theforegroundcoloroftheparameterhintwindow
Completionoverwritebackground
Thebackgroundcolorofthecompletionoverwritewindow
Completionoverwriteforeground

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 177/322
12/10/2015 Javadevelopmentuserguide
Theforegroundcolorofthecompletionoverwritewindow
Sourcehoverbackground
Thebackgroundcolorforthesourcehover.Thesourcehovershowsthesourcecodeoftheelementunder
themousepointer.

Javaeditor

Javaeditor
Codeformatterpreferences
Javaoutline
Javacontentassist
QuickFix
QuickAssist

5.3.1.6.1.JavaContentAssistPreferences
IndicateyourpreferencesfortheContentAssistsettingsonthe Java>Editor>ContentAssistpreferencepage.

Option Description Default

Insertion
Completioninserts/Completion IfCompletioninsertsison,thecompletiontextisinsertedatthecaretposition,soitneveroverwritesanyexistingtext. Completion
overwrites IfCompletionoverwritesison,thecompletiontextreplacesthecharactersfollowingthecaretpositionuntiltheendoftheword. inserts
NotethatpressingCtrlwhenapplyingacompletionproposaltogglesbetweenthetwoinsertionmodes.

Insertsingleproposals Ifenabled,codeassistwillchooseandinsertautomaticallysingleproposals. On
automatically
Insertcommonprefixes Ifenabled,codeassistwillautomaticallyinsertthecommonprefixofallpossiblecompletionssimilartoUnixshellexpansion.This Off
automatically canbeusedrepeatedly,evenwhilethecodeassistwindowisbeingdisplayed.
Addimportinsteadofqualified Ifenabled,typeproposalswhichareinotherpackageswillinvoketheadditionofthecorrespondingimportdeclaration.Otherwise, On
name thetypewillbeinsertedfullyqualified.
Usestaticimports Ifenabled,methodproposalsforstaticmethodswillinvoketheadditionofthecorrespondingstaticimportdeclaration.Otherwise,a On
nonstaticimportforthedeclaringtypewillbeadded.
AddthemethodortypecontainingthemethodtotheFavoritespreferencepagetogetaproposalforsuchmethods.

Fillmethodargumentsandshow Ifenabled,codeassistwilladdargumentwhencompletingamethod.Itwillalsooffermatchingvariables,fieldsormethod On
guessedarguments invocationsfromthecontextwhereamethodproposalisinserted.
Insertparameternames Ifselected,codeassistwillfilltheargumentswiththeparameternamesusedinthemethoddeclaration. Off
Insertbestguessedarguments Ifselected,codeassistwillfilltheargumentswiththebestmatchingvariable,fieldormethodinvocationfromthecontextwherea Off
methodproposalisinserted.

SortingandFiltering
ConfigureTypeFilters.
Sortproposals Selecthowtheproposalsshouldbesortedinthecontentassistpopup. by
relevance
Showcamelcasematches Ifenabled,camelcasematchesaredisplayed(i.e.NPEisexpandedtoNullPointerException). On
Hideproposalsnotvisibleinthe Ifenabled,theJavaelementproposalsarelimitedbytherulesofvisibility.Forexample,privatefieldproposalsofotherclasses On
invocationcontext wouldnotbedisplayed.
Hidedeprecatedreferences Ifenabled,referencestodeprecatedJavaelementsarenotdisplayed. Off

AutoActivation
Enableautoactivation Ifenabled,codeassistcanbeinvokedautomatically. On
TheconditionforautomaticinvocationisspecifiedwiththepreferencesAutoactivationdelay,AutoactivationtriggersforJava
andAutoactivationtriggersforJavadoc.

Autoactivationdelay Thetimeinmillisecondsafterwhichcodeassististriggeredafteranautoactivationtriggercharacterisencounteredandnoother 200


characterhasbeentyped.
AutoactivationtriggersforJava IfoneofthetriggercharactersistypedinsideJavasourcecode(butnotinsideaJavadoccomment)andnoothercharacteristyped '.'
beforetheautoactivationdelaytimesout,thecodeassistisinvoked.
Autoactivationtriggersfor IfoneofthetriggercharactersistypedinsideaJavadocandnoothercharacteristypedbeforetheautoactivationdelaytimesout, '@#'
Javadoc thecodeassistisinvoked.

Content/CodeAssist
TypeFilters

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 178/322
12/10/2015 Javadevelopmentuserguide
5.3.1.6.1.1.AdvancedJavaContentAssistPreferences
IndicateyourpreferencesfortheAdvancedsettingsonthe Java>Editor>ContentAssist>Advancedpreferencepage.

Option Description Default

Selecttheproposalkinds Selectalltheproposalkindswhicharecontainedinthecontentassistlistwheninvokingcontentassistthe OtherJavaProposals,SWT


containedinthe'default' firsttimewithCtrl+Space. TemplateProposals,Template
contentassistlist Proposals,TypeProposals

Contentassistcycling Selecttheproposalkindstocyclethroughandthecycleorderwhenrepeatedlyinvokingcontentassist TemplateProposals,SWTTemplate


(Ctrl+Space).SelectaproposalkindandinvokeUporDowntochangetheorder. Proposals

Timeoutforfetchinga IfaparameternamecouldnotbefetchedfromattachedJavadocwithinthespecifiedamountoftimethenthe 50ms


parameternamefrom attempttofetchitisabandoned.Increasethevalueifyouhaveproblemsfetchingthename,forinstancedue
attachedJavadoc toaslownetworkconnection.

Content/CodeAssist
ContentAssistpreferencepage

5.3.1.6.1.2.JavaContentAssistFavoritesPreferences
Indicateyourpreferencessettingsforthecontentassistforstaticmembersonthe Java>Editor>ContentAssist>Favoritespreferencepage.
Youcandefinealistofstaticmembersandtypescontainingstaticmembersonthispage.Contentassistwillproposethosememberseveniftheimportismissing.
Toseethestaticimportproposals,makesureUsestaticimportsisenabledonthe ContentAssistpreferencepage

Action Description

NewType Addanewtypetothelist.Allstaticmembersdeclaredbytheaddedtypewillbeproposedbycontentassist.

NewMember Addastaticmembertothelist.Thememberwillbeproposedbycontentassist.

Edit Edittheselectedentry.

Remove Removestheselectedentryfromthelist.

Content/Codeassist
Contentassistpreferencepage

5.3.1.6.2.JavaEditorFoldingPreferences
IndicateyourpreferencesfortheFoldingsettingsonthe Java>Editor>Foldingpreferencepage.

Option Description Default

Enablefolding Ifenabled,differentsectionsintheJavaeditorcanbefoldedandexpanded. On

Comments Ifenabled,commentsarefoldedwhenopeninganeweditor. Off

HeaderComments Ifenabled,headerCommentsarefoldedwhenopeninganeweditor. On

Innertypes Ifenabled,innertypesarefoldedwhenopeninganeweditor. Off

Members Ifenabled,Javamembersarefoldedwhenopeninganeweditor. Off

Imports Ifenabled,importsarefoldedwhenopeninganeweditor. On

JavaEditorpreferencepage

5.3.1.6.3.JavaHoversPreferences
IndicateyourpreferencesfortheHoverssettingsonthe Java>Editor>Hoverspreferencepage.

Option Description Default

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 179/322
12/10/2015 Javadevelopmentuserguide
Expandverticalruler Ifenabled,whentherearemultipleiconsperlineshownonverticalruler,thentheiconsareexpandedwhenhoveringoverit.This Off
iconsuponhovering allowstoseeallicons.Changingthispreferencedoesnotaffectalreadyopenededitors.

TextHoverkeymodifier Theselectedhoversinthislistareusedtogeneratethehovercontent.Akeymodifiercanbegiventoeachhovertypetoforcethe CombinedHover,


preferences editortoonlyevaluatethishoverwhenpressingtheassignedkeymodifier. Source(withShift)

Javaeditorpreferencepage

5.3.1.6.4.MarkOccurrencesPreferences
IndicateyourpreferencesfortheMarkOccurrencessettingsonthe Java>Editor>MarkOccurrencespreferencepage.

Option Description Default

Markoccurrencesoftheselectedelementinthecurrentfile Ifenabled,thenyou'llseewithinafile,whereavariable,method,typeorotherelementisreferenced. On

Alistofelementscanbeenabledanddisabledonthispreferencepage.Allareenabledbydefault.

JavaEditorpreferencepage

5.3.1.6.5.JavaSaveActionsPreferences
IndicateyourpreferencesfortheSaveActionssettingsonthe Java>Editor>SaveActionspreferencepage.
AsetofactionswhichareexecutedoneachsaveoftheJavaeditorcanbespecifiedonthispage.

Option Description Default

Performtheselected Ifenabled,thentheselectedactionsbelowwillbeexecutedonsave. Off


actionsonsave

Formatsourcecode Ifenabled,thenthesourcecodewillbeformattedoneachsave.Thecodewillbeformattedaccordingtotheactiveprofileselectedonthe Off


Java>CodeStyle>Formatterpreferencepage.

Formatalllines Ifselected,alllinesinthefilewillbeformattedonsave. On

Formateditedlines Ifselected,onlythelinesthathavebeenmodifiedsincethelastsaveareformattedonsave. Off

Organizeimports Ifenabled,thentheimportswillbeorganizedoneachsave.ChangetheorganizeimportsettingsontheJava>CodeStyle>Organize On
Importspreferencepage.

Additionalactions Ifenabled,thenadditionalactionswillbeexecutedonsave.ToaddandremoveactionsselectConfigure.... Off

Javaeditorpreferencepage
CleanUppreferencepage

5.3.1.6.6.JavaSyntaxColoringPreferences
IndicateyourpreferencesfortheSyntaxColoringsettingsonthe Java>Editor>SyntaxColoringpreferencepage.
SyntaxColoringspecifieshowJavasourcecodeisrendered.Notethatgeneraltexteditorsettingssuchasthebackgroundcolorcanbeconfiguredonthegeneral'TextEditors'
preferencepages.Fontsmaybeconfiguredonthegeneral'ColorsandFonts'preferencepage.

Option Description Default

Element
Eachcategory(Java,JavadocandComments)containsalistoflanguageelementsthatmayberenderedwithitsowncolorandstyle. defaultcolorsandstyles
Notethatsomesemantichighlightingoptionscanbedisabledbytheuserinordertoensureeditorperformanceonlowendsystems.

Preview
DisplaysthepreviewofaJavasourcecoderespectingthecurrentcolorsandstyles. n/a

Javaeditor

Javaeditorpreferencepage

5.3.1.6.7.JavaEditorTemplatesPreferences
http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 180/322
12/10/2015 Javadevelopmentuserguide
The Java>Editor>Templatespreferencepageallowstocreatenewandeditexistingtemplates.Atemplateisaconveniencefortheprogrammertoquicklyinsertoften
reoccurringsourcecodepatterns.
Thefollowingbuttonsallowmanipulationandconfigurationoftemplates:

Action Description

New... OpenstheTemplatedialogtocreateanewtemplate.

Edit... OpenstheTemplatedialogtoeditthecurrentlyselectedtemplate.

Remove Removesallselectedtemplates.

Restore Restoresanypreconfiguredtemplatesthathavebeenremoved.
Removed

Revertto Restoresanypreconfiguredtemplatestotheirdefault.Thisdoesnotmodifyusercreatedtemplates.
Default

Import... Importstemplatesfromthefilesystem.

Export... Exportsallselectedtemplatestothefilesystem.

Usecode Ifenabled,thetemplateisformattedaccordingtothecodeformattingrulesspecifiedintheCodeFormatterpreferences,priortoinsertion.Otherwise,thetemplate
formatter isinsertedasis,butcorrectlyindented.

Templates
Templatevariables

Templateediting
Javacontentassist
Tasktagpreferences
Codetemplatespreferences
Codestylepreferences

5.3.1.6.7.1.JavaEditorTemplatesPreferences
Thefollowingfieldsandbuttonsappearinthedialog:

Option Description
Name Thenameofthetemplate.
Context Thecontextdetermineswherethetemplatecanbeusedandthesetofavailablepredefinedtemplatevariables.TheJavaeditordefinesacontextforJavaand
Javadocareas.
Javadoc:ProposalisonlyofferedinJavadoccomments
Java:ProposalisonlyofferedinJavacode
Javatypemembers:ProposalisonlyofferedwhencompletingaJavatypemember
Javastatement:ProposalisonlyofferedwhencompletingaJavastatement
SWT:ProposalisonlyofferedwhencompletinginJavacodewithSWTonthebuildpath
SWTtypemembers:ProposalisonlyofferedwhencompletingaJavatypememberwithSWTonthebuildpath
SWTstatement:ProposalisonlyofferedwhencompletingaJavastatementwithSWTonthebuildpath

Automatically Ifselected,codeassistwillautomaticallyinsertthetemplateifitistheonlyproposalavailableatthecaretposition.
insert
Description Adescriptionofthetemplate,whichisdisplayedtotheuserwhenchoosingthetemplate.
Pattern Thetemplatepattern.
InsertVariables... Displaysalistofpredefinedcontextspecifictemplatevariables.

Templates
Templatevariables

Templatespreferences
Javacontentassist
Tasktagpreferences
Codetemplatespreferences
Codestylepreferences

5.3.1.6.8.JavaEditorTypingPreferences

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 181/322
12/10/2015 Javadevelopmentuserguide
Indicateyourpreferencesforthesmartinsertsettingsonthe Java>Editor>Typingpreferencepage.ThosepreferencesareonlyconsideredifSmartInsertModeappearsin
thestatusline.ThiscanbetoggledintheEditmenu.

Option Description Default

Automaticallyclose Selectforwhichcharactersaclosingcharactershouldbeinsertedwhentypingtheopeningcharacter. Allon

Automaticallyinsertatcorrectposition Selectwhichcharactersshouldbeautomaticallyinsertedwhentheyarerequired. Alloff

Enterkeyadjuststheindentationonthenewline Ifenabled,smartindentationwillbeusedtoindentthenewlineafterpressingthe'Enter'key. On

Tabkeyadjuststheindentationofthecurrentline Ifenabledthenthe'Tab'keycanbeusedtoindentthecurrentline. On

Adjustindentation WhenpastingJavacodefromtheclipboardadjustitsindentationtothecurrentindentationlevel. On

Updateimports WhenpastingJavacodefromtheclipboardaddtherequiredimportstatementstotheimportsection. On

Wrapautomatically Ifenabled,stringliteralsarewrappedwhentheyexceedthemaxlinelength. On

Escapetextwhenpastingintoastringliteral Ifenabled,specialcharactersinpastedstringsareescapedwhentheyarepastedintoanexistingstringliteral. Off

Javaeditorpreferencepage

5.3.1.7.InstalledJREsPreferences
Thefollowingpreferencescanbesetusingthe Java>InstalledJREspreferencepage.
ThispageallowsadefaultJREtobeselectedaswellasaddingnewJREinstallations.

Option Description

InstalledJREs ThecurrentlistingofinstalledJREs,allowingyoutoselecttheonetoactastheworkspacedefault

Add... AddsanewJREdefinitiontotheworkbench.

Edit... AllowsyoutoedittheselectedJRE.

Duplicate... CreatesanewJREwiththesameattributesastheselectedJRE.
Remove RemovestheselectedJREfromtheworkbench.

Search... AutomaticallysearchesforJREsinstalledinthelocalfilesystemandcreatescorrespondingJREdefinitionsintheworkspace.

ClasspathVariables
Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging

WorkingwithJREs
AddinganewJREdefinition
DeletingaJREdefinition
AssigningthedefaultJREfortheworkbench
ChoosingaJREforlaunchingaproject
LaunchingaJavaprogram
Runninganddebugging
Usingexternalnullannotations

ExecutionEnvironmentPreferences
JavaDebugPreferences
Run/DebugPreferences
SourceAttachment

5.3.1.7.1.ExecutionEnvironmentsPreferences
Thefollowingpreferencescanbesetusingthe Java>ExecutionEnvironmentspreferencepage.
Thesepreferencesdescribealloftheavailableexecutionenvironments,allowingdefaultJREinstallationstobespecifiedforanygivenenvironment.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 182/322
12/10/2015 Javadevelopmentuserguide
Option Description Default

Execution Thelistingofallavailableexecutionenvironments
environments
Compatible
JREs ThelistingofcompatibleJREinstallationsthatarecompatiblewiththeselectedexecutionenvironment.Youcanselectone(ornone)ofthe
installationstouseasthedefaultfortheselectedexecutionenvironment
AnyJREinstallationsthatperfectlymatchtheexecutionenvironmentaremarkedwithalabel'(perfectmatch)'

Environment Providesadescriptionoftheselectedexecutionenvironment
description

Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging

LaunchingaJavaprogram
Runninganddebugging

InstalledJREsPreferences
JavaDebugPreferences
Run/DebugPreferences

5.3.1.8.JUnitPreferences
The Java>JUnitpreferencepageletsyouconfigurethestacktracefilterpatternsforJUnit.ThepatternsareusedintheJUnitviewtocontrolwhichentriesarevisibleinstack
traces.

Action Description

Enableassertionsfor Ifenabled,thenJUnittestwillbelaunchedwithassertionsenabled.
newJUnitlaunch
configurations

Shownewlylaunched Bydefault,anewJUnittestrunonlyshowsupinthewindowwherethe
testinallJUnitviews testwasstarted.Enablethisoption,ifyouprefertoseethelatesttestinall
openJUnitviews.

AddFilter Allowstoaddacustomfilterpattern.Thisactioninsertsanemptypattern
whichcanbeedited.

AddClass... Allowstoaddclassestobefiltered.ThisactionopenstheOpenType
dialogtochooseatypetobefilteredinthestacktraces.

AddPackages... Allowstoaddpackagestobefiltered.Thisactionopensapackage
selectiondialogtochoosethepackagestobefilteredinthestacktraces.

Remove Removesthecurrentlyselectedstacktracefilterpattern.

EnableAll Enablesallstacktracefilterpatterns.

DisableAll Disablesallstacktracefilterpatterns.

UsingJUnit

Opentype

5.3.1.9.PropertiesFilesEditorPreferences
IndicateyourpreferencesforthePropertiesFilesEditorsettingsonthe Java>PropertiesFilesEditorpreferencepage.
Syntaxcoloringspecifieshowthecontentof'.properties'filesrendered.Notethatgeneraltexteditorsettingssuchasthebackgroundcolorcanbeconfiguredonthegeneral'Text
Editors'preferencepages.

Option Description Default

Element

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 183/322
12/10/2015 Javadevelopmentuserguide
Alistofelementsthatmayberenderedwithitsownforegroundcolorandstyle. defaultcolorsandstyles

Preview
Displaysthepreviewofapropertiesfilerespectingthecurrentcolorsandstyles. n/a

5.3.2.DebugPreferences
Thefollowingpreferencescanbesetusingthe Run/Debugpreferencepage.
Thepreferencesherearegenerictoalldebuggers,andgovernstylisticandpromptingoptions

Option Description Default

Reuseeditorwhen Thedebuggerdisplayssourcecodeinaneditorwhensteppingthroughanapplication.Whenthisoptionison,thedebuggerwillreusetheeditor On
displayingsource thatitopenedtodisplaysourcefromdifferentsourcefiles.Thispreventsthedebuggerfromopeninganexcessivenumberofeditors.Whenthis
code optionisoff,thedebuggerwillopenaneweditorforeachsourcefilethatneedstobedisplayed.

Activatethe Thisoptionbringsattentiontothedebuggerwhenabreakpointisencountered,byactivatingtheassociatedwindow.Thevisualresultvariesfrom On
workbenchwhena platformtoplatform.Forexample,onWindows,theassociatedwindow'stitlebarwillflash.
breakpointishit
Activatethedebug Thisoptionbringsattentiontothedebugviewwhenabreakpointisencountered.Iftheviewisalreadyopenitwillbeactivated.Iftheviewisnot On
viewwhena alreadyopenitwillbeopenedautomatically.
breakpointishit
Skipbreakpoints Thisoptioncontrolswhetherbreakpointsareignoredwhenperforminga'RuntoLine'operation.Whentheoptionison,thedebuggerdoesnot Off
duringa'RuntoLine' suspendatbreakpointsencounteredwhena'RuntoLine'operationisinvoked.Whentheoptionisoff,breakpointsbehavenormally.
operation
Promptfor Thisoptioncontrolswhetheryouwillbepromptedforconfirmationwhenyoutrytodeleteallofyourbreakpoints On
conformationwhen
deletingall
breakpoints
Promptfor Thisoptioncontrolsifyouwillbepromptedforconfirmationwhenyoutrytodeleteabreakpointcontainer,e.g.abreakpointworkingset On
confirmationwhen
deletingbreakpoint
containers
Changedvaluecolor Thisoptionallowsyoutochangethecolorofachangedvalueinthevariablesview,expressionsview,memoryview,anywhererunningprogram Red
variablesarerendered
Changedvalue Thisoptionallowsyoutochangetheselectioncolorofachangedvariable,e.g.inthevariablesviewshowingcolumns Yellow
backgroundcolor
Memoryunbuffered Thisoptionallowsyoutochangetherenderingcolorofunbufferedmemoryblocksinthememoryview Grey
color
Memorybuffered Thisoptionallowsyoutochangetherenderingcolorofbufferedmemoryblocksinthememoryview Black
color

Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging

LaunchingaJavaprogram
Runninganddebugging

ConsolePreferences
InstalledJREsPreferences
JavaDebugPreferences
LaunchingPreferences
PerspectivesPreferences
StringSubstitutionPreferences
ViewManagementPreferences

5.3.2.1.ConsolePreferences
Thefollowingpreferencescanbesetusingthe Run/Debug>Consolepreferencepage.
Theconsoledisplaysoutputfromrunningapplications,andallowskeyboardinputtobereadbyrunningapplications.

Option Description Default

Fixedwidthconsole Thispreferencecontrolswhethertheconsolehasafixedcharacterwidth.Whenon,amaximumcharacterwidthmustalsobespecified.Some Off


applicationswritelonglinestotheconsolewhichrequirehorizontalscrollingtoread.Thiscanbeavoidedbysettingtheconsoletouseafixed
width,automaticallywrappingconsoleoutput.

Limitconsoleoutput Thispreferencelimitsthenumberofcharactersbufferedintheconsole.Whenon,amaximumbuffersizemustalsobespecified.Whenconsole On
outputsurpassesthespecifiedmaximum,outputistruncatedfromthebeginningofthebuffer.
DisplayedTab Allowsthedefaultwidth,incharacters,ofatabtobespecified 8
Width

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 184/322
12/10/2015 Javadevelopmentuserguide
ShowWhen Thispreferencewillforcetheconsoletoshowwhensomethingiswrittentothesystemoutstream.Aforcedshowcanmeanthataconsolewillbe On
ProgramWritesto opened,orthattheconsolewillbebroughttothetopifitisalreadyopen.
StandardOut
ShowWhen Thispreferencewillforcetheconsoletoshowwhensomethingiswrittentothesystemerrstream.Aforcedshowcanmeanthataconsolewillbe On
ProgramWritesto opened,orthattheconsolewillbebroughttothetopifitisalreadyopen.
StandardError

StandardOutText Thispreferencecontrolsthecoloroftextwrittentothestandardoutputstreambyanapplication. Black


Color

StandardErrorText Thispreferencecontrolsthecoloroftextwrittentothestandarderrorstreambyanapplication. Red


Color

StandardInText Thispreferencecontrolsthecoloroftexttypedintotheconsoletobereadbyanapplication. Green


Color

BackgroundColor Thispreferencecontrolsthecolorofthebackgroundoftheconsole White

YoucanalsoclicktheChangebuttontosetthefontfortheConsole.

Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging

LaunchingaJavaprogram
Runninganddebugging

ConsoleView
InstalledJREsPreferences
JavaDebugPreferences
LaunchingPreferences
PerspectivesPreferences
Run/DebugPreferences
StringSubstitutionPreferences
ViewManagementPreferences

5.3.2.2.LaunchingPreferences
Thesepreferencesallowyoutoconfigureoptionsrelatedtolaunchingprogramsingeneral,andgovernsuchthingsaswaitingforbuilds,savingfilesbeforelaunching,etc.
Thefollowingpreferencescanbesetusingthe Run/Debug>Launchingpreferencepage.

Option Description Default

Saverequireddirtyeditorsbefore Prompt
launching Thisoptioncontrolswhethertheuserwillbepromptedtosaveanydirtyeditorsbeforeanapplicationislaunched.The
allowablesettingsare:
Alwayswhenthisoptionisselected,theuserisneverpromptedtosavedirtyeditors,andeditorsare
automaticallysaved.
Neverwhenthisoptionisselected,theuserisneverpromptedtosavedirtyeditors,andeditorsarenot
automaticallysaved.
Promptwhenthisoptionisselected,theuserispromptedtosavedirtyeditorsbeforelaunchinganapplication.

Waitforongoingbuildtocomplete Always
beforelaunching Thisoptioncontrolswhetheralaunchwillwaitforanalreadyexecutingbuildtocompletebeforelaunchinganapplication.
Theallowablesettingsare:
Alwayswhenthisoptionisselected,alaunchwillalwayswaitforthependingbuildtocomplete
Neverwhenthisoptionisselected,alaunchwillneverwaitforthependingbuildtocomplete
Promptwhenthisoptionisselected,theuserispromptedtowaitforthependingbuildtocompletewhenthey
launch

Launchindebugmodewhenever Never
theworkspacecontainsbreakpoints Thisoptioncontrolswhetheralaunchwillbeperformedindebugmode,evenwhenrunispressed,whentheworkspace
containsbreakpoints.Theallowableoptionsare:
Alwayswhenthisoptionisselected,alaunchwillalwaysbeperformedindebugmodewhenbreakpointsare
present,nomatterwhichlaunchbuttonispressed(runordebug)
Neverwhenthisoptionisselected,alaunchwillalwaysbeperformedintheuserspecifiedmode
Promptwhenthisoptionisselected,theuserispromptedtolaunchindebugmodewhentheworkspacecontains
breakpoints

Continuelaunchifprojectcontains Prompt
errors Thisoptioncontrolswhetheralaunchshouldbeperformedwhenarelatedprojectcontainsanerror.Theallowable
optionsare:
Alwayswhenthisoptionisselected,alaunchwillcontinueinthefaceofcompilationerrors
Promptwhenthisoptionisselected,theuserispromptedtoproceedwithalaunchwhenrelevantcompilation

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 185/322
12/10/2015 Javadevelopmentuserguide
errorsareinanassociatedproject

Build(ifrequired)beforelaunching Iftheworkspacerequiresbuilding,anincrementalbuildwillbeperformedpriortolaunchinganapplication. On

Removeterminatedlauncheswhen Whenanapplicationislaunched,allterminatedapplicationsintheDebugviewareautomaticallycleared. On
anewlaunchiscreated

Sizeofrecentlylaunched ThisoptioncontrolshowmanylauncheswillappearintheRun/Debugpulldownlaunchhistorymenus. 10
applicationslist

LaunchOperation LaunchSelected
Newin3.3istheabilitytolaunchtheselectedresourceoreditor.Thelaunchoperationpreferenceallowsuserstoswitch withLaunch
betweenusingtheold'alwayslaunchlast'behaviorandthenew'launchselectedresourceoreditor'behavior. Project
Ifthepreferencetouselaunchselectedresourceoreditorisselected,youcanthencustomizewhathappensifthe
selectedresourceoreditorisnotlaunchable.
Therearetwochoicesforthis
1. trytolaunchtheparentprojectoftheresourceoreditor
2. launchthepreviousthingyoulaunched.

Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging

LaunchingaJavaprogram
Runninganddebugging

RunandDebugtoolbaractions
ConsolePreferences
DefaultLaunchersPreferences
InstalledJREsPreferences
JavaDebugPreferences
LaunchConfigurationsPreferences
PerspectivesPreferences
Run/DebugPreferences
StringSubstitutionPreferences
ViewManagementPreferences

5.3.2.2.1.DefaultLaunchersPreferences
Thefollowingpreferencescanbesetusingthe Run/Debug>Launching>DefaultLauncherspreferencepage.
TheDefaultLauncherspreferenceallowsyoutoselectwhatlaunchtoolingistobeusedifmorethanonekindoftoolingexistsforthesamething,forexample,considerusingtwo
profilersatthesametimeforJavaprograms.Forthemostpart,thispageremainsdisabled,asconcurrentoverlappingtoolingisveryrare,butintheeventthereisoverlap,thepage
willenableandpresenttheuserwiththelaunchtypesthatconflictandwhatmodestheyconflicton.
ThefollowingimageshowsthepagewithconflictingtoolingforJavatypesintherun,debugandAlternate2modes.Inthisexampleapreferredlaunchercanbeselected
independentlyforeachoftheconflictingmodes.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 186/322
12/10/2015 Javadevelopmentuserguide
Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging

LaunchingaJavaprogram
Runninganddebugging

InstalledJREsPreferences
JavaDebugPreferences
LaunchConfigurationsPreferences
LaunchingPreferences
Run/DebugPreferences

5.3.2.2.2.LaunchConfigurationsPreferences
Thefollowingpreferencescanbesetusingthe Run/Debug>Launching>LaunchConfigurationspreferencepage.
Thispageallowsyousetfilteringoptionsthatareusedthroughouttheworkbenchtolimittheexposureofcertainkindsoflaunchconfigurations.Thesefilteringsettingaffectthe
launchdialog,launchhistoriesandtheworkbench.

Option Description Default

Filterconfigurationsin Filteroutconfigurationsthatareassociatedwithaprojectthatiscurrentlyclosed On
closedprojects
Filtersconfigurationin Filteroutconfigurationsthatareassociatedwithaprojectthathasbeendeletedoraresimplynolongeravailable(notintheworkspace,etc) On
deletedormissing
projects
Applywindowsworking Appliesthefilteringfromanyworkingsetscurrentlyactivetothevisibilityofconfigurationsassociatedtoresourcesintheactiveworkingsets. On
set i.e.ifprojectPhastwoconfigurationsassociatedwithit,butisnotinthecurrentlyactiveworkingset,theconfigurationsdonotappearinthe
UI,muchlikePdoesnot.
Filtercheckconfiguration Filterallconfigurationsoftheselectedtyperegardlessoftheotherfilteringoptions.ForexampleifyouspecifytofilterJavatype Off
types configurations,allJavatypeconfigurationswillbefilteredfromtheUI,notjustonesthatfallundertheotherfilteringcategories.
Deleteconfigurations Anylaunchconfigurationsassociatedwithaprojectbeingdeletedwillalsobedeletedifthisoptionisenabled.Oncedeletedtheconfigurations On
whenassociatedproject arenotrecoverable.
isdeleted
Migration
AsEclipsematuresandnewfeaturesareaddedtothelaunchingframework,theresometimesexiststheneedtomakechangestolaunch
configurations.Someofthesechangesaremadeautomatically,butthosethatarenot(nonreversibleones)areleftuptotheenduser.
Themigrationsectionallowsuserstoselfmigrateanylaunchconfigurationsthatrequireit.UponpressingtheMigrate...button,ifthereare
anyconfigurationsrequiringmigration,theyarepresentedtotheuser,andtheusercanselecttheonestheywanttomigrate.Configuration
migrationisnotundoable.

Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging

LaunchingaJavaprogram
Runninganddebugging

DefaultLaunchersPreferences
InstalledJREsPreferences
JavaDebugPreferences
LaunchingPreferences
Run/DebugPreferences

5.3.2.3.PerspectivesPreferences
Thefollowingpreferencescanbesetusingthe Run/Debug>Perspectivespreferencepage.
Thepreferencesonthispageallowyoutosetwhich,ifanyperspectivesareautomaticallyopenedwhenlaunchersareusedincertainmodes

Option Description Default

Opentheassociatedperspective Never
whenlaunching Thisoptioncontrolsifthespecifiedperspectivewillbeswitchedtoautomaticallyornotwhenlaunching
Alwaysthespecifiedperspectivewillalwaysbeopened
Neverthespecifiedperspectivewillneverbeopened
Prompttheuserwillbepromptedtoswitchtothespecifiedperspective

Opentheassociatedperspective Prompt
Thisoptioncontrolsifthespecifiedperspectivewillbeswitchedtowhentheapplicationsuspends

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 187/322
12/10/2015 Javadevelopmentuserguide
whenanapplicationsuspends Alwaysthespecifiedperspectivewillalwaysbeopened
Neverthespecifiedperspectivewillneverbeopened
Prompttheuserwillbepromptedtoswitchtothespecifiedperspective

Launcher/Perspectivechoices Thisoptionareaallowsyoutocustomizewhatperspectivewillbeopenedforagivenlaunchandmodethatitsupports.Forexample,
youcansaythatyouwanttoopentheJavaperspectivewhenusingtheJavaJDTlauncherintherunmodeonly.

Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging

LaunchingaJavaprogram
Runninganddebugging

ConsolePreferences
InstalledJREsPreferences
JavaDebugPreferences
LaunchingPreferences
Run/DebugPreferences
StringSubstitutionPreferences
ViewManagementPreferences

5.3.2.4.StringSubstitutionPreferences
Thefollowingpreferencescanbesetusingthe Run/Debug>StringSubstitutionpreferencepage.
Thispreferencepageisusedsolelyforthepurposeofcreatingstringvariablestobereusedinotherlocationsthatacceptstringvariablesubstitution.
TheplatformSDKforEclipseusesstringvariablesinthelaunchdialogforsettingprogramandVMargumentsforcertaintypesoflaunchconfigurations,aswellasallowing
substitutionsforAnttargetsintheExternalToolslaunchdialog.ConsiderthefollowingscreenshotwhichshowstheStringSubstitutionpreferencepagewithanewTESTstring
variablecreated.

InthiscasetheTESTvariabledoesnothing,butinthe'real'worlditcouldpointtoadirectoryorprogramthatyouwouldliketoreusethepathforinconfigurations,etc.
Ifwenowwanttoleveragethisnewvariable,wecandosofromthelaunchdialogontheargumentstab(forthoseconfigurationsthathaveastandardargumentstab),byselecting
theVariables...buttonforeithertheprogramorVMargumentstextarea.SelectingtheVariablesbuttonopensadialogwithalistingofallofthestringvariablesavailable.
InthefollowingscreenshotwecanseetheTESTvariableavailableinthelist.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 188/322
12/10/2015 Javadevelopmentuserguide

WecannowselecttheTESTvariableandinsertinasanargumentifwewish,asshowninthefollowingscreenshot.

TheothermentionedplatformuseofstringsubstitutionintheExternalToolslaunchdialog,usedwithAntconfigurations,asshowninthefollowingscreenshot.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 189/322
12/10/2015 Javadevelopmentuserguide

Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging

LaunchingaJavaprogram
Runninganddebugging

ConsolePreferences
InstalledJREsPreferences
JavaDebugPreferences
LaunchingPreferences
PerspectivesPreferences
Run/DebugPreferences
ViewManagementPreferences

5.3.2.5.ViewManagementPreferences
Thefollowingpreferencescanbesetusingthe Run/Debug>ViewManagementpreferencepage.
Thesepreferencesallowyoutoconfigurewhichviewswillactivelysupportautomaticviewopening.

Option Description Default

Perspectives Thelistingofperspectivestoselectwhichoneswillsupportautomaticviewopening
Donotautomaticallyopen/closeviewswhichhavebeenmanually Thisoptioncontrolsifviewsmanuallyopened/closedwillbeaffectedbyview On
opened/closed management
Resetbutton Resetsthelistingofsupportingperspectives.

Debugger
Javaperspectives
Javaviews
Localdebugging
Remotedebugging

LaunchingaJavaprogram
Runninganddebugging

ConsolePreferences
InstalledJREsPreferences
JavaDebugPreferences
LaunchingPreferences
PerspectivesPreferences

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 190/322
12/10/2015 Javadevelopmentuserguide
Run/DebugPreferences
StringSubstitutionPreferences

5.4.1.JavadocLocationDialog
ThisdialogletsyoudefinethelocationoftheJavadocdocumentationforaJARoraJavaproject.
Youcanreachthisdialogthefollowingways:
SelectaJARorJavaproject,openthecontextmenuandselectProperties>JavadocLocationorusePropertiesfromtheFilemenu
IntheJavadocgenerationwizard,ontheStandarddocletsettingspage,chooseConfigure
JavadoccanbeattachedtoJARs,classfoldersorJavaprojects.Forprojectsitdocumentstheelementsofallsourcefolders,forJARsandclassfolders,elementscontainedinthe
JARaredocumented.Thelocationisusedby
OpenAttachedJavadocintheNavigatemenutoopentheattachedJavadocofanelement
ContextHelp(F1)topointtoaJavadoclocation
JavadocExportWizardtolinktootherdocumentationorasdefaultdestinationforaproject'sdocumentation
ValidlocationsareURLsthatpointtoafoldercontainingtheAPIdocumentation'sindex.htmlandpackagelistfile.Examplesare:

file:///M:/JAVA/JDK1.2/DOCS/API/
http://download.oracle.com/javase/6/docs/api/

Option Description Default

<empty>
Javadoc SpecifythelocationofthegeneratedJavadocdocumentation.YoucanBrowseinthelocalfilesystemforaJavadoclocation(willresultinafile://URL)
URL

Validate Validatethecurrentlocationbytryingtoaccesstheindex.htmlandpackagelistfilewiththegivenURL.Ifthevalidationwassuccessful,youcandirectly
openthedocumentation.

JavadocforJARsandclassfolderscanalsobelocatedinsideanarchiveavailableonthelocalfilesystem.Inthatcasethelocationofthearchiveaswellasthelocationofthedoc
insidethearchivehastobespecified.

Option Description Default

<empty>
Archive SpecifythelocationofthearchivethatcontainsthegeneratedJavadocdocumentation.YoucanBrowseinthelocalfilesystemforaJavadoclocation
location

<empty>
Pathwithin SpecifythepathinsidethearchivethatcontainsthegeneratedJavadocdocumentation.YoucanBrowsetoseethecontentofthearchive.
archive

Validate Validatethecurrentlocationbytryingtoaccesstheindex.htmlandpackagelistfilewiththegivenURL.Ifthevalidationwassuccessful,youcan
directlyopenthedocumentation.

5.4.2.JavaBuildPath
TheoptionsinthispageindicatethebuildpathsettingsforaJavaproject.Youcanreachthispagethroughtheprojectproperties(Project>Properties>JavaBuildPath)fromthe
contextmenuonacreatedprojectortheFilemenuoftheworkbench.
Thebuildclasspathisalistofpathsvisibletothecompilerwhenbuildingtheproject.

Sourcetab
Sourcefoldersaretoplevelfoldersintheprojecthierarchy.Theyaretherootofpackagescontaining.javafiles.Thecompilerwilltranslatethecontainedfilesto.classfilesthatwill
bewrittentotheoutputfolder.
Sourcefoldersallowtostructuretheproject,forexampletoseparatetestfromtheapplicationintwosourcefolders.Withinasourcefolder,amoredetailedstructuringcanbe
achievedbyusingpackages.
Eachsourcefoldercandefineanexclusionfiltertospecifywhichresourcesinsidethefoldershouldnotbevisibletothecompiler.
ResourcesexistinginsourcefoldersarecopiedtotheoutputfolderunlessthesettingintheJava>Compiler>Buildingpreferencepagespecifiesthattheresourceisfiltered.The
outputfolderisdefinedperprojectexceptifasourcefolderspecifiesitsownoutputfolder.
Sourcefolderoptions:
Option Description
AddFolder Createsanewfoldertocontainsource
LinkSource Createsanewfolderthatlinkstoanlocationoutsideoftheworkspace
Edit Allowstomodifythecurrentlyselectedsourcefolderorsourcefolderattribute.
Removestheselectedfoldersfromtheclasspath.Thisdoesnotdeletethe
Remove
foldersnortheircontents.
Allowoutputfolder
Shows/Hidesthe'outputfolder'attributeofthesourcefolders
persourcefolder

Sourcefolderattributes:
Attribute Description
Exclusionfilter Selectswhichresourcesarenotvisibletothecompiler.FordetailsseeInclusion
andexclusionpatterns.
Outputfolder OnlyavailablewhenAllowoutputfolderpersourcefolderischecked.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 191/322
12/10/2015 Javadevelopmentuserguide
Definesasourcefolderspecificoutputlocation.Ifnotsettheproject'sdefault
outputfolderisused.
Nativelibrary Definesthefolderthatcontainsthenativelibraries(forexample'dll'or'o'files)
location requiredatruntimebythesourcesinthesourcefolder.

Atthebottomofthispage,theDefaultoutputfolderfieldallowsyoutoenterapathtoafolderpathwherethecompilationoutputforthisprojectwillreside.Thedefaultoutputis
usedforsourcefoldersthatdonotspecifyanownoutputfolder.UseBrowsetoselectanexistinglocationfromthecurrentproject.

Projectstab
IntheRequiredprojectsonthebuildpathlist,youcanaddprojectdependenciesbyselectingotherworkbenchprojectstoaddtothebuildpathforthisnewproject.
Addingarequiredprojectindirectlyaddsallitsclasspathentriesmarkedas'exported'.SettingaclasspathentryasexportedisdoneintheOrderandExporttab.
Theprojectsselectedhereareautomaticallyaddedtothereferencedprojectslist.Thereferencedprojectlistisusedtodeterminethebuildorder.Aprojectisalwaysbuildafterallits
referencedprojectsarebuilt.

Action Description
Add Addanotherprojectintheworkspacetothebuildpathofthisproject.
Edit Edittheclasspathattributeofarequiredproject.
Remove Removestheselectedrequiredprojectsfromthelist.
Projectentryattributes:
Attribute Description
Nativelibrary Specifieswherenativelibraryrequiredfortheprojecttooperatecanbefound.
location
Accessrules Specifiesaccessrulesforprojectcontainedinthelibrary.Thisallowstohide
contentofaproject.

Librariestab
Onthispage,youcanaddlibrariestothebuildpath.
Bydefault,thelibrarylistcontainsanentryrepresentingtheJavaruntimelibrary.ThisentrypointstotheJREselectedasthedefaultJRE.ThedefaultJREisconfiguredintheJava
>Debug>InstalledJREspreferencespage.
Librariestaboptions:
Option Description
AddJARs AllowsyoutonavigatetheworkbenchhierarchyandselectJARfilestoaddto
thebuildpath.
AddExternal Allowsyoutonavigatethefilesystem(outsidetheworkbench)andselectJAR
JARs filestoaddtothebuildpath.
AddVariable Allowsyoutoaddclasspathvariablestothebuildpath.Classpathvariablesare
anindirectiontoJARswiththebenefitofavoidinglocalfilesystempathsina
classpath.Thisisneededwhenprojectsaresharedinateam.
VariablescanbecreatedandeditedintheJava>BuildPath>Classpath
Variablespreferencepage.
AllowstoaddapredefinedlibrariesliketheJRESystemLibrary.Suchlibraries
AddLibrary canstandforanarbitrarynumberofentries(visibleaschildrennodeofthe
librarynode)
Allowstonavigatetheworkbenchhierarchyandselectaclassfolderforthe
AddClassFolder
buildpath.Theselectiondialogalsoallowsyoutocreateanewfolder.
Allowstonavigatethefilesystem(outsidetheworkbench)andselectaclass
AddExternal
folderforthebuildpath.Theselectiondialogalsoallowsyoutocreateanew
ClassFolder
folder.
Edit Allowsyoutomodifythecurrentlyselectedlibraryentryorentryattribute
Remove Removestheselectedelementfromthebuildpath.Thisdoesnotdeletethe
resource.
MigrateJARFile MigrateaJARonthebuildpathtoanewerversion.Ifthenewerversion
containsrefactoringscriptstherefactoringstoredinthescriptwillbeexecuted.

Librarieshavethefollowingattributes(presentedaslibraryentrychildrennodes):
Libraryentryattributes:
Attribute Description
Source Specifieswherethelibrary'ssourcecanbefound.
attachment
Javadoclocation Specifieswherethelibrary'sJavadocdocumentationcanbefound.Ifspecified
youcanuseShift+F2onanelementofthislibrarytoopenitsdocumentation.
External Specifieswhereexternalannotationsforthelibrarycanbefound.Ifspecified
annotations theseannotationswillbeconsideredbyJDTforitsstaticnullanalysis.
Nativelibrary Specifieswherenativelibraryrequiredforthelibrarytooperatecanbefound.
location
Accessrules Specifiesaccessrulesforresourcescontainedinthelibrary.Thisallowstohide
contentofalibrary.

OrderandExporttab

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 192/322
12/10/2015 Javadevelopmentuserguide
IntheBuildclasspathorderlist,youcanclicktheUpandDownbuttonstomovetheselectedpathentryupordowninthebuildpathorderforthisnewproject.
Checkedlistentriesaremarkedasexported.Exportedentriesarevisibletoprojectsthatrequiretheproject.UsetheSelectAllandDeselectAlltochangethecheckedstateofall
entries.Sourcefoldersarealwaysexported,andcannotbedeselected.

Buildclasspath
Classpathvariables
Inclusionandexclusionpatterns

FrequentlyaskedquestionsonJDT
Classpathvariablespreferences
Buildpathpreferences
Compilerpreferences

5.4.3.JavaCompilerPage
TheoptionsinthispageindicatethecompilersettingsforaJavaproject.
Youcanreachthispagethroughthe
JavaCompilerpropertypage(File>Properties>JavaCompiler)fromthecontextmenuonacreatedprojectortheFilemenu
Aprojectcaneitherreuseworkspacedefaultsettingsoruseitsowncustomsettings.

Option Description

Enableproject Onceselected,compilersettingscanbeconfiguredforthisproject.AllJavacompilerpreferencescanbecustomized.Atanytime,itispossibletorevertto
specificsettings workspacedefaults,byusingthebuttonRestoreDefaults.

Buildclasspath

Javacompilerpreferences
JavaBuildPathproperties
FrequentlyaskedquestionsonJDT

5.4.4.JavaTaskTagsPage
TheoptionsinthispageindicatethetasktagsforaJavaproject.
Youcanreachthispagethroughthe
Javatasktagspropertypage(File>Properties>JavaCompiler>TaskTags)fromthecontextmenuonacreatedprojectortheFilemenu
Aprojectcaneitherreuseworkspacedefaultsettingsoruseitsowncustomsettings.

Option Description

Enableprojectspecific Onceselected,tasktagscanbeconfiguredforthisprojectasintheTasktagspreferencepage.Atanytime,itispossibletoreverttoworkspace
settings defaults,byusingthebuttonRestoreDefaults.

Tasktagpreferences

5.4.5.SourceAttachmentPropertyPage
Tobrowsethesourceofatypecontainedinlibraryyoucanattachasourcearchiveorsourcefoldertothislibrary.Theeditorwillthenshowthesourceinsteadofthedecompiled
code.Settingthesourceattachmentalsoallowssourcelevelsteppingwiththedebugger.
TheSourceAttachmentdialogcanbereachedinseveralways:
SelectaJARinthePackageExplorerandchooseProperties>JavaSourceAttachmentfromthecontextmenuortheProjectmenu
OpentheJavaBuildPathpageofaproject(Projects>Properties>JavaBuildPath).OntheLibrariespageexpandthelibrary'snodeandselecttheSourceattachment
attributeandpressEdit
Openaneditoronaclassfile.IfthesourceattachmenthasnotalreadybeenconfiguredforthisJAR,theeditorcontainsabuttonAttachSource
DependingofhowaJARwascontributedtotheclasspath,youcanseedifferenttypesofSourceattachmentdialogs:

JAR
InthePathfield,enterthepathofanarchiveorafoldercontainingthesource.UseeithertheWorkspace,ExternalFileortheExternalFolderbuttontobrowseforalocation.
ForasourceattachmentinanexternallocationyoucanalsospecifyanoptionalEncodingforreadingthesourceattachment.Bydefaulttheworkspaceencodingisused.

Variable
IntheLocationVariablePathfieldenteravariablepaththatpointstothesourceattachment'slocation.Avariablepathhasasfirstsegmentavariable(whichwillresolvetoafolder
orfile),therestisanoptionalpathextension(e.g.MYVARIABLE/src.jar).UseeithertheVariablebuttontoselectanexistingvariableandtheExtensionbuttontoselectthe
extensionpath.TheExtensionbuttonisonlyenabledwhenthevariablecanbeextended(resolvestoafolder)
JRE_SRCisareservedvariablethatpointstoaJREselectedintheInstalledJREspreferencepage( Java>InstalledJREs).Gotothispreferencepagetoconfigurethesource

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 193/322
12/10/2015 Javadevelopmentuserguide
attachmentfortheJRE'slibrary..

Buildclasspath

InstalledJREspreferences
Javabuildpathproperties

5.4.6.Run/DebugPropertiesPage
Thispropertypageallowsyoutoviewandmanagealllaunchconfigurationsthatapplytothepages'correspondingresource.

Option Description
Launch Thelistshowsallofthelaunchconfigurationsinthecurrentworkspacethatapplytothepropertypages'correspondingresource.
Configuration
List
New... TheNew...buttoncanbeusedtocreateanewlaunchconfigurationthatappliestothecorrespondingresource.Whenselected,theNew...buttonwillpresentyou
withadialogofallofthelaunchconfigurationtypesthatcanbeusedtomakeaconfigurationthatappliestothecorrespondingresource.
Duplicate TheDuplicatebuttonisusedtomakeanidenticalcopyofaselectedlaunchconfiguration.
Edit... TheEdit...buttonwillopenthelaunchconfigurationeditdialog,allowingyoutochangetheselectedlaunchconfiguration.
Delete TheDeletebuttonisusedtodeletetheselectedlaunchconfiguration.

LocalDebugging
RemoteDebugging

LaunchingaJavaProgram
LaunchingaJavaprogramindebugmode
PreparingtoDebug
Relaunchingaprogram
LaunchingaJavaapplet
DisconnectingfromaVM
UsingtheremoteJavaapplicationlaunchconfiguration

RunandDebugtoolbaractions

5.5.2.RefactoringWizard
Adialogbaseduserinterfaceguidesyouthroughthestepsnecessarytoexecuteaselectedrefactoring.Dependingonthecomplexityoftherefactoring,eitherawizardorasimple
dialogisusedtogatherinformationthatisrequiredfortherefactoring.

Inputpages
Theinputpagesgatherinformationthatisrequiredfortherefactoring.AfteryouhaveprovidedtherequiredinputyoucanclickOkorFinishtocarryouttherefactoringwithout
previewingtheresults.IfyouwanttopreviewthechangespressPrevieworNext

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 194/322
12/10/2015 Javadevelopmentuserguide
Previewpage
TheJDTallowsyoutopreviewtheresultsofarefactoringactionbeforeyouexecuteit.
Thepreviewpageconsistsoftwoparts:
AtreeatthetopcontainingallJavaelementsaffectedbytherefactoring.Eachtoplevelnodeinthetreerepresentsonecompilationunit.
Somerefactoringsallowtofilterthetreebydifferentkindofchangesmadebytherefactoring.UsetheFilterChangesdropdowntochangethefiltering.
Acomparevieweratthebottom.Theleftsideofthecompareviewershowstheoriginal,therightsidedisplaystherefactoredsource.

Problempage
TheRefactoringProblempageindicatesiftherearesuspected,potential,ordefiniteproblemswiththerefactoringactionyouareattempting.
Fourtypesofproblemsarepossible:
Information
AproblemdescribedasInformationwillnotaffecttherefactoringinanyway,norwillitnegativelyaffectthecodeintheworkbench.Youcanmostlikelyignorethistypeof
problem.
Warnings
Warningsattempttopredictcompilewarnings.Thistypeofproblemmostlikelywillnotnegativelyaffectthecodeinyourworkbench.
Errors
AproblemdescribedasanErrorisverylikelytocausecompileerrorsorchangeyourworkbenchcodesemantically.Youcanchoosetocontinuewiththerefactoringinspiteof
theseerrors,althoughitisnotrecommended.
Stopproblems
Thistypeofproblempreventstherefactoringfromtakingplace.Forexample,ifyouselectacommentandchoosetheExtractMethodcommandfromit,theworkbenchwill
issueastopproblemontherefactoringattemptbecauseyoucannotextractacomment.
Iftherearen'tanystopproblemsthentherefactoringcanbecarriedoutbypressingtheFinishbutton.Topreviewtheresultsoftherefactoringaction,presstheNext>button.

RefactoringwithoutDialog
ItisalsopossibletorenameaJavaelementwithoutshowingadialog.ThiscanbeenabledanddisabledontheJavapreferencepage.Ifenabled,thenthenewnameforanJava
elementcanbetypedintotheeditorwhentherenamerefactoringisinvoked.

Refactoringsupport

Refactoringactions
Icons

5.5.3.ExtractMethodErrors
Whenyouattempttoextractamethod,youmaygetoneormoreofthefollowingcommonerrors:
SelectedblockreferencesalocaltypedeclaredoutsidetheselectionAlocaltypedeclarationisnotpartoftheselectionbutisreferencedbyoneofthe
statementsselectedforextraction.Eitherextendtheselectionthatitincludesthelocaltypedeclarationorreducetheselectionthatnoreferencetothelocaltypedeclarationis
selected.
AlocaltypedeclaredintheselectedblockisreferencedoutsidetheselectionTheselectioncoversalocaltypedeclarationbutthetypeisalsoreferenced
outsidetheselectedstatements.Eitherextendtheselectionthatisincludesallreferencestothelocaltypeorreducetheselectionthatthelocaltypedeclarationisn'tselected.
Ambiguousreturnvalue:selectedblockcontainsmorethanoneassignmenttolocalvariableMorethanoneassignmenttoalocalvariablewasfoundinsidethe
selectedblock.Eitherreducetheselectionthatonlyoneassignmentisselectedorextendtheselectionthatatleastallreferenceexceptofonetothelocalvariablesare
coveredbytheselectiontoo.
Ambiguousreturnvalue:expressionaccesstolocalandreturnstatementselectedTheselectedstatementgeneratesmorethanonereturnvalue.Thisisfor
examplethecaseifanexpressionisselectedandanexpression'sargumentismodifiedaswell.Toremedythisproblemextendtheselectiontocoverthereadaccessofthe
modifiedargumentaswell.
Selectioncontainsabreakstatementbutthecorrespondingbreaktargetisn'tselectedToremedytheproblemeitherextendtheselectiontoincludethebreak/
continuetargetorreducetheselectionthatthebreak/continuestatementisn'tcoveredbytheselection.
Selectioncontainsacontinuestatementbutthecorrespondingcontinuetargetisn'tselectedToremedytheproblemeitherextendtheselectiontoincludethe
break/continuetargetorreducetheselectionthatthebreak/continuestatementisn'tcoveredbytheselection.
SelectionstartsinsideacommentPartsofacommentcannotbeextracted.Eitherextendtheselectionthatitcoversthewholecommentorreducetheselectionthatthe
commentisn'tcoveredatall.
SelectionendsinsideacommentPartsofacommentcan'tbeextracted.Eitherextendtheselectionthatitcoversthewholecommentorreducetheselectionthatthe
commentisn'tcoveredatall.
CannotextractselectionthatendsinthemiddleofastatementAdjustselectionsothatitfullycoversasetofstatementsorexpressions.Theuserscanextend
theselectiontoavalidrangeusingtheExpandSelectiontointheEditmenu.

Javadevelopmenttools(JDT)
Refactoringsupport

Sourcemenu
Refactormenu

5.6.1.JavaSearchTab
ThistabintheSearchdialogallowsyoutosearchforJavaelements.ToshowthetabinvokeSearch>Java.

Searchstring

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 195/322
12/10/2015 Javadevelopmentuserguide
Inthisfield,typetheexpressionforwhichyouwishtosearch,usingthewildcardcharactersmentionedinthedialogasneeded.Thisfieldisinitializedbasedonthecurrentselection.
Typepatternshavethefollowingsyntax:
[qualification'.']typeName['<'typeArguments'>']
Examples:
java.lang.Object
Runnable
List<String>

Typeargumentscanbespecifiedtosearchforreferencestoparameterizedtypesusingfollowingsyntax:
'<'{['?'{'extends'|'super'}]type(','['?'{'extends'|'super'}]type)*|'?'}'>'
Notethat:
'*'isnotvalidinsidetypeargumentsdefinition<>
'?'istreatedasawildcardwhenitisinside<>(i.e.itmustbeputonfirstpositionofthetypeargument)

Methodpatternshavethefollowingsyntax:
[declaringType'.']['<'typeArguments'>']methodName['('parameterTypes')'][returnType]
Typeargumentshavethesamesyntaxasexplainedinthetypepatternssection.
Examples:
java.lang.Runnable.run()void
main(*)
<String>toArray(String[])

Constructorpatternshavethefollowingsyntax:
['<'typeArguments'>'][declaringQualification'.']typeName['('parameterTypes')']
Typeargumentshavethesamesyntaxasexplainedinthetypepatternssection.
Notethattheconstructornameshouldnotbeenteredasitisalwaysthesameasthetypename.
Examples:
java.lang.Object()
Test(*)
<Exception>Sample(Exception)

Fieldpatternshavethefollowingsyntax:
[declaringType'.']fieldName[fieldType]
Examples:
java.lang.String.serialVersionUIDlong
field*

Packagepatternshavethefollowingsyntax:
packageNameSegment{'.'packageNameSegment}
Examples:
java.lang
org.e*.jdt.c*e

SearchFor
Selecttosearchforoneofthefollowingkindsofelements:
Type
Method
Package
Constructor
Field

LimitTo
Selecttolimityoursearchresultstooneofthefollowingkindsofmatches:
Declarations
Implementors(availableonlywhensearchingfortypes)
References
Alloccurrences
Readaccess(availableonlywhensearchingforfields)
Writeaccess(availableonlywhensearchingforfields)
Matchlocations(availableonlywhensearchingfortypesormethodsreferences).
Matchlocationsallowtofurthernarrowthelocationofmatches.
Selectthelocationwheretosearchfor:
typereference:
Superclassdeclarations
Annotations
Fieldtypes

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 196/322
12/10/2015 Javadevelopmentuserguide
Localvariabletypes
Methodreturntypes
Methodparametertypes
Thrownexceptiontypes
Typeparameterbounds
Wildcardbounds
Typeargument
Castexpressions
Catchclauses
Classinstancecreations
'instanceof'checks
methodreference:
'this.'references
Implicit'this.'references
'super.'references
Qualifiedreferences
'::'methodreferences

SearchIn
Selectwhereinthescopetosearchforresults
Sources:Searchinallsourcefilesinthescope
Requiredprojects:Searchinallrequiredprojects
JRElibraries:SearchinJRElibrariesonthebuildpath
Applicationlibraries:Searchinlibrariesonthebuildpath

Scope
Selecttolimityoursearchresultstooneofthefollowingscope
Workspace
Selectedresources
EnclosingProjects
WorkingSet
PressChoosetoselectorcreateaworkingset.

Searchresultview,filters
ThesearchresultsarepresentedintheSearchview.
TheViewMenucontainstheseoptions:
ShowAsList
Presentsresultsinaflatlist.Inthismode,thecontextmenucontainsaSortBymenuwithoptionsName,Path,ParentName.
ShowasTree
Presentsresultsinahierarchy.Inthismode,4buttonsappearintheviewtoolbar,whereyoucanGroupbyProject,Package,File,orType.
Filters
Variousfiltersallowtoexcludecertainsearchresults,forexamplepotentialmatches,matchesinimports,Javadocs,deprecated,nonpublic,staticornonstaticelements.
Fortypes,therearefiltersforinexactornonmatchingtypearguments.
Formethods,there'safilterforreferencestooverridingmethods.
Forfields,therearefiltersforreadorwriteaccesses.

Javasearch

Search

5.8.JavaViewsandEditors

Javaeditor
Javaviews
Javadevelopmenttools(JDT)

Changingtheappearanceoftheconsoleview
Openinganeditorforaselectedelement
Openinganeditoronatype

Javaeditoractions
Breakpointsview
Consoleview
Debugview
Displayview

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 197/322
12/10/2015 Javadevelopmentuserguide
Expressionsview
Javaeditor
PackageExplorerview
Variablesview
Javaoutline
JavascrapbookPage
TypeHierarchyview
CallHierarchyview

5.8.1.BreakpointsView
TheBreakpointsViewlistsallthebreakpointsyoucurrentlyhavesetinyourworkspace.
Youcandoubleclickabreakpointtodisplayitslocationintheeditor(ifapplicable).Youcanalsoenableordisablebreakpoints,deletethem,addnewones,groupthembyworking
set,orsethitcounts.
IntheexampleshownbelowtheGroupby>BreakpointTypesoptionisturnedon.

ThebreakpointsviewdisplaysdetailsoftheselectedbreakpointandcanbeusedtoconfigureattributesoftheselectedbreakpointsimilartotheBreakpointProperties...action.The
orientationofthedetailpanecanbeconfiguredfromtheviewdropdownmenu.

ThecommandsavailableintheBreakpointsViewarelistedbelow.
BreakpointsViewCommands

Command Name Description Availability

Access Changesiftheselectedwatchpointshouldsuspendonaccesstoitsassociatedfield. Contextmenu


AddExceptionBreakpoint Opensthecreateexceptionbreakpointdialog. Viewaction

BreakpointProperties... Opensthebreakpointspropertiesdialog. Contextmenu


Caught Changesiftheselectedexceptionbreakpointshouldsuspendwhenthespecifiedtypeof Contextmenu
exceptioniscaught.
CollapseAll Collapsesalloftheitemsintheview. Viewaction

Copy Copiestheselectedbreakpointstothesystemclipboard. Contextmenu

Disable Changestheselectedbreakpoint(s)tobedisabled. Contextmenu

Enable Changestheselectedbreakpoint(s)tobeenabled. Contextmenu

Entry Changesiftheselectedmethodbreakpointshouldsuspendonentrytotheassociated Contextmenu


method.
Exit Changesiftheselectedmethodbreakpointshouldsuspendonexitfromtheassociated Contextmenu
method.
ExpandAll Expandsalloftheitemsintheview. Viewaction

ExportBreakpoints... Openstheexportbreakpointswizard. Contextmenu

GotoFile Opensthecorrespondinglocationofthebreakpointinthejavaeditor. Contextmenuandviewaction

GroupBy... Allowsyoutoselectanalternategroupingforyourbreakpointsorcreateyourown. Viewaction


HitCount Allowsyoutosetorchangethehitcountfortheselectedbreakpoint. Contextmenu

ImportBreakpoints... Openstheimportbreakpointswizard. Contextmenu

LinkwithView ChangesifthebreakpointsshouldbelinkedtotheDebugView. Viewaction

Modification Changesiftheselectedwatchpointshouldsuspendwhenitsassociatedfieldismodified. Contextmenu

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 198/322
12/10/2015 Javadevelopmentuserguide
Paste Pastescopiedbreakpointsintotheview. Contextmenu

RemoveAll Removesallbreakpointsfromtheview. Contextmenuandviewaction

RemoveSelectedBreakpoints Removesonlytheselectedbreakpoint(s)fromtheview. Contextmenuandviewaction

SelectAll Selectsallofthebreakpointsintheview. Contextmenu


SelectDefaultWorkingSet Allowsyoutochoosewhichworkingsetwillbethedefaultone. Viewaction

ShowQualifiedNames Changesifqualifiednamesareshownornot. Viewaction

ShowSupportedBreakpoints Changesifonlysupportedbreakpointsshouldbeshownornot. Viewaction

SkipAll Setsallbreakpointstobeskipped. Viewaction

Suspend Allowsyoutochoosewhattosuspendwhentheselectedbreakpointishit. Contextmenu

Uncaught Changesiftheselectedexceptionbreakpointshouldsuspendwhenthespecifiedtypeof Contextmenu


exceptionisnotcaught.
WorkingSets... Openstheworkingsetsdialog. Viewaction

Breakpoints
Javaviews
Javaperspectives

Addingbreakpoints
Applyinghitcounts
CatchingJavaexceptions
Removingbreakpoints
Enablinganddisablingbreakpoints
Managingconditionalbreakpoints
Settingmethodbreakpoints

Viewsandeditors

5.8.1.1.WatchpointAccess
SelecttheAccesscommandtochangeifthecurrentlyselectedwatchpointwillsuspendwhenitsassociatedfieldisaccessedorread.

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

BreakpointsView
WatchpointAccessOption

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 199/322
12/10/2015 Javadevelopmentuserguide
5.8.1.2.AddJavaExceptionBreakpoint
SelecttheAddExceptionBreakpointcommand[ ]toaddaJavaexceptionbreakpoint.
Intheresultingdialog:
IntheChooseanExceptionfield,typeastringthatiscontainedinthenameoftheexceptionyouwanttoadd.Youcanusewildcardsasneeded("*"foranystringand"?"for
anycharacter).
IntheMatchingtypeslist,selecttheexceptionyouwanttoadd.
SelectCaughtandUncaughtasneededtoindicateonwhichexceptiontypeyouwanttosuspendtheprogram.
TheAddJavaExceptionBreakpointDialog.

Breakpoints

CatchingJavaexceptions
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

BreakpointsView
RunMenu
CaughtExceptionOption
UncaughtExceptionOption

5.8.1.3.BreakpointProperties...
SelecttheBreakpointProperties...commandtoopenthebreakpointpropertiesdialogforthecurrentlyselectedbreakpoint.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 200/322
12/10/2015 Javadevelopmentuserguide

Thereareseparatepropertiesforeachtypeofbreakpoint,thusresultinginvaryingpropertiesdialogs.Theexamplegivenbelowisforalinebreakpoint.

Addingbreakpoints
Applyinghitcounts
CatchingJavaexceptions
Removingbreakpoints
Enablinganddisablingbreakpoints
Managingconditionalbreakpoints
Settingmethodbreakpoints

BreakpointsView
Conditionoption
Enabledoption
Hitcountoption
Exceptionbreakpointcaughtoption
Exceptionbreakpointsuspendonsubclassoption
Exceptionbreakpointuncaughtoption
Methodbreakpointentryoption
Methodbreakpointexitoption
SuspendPolicy
Watchpointaccessoption
Watchpointmodificationoption

5.8.1.4.ExceptionBreakpointCaught
SelecttheCaughtcommandtochangeifthecurrentlyselectedJavaexceptionbreakpointwillsuspendoncaughtexceptionsofthesametype.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 201/322
12/10/2015 Javadevelopmentuserguide

Breakpoints

Addingbreakpoints
CatchingJavaexceptions
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

BreakpointsView
CaughtExceptionOption

5.8.1.5.CollapseAll
SelecttheCollapseAllcommand[ ]tocollapseallofthecurrentlyelementsintheview.
Thiscommandappliesto:
BreakpointsView
ExpressionsView
RegistersView
VariablesView

5.8.1.6.Copy
SelecttheCopycommand[ ]tocopytheselectedcontentsfromtheviewontothesystemclipboard.YoucanalsousethestandardkeyboardshortcutCtrl+C.
Thiscommandappliesto:
BreakpointsView
ConsoleView
DebugView
DisplayView
ExpressionsView
RegistersView
VariablesView
DetailPane(intheExpressionsViewandVariablesView)

5.8.1.7.DisableBreakpoints
SelecttheDisablecommand[ ]todisablethecurrentlyselectedbreakpoint(s).

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 202/322
12/10/2015 Javadevelopmentuserguide

BreakpointsView
BreakpointEnabledOption

5.8.1.8.EnableBreakpoints
SelecttheEnablecommand[ ]toenablethecurrentlyselectedbreakpoint(s).

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

BreakpointsView
BreakpointEnabledOption

5.8.1.9.MethodBreakpointEntry
SelecttheEntrycommandtochangeiftheselectedmethodbreakpointwillsuspendonentrytotheassociatedmethod.

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

BreakpointsView
MethodBreakpointEntryOption

5.8.1.10.MethodBreakpointExit
SelecttheExitcommandtochangeiftheselectedmethodbreakpointwillsuspendonexitfromtheassociatedmethod.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 203/322
12/10/2015 Javadevelopmentuserguide

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

BreakpointsView
MethodBreakpointExitOption

5.8.1.11.ExpandAll
SelecttheExpandAllcommand[ ]toexpandalloftheitemsintheBreakpointsView.

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

BreakpointsView

5.8.1.12.ExportBreakpoints
SelecttheExportBreakpoints...command[ ]tostartthe ExportBreakpointswizardwhichwillhelpyouexportbreakpointstoafile.

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

BreakpointsView
ExportBreakpointswizard
ImportBreakpointswizard
ImportBreakpointscommand

5.8.1.13.GotoFileforBreakpoint

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 204/322
12/10/2015 Javadevelopmentuserguide
SelecttheGotoFilecommand[ ]toopentheassociatedresourceforthebreakpoint,makeitactiveandhighlightthelocationofthebreakpoint.Iftheresourceisalreadyopenit
ismadeactiveandthebreakpointlocationishighlighted.

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

BreakpointsView

5.8.1.14.GroupBreakpointsBy
SelecttheGroupByviewmenuitemtogroupthebreakpointsintheBreakpointsViewinoneofachoiceofpredefinedorderings.

Theorderingsareasfollows:
Breakpointsastandardlistofallbreakpoints
BreakpointTypesallbreakpointsorganizedintotheirrespectivetypes
BreakpointWorkingSetsallbreakpointsareorganizedintotheworkingsetstheybelongto
Filesallbreakpointsareorganizedbythefilesthattheybelongto
Projectsallbreakpointsareorganizedbytheprojectthattheybelongto
ResourceWorkingSetsallbreakpointsareorganizedbytheresourceworkingsetsthattheybelongto
Advanced...Seebelow.
TheAdvanced...commandopensadialogthatallowsyoutospecifymultiplelevelsofgroupingsforyourbreakpoints.Forexampleyoucouldhavebreakpointgroupedbytype,
whicharethenfurthergroupedbyresourceworkingset,whicharethenfurthergroupedbyprojects.
BelowistheGroupBreakpointsdialog.

Breakpoints

Addingbreakpoints
Createabreakpointworkingset
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 205/322
12/10/2015 Javadevelopmentuserguide

BreakpointsView

5.8.1.15.BreakpointHitCount
SelecttheHitCountcommand[ ]toeditthehitcountforthecurrentlyselectedbreakpoint.
ThecommandopenstheSetBreakpointHitCountdialogwhichallowsyoutoenteranintegervaluehitcounttoapplytotheselectedbreakpoint.
TheSetBreakpointHitCountDialog.

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

BreakpointsView
BreakpointHitCountOption

5.8.1.16.ImportBreakpoints
SelecttheImportBreakpoints...command[ ]tostartthe ImportBreakpointswizardwhichwillhelpyouimportbreakpointsintoyourworkspace.

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

BreakpointsView
ExportBreakpointswizard
ImportBreakpointswizard
ExportBreakpointscommand

5.8.1.17.LinkBreakpointsViewwithDebugView
SelecttheLinkwithDebugViewcommand[ ]tohavetheBreakpointsViewbeupdatedwithinformationfromtheDebugView.Whenanapplicationsuspendsonabreakpoint
intheDebugView,theassociatedbreakpointwillbehighlightedintheBreakpointsView.

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

BreakpointsView

5.8.1.18.WatchpointModification
SelecttheModificationcommandtochangeifthecurrentlyselectedwatchpointwillsuspendwhenitsassociatedfieldismodifiedorwrittento.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 206/322
12/10/2015 Javadevelopmentuserguide

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

BreakpointsView
WatchpointModificationOption

5.8.1.19.Paste
SelectthePastecommand[ ]tocopymaterialfromthesystemclipboardintothecurrentview.YoucanalsousethestandardkeyboardshortcutCtrl+V.
Thiscommandappliesto:
BreakpointsView
ConsoleView
DisplayView
DetailPane(intheExpressionsViewandVariablesView)

5.8.1.20.RemoveSelectedBreakpoint
SelecttheRemovecommand[ ]toremovetheselectedbreakpoint(s)fromtheBreakpointsView.

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

BreakpointsView

5.8.1.21.RemoveAllBreakpoints
SelecttheRemoveAllcommand[ ]toremoveallbreakpointsfromtheBreakpointsView.

Breakpoints

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 207/322
12/10/2015 Javadevelopmentuserguide
Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

BreakpointsView

5.8.1.22.SelectAll
Choosethiscommandtoselectallofthecontentintheview.YoucanalsousethestandardkeyboardshortcutCtrl+A.
Thiscommandappliesto:
BreakpointsView
ConsoleView
DisplayView
ExpressionsView
RegistersView
VariablesView
DetailPane(intheExpressionsViewandVariablesView)

5.8.1.23.SelectDefaultBreakpointWorkingSet
ChoosetheSelectDefaultWorkingSet...command[ ]toselectadefaultworkingset.
ThecommandopenstheSelectDefaultWorkingSetdialog,whichisthenusedtoselectaworkingsettobethedefault.

Breakpoints

Addingbreakpoints
CreateWorkingset
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

BreakpointsView

5.8.1.24.ShowQualifiedNames
SelecttheShowQualifiedNamescommand[ ]thechangewhetherqualifiednamesshouldbeshownintheviewornot.
Thiscommandappliesto:
BreakpointsView
ExpressionsView
VariablesView

ViewDisplayCommands

5.8.1.25.ShowSupportedBreakpoints
SelecttheShowSupportedBreakpointscommand[ ]toindicateifonlybreakpointsapplicabletothecurrentdebugtargetshouldbevisibleintheBreakpointsView.
Example:IfyouhaveC/C++andJavabreakpoints,withthisoptionturnedonyouwillonlyseethosebreakpointsapplicabletowhatyouarecurrentlydebugging.Meaningthatwhen
youaredebuggingaJavaprogramtheBreakpointsViewwillonlydisplayJavabreakpoints.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 208/322
12/10/2015 Javadevelopmentuserguide

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

BreakpointsView

5.8.1.26.SkipAllBreakpoints
SelecttheSkipAllBreakpointscommand[ ]tomarkallbreakpointsinthecurrentviewasskipped.Breakpointsmarkedasskippedwillnotsuspendexecution.
TheBreakpointsViewshowingallbreakpointsmarkedasskipped.

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

BreakpointsView

5.8.1.27.BreakpointSuspend
SelecttheSuspendcommand[ ]tochangethesuspendpolicyofabreakpointbetweensuspendingtheentireVMandthethreadinwhichthebreakpointsuspended.
Thereisonlyonemenuitemvisibleatanyonegiventime,showingyouwhichsuspendpolicyyouwillbechangingtoshouldyouselectit.
Youcanchangethedefaultsuspendpolicyforallnewlycreatedbreakpointsonthe Java>Debugpreferencepage.

Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

BreakpointsView
BreakpointSuspendPolicyOption

5.8.1.28.BreakpointViewWorkingSets
SelecttheWorkingSets...commandtoopentheworkingsetsdialog,whichallowsyoutoadd/remove/editworkingsets.
TheWorkingSet...command.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 209/322
12/10/2015 Javadevelopmentuserguide

TheSelectWorkingSetdialog.

Breakpoints

Addingbreakpoints
CreateWorkingset
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

BreakpointsView

5.8.1.29.ExceptionBreakpointUncaught
SelecttheUncaughtcommandtochangeiftheselectedJavaexceptionbreakpointwillsuspendforuncaughtexceptionsofthesametype.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 210/322
12/10/2015 Javadevelopmentuserguide
Breakpoints

Addingbreakpoints
Removingbreakpoints
LaunchingaJavaprogram
Runninganddebugging

BreakpointsView
ExceptionBreakpointUncaughtOption

5.8.2.ConsoleView
TheConsoleViewdisplaysavarietyofconsoletypesdependingonthetypeofdevelopmentandthecurrentsetofusersettings.

ThethreeconsolesthatareprovidedbydefaultwiththeEclipsePlatformare:
TheProcessConsole
TheStacktraceConsole
TheCVSConsole
Youcanchangesettingsforconsolesonthe Run/Debug>Consolepreferencepage.
ThecommandsavailableintheConsoleViewarelistedbelow.
ConsoleViewCommands

Command Name Description Availability

Contextmenuandviewaction
ClearConsole Clearsthecurrentlyactiveconsole,andisavailableasbothaviewcommandanda
contextualmenuitem.

DisplaySelectedConsole Opensalistingofcurrentconsolesandallowsyoutoselectwhichoneyouwouldliketo Viewaction


see.
OpenConsole Opensanewconsoleoftheselectedtype. Viewaction

Pin Pinsthecurrentconsoletoremainontopofallotherconsoles. Viewaction

ScrollLock Changesifscrolllockshouldbeenabledornotinthecurrentconsole. Contextmenuandviewaction

Javaviews
Javaperspectives

Changingtheappearanceoftheconsoleview
Viewsandeditors

ConsolePreferences
CVSConsole
ProcessConsole
StacktraceConsole
Viewsandeditors

5.8.2.1.CVSConsole
TheCVSConsoledisplaystheoutputfromcurrentandrecentCVSoperations.

TheextracommandsavailableintheCVSConsolearelistedbelow.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 211/322
12/10/2015 Javadevelopmentuserguide
CVSConsoleCommands

Command Name Description Availability

Copy Copiestheselectedmaterialfromtheconsoleontothesystemclipboard. Contextmenu

Cut Copiestheselectedmaterialtothesystemclipboardandremovesitfromtheconsole. Contextmenu

Find/Replace Allowsyoutosearchforandreplaceaspecifiedexpression. Contextmenu


OpenLink Allowsyoutofollowthehyperlinkwhichwasrightclickedoninthecurrentstacktrace. Contextmenu
Paste Pastesmaterialsavedonthesystemclipboardintothecurrentconsole. Contextmenu

SelectAll Selectsallofthecontentsofthecurrentconsole. Contextmenu

Javaviews
Javaperspectives

Changingtheappearanceoftheconsoleview
Viewsandeditors

ConsoleView
ProcessConsole
StacktraceConsole

5.8.2.1.2.Cut
SelecttheCutcommand[ ]tocopytheselectedcontentsfromtheviewtothesystemclipboardandremovetheselectionfromtheview.Youcanalsousethestandardkeyboard
shortcutCtrl+X.
Thiscommandappliesto:
ConsoleView
DisplayView
DetailPane(intheExpressionsViewandVariablesView)

5.8.2.1.3.Find/Replace
SelecttheFind/Replacecommandtosearchforandreplacespecificstatementsorportionsofstatements.YoucanalsousethekeyboardshortcutCtrl+F.
Theresultingfind/replacedialog.

Thiscommandappliesto:
ConsoleView
DisplayView
DetailPane(intheExpressionsViewandVariablesView)

5.8.2.1.4.OpenLink
SelecttheOpenLinkcommandtofollowadetectedhyperlinkintheStacktraceConsoleortheCVSConsole.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 212/322
12/10/2015 Javadevelopmentuserguide

Javaviews
Javaperspectives

Changingtheappearanceoftheconsoleview
Viewsandeditors

ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole

5.8.2.2.ProcessConsole
TheProcessConsoleshowstheoutputofaprocessandallowsyoutoprovidekeyboardinputtoaprocess.

TheProcessConsoleshowsthreedifferentkindsoftext:
Standardoutput
Standarderror
Standardinput
Youcanchoosethedifferentcolorsforthesekindsoftextonthe Run/Debug>Consolepreferencepage.
TheextracommandsavailableintheProcessConsolearelistedbelow.
ProcessConsoleCommands

Command Name Description Availability

Copy Copiestheselectedmaterialfromtheconsoleontothesystemclipboard. Contextmenu

Cut Copiestheselectedmaterialtothesystemclipboardandremovesitfromtheconsole. Contextmenu

Find/Replace Allowsyoutosearchforandreplacesspecifiedexpression. Contextmenu


Paste Pastesmaterialsavedonthesystemclipboardintothecurrentconsole. Contextmenu

Preferences... OpenstheConsolePreferencePage,allowingyoutocustomizeyouconsoles. Contextmenu


RemoveAllTerminated Removesalloftheterminatedlaunchesfromthecurrentconsole. Contextmenuandviewaction
Launches
RemoveLaunch Removesthecurrentlaunchfromtheconsole. Viewaction

Terminate Terminatestherunninglaunchinthecurrentconsole. Viewaction

SelectAll Selectsallofthecontentsofthecurrentconsole. Contextmenu


ShowConsoleWhenStandard Willopen(ifneeded)andbringaconsoletothefrontwheninformationiswrittentothe ViewAction
OutChanges System.outstream
ShowConsoleWhenStandard Willopen(ifneeded)andbringaconsoletothefrontwheninformationiswrittentothe ViewAction
ErrorChanges System.errstream

Javaviews
Javaperspectives

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 213/322
12/10/2015 Javadevelopmentuserguide

Changingtheappearanceoftheconsoleview
Viewsandeditors

ConsoleView
StacktraceConsole
CVSConsole

5.8.2.2.3.ConsolePreferences
SelectthePreferences...commandtoopenthe Run/Debug>Consolepreferencepage.
ThiscommandonlyappliestotheProcessConsole.

Javaviews
Javaperspectives

Changingtheappearanceoftheconsoleview
Viewsandeditors

ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole

5.8.2.2.6.RemoveAllTerminatedLaunches
SelecttheRemoveAllTerminatedcommand[ ]toremovealloftheterminatedlaunchesfromtheProcessConsole.

Javaviews
Javaperspectives

Changingtheappearanceoftheconsoleview
Viewsandeditors

ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole

5.8.2.2.7.RemoveLaunch
SelecttheRemoveLaunchcommand[ ]toremovethecurrentlaunchfromtheProcessConsole.

Javaviews
Javaperspectives

Changingtheappearanceoftheconsoleview
Viewsandeditors

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 214/322
12/10/2015 Javadevelopmentuserguide

ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole

5.8.2.2.9.ShowConsoleWhenStandardOutChanges
SelecttheShowConsoleWhenStandardOutChangescommand[ ]tohaveaconsoleopened(ifnotopenalready)andbroughttothefrontiftheassociatedprocessofthe
currentProcessConsolewritestoStandard.out.

Javaviews
Javaperspectives

Changingtheappearanceoftheconsoleview
Viewsandeditors

ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole

5.8.2.2.10.ShowConsoleWhenStandardErrorChanges
SelecttheShowConsoleWhenStandardErrorChangescommand[ ]tohaveaconsoleopened(ifnotopenalready)andbroughttothefrontiftheassociatedprocessofthe
currentProcessConsolewritestoStandard.err.

Javaviews
Javaperspectives

Changingtheappearanceoftheconsoleview
Viewsandeditors

ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole

5.8.2.2.11.Terminate
SelecttheTerminatecommand[ ]toterminatetheprocessthatisassociatedwiththecurrentProcessConsole.

Javaviews
Javaperspectives

Changingtheappearanceoftheconsoleview
Viewsandeditors

ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole

5.8.2.3.StacktraceConsole
TheStacktraceConsoledisplaysaJavastacktraceinanicelyformattedmanner,providinghyperlinksupporttoquicklyjumptosourcecodelocations.

TheextracommandsavailableintheStacktraceConsolearelistedbelow.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 215/322
12/10/2015 Javadevelopmentuserguide
StacktraceConsoleCommands

Command Name Description Availability

AutoFormat Automaticallyformatsstacktraceswhenpastedintoastacktraceconsole ViewAction

Copy Copiestheselectedmaterialfromtheconsoleontothesystemclipboard. Contextmenu

Cut Copiestheselectedmaterialtothesystemclipboardandremovesitfromtheconsole. Contextmenu

Find/Replace Allowsyoutosearchforandreplacesspecifiedexpression. Contextmenu


Format Reformatsthecurrentstacktrace.Thiscommandinonlyavailabletostacktraceconsoles. Contextmenu
OpenLink Allowsyoutofollowthehyperlinkwhichwasrightclickedoninthecurrentstacktrace. Contextmenu
Paste Pastesmaterialsavedonthesystemclipboardintothecurrentconsole. Contextmenu

SelectAll Selectsallofthecontentsofthecurrentconsole. Contextmenu

Javaviews
Javaperspectives

Changingtheappearanceoftheconsoleview
Viewsandeditors

ConsoleView
CVSConsole
ProcessConsole

5.8.2.3.1.ConsoleAutoformat
SelecttheAutoformatcommand[ ]toautomaticallyreformatanystacktracepastedintotheStacktraceConsole.
Thiscommandisonlyavailabletostacktraceconsoles.

Javaviews
Javaperspectives

Changingtheappearanceoftheconsoleview
Viewsandeditors

ConsoleView
CVSConsole
ProcessConsole

5.8.2.3.5.ConsoleFormat
SelecttheFormatcommandtoreformatthecurrentstacktraceintheStacktraceConsole.YoucanalsousethekeyboardshortcutCtrl+Shift+F.
Thiscommandisonlyavailabletostacktraceconsoles.

Javaviews
Javaperspectives

Changingtheappearanceoftheconsoleview
Viewsandeditors

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 216/322
12/10/2015 Javadevelopmentuserguide

ConsoleView
CVSConsole
ProcessConsole

5.8.2.4.ClearConsole
SelecttheClearConsolecommand[ ]toclearallofthecontentsintheConsoleView.

Javaviews
Javaperspectives

Changingtheappearanceoftheconsoleview
Viewsandeditors

ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole

5.8.2.5.DisplaySelectedConsole
SelecttheDisplaySelectedConsolecommand[ ]tobringtheconsoleselectedfromtheresultinglistintofocus.
Note:thiscommandisonlyenabledifyouhavemorethanoneconsoleopen.

Javaviews
Javaperspectives

Changingtheappearanceoftheconsoleview
Viewsandeditors

ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole

5.8.2.6.OpenConsole
SelecttheOpenConsolecommand[ ]toopenanewspecifictypeofconsoleintheConsoleView.
Theresultingmenufromselectingthedropdownarrowonthecommand.

Javaviews
Javaperspectives

Changingtheappearanceoftheconsoleview
Viewsandeditors

ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole

5.8.2.7.PinConsole
SelectthePinConsolecommand[ ]toensurethatthecurrentconsoleremainsontopofallotherconsoles.
Forexampleifyouhadtwoconsoles,sayaProcessConsoleandaStacktraceConsole,andyouhadthestacktraceconsolepinned,evenifoutputiswrittentotheprocess

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 217/322
12/10/2015 Javadevelopmentuserguide
consoleitwillnotcometofocusinfrontofthestacktraceconsole.

Javaviews
Javaperspectives

Changingtheappearanceoftheconsoleview
Viewsandeditors

ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole

5.8.2.8.ScrollLock
SelecttheScrollLockcommand[ ]tochangewhetherscrolllockshouldbeenabledordisabledforallopenconsoles.

Javaviews
Javaperspectives

Changingtheappearanceoftheconsoleview
Viewsandeditors

ConsoleView
CVSConsole
ProcessConsole
StacktraceConsole

5.8.3.DebugView
TheDebugViewallowsyoutomanagethedebuggingorrunningofaprogramintheworkbench.Itdisplaysthestackframeforthesuspendedthreadsforeachtargetyouare
debugging.Eachthreadinyourprogramappearsasanodeinthetree.Itdisplaystheprocessforeachtargetyouarerunning.
Ifthethreadissuspended,itsstackframesareshownaschildelements.

TheExecutionControlCommandsallowyoutodebugyourprogram,starting,stoppingandsteppingthroughthecode.
DebugViewCommands

Command Name Description Availability


Automatic Configuresthedebugviewtoswitchlayoutbetweenatreeandabreadcrumbviewerautomaticallywhentheviewis
Viewaction
resized.


AutoExpand ConfigurestheDebugBreadcrumbDropdowntoautomaticallyexpandelementswhenopened.
Viewaction
Breadcrumb


Breadcrumb Configuresthedebugviewlayouttouseabreadcrumbviewer. Viewaction

CopyStack Copiestheselectedstackofsuspendedthreadsaswellasthestateoftherunningthreadstotheclipboard. Contextmenu

Contextmenuand
Disconnect Disconnectsthedebuggerfromtheselecteddebugtargetwhendebuggingremotely.
viewaction

DroptoFrame Thiscommandletsyoudropbackandreenteraspecifiedstackframe.Thisfeatureissimilarto"runningbackwards"
andrestartingyourprogrampartwaythrough.
Todropbackandreenteraspecifiedstackframe,selectthestackframethatyouwantto"drop"to,andselectDrop
toFrame.
Contextmenuand
Somecaveatsapplytothisfeature: viewaction
Youcannotdroppastanativemethodonthestack.
Globaldataareunaffectedandwillretaintheircurrentvalues.Forexample,astaticvectorcontainingelements

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 218/322
12/10/2015 Javadevelopmentuserguide
willnotbecleared.
Note:ThiscommandisonlyenablediftheunderlyingVMsupportsthisfeature.
Edit[configuration Opensthelaunchconfigurationdialogontheassociatedlaunchconfiguration,allowingyoutomakechanges.
Contextmenu
name]...
EditStepFilters OpenstheStepFilteringpreferencepagetoallowingeditingofstepfilters Contextmenu
EditSourceLookup Opensthesourcelookupdialog,allowingyoutomakechanges. Contextmenu

FilterPackage Addsthecontainingpackageforthetypefromthecurrentsuspendedexecutiontothelistingofstepfilters Contextmenu


FilterType Addsthetypefromthecurrentsuspendedexecutiontothelistingofstepfilters Contextmenu
Find... Opensthedebugviewelementsearchingdialog. Contextmenu
LookupSource Forcessourcelookuptotakeplace Contextmenu
OpenDeclaredType Opensthedeclaredtypefortheselectedstackframeinaneweditor. Contextmenu
OpenDeclaredType Opensthetypehierarchyforthedeclaredtypeoftheselectedstackframe.
Contextmenu
Hierarchy

Properties Thiscommanddisplaysthepropertiesoftheselectedlaunch.Italsoallowsyoutoviewthefullcommandlinefora
Contextmenu
selectedprocess.

Relaunch Thiscommandrelaunchestheselecteddebugtarget. Contextmenu

RemoveAll Clearsallterminateddebugtargetsfromtheviewdisplay. Contextmenuand


TerminatedLaunches viewaction

Contextmenu,Run
Resume Resumesasuspendedthread.
menuandviewaction

ShowMonitors
Thisoptioncanbetoggledtodisplayorhidemonitors.
Viewaction
Note:thiscommandwillonlydisplaymonitorinformationiftheunderlyingVMsupportsit.

ShowQualified Thisoptioncanbetoggledtodisplayorhidequalifiednames.
Viewaction
Names

ShowSystem Thisoptioncanbetoggledtodisplayorhidesystemthreads
Viewaction
Threads
ShowThreadGroups Thisoptioncanbetoggledtodisplayorhidethreadgroups Viewaction

Contextmenu,Run
StepInto Stepsintothehighlightedstatement.
menuandviewaction

StepOver Stepsoverthehighlightedstatement.Executionwillcontinueatthenextlineeitherinthesamemethodor(ifyouare
attheendofamethod)itwillcontinueinthemethodfromwhichthecurrentmethodwascalled. Contextmenu,Run
menuandviewaction
Thecursorjumpstothedeclarationofthemethodandselectsthisline.

Contextmenu,Run
StepReturn Stepsoutofthecurrentmethod.Thisoptionstopsexecutionafterexitingthecurrentmethod.
menuandviewaction

Contextmenu,Run
Suspend Suspendstheselectedthreadofatargetsothatyoucanbrowseormodifycode,inspectdata,step,andsoon.
menuandviewaction

Contextmenu,Run
Terminate Terminatestheselecteddebugtarget.
menuandviewaction

Terminate/Disconnect Terminatesallactivelaunchesintheview.
Contextmenu
All

Terminateand Terminatestheselecteddebugtargetandrelaunchesit.
Contextmenu
Relaunch

Terminateand Terminatestheselecteddebugtargetandremovesitfromtheview.
Contextmenu
Remove


Tree Configuresthedebugviewlayouttouseatreeviewer. Viewaction

UseStepFilters Togglesstepfilterson/off.Whenon,allstepfunctionsapplystepfilters. Contextmenu,Run


menuandviewaction

Debugger
Javaviews
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 219/322
12/10/2015 Javadevelopmentuserguide
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugPreferences
Viewsandeditors
RunMenu

5.8.3.1.ExecutionControlCommands
Executioncontrolcommandsallowyoutochangetheexecutionstateofcodebeingexecuted.
JavaExecutionControlCommands

Command Name Description Availability

Contextmenu,Run
Resume Resumesasuspendedthread.
menuandviewaction

Contextmenu,Run
StepInto Stepsintothehighlightedstatement.
menuandviewaction

StepOver Stepsoverthehighlightedstatement.Executionwillcontinueatthenextlineeitherinthesamemethodor(ifyouare
attheendofamethod)itwillcontinueinthemethodfromwhichthecurrentmethodwascalled. Contextmenu,Run
menuandviewaction
Thecursorjumpstothedeclarationofthemethodandselectsthisline.

Contextmenu,Run
StepReturn Stepsoutofthecurrentmethod.Thisoptionstopsexecutionafterexitingthecurrentmethod.
menuandviewaction

Contextmenu,Run
Suspend Suspendstheselectedthreadofatargetsothatyoucanbrowseormodifycode,inspectdata,step,andsoon.
menuandviewaction

Contextmenu,Run
Terminate Terminatestheselecteddebugtarget.
menuandviewaction

Terminate& Terminatestheselecteddebugtargetandrelaunchesit.
Contextmenu
Relaunch

Terminate&Remove Terminatestheselecteddebugtargetandremovesitfromtheview. Contextmenu

Terminate/Disconnect Terminatesallactivelaunchesintheview.
Contextmenu
All

SeetheDebugViewformoreinformation.

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences
RunMenu

5.8.3.1.1.Resume
SelecttheResumecommand[ ]toresumetheexecutionofthecurrentlysuspendeddebugtarget.

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 220/322
12/10/2015 Javadevelopmentuserguide
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences
ExecutionControlCommands
RunMenu

5.8.3.1.2.StepInto
SelecttheStepIntocommand[ ]tostepintothenextmethodcallatthecurrentlyexecutinglineofcode.
Tostepintoamethodyoumusthaveexecutionsuspendedandbesteppingthroughcode.

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences
ExecutionControlCommands
RunMenu
StepReturn
StepOver

5.8.3.1.3.StepOver
SelecttheStepOvercommand[ ]tostepoverthenextmethodcall(withoutenteringit)atthecurrentlyexecutinglineofcode.Eventhoughthemethodisneversteppedinto,the
methodwillbeexecutednormally.
Tostepoveramethodyoumusthaveexecutionsuspendedandbesteppingthroughcode.

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences
ExecutionControlCommands
RunMenu
StepReturn
StepInto

5.8.3.1.4.StepReturn
SelecttheStepReturncommand[ ]toreturnfromamethodwhichhasbeensteppedinto.Eventhoughwereturnfromthemethod,theremainderofthecodeinsidethemethod
willbeexecutednormally.
Tostepreturnfromamethodyoumusthaveexecutionsuspendedandbesteppingthroughcode.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 221/322
12/10/2015 Javadevelopmentuserguide
Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences
ExecutionControlCommands
RunMenu
StepInto
StepOver

5.8.3.1.5.Suspend
SelecttheSuspendcommand[ ]tohalttheexecutionofthecurrentlyselectedthreadinadebugtarget.Oncetheselectedthreadissuspendedyoucanthenexamineitsstack
frames.

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences
ExecutionControlCommands
Resume
RunMenu

5.8.3.1.6.Terminate
SelecttheTerminatecommand[ ]toterminatethelaunchassociatedwiththeselecteddebugtarget.
OncealaunchisterminateditcanbeautomaticallyremovedfromtheDebugView.Tochangethissettingusethe Run/Debug>Launchingpreferencepage.

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences
ExecutionControlCommands
Relaunch
RemoveAllTerminated
RunMenu
Terminate/DisconnectAll
TerminateandRelaunch
TerminateandRemove

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 222/322
12/10/2015 Javadevelopmentuserguide
5.8.3.1.7.Terminate/DisconnectAll
SelecttheTerminate/DisconnectAllcommand[ ]toterminatealltherunningdebugtargetsintheDebugandConsoleView.Ifthetargetcannotbeterminated,itwillbe
disconnected.
OncealaunchisterminateditcanbeautomaticallyremovedfromtheDebugandConsoleView.Tochangethissettingusethe Run/Debug>Launchingpreferencepage.

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
ConsoleView
Debugpreferences
ExecutionControlCommands
Relaunch
RemoveAllTerminated
Terminate
TerminateandRelaunch
TerminateandRemove

5.8.3.1.8.TerminateandRelaunch
SelecttheTerminateandRelaunchcommand[ ]tofirstterminatetheselecteddebugtargetandsecondly,relaunchit.
OncealaunchisterminateditcanbeautomaticallyremovedfromtheDebugView.Tochangethissettingusethe Run/Debug>Launchingpreferencepage.

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences
ExecutionControlCommands
RemoveAllTerminatedLaunches
Terminate
Terminate/DisconnectAll
TerminateandRemove

5.8.3.1.9.TerminateandRemove
SelecttheTerminateandRemovecommand[ ]toterminatethelaunchassociatedwiththeselecteddebugtargetandremoveitfromtheDebugView.

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 223/322
12/10/2015 Javadevelopmentuserguide
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences
ExecutionControlCommands
Relaunch
RemoveAllTerminated
Terminate
Terminate/DisconnectAll
TerminateandRelaunch

5.8.3.3.Disconnect
SelecttheDisconnectcommand[ ]toterminatetheconnectionbetweenthedebuggerandtheremotedebugtarget.

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences

5.8.3.4.DroptoFrame
SelecttheDroptoFramecommand[ ]toreentertheselectedstackframeintheDebugView.
NotethiscommandisonlyavailableifthecurrentVMsupportsdroptoframeandtheselectedstackframeisnotthetopframeoraframeinanativemethod.

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences

5.8.3.5.Edit...
SelecttheEdit...commandtoopentheLaunchConfigurationDialog,andallowyoutoeditthelaunchconfigurationfortheselectedtarget.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 224/322
12/10/2015 Javadevelopmentuserguide

Theresultinglaunchconfigurationdialog,inthisexampleaJavaApplicationtype.

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences

5.8.3.6.EditSourceLookup
SelecttheEditSourceLookup...command[ ]toopentheSourcePathDialog,whichallowsyoutomakechangestothesourcelookuppathoftheselecteddebugtarget.
TheSourcePathDialog:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 225/322
12/10/2015 Javadevelopmentuserguide

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences

5.8.3.7.EditStepFilters
SelecttheEditStepFilterscommandtoopenthe Java>Debug>StepFilteringpreferencepage,whichallowsyoutoaddandconfigurestepfilters.

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 226/322
12/10/2015 Javadevelopmentuserguide
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences
ExecutionControlCommands
FilterPackageCommand
FilterTypeCommand
UseStepFiltersCommand

5.8.3.8.FilterPackage
SelecttheFilterPackagecommandtoaddthepackageoftheselectedstackframetothelistofitemstobefilteredviastepfiltering.
Forexample,ifthecurrentlyselectedstackframeisoftypejava.lang.Object,andyouselecttheFilterPackagecommandthenjava.lang.*willbeaddedtothelistoftypestobe
filteredviastepfiltering.
Warning:Youcaninadvertentlyfilteroutmorethanyouexpectwhenusingthiscommand,takecareinitsuse.

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences
ExecutionControlCommands
EditStepFiltersCommand
FilterTypeCommand
UseStepFiltersCommand

5.8.3.9.FilterType
SelecttheFilterTypecommandtoaddthetypeassociatedwiththeselectedstackframetothelistoftypestobefilteredviastepfiltering.
Forexample,ifthecurrentlyselectedstackframeisassociatedwiththetypejava.lang.Object,andyouselecttheFilterTypecommandthenjava.lang.Objectwillbeaddedtothe
listoftypestobefilteredviastepfiltering.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 227/322
12/10/2015 Javadevelopmentuserguide

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences
StepCommands
EditStepFiltersCommand
UseStepFiltersCommand
FilterPackageCommand

5.8.3.10.Find...
SelecttheFind...commandtoopentheFindDialogwhichallowsyoutosearchforspecificelementswithintheview.YoucanalsousethekeyboardshortcutCtrl+F.
TheFindDialog:

Thiscommandappliesto:
DebugView
ExpressionsView
RegistersView
VariablesView

5.8.3.11.LookupSource

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 228/322
12/10/2015 Javadevelopmentuserguide
SelecttheLookupSourcecommandtoforceasourcelookuptotakeplace.Iftherequestedsourcefileisnotopen,itwillbeopenedandthecorrespondinglineofexecutionwillbe
highlighted.

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences
EditSourceLookup

5.8.3.12.OpenDeclaredType
SelecttheOpenDeclaredTypecommandtoopenaneditoronthedeclaredtypeofthecurrentlyselectedstackframeintheDebugView.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 229/322
12/10/2015 Javadevelopmentuserguide

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences

5.8.3.13.OpenDeclaredTypeHierarchy
SelecttheOpenDeclaredTypeHierarchycommandtoopenthedeclaredtypeofthecurrentlyselectedstackframeintheTypeHierarchyView.

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 230/322
12/10/2015 Javadevelopmentuserguide
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences

5.8.3.14.Properties
SelectthePropertiescommandtoopenthepropertiesdialogfortheselecteddebugtarget,thread,threadgroup,processorstackframe.

Fromtheresultingdialogyoucancopyinformationabouttheselecteddebugtargetandviewtheactualcommandlineusedtorunthetarget.

YoucanalsoviewthecapabilitiesoftheVMusedtolaunchtheassociatedtarget

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 231/322
12/10/2015 Javadevelopmentuserguide

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences

5.8.3.15.Relaunch
SelecttheRelaunchcommand[ ]torelaunchtheselecteddebugtargetintheDebugView.

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences
ExecutionControlCommands
RemoveAllTerminatedLaunches
RunMenu
Terminate
Terminate/DisconnectAll
TerminateandRelaunch
TerminateandRemove

5.8.3.16.RemoveAllTerminated

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 232/322
12/10/2015 Javadevelopmentuserguide
SelecttheRemoveAllTerminatedcommand[ ]tocleartheDebugViewofallterminatedlaunches.

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences
Relaunch
Terminate
Terminate/DisconnectAll
TerminateandRelaunch
TerminateandRemove

5.8.3.17.ShowMonitors
SelecttheShowMonitorscommand[ ]tochangeifmonitorinformationwillbeshownforsuspendedthreads.
Note:ThedisplayofmonitorinformationmustbesupportedbytheunderlyingVM.IfusinganIBMorSUNVM,anyversiongreaterthan1.4willsupportmonitorinformation.
Considerthefollowingcodeexample:

/**
*HelloWorld
*/
publicclassHelloWorld{

publicstaticvoidmain(String[]args){
Objectmutex=newObject()
synchronized(mutex){
System.out.println("HelloWorld!")
}
}
}

IftheabovecodesnippetisrunonasupportingVMwithShowMonitorsselected,themonitorinformationisrepresentedasa'key'andappearingbeforeanystackframesasachild
ofasuspendedthread.

Ifhowever,werunthesamesnippetonanunsupportedVMwithShowMonitorsselected,wearealertedthatmonitorinformationisnotsupportedbytheVM.

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 233/322
12/10/2015 Javadevelopmentuserguide
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences
ShowSystemThreads
ShowThreadGroups

5.8.3.19.ShowSystemThreads
SelecttheShowSystemThreadscommand[ ]tochangeifsystemthreadsshouldbeshownintheDebugView.

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences
ShowMonitors
ShowSystemThreads
ShowThreadGroups

5.8.3.20.ShowThreadGroups
SelecttheShowThreadGroupscommand[ ]tochangeifthreadgroupsshouldbeusedtoorganizethreadsdisplayedintheDebugView.

Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences
ShowMonitors
ShowSystemThreads
ShowThreadGroups

5.8.3.21.UseStepFilters
SelecttheUseStepFilterscommand[ ]tochangewhetherstepfiltersshouldbeusedintheDebugView.YoucanalsousethekeyboardshortcutShift+F5.
Stepfiltersarecommonlyusedtofilterouttypesthatyoudonotwishtoseeorstepthroughwhiledebugging.
Forexample,ifyoudidnotwanttotheseeorstepthroughanythingfromtheclassjava.lang.Object,youwouldaddthistothelistoffilteredtypes.Addingtypestothelistofthose
tobefilteredcanbedoneinoneoftwoways:
1. ViathecontextmenuRightclickonthestackframeforthetypeyouwishtofilterandusetheFilterTypeorFilterPackagecommand.
2. Viathe Java>Debug>StepFilteringpreferencepage.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 234/322
12/10/2015 Javadevelopmentuserguide
Debugger
Localdebugging
Remotedebugging

Changingdebuggerlaunchoptions
ConnectingtoaremoteVMwiththeRemoteJavaapplicationlaunchconfiguration
DisconnectingfromaVM
LaunchingaJavaprogram
Preparingtodebug
Resumingtheexecutionofsuspendedthreads
Runninganddebugging
Steppingthroughtheexecutionofaprogram
Suspendingthreads

DebugView
Debugpreferences
ExecutionControlCommands
EditStepFilters
RunMenu

5.8.4.DisplayView
TheDisplayViewdisplaystheresultofevaluatinganexpressioninthecontextofthecurrentstackframe.Youcanevaluateanddisplayaselectioneitherfromtheeditorordirectly
fromtheDisplayView.

Thecommandsavailableinthedisplayviewarelistedbelow.
DisplayViewCommands

Command Name Description Availability

Clear Clearsthecurrentcontentsoftheview. Contextmenuandviewaction

Copy Copiestheselectedstatementstothesystemclipboard. Contextmenu

ContentAssist Opensthecontentassistpopupforcontextsensitivecodingassistance Contextmenu

Cut Copiestheselectedstatementstothesystemclipboardandremovesthemfromtheview. Contextmenu

Display Displaystheresultoftheselectedstatementinlineintheview. Contextmenuandviewaction

Execute Runstheselectedstatement.Thisactionisanalogoustorunningthestatementinnormalcode. Contextmenuandviewaction

Find/Replace Allowsyoutosearchforandreplacespecificstatements,orportionsofstatements Contextmenu


InspectResult Allowsyoutoinspectwhatthereturnvalueoftheselectedstatementwillbe. Contextmenuandviewaction

Paste Copiesmaterialfromthesystemclipboardintotheview Contextmenu

SelectAll Selectsallofthestatementsintheview Contextmenu

Javaviews
Javaperspectives

Evaluatingexpressions

Viewsandeditors

5.8.4.1.Clear
SelecttheClearcommand[ ]toremoveallofthecontentsfromtheview.

DisplayView

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 235/322
12/10/2015 Javadevelopmentuserguide
5.8.4.2.ContentAssist
SelecttheContentAssistcommand[ ]toopentheContentAssistpopupdialog.YoucanalsousethekeyboardshortcutCtrl+Spacebarwithintheview.
Theresultingdialogprovidesyouwithcontextsensitivecodinghelpbymakingavailablealistingofallapplicablejavacodeelementsforthelocationcontentassistwasactivated.

Thiscommandappliesto:
JavaEditor
DisplayView
DetailPane(intheExpressionsViewandVariablesView)

EvaluatingExpressions

5.8.4.5.Display
SelecttheDisplaycommand[ ]tohavetheselectedstatementevaluatedandtheresultsdisplayedinlineintheDisplayVieworinapopupdialog(thatcanbemovedtothe
DisplayView).
Forexample,considerwehavethefollowingstatementselectedintheDisplayView:

AfterweselecttheDisplaycommandwenoticethattheresultisinsertedinlineintheview.Inthefollowingcasethough,aprintln()statementdoesnothaveanexplicitreturn
value,sothatiswhatiswrittenintheview.

Thiscommandappliesto:
JavaEditor
DisplayView
DetailPane(intheExpressionsViewandVariablesView)
RunMenu

EvaluatingExpressions

5.8.4.6.Execute
SelecttheExecutecommand[ ]tohavetheselectedstatementexecutedasthoughitwasruninnormalJavacode.
Thiscommandappliesto:
JavaEditor
DisplayView
DetailPane(intheExpressionsViewandVariablesView)
RunMenu

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 236/322
12/10/2015 Javadevelopmentuserguide

EvaluatingExpressions

5.8.4.8.InspectSelectedStatement
SelecttheInspectcommand[ ]toevaluatetheselectedexpressionandhaveitsresultdisplayedinapopupbox.

YoucanalsomovetheinspectedstatementtotheExpressionsViewbypressingCtrl+Shift+Ioncethepopuphasbeenopened.
Thiscommandappliesto:
JavaEditor
DisplayView
DetailPane(intheExpressionsViewandVariablesView)
RunMenu

EvaluatingExpressions

5.8.5.ExpressionsView
DatacanbeinspectedintheExpressionsView.Youcaninspectdatafromascrapbookpage,astackframeofasuspendedthread,andotherplaces.TheExpressionsViewopens
automaticallywhenanitemisaddedtotheview.EntriesintheExpressionsViewcanbeselectedtohavemoredetailedinformationbedisplayedintheDetailPane.When
debuggingaJavaprogram,datathatcontainsvariablescanbeexpandedtoshowthevariablesandthefieldsthevariablescontain.
TheExpressionsView.TheDetailPaneistheareaatthebottomoftheviewdisplayingtext..

TherearemanycommandsavailableintheExpressionsView:
ViewDisplayCommandsaffectwhatdataandvariablesaredisplayedandhowtheyarepresented.
TheDetailPanehasmanycommandsavailablebyrightclickingonit.
ViewLayoutCommandsaffecthowthedetailpaneisoriented.
Othercommandsarelistedbelow.
VariablesViewCommands
AddWatch Allowsyoutoaddawatchexpression.
Contextmenu
Expression
AllInstances OpensapopupdialogdisplayingalistofallinstancesoftheselectedJavatype.YourJavavirtualmachinemustsupport
Contextmenu
instanceretrieval.
AllReferences OpensapopupdialogdisplayingalistofallJavaobjectsthathavereferencestotheselectedvariable.YourJavavirtual
Contextmenu
machinemustsupportreferenceretrieval.
ChangeValue... Allowsyoutochangethevaluefortheunderlyingselectedvariable. Contextmenu

CollapseAll Collapsesallthecurrentlyexpandedvariables. Viewaction

CopyExpressions Copiestheselectedexpressionsandvariablestothesystemclipboard. Contextmenu

ConverttoWatch Convertstheselectedinspectexpressiontoacorrespondingwatchexpression.
Contextmenu
Expression
Disable Disablesacurrentlyenabledexpression. Contextmenu
EditLogicalStructure Allowyoutoeditthelogicalstructureoftheselectedvariable Contextmenu
EditWatch Allowsyoutoeditthecurrentlyselectedexpression.
Contextmenu
Expression
Enable Enablesacurrentlydisabledexpression. Contextmenu

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 237/322
12/10/2015
Enable Enablesacurrentlydisabledexpression. Javadevelopmentuserguide Contextmenu
Find... Opensthesearchdialogtofindelementsinthevariablesview. Contextmenu
Inspect Createsanewinspectexpressionfortheselectedvariableandaddsittotheview. Contextmenu

InstanceBreakpoints... Allowsyoutofilterexistingbreakpointstotheselectedvariableinstance. Contextmenu


JavaPreferences... Opensseveralpreferencepagescontainingoptionsthataffecttheview. Viewaction
NewDetailFormatter... Allowsyoutocreateyourowndetailformatterforthattypeofvariable. Contextmenu
OpenActualType Openstheactualtypeoftheselectedvariable. Contextmenu
OpenActualType Openstheactualtypehierarchyfortheactualtypeoftheselectedvariable.
Contextmenu
Hierarchy
OpenDeclaredType Opensthedeclaredtypefortheselectedvariableinaneweditor. Contextmenu
OpenDeclaredType Opensthetypehierarchyforthedeclaredtypeoftheselectedvariable.
Contextmenu
Hierarchy
Reevaluate Reevaluatesthecurrentlyselectedexpression.
Contextmenu
Expression
Remove Removesthecurrentlyselectedexpression(s)fromtheview. Contextmenuand
viewaction
RemoveAll Removesalloftheexpressionsfromtheview. Contextmenuand
viewaction
SelectAll Selectsallofthevariablesintheview. Contextmenu
ShowStructureAs... Allowsyoutoselectadifferentformatterforshowingtheselectedlogicalstructuretypevariable. Contextmenu
ShowDetailsAs... Allowsyoutoselectadifferentdetailpaneforshowingdetailedinformationaboutselectedvariables. Contextmenu
ToggleWatchpoint Createsanewwatchpointonthecurrentlyselectedfieldorremovesthewatchpointifonealreadyexists. Contextmenu

Javaviews
Javaperspectives
Scrapbook

Evaluatingexpressions
Suspendingthreads

DetailPane
ViewDisplayCommands
ViewLayoutCommands

5.8.5.1.DetailPane
TheDetailPanedisplaysdetailedinformationaboutaselectioninthefollowingviews:
ExpressionsView
RegistersView
VariablesView
TheVariablesViewwiththedetailpanehighlighted.

Bydefault,theDetailPanedisplaysinformationasmarkeduptext(textishighlighted,bolded,underlined,etc.accordingtotoolspecificsettings).Forexample,whendebugginga
Javaprogram,theDetailPanedisplaystoString()valueofJavaobjects.
Ifothertypesofdetailpanesareavailable,theycanbeaccessedbyrightclickingonavariableandgoingtothe"ShowDetailsAs"menu.Thismenuwillnotbeavailableunless
thereismorethanonepossibletypeofdetailpaneforthecurrentselection.Themarkeduptextviewerdetailpanethatisavailablebydefaultistheonlydetailpaneprovidedbythe
Eclipseplatform.
AnumberofcommandsareavailableinthedefaultDetailPane.TheyareaccessedbyrightclickingtheDetailPanetoopenupacontextmenu.
DetailPaneCommands

Command Name Description Availability

AssignValue Assignsanewvaluetothecurrentlyselectedvariablebyevaluatingthetextinthedetailpane. Contextmenu

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 238/322
12/10/2015 Javadevelopmentuserguide
ContentAssist OpenstheContentAssistpopupdialog,offeringcodecompletionhelp. Contextmenu

Cut Copiestheselectedmaterialtothesystemclipboardandremovesitfromthedetailpane. Contextmenu

Copy Copiestheselectedmaterialfromthedetailpaneontothesystemclipboard. Contextmenu

Display Evaluatestheselectedtextanddisplaystheresultinapopupdialog. Contextmenu

Execute ExecutestheselectedtextasnormalJavacode. Contextmenu

Find/Replace Allowsyoutosearchforandreplaceaspecifiedexpression. Contextmenu


ForceReturn Allowsyoutoimmediatelyreturnfromthemethodinwhichexecutionissuspended. Contextmenu
Inspect Allowsyoutoinspectwhatthereturnvalueoftheselectedstatementwillbe. Contextmenu

MaxLength Opensadialogallowingyoutochangethemaximumnumberofcharactersdisplayedinthedetailpane. Contextmenu


Paste Pastesmaterialsavedonthesystemclipboardintothedetailpane. Contextmenu

SelectAll Selectsalltextinthedetailpane. Contextmenu


WrapText Changeifthetextdisplayedinthedetailpaneshouldwrapatthepredefinedwidthornot. Contextmenu

ExpressionsView
VariablesView

5.8.5.1.1.AssignValue
SelecttheAssignValuecommandtoassignanewvaluetothecurrentlyselectedvariablebyevaluatingthetextinthedetailpane.
Thiscommandappliesto:
DetailPane(intheExpressionsViewandVariablesView)

EvaluatingExpressions

5.8.5.1.8.ForceReturn
SelecttheForceReturncommandtoreturnfromthecurrentmethodwiththespecifiedvalue.
Youcanforceanearlyreturnfromamethod(onlyavailablewhendebuggingonaJavaSE6virtualmachine).Thisreturnsavaluefromthecurrentstackframewithoutexecutingany
moreinstructionsinthemethodandreleasesanylocksobtainedbysynchronizedblocks.AreturnvalueiscreatedbyselectinganexpressionandForceReturn(Alt+Shift+F).This
actionisavailablefromtheJavaeditor'scontextmenu,toplevelRunmenu,intheDisplayView,andinthedetailpaneoftheVariablesView.
Forcinganearlyreturnfromanonvoidmethodrequiresanexpressiontobeevaluated.Forexample,ifamethodwasgoingtoreturnfalseyoucouldreturnavalueoftrueby
selectinganexpressionintheDisplayViewandinvokingForceReturn.Inthefollowingexample,elementCountisnotequaltozero,andwouldreturnfalse(seedebughover
showingthevalueofelementCount).

FromtheDisplayView,wecouldenterthevaluewewantreturned,selectitandusetheForceReturncommandtoforcethemethodisEmpty()toreturnwiththatvalue(inthe
followingexamplewewillforceisEmpty()toreturnwiththevaluetrue).

Thiscommandappliesto:
JavaEditor
DisplayView
DetailPane(intheExpressionsViewandVariablesView)
RunMenu

EvaluatingExpressions

5.8.5.1.10.MaxDetailPaneLength
TheMaxLength...commandtoopensadialogallowingyoutochangethemaximumnumberofcharactersdisplayedintheDetailPane
Thiscommandappliesto:
DetailPane(intheExpressionsViewandVariablesView)

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 239/322
12/10/2015 Javadevelopmentuserguide
5.8.5.1.13.WrapText
SelecttheWrapTextcommandtochangeifthetextdisplayedintheDetailPaneshouldwrapatthepredefinedwidthornot.
Thiscommandappliesto:
DetailPane(intheExpressionsViewandVariablesView)

5.8.5.2.VariableDisplayCommands
Viewdisplaycommandsaffectwhatvariablesaredisplayedintheviewandhowtheyarepresented.
Thesecommandsapplyto(somecommandsapplytoadditionalviews):
ExpressionsView
VariablesView
TheShowTypeNamesandShowLogicalStructurescommandsareavailableontheviewtoolbar.Theotheractionscanbefoundinthedropdownmenuoftheviewasshown
below.

ViewDisplayCommands

Command Name Description Availability

ShowConstants Changeswhetherconstantsshouldbeshownintheview. Viewaction

ShowLogical Changeswhetherlogicalstructuresshouldbeshownintheview.
Viewaction
Structures


ShowNullArray Changewhethernullarrayentriesshouldbeshownintheview.
Viewaction
Entries

ShowQualifiedNames Changeswhetherqualifiednamesshouldbeshownintheview. Viewaction

ShowReferences Changeswhetherreferencestovariablesshouldbedisplayedintheview.YourJavavirtualmachinemustsupportreference
Viewaction
retrieval.

ShowStaticFields Changeswhetherstaticfieldsshouldbeshownintheview. Viewaction

ShowTypeNames Changeswhethertypenamesshouldbeshownintheview. Viewaction

ExpressionsView
VariablesView
DetailPane

5.8.5.2.1.ShowConstants
SelecttheShowConstantscommand[ ]tochangeifconstantsshouldbeshownintheviewornot.
Thiscommandappliesto:
ExpressionsView
VariablesView

ViewDisplayCommands

5.8.5.2.2.ShowLogicalStructures
SelecttheShowLogicalStructurescommand[ ]tochangeiflogicalstructuresshouldbeshownintheviewornot.
Thiscommandappliesto:
ExpressionsView

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 240/322
12/10/2015 Javadevelopmentuserguide
RegistersView
VariablesView

ViewDisplayCommands

5.8.5.2.3.ShowNullArrayEntries
SelecttheShowNullArrayEntriescommandtochangeifnullarrayentriesshouldbeshownintheviewornot.
Thiscommandappliesto:
ExpressionsView
VariablesView

ViewDisplayCommands

5.8.5.2.5.ShowReferences
SelecttheShowReferencescommand[ ]tochangeifreferencesshouldbedisplayedasvariablesintheview.Whenturnedon,eachJavavariablethatsupportsreferenceswill
haveanewchilditemwiththename"'<variablename>'referencedfrom:".ThisnewvariablecontainsalistofallJavaobjectsthatholdareferencetotheparentobject.Youcanget
atextlistinthedetailpanebyclickingonthereferencelistvariableorexplorethedetailsofeachreferencingobjectbyexpandingthevariables.
ReferenceswillonlyappearintheviewiftheJavaVirtualMachineyouareusingsupportsreferenceretrieval.
Thiscommandappliesto:
ExpressionsView
VariablesView
TheVariablesViewwithShowReferencesturnedon.Inthiscase,theMapisreferencesbyoneobject,aHashMap$EntrySet.

ViewDisplayCommands

5.8.5.2.6.ShowStaticFields
SelecttheShowStaticFieldscommand[ ]tochangeifstaticfieldsshouldbeshownintheviewornot.
Thiscommandappliesto:
ExpressionsView
VariablesView

ViewDisplayCommands

5.8.5.2.7.ShowTypeNames
SelecttheShowTypeNamescommand[ ]tochangeiftypenamesshouldbeshownintheviewornot.
Thiscommandappliesto:
ExpressionsView
RegistersView
VariablesView

ViewDisplayCommands

5.8.5.3.ViewLayoutCommands

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 241/322
12/10/2015 Javadevelopmentuserguide
ViewlayoutcommandsaffecttheorientationoftheDetailPaneintheview.Inaddition,theVariablesViewhascommandsthatallowyoutochangecolumnsettings.
Thesecommandsapplyto:
ExpressionsView
RegistersView
VariablesView
ThecommandsareavailableundertheLayoutmenu,whichisshownbelowintheVariablesView.

DetailPaneDisplayCommands

Command Name Description Availability

ShowColumns Changesifcolumnsshouldbeshownintheviewornot.VariablesViewonly. Viewaction

SelectColumns... Allowsyoutoselectwhichcolumnsareshownwhencolumnsarevisible.VariablesViewonly. Viewaction


Horizontal Displaysthedetailpaneattherightsideoftheview,aligningthepartsoftheviewhorizontally. Viewaction

Displaysthedetailpaneatthebottomoftheview,aligningthepartsoftheviewvertically.
Vertical Viewaction

ViewOnly Hidesthedetailpane. Viewaction

ExpressionsView
VariablesView

5.8.5.3.1.ShowColumns
SelecttheShowColumnscommand[ ]tochangeifcolumnsshouldbeusedtodisplayvariableinformationintheVariablesView.IfShowColumnsisturnedon,theSelect
Columnscommandwillbeavailable,allowingyoutochoosewhichcolumnsarevisible.
Thiscommandappliesto:
VariablesView

ViewLayoutCommands

5.8.5.3.2.SelectColumns
SelecttheSelectColumns...commandtoopenadialogthatwillallowyoutochoosewhichcolumnstodisplayintheVariablesView.
Intheresultingdialogyoucanselectwhichcolumnswillbedisplayed.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 242/322
12/10/2015 Javadevelopmentuserguide

Thiscommandappliesto:
VariablesView

ViewLayoutCommands

5.8.5.3.3.HorizontalLayout
SelecttheHorizontalcommand[ ]torevealtheDetailPaneandsetitinahorizontalalignmentwithintheview.
Thiscommandappliesto:
ExpressionsView
MemoryView
RegistersView
VariablesView

ViewLayoutCommands
DetailPane
ExpressionsView
VariablesView

5.8.5.3.4.VerticalLayout
SelecttheVerticalcommand[ ]torevealtheDetailPaneandsetitinaverticalalignmentwithintheview.
Thiscommandappliesto:
ExpressionsView
MemoryView
RegistersView
VariablesView

ViewLayoutCommands
DetailPane
ExpressionsView
VariablesView

5.8.5.3.5.ViewOnly
SelecttheViewOnlycommand[ ]tohidetheDetailPanewithintheview.Thenameofthecommandwillchangebasedonthecurrentview.Forexample,intheVariables
View,thecommandisnamed'VariablesViewOnly'.
Thiscommandappliesto:
ExpressionsView
RegistersView
VariablesView

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 243/322
12/10/2015 Javadevelopmentuserguide
ViewLayoutCommands
DetailPane
ExpressionsView
VariablesView

5.8.5.4.AddWatchExpression
SelecttheAddWatchExpressioncommand[ ]toopenthecreatenewexpressiondialog,whichallowsyoutocreateanewwatchexpressionandaddittotheExpressions
View.
Theaddwatchexpressiondialog.

Evaluatingexpressions

ExpressionsView

5.8.5.5.AllInstances
SelecttheAllInstancescommand[ ]toopenapopupcontainingalistofallJavaobjectinstancesoftheselectedtypethatexistinthecurrentdebugtarget.Thecommandhasa
keyboardshortcutofCtrl+Shift+N.ThiscommandisonlyavailableiftheJavavirtualmachineyouarecurrentlyusingsupportsinstanceretrieval.
Thetypetosearchforcanbeselectedinseveralways:
IntheJavaEditor,highlightorplacethecursorinthenameofatypeoraconstructorforatype.
IntheOutlineView,selectatypeorconstructor.
IntheExpressionsVieworVariablesView,selectaJavaobjectvariable.
Oncethepopuphasopened,youcanmovethelisttotheExpressionsViewbypressingCtrl+Shift+I.
Thereisamaximumnumberofinstancesthevirtualmachinewillreturn.Thismaximumcanbechangedonthe Java>Debug>HeapWalkingpreferencepage.
Thiscommandappliesto:
JavaEditor
OutlineView
ExpressionsView
VariablesView

EvaluatingExpressions
RunMenu

5.8.5.6.AllReferences
SelecttheAllReferences...command[ ]toopenapopupcontainingalistofallJavaobjectsinthecurrentdebugtargetthathavereferencestotheselectedvariable.The
selectedvariableintheviewmustbeaJavaobject.ThiscommandisonlyavailableiftheJavavirtualmachineyouarecurrentlyusingsupportsreferenceretrieval.
Oncethepopuphasopened,youcanmovethelisttotheExpressionsViewbypressingCtrl+Shift+I.
Thereisamaximumnumberofreferencesthevirtualmachinewillreturn.Thismaximumcanbechangedonthe Java>Debug>HeapWalkingpreferencepage.
Thiscommandappliesto:
ExpressionsView
VariablesView

EvaluatingExpressions
RunMenu

5.8.5.7.ChangeVariableValue
SelecttheChangeValue...command[ ]toopenadialoginwhichyoucanchangethevalueoftheselectedvariableorregister.
IntheVariablesView,ifvariablesaredisplayedinthecolumnform,variablevaluescanalsocanbechangedbydirectlyeditingthevalueinthecolumn.
WhendebuggingaJavaprogram,therearethreedifferenttypesofdialogsthatthiscommandcanopen.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 244/322
12/10/2015 Javadevelopmentuserguide
TheChangePrimitiveValueDialogisusedtochangethevalueofaprimitivesuchasanint,long,orchar.

TheChangeObjectValueDialogisusedtochangethevalueofanObject.Therearetwoformsofthisdialog.
Formostobjectsyoumustenteranexpressionthatwillbeevaluatedtogeneratetheresultingvalue.

However,wheneditingJavaStrings,youmayalsoenterliteraltext.

Thiscommandappliesto:
ExpressionsView
RegistersView
VariablesView

EvaluatingExpressions

5.8.5.10.ConverttoWatchExpression
SelecttheConverttoWatchExpressioncommandtoconvertthecurrentlyselectedinspectexpressiontoawatchexpression.
Note:theinspectexpressionisremovedfromtheviewoncethewatchexpressioniscreated.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 245/322
12/10/2015 Javadevelopmentuserguide

ExpressionsView

5.8.5.11.DisableWatchExpression
SelecttheDisablecommandtodisabletheselectedwatchexpression.

ExpressionsView
EnableWatchExpression

5.8.5.12.EditWatchExpression...
SelecttheEditWatchExpression...commandtoopentheeditingdialogfortheselectedwatchexpression.
Theeditwatchexpressioncommand.

Theresultingeditdialog.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 246/322
12/10/2015 Javadevelopmentuserguide

ExpressionsView

5.8.5.13.EnableWatchExpression
SelecttheEnablecommandtoenabletheselectedwatchexpression.Theexpressionmustbedisabledforthiscommandtobeavailable.

ExpressionsView
DisableWatchExpression

5.8.5.15.InspectSelectedVariable
SelecttheInspectcommand[ ]tocreateaninspectexpressionassociatedwiththeselectedvariableandaddittotheExpressionsView.
Thiscommandappliesto:
ExpressionsView
VariablesView

EvaluatingExpressions

5.8.5.16.ViewJavaPreferences
SelecttheJavaPreferences...commandtoopenthepreferencepagescontainingoptionsrelatingtotheVariablesViewandtheExpressionsView.

Therearefourpagesintotalthatareshown,allasentriesinthetreeonthelefthandsideofthePreferencesDialog.
Thesepagesare:
The Java>Debug>DetailFormatterspreferencepage.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 247/322
12/10/2015 Javadevelopmentuserguide
The Java>Debug>HeapWalkingpreferencepage.
The Java>Debug>LogicalStructurespreferencepage.
The Java>Debug>PrimitiveDisplayOptionspreferencepage.
Thiscommandappliesto:
ExpressionsView
VariablesView

5.8.5.17.ReevaluateWatchExpression
SelecttheReevaluateWatchExpressioncommandtoforcetheselectedwatchexpressiontobeevaluated.

ExpressionsView

5.8.5.18.RemoveSelectedExpressions
SelecttheRemovecommand[ ]toremovetheselectedwatchexpression(s)fromtheExpressionsView.
Youcanalsoperformthissameactionbyselectingtheexpression(s)thatyouwishtoremoveandpressingtheDeletekey.

ExpressionsView

5.8.5.19.RemoveAllExpressions
SelecttheRemoveAllExpressionscommand[ ]theremovealloftheexpressionsfromtheExpressionsView.

ExpressionsView

5.8.5.21.ToggleFieldWatchpoint
SelecttheToggleWatchpointcommand[ ]tocreateanewwatchpointonthecurrentlyselectedfield.Wheneverthatfieldisaccessedormodified,executionwillbesuspended.
Iftheselectedfieldalreadyhasawatchpoint,selectingthiscommandwillremoveit.YoumustselectaJavafieldobjecttousethiscommand.
Thiscommandappliesto:
ExpressionsView
VariablesView

Breakpoints

Addingbreakpoints

5.8.6.PackageExplorerView
ThePackageExplorerview,shownbydefaultintheJavaperspective,showstheJavaelementhierarchyoftheJavaprojectsinyourworkbench.ItprovidesyouwithaJavaspecific
viewoftheresourcesshownintheNavigator.Theelementhierarchyisderivedfromtheproject'sbuildpaths.
Foreachproject,itssourcefoldersandreferencedlibrariesareshowninthetree.YoucanopenandbrowsethecontentsofbothinternalandexternalJARfiles.OpeningaJava
elementinsideaJARopenstheCLASSfileeditor,andifthereisasourceattachmentfortheJARfile,itscorrespondingsourceisshown.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 248/322
12/10/2015 Javadevelopmentuserguide
Toolbarbuttons
Command Name Description


Back Navigatestothemostrecentlydisplayedstateoftheviewwithadifferentelementatthetoplevel.


Forward Navigatestothestateoftheviewwithadifferentelementatthetoplevelthatwasdisplayedimmediatelyafterthecurrentstate.


Up Navigatestotheparentcontainerofthepackagethatiscurrentlydisplayedatthetoplevelintheview.

CollapseAll Collapsesalltreenodes.

LinkwithEditor Linksthepackageexplorer'sselectiontotheactiveeditor.


TopLevelElements> ShowsprojectastoplevelelementsinthePackageExplorer.Onlyprojectswhicharepartofthecurrentlyactiveworkingsetsareshown.
Projects Followingactionscanbeusedtoconfiguretheactiveworkingsets:
SelectWorkingSet:OpenstheSelectWorkingSetdialogtoallowselectingtheworkingsetfromwhichelementsshouldbeshown.
DeselectWorkingSet:Deselecttheactiveworkingsets.Allelementsareshownafterinvokingthisaction
EditActiveWorkingSet:OpenstheEditWorkingSetwizardtoeditthecurrentlyactiveworkingset


TopLevelElements> ShowsWorkingSetsastoplevelelementsinthePackageExplorer.
WorkingSets
TheConfigureWorkingSets...actioncanbeusedtoopenadialogwhichallowstoconfigurethevisibleworkingsets.

Filters... OpenstheJavaelementfiltersdialog.

Javaviews
Javaperspectives
Workingsets

Javaelementfiltersdialog
Viewsandeditors

5.8.6.1.JavaElementFiltersDialog
ThisdialogletsyoudefineJavaelementfiltersforthePackageExplorerviewandotherJavaviews.

Option Description Default

Namefilterpatterns Ifenabled,acommaseparatedlistofpatternscanbespecifiedadditionally. Off

Selecttheelementstoexcludefromtheview Listofpredefinedfilterswhichcanbeenabled. .*resources,


Emptylibrarycontainers
Emptyparentpackages,
Importdeclarations,
Innerclassfiles,
Packagedeclarations,
Syntheticmembers

TheFilterdescriptionfielddisplaysthedescriptionforthecurrentlyselectedfilter.

Filteringelements

PackageExplorerview

5.8.7.VariablesView
TheVariablesViewdisplaysinformationaboutthevariablesassociatedwiththestackframeselectedintheDebugView.WhendebuggingaJavaprogram,variablescanbe
selectedtohavemoredetailedinformationbedisplayedintheDetailPane.Inaddition,Javaobjectscanbeexpandedtoshowthefieldsthatvariablecontains.
TheVariablesView,shownwithcolumns.TheDetailPanetheareaatthebottomoftheviewdisplayingtext.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 249/322
12/10/2015 Javadevelopmentuserguide

TherearemanycommandsavailableintheVariablesView:
ViewDisplayCommandsaffectwhatvariablesaredisplayedandhowtheyarepresented.
TheDetailPanehasmanycommandsavailablebyrightclickingonit.
ViewLayoutCommandsaffecthowthedetailpaneisorientedandwhethercolumnsaredisplayed.
Othercommandsarelistedbelow.
VariablesViewCommands

Command Name Description Availability

AllInstances OpensapopupdialogdisplayingalistofallinstancesoftheselectedJavatype.YourJavavirtualmachinemustsupport Context


instanceretrieval. menu
AllReferences OpensapopupdialogdisplayingalistofallJavaobjectsthathavereferencestotheselectedvariable.YourJavavirtual Context
machinemustsupportreferenceretrieval. menu
ChangeValue... Allowsyoutochangethevaluefortheunderlyingselectedvariable. Context
menu
CollapseAll Collapsesallthecurrentlyexpandedvariables. Viewaction

Context
CopyVariables Copiestheselectedvariablestothesystemclipboard.
menu

CreateWatch Allowsyoutocreateawatchexpressionfortheselectedvariable. Context


Expression menu
EditLogicalStructure Allowyoutoeditthelogicalstructureoftheselectedvariable Context
menu
Find... Opensthesearchdialogtofindelementsinthevariablesview. Context
menu
Inspect Createsanewinspectstatementfortheselectedvariableandaddsittotheexpressionsview. Context
menu
InstanceBreakpoints... Allowsyoutofilterexistingbreakpointstotheselectedvariableinstance. Context
menu
JavaPreferences... Opensseveralpreferencepagescontainingoptionsthataffecttheview. Viewaction
NewDetailFormatter... Allowsyoutocreateyourowndetailformatterforthattypeofvariable. Context
menu
OpenActualType Openstheactualtypeoftheselectedvariable. Context
menu
OpenActualType Openstheactualtypehierarchyfortheactualtypeoftheselectedvariable. Context
Hierarchy menu
OpenDeclaredType Opensthedeclaredtypefortheselectedvariableinaneweditor. Context
menu
OpenDeclaredType Opensthetypehierarchyforthedeclaredtypeoftheselectedvariable. Context
Hierarchy menu
SelectAll Selectsallofthevariablesintheview. Context
menu
ShowStructureAs... Allowsyoutoselectadifferentformatterforshowingtheselectedlogicalstructuretypevariable. Context
menu
ShowDetailsAs... Allowsyoutoselectadifferentdetailpaneforshowingdetailedinformationaboutselectedvariables. Context
menu
ToggleWatchpoint Createsanewwatchpointonthecurrentlyselectedfieldorremovesthewatchpointifonealreadyexists. Context
menu

Javaviews
Javaperspectives

Suspendingthreads
Evaluatingexpressions

DetailPane

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 250/322
12/10/2015 Javadevelopmentuserguide
ViewDisplayCommands
ViewLayoutCommands
ExpressionsView

5.8.7.9.CreateWatchExpression
SelecttheCreateWatchExpressioncommand[ ]tocreateanewexpressionbasedontheselectedvariableandaddittotheExpressionsView.

Evaluatingexpressions

ExpressionsView
VariablesView

5.8.8.Javaoutline
ThisviewdisplaysanoutlineofthestructureofthecurrentlyactiveJavafileintheeditorarea.

Toolbarbuttons
Command Name Description

GointoTopLevelType Makesthetopleveltypeofthecompilationunitthenewinputforthisview.Packagedeclarationandimportstatementsarenolongershown.

CollapseAll Collapsealltopleveltypes.

Sort Thisoptioncanbetoggledtoeithersorttheoutlineelementsinalphabeticalorderorsequentialorder,asdefinedontheJava>Appearance
>MemberSortOrderpreferencepage.

HideFields Showsorhidesthefields.

HideStaticFieldsand Showsorhidesthestaticfieldsandmethods.
Methods

HideNonPublic Showsorhidesthenonpublicfieldsandmethods.
Members

HideLocalTypes Showsorhidesthelocaltypes.

Javaeditor
Javaviews
FilteringinJavaviews
Javaelementdecorations
SortingelementsinJavaviews
PresentationoptionsforJavaviews

Restoringadeletedworkbenchelement
Settingmethodbreakpoints

Overridemethods
Viewsandeditors

5.8.9.JavaScrapbookPage
ThescrapbookallowsJavaexpressionstoberun,inspected,anddisplayed,underthecontrolofthedebugger.
Note:Contentassist(suchascodeassist)isavailableonscrapbookpages.
JavaScrapbookpagebuttons

Command Name Description

RunSnippet Runninganexpressionevaluatesanexpressionbutdoesnotdisplayaresult.

Display Displayingshowstheresultofevaluatinganexpressionasastringinthescrapbookeditor.

Inspect InspectingshowstheresultofevaluatinganexpressionintheExpressionsview.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 251/322
12/10/2015 Javadevelopmentuserguide
Terminate ThiscommandterminatestheJavaVMthatisusedtoevaluateexpressions.

SettheImportDeclarations Thiscommandssetstheimportdeclarationstobeusedforthecontextofevaluatingthecode

Scrapbook

CreatingaJavascrapbookpage
Displayingtheresultofevaluatinganexpression
Inspectingtheresultofevaluatinganexpression
Executinganexpression

NewJavascrapbookpagewizard

5.8.10.TypeHierarchyView
Thisviewshowsthehierarchyofatype.TheTypeHierarchyviewconsistsoftwopanes:
TypeHierarchytreepane
Memberlistpane(optional)

TypeHierarchytreepanetoolbarbuttons
Thetypehierarchytreeshowssupertypes,suptypesorbothofagiventypedependingontheselectionmadeinthetoolbar.

Command Name Description

PreviousHierarchy Thismenudisplaysahistoryofpreviouslydisplayedtypehierarchies.
Inputs

ShowtheType Thiscommanddisplaysthetypeinitsfullcontext(i.e.,superclassesandsubclasses)intheTypeHierarchyview.Toseeforwhichtypethe
Hierarchy hierarchyisshown,hoverovertheviewtitle(e.g.,"Types").

Showthe ThiscommanddisplaysthesupertypesandthehierarchyofallimplementedinterfacesofthetypeintheTypeHierarchyview.Thetreestartsat
Supertype theselectedtypeanddisplaystheresultoftraversingupthehierarchy.
Hierarchy
Note:Theselectedtypeisalwaysatthetoplevel,intheupperleftcorner.

ShowtheSubtype Thiscommanddisplaysthesubtypesoftheselectedclassand/orallimplementorsoftheinterfaceintheTypeHierarchyview.Thetreestartsat
Hierarchy theselectedtypeanddisplaystheresultoftraversingdownthehierarchy
Note:Theselectedtypeisalwaysatthetoplevel,intheupperleftcorner.

Layout>Hierarchy Hidesthememberlistpane.
ViewOnly

Memberlistpanetoolbarbuttons
Thememberlistpanedisplaysthemembersofthecurrentlyselectedtypeinthetypehierarchytreepane.

Command Name Description

LockViewandShowMembersin ShowsthemembersimplementingtheselectedmethodOnlytypesimplementingthemethodareshown.
Hierarchy
Whentheviewislocked,thememberlistpanenolongertrackstheselectioninthehierarchypaneabove.

ShowAllInheritedMembers Showsorhidesallmethodsandfieldsinheritedbybaseclasses.Whenthisoptionisset,thenameofthetypethatdefinesthe
methodisappendedtothemethodname.

SortMembersbytheDefining Sortsthemembersaccordingtothetypeinwhichtheyaredefined.
Type

HideFields Showsorhidesthefields.

HideStaticFieldsandMethods Showsorhidesthestaticfieldsandmethods.

HideNonPublicMembers Showsorhidesthenonpublicfieldsandmethods.

Javaviews

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 252/322
12/10/2015 Javadevelopmentuserguide

Viewsandeditors

5.8.11.CallHierarchyView
TheCallHierarchyviewshowscallersandcalleesforaselectedJavamember.
CallHierarchycommands:

Command Name Description

Refresh Refreshthewholehierarchy

Refresh(context Refreshtheselectedelementsandtheirdirectchildren
menu)

CancelCurrentSearch Cancelthecurrentrunningsearch.Usefulforlongrunningsearches.

ShowCallerHierarchy Showallcallersinthesearchscopeoftheselectedmember.

ShowCalleeHierarchy Showallmemberswhicharecalledbythecurrentlyselectedmember.

ShowHistoryList Thismenudisplaysahistoryofpreviouslydisplayedcallhierarchies.

PintheCallHierarchy PinsthecurrentviewandenablestheusertoopenmultipleCallHierarchyviewsatthesametime.
View


Layout Specifiesthelayoutofthecallhierarchyviews


FieldAccesses Specifieswhichfieldaccessestoshow:Readorwriteaccesses,orboth


SearchIn... SpecifieswhereinthescopetheCallHierarchyshouldsearchforresults.


SearchScope Definesthescopeforthesearchforcallers.

Filters Specifiesthepatternswhosematchingmemberswillbehiddenfromtheview.


Expandwith Expandsandreplacesaninstancemethod'snormalchildrenwith:
Constructors(context
menu) theconstructorsofthemethod'sdeclaringclass
anodethatcontainsthedirectcallersofthemethod
Thisisespeciallyusefulformethodsinanonymousclasses.


Expandwith Specifiesthelistoftypeswhoseinstancemethodsareexpandedwithconstructorsbydefault.Thefeaturecanalsobeenabledordisabled
Constructors... forallmethodsdeclaredinanonymoustypesatonceusingtheAllmethodsinanonymoustypesoption.

RemovefromView Removetheselectednodesfromtheview

Javaviews

Viewsandeditors

5.8.12.JUnitView
TheJUnitviewshowsyoutheJUnittestrunprogressandstatus,andallowsyoutoreruntests.
JUnitViewcommands:

Command Name Description

NextFailedTest Navigatestothenextfailedtest.

PreviousFailedTest Navigatestothepreviousfailedtest.

ShowFailuresOnly Showsonlyfailedtests.

ScrollLock Changesifscrolllockshouldbeenabledornot.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 253/322
12/10/2015 Javadevelopmentuserguide

RerunTest Rerunthetest.

RerunTestFailuresFirst Rerunthetest,andrunthefailuresfirst.

StopJUnitTestRun StopsthecurrentJUnittestrun.

TestRunHistory Thismenudisplaysahistoryofpreviouslyruntests.


ClearTerminated Clearsalltheterminatedtestrunsfromthehistroy.


Import... ImportsatestrunresultfromaXMLfile.


ImportfromURL... ImportsatestrunresultviaanURL.


ImportURLfromClipboard ImportsatestrunresultviaanURLplacedonclipboard.


Export ExportsthetestrunresulttoaXMLfile.

ShowTestsinHierarchy Showsthetestsinahierarchicallayout.


ShowExecutionTime Showsexecutiontimeforthetests.


Layout SpecifiesthelayoutoftheJUnitview.


ActivateonError/FailureOnly ChangesiftheJUnitviewshouldbeactivatedonlyonerror/failureornot.

Javaviews

Viewsandeditors

5.8.13.JavadocView
TheJavadocviewshowstheJavadocoftheelementselectedintheJavaeditororinaJavaview.
Youcanalsoclickindividualpackagenamesdisplayedintheheadertoseeapackage'sJavadoc.
JavadocViewcommands:

Command Name Description

Back Navigatestothepreviouspage.

Forward Navigatestothenextpage.

LinkwithSelection LinkstheJavadocview'sinputwiththeselectionintheJavaeditororinaJavaview.

LinkwithSelection(showinglastvalidinput) IndicatesthattheJavadocview'scontentisnolongerinsyncwiththecurrentselection.

OpenInput OpensthecurrentinputelementoftheJavadocviewintheJavaeditor.

OpenAttachedJavadocinaBrowser(Shift+F2) OpenstheattachedjavadocofcurrentinputoftheJavadocviewinabrowser.

Javaviews

Viewsandeditors

5.9.1.Content/CodeAssist
IntheJavaeditorpressCtrl+Spaceoncodetocomplete.Thisopensalistofavailablecodecompletions.Sometipsforusingcodeassistarelistedinthefollowingparagraph:
Youcanusethemouseorthekeyboard(UpArrow,DownArrow,PageUp,PageDown,Home,End,Enter)tonavigateandselectlinesinthelist.
Ifyouselectalineinthecontentassistlist,youcanviewJavadocinformationforthatline.
ClickingorpressingEnteronaselectedlineinthelistinsertstheselectionintotheeditor.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 254/322
12/10/2015 Javadevelopmentuserguide
YoucanaccessspecializedcontentassistfeaturesinsideJavadoccomments.

ConfigurethebehaviorofthecontentassistintheJava>Editor>CodeAssistpreferencepage.

Javaeditor
Javadevelopmenttools(JDT)

Editmenu
Javaeditorpreferences
Templatespreferences

5.9.2.Formatter
IntheJavaeditorpressCtrl+Shift+Foncodetoformatit.Ifnoselectionissetthentheentiresourceisformattedotherwiseonlytheselectionwillbe.Sometipsforusingthe
formatterarelistedintheparagraphsofthischapter.
NotethattheJavaFormatterpreferencesareaccessibleonthe JavaFormatterpreferencepage.

Disablingformatterinsidesections
Youcandisable/enabletheformatterinoneorseveralsectionsinthecodeasshowninthesamplebelow:

Thesnippetaboveusedefaulttagnames,buttheycanbechangedontheOff/OntagstaboftheJavaFormatterpreferencepage.

Wrapoutermostmethodcalls
Sinceversion3.6,theJavaformatternowtriestowraptheoutermostmethodcallsfirsttohaveabetteroutputwhenwrappingnestedmethodcalls.
Hereisanexampleofaformattedcodewheretheformatterhaswrappedthelinebetweentheargumentsoftheoutermostmessagecalltokeepeachnestedmethodcallonasingle
line:

Anewpreferenceallowsyoutodisablethisstrategy,typicallyifyouwanttoformatyourcodeasbefore,thenuncheckthePreferwrappingouterexpressionspreference
accessibleontheLinewrappingtaboftheJavaFormatterpreferencepage.
Note:Currentlythenewstrategyonlyappliestonestedmethodcalls,butthatmightbeextendedtoothernestedexpressionsinfutureversions.

CondenseJavadocandblockcomments
Userscanreducethenumberoflinesofformattedmultilinescommentsasshownintheexamplebelow:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 255/322
12/10/2015 Javadevelopmentuserguide

Toactivatethisbehavioruncheckthe/*and*/onseparatelinespreferenceaccessibleontheCommentstaboftheJavaFormatterpreferencepage.
ThesamekindofpreferenceisalsoavailablefortheJavadoccomments.

Preserveuserlinebreaks
Userscanpreservelinebreaksbynotjoininglinesincodeorcomments.
Forexample,thealreadywrappedlinesofthereturnstatementinthefollowingtestcase:

willbepreservedbytheformatterwhentheNeverjoinlinespreferenceisused,henceproducesthefollowingoutputwhenformatted:

ToactivatethisbehaviorchecktheNeverjoinlinespreferenceaccessibleontheLineWrappingandtheCommentstabsoftheJavaFormatterpreferencepage.

Javaeditor
Javadevelopmenttools(JDT)

Editmenu
Javaeditorpreferences
Formatterpreferences

5.9.3.QuickFix
TheJavaeditorofferscorrectionstoproblemsfoundwhiletypingandaftercompiling.Toshowthatcorrectionproposalsareavailableforaproblemorwarning,a'lightbulb'isvisible
ontheeditor'sannotationbar.

LeftclickonthelightbulborinvokingCtrl+1(Edit>QuickFix)bringsuptheproposalsfortheproblematthecursorposition.
Eachquickfixshowsapreviewwhenselectedintheproposalwindow.

Quickfixesarealsoshowndirectlyinproblemhovers(butthere,nopreviewisavailable).

Usagehint:Quickfixesarenotonlyusefultofixerrorsthataccidentallyoccurred.Anothercommonusagepatternistoinentionallywrite"incorrect"code,forexamplebyreferringto
alocalvariablethatisnotdeclaredyet.Then,theCreatelocalvariableQuickFixcangeneratethedeclarationinnotime,anditcaneveninferthevariabletype.
Someselectedquickfixescanalsobeassignedwithdirectshortcuts.Youcanconfiguretheseshortcutsonthe General>Keyspreferencepage(inthe'Source'category).
Somequickfixesoffertofixallproblemsofthesamekindinthecurrentfileatonce.Theinformationtextintheproposalwindowcontainsthisinformationforallapplicableproposals.
Tofixallproblemsofthesamekind,pressCtrl+Enter.
Here'saselectionofavailablequickfixes:

PackageDeclaration
Addmissingpackagedeclarationorcorrectpackagedeclaration
Movecompilationunittopackagethatcorrespondstothepackagedeclaration

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 256/322
12/10/2015 Javadevelopmentuserguide
Imports
Removeunused,unresolvableornonvisibleimport
Invoke'Organizeimports'onproblemsinimports

Types
Createnewclass,interface,enum,annotationortypevariableforreferencestotypes
thatcannotberesolved
Changevisibilityfortypesthatareaccessedbutnotvisible
Renametoasimilartypeforreferencestotypesthatcannotberesolved
Addimportstatementfortypesthatcannotberesolvedbutexistintheproject
Addexplicitimportstatementforambiguoustypereferences(twoimportondemandsfor
thesametype)
Ifthetypenameisnotmatchingwiththecompilationunitnameeitherrenamethetypeor
renamethecompilationunit
Removeunusedprivatetypes
Addmissingtypeannotationattributes

Constructors
Createnewconstructorforreferencestoconstructorsthatcannotberesolved(this,
superornewclasscreation)
Reorder,addorremoveargumentsforconstructorreferencesthatmismatchparameters
Changemethodwithconstructornametoconstructor(removereturntype)
Changevisibilityforconstructorsthatareaccessedbutnotvisible
Removeunusedprivateconstructor
Createconstructorwhensupercalloftheimplicitdefaultconstructorisundefined,not
visibleorthrowsanexception
Iftypecontainsunimplementedmethods,changetypemodifierto'abstract'oraddthe
methodtoimplement

Methods
Createnewmethodforreferencestomethodsthatcannotberesolved
Renametoasimilarmethodforreferencestomethodsthatcannotberesolved
Reorderorremoveargumentsformethodreferencesthatmismatchparameters
Correctaccess(visibility,static)ofreferencedmethods
Removeunusedprivatemethods
Correctreturntypeformethodsthathaveamissingreturntypeorwherethereturntype
doesnotmatchthereturnstatement
Addreturnstatementifmissing
Fornonabstractmethodswithnobodychangeto'abstract'oraddbody
Foranabstractmethodinanonabstracttyperemoveabstractmodifierofthemethodor
maketypeabstract
Foranabstract/nativemethodwithbodyremovetheabstractornativemodifierorremove
body
Changemethodaccessto'static'ifmethodisinvokedinsideaconstructorinvocation
(super,this)
Changemethodaccesstodefaultaccesstoavoidemulatedmethodaccess
Add'synchronized'modifier
OverridehashCode()
Openthe'GeneratehashCode()andequals()'wizard

Fieldsandvariables
Correctaccess(visibility,static)ofreferencedfields
Createnewfields,parameters,localvariablesorconstantsforreferencestovariables
thatcannotberesolved
Renametoavariablewithsimilarnameforreferencesthatcannotberesolved
Removeunusedprivatefields
Correctnonstaticaccessofstaticfields
Add'final'modifiertolocalvariablesaccessedinoutertypes
Changefieldaccesstodefaultaccesstoavoidemulatedmethodaccess
Changelocalvariabletypetofixatypemismatch
Initializeavariablethathasnotbeeninitialized
Creategetterandsettersforinvisibleorunusedfields
Createloopvariabletocorrectanincompleteenhanced'for'loopbyaddingthetypeof
theloopvariable

ExceptionHandling
Removeunneededcatchblock
Removeunneededexceptionsfromamulticatchclause(1.7orhigher)
Handleuncaughtexceptionbysurroundingwithtry/catchoraddingcatchblocktoa
surroundingtryblock
Handleuncaughtexceptionsbysurroundingwithtry/multicatchoraddingexceptionsto
existingcatchclause(1.7orhigher)
Handleuncaughtexceptionbyaddingathrowdeclarationtotheparentmethodorby
generalizeanexistingthrowdeclaration

BuildPathProblems
AddamissingJARorlibraryforanunresolvabletype
Openthebuildpathdialogforaccessrestrictionproblemsormissingbinaryclasses.
ChangeprojectcomplianceandJREto1.5
ChangeworkspacecomplianceandJREto1.5

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 257/322
12/10/2015 Javadevelopmentuserguide
Others
Addcastorchangecasttofixtypemismatches
Letatypeimplementaninterfacetofixtypemismatches
Addtypeargumentstorawreferences
Completeswitchstatementsoverenums
Removedeadcode
Insert'//$FALLTHROUGH$'
Insertnullcheck
FornonNLSstringsopentheNLSwizardormarkasnonNLS
Addmissing@Override,@Deprecatedannotations
AddmissingJavadoccomments
AddmissingJavadoctags
Suppressawarningusing@SuppressWarnings
Throwtheallocatedobject
Returntheallocatedobject
Add@SafeVarargsannotationforheappollutionwarnings(1.7orhigher)
Removeinvalid@SafeVarargsannotations(1.7orhigher)
Removeredundanttypearguments(1.7orhigher)
Addinferredtypearguments(1.5and1.6)
Removeunusedtypeparameter(1.5orhigher)

QuickAssistsareproposalsavailableevenifthereisnoproblemorwarning.SeetheQuickAssistpageformoreinformation.

Javaeditor
Quickfixandassist

QuickAssist
JDTactions

5.9.4.QuickAssist
Quickassistsperformlocalcodetransformations.TheyareinvokedonaselectionorasinglecursorintheJavaeditorandusethesameshortcutasquickfixes(Ctrl+1),butquick
assistareusuallyhiddenwhenanerrorisaround.Toshowthemevenwitherrorspresentonthesameline,pressCtrl+1asecondtime.

Aselectionofquickassistscanbeassignedtoadirectshortcut.Bydefault,theseare:
Renameinfile:Ctrl+2,R
Assigntolocal:Ctrl+2,L
Assigntofield:Ctrl+2,F
Assignmoreshortcutsorchangethedefaultshortcutsonthe General>Keyspreferencepage(inthe'Source'category).

Aquickassistlightbulbcanbeturnedononthe Java>Editorpreferencepage.

Name Codeexample Invocationlocation

Inverseifstatement if(x)a()elseb() > if(!x)b()elsea() On'if'statementswith


'else'block

Converttoif!return if(x==1)a() > if(x!=1)return Onan'if'statement


a()

Inverseboolean a&&!b > !a||b Onabooleanexpression


expression

Invertlocalvariable booleana=false > booleannotA=true Onabooleanvariable


if(a){} if(!notA){}

Invertequals a.equals(b) > b.equals(a) Onainvocationof


'equals'

Inverseconditional x?b:c > !x?c:b Onaconditional


expression expression

Pullnegationup b&&c > !(!b||!c) Onabooleanexpression

Pushnegationdown !(b&&c) > !b||!c Onanegatedboolean


expression

Removeextra if((a==b)&&(c!=d){} > if(a==b&&c!=d){} Onselectedexpressions


parentheses

Putexpressionin returna>10?1:2 > return(a>10)?1:2 Onselectedexpression


parentheses

Putexpressionsin if(a==b&&c!=d){} > if((a==b)&&(c!=d)){} Onselectedexpressions


parentheses

Joinnestedif if(a){if(b){}} > if(a&&b){} Onanestedifstatement


statements

Swapnestedif if(a){if(b){}} > if(b){if(a){}} Onanestedifstatement


statements

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 258/322
12/10/2015 Javadevelopmentuserguide
Splitifstatementwith if(a&&b){} > if(a){if(b){}} Onanand'edexpression
and'edexpression ina'if'

Joinselected'if' if(a)x()if(b)x() > if(a||b)x() Onselected'if'


statementswith|| statements

Join'if'sequenceinif if(a)x()if(b)y() > if(a)x()elseif(b)y() Onselected'if'


elseif statements

Splitifstatementwith if(a||b)x() > if(a)x()if(b)x() Onanor'dexpressionin


or'dexpression a'if'

Ifelseassignmentto if(a)x=1elsex=2 > x=a?1:2 Onan'if'statement


conditionalexpression

Ifelsereturnto if(a)return1 > returna?1:2 Onan'if'statement


conditionalexpression elsereturn2

Conditionalexpression x=a?1:2 > if(a)x=1elsex=2 Onaconditional


assignmenttoIfelse expression

Conditionalexpression returna?1:2 > if(a)return1elsereturn2 Onaconditional


returntoIfelse expression

SwitchtoIfelse switch(kind){ > if(kind==1){ Onaswitchstatement


case1:return1 return1
case2:return2 }elseif(kind==2){
} return2
}

Convertifelsetoswitch if(kind==1){ > switch(kind){ Onan'if'statement


return1 case1:return1
}elseif(kind==2){ case2:return2
return2 }
}

Addmissingcase switch(e){ > switch(e){ Onaswitchstatement


statementsonenums } caseE1:break
caseE2:break
}

Exchangeoperands a+b > b+a Onaninfixoperation

Castandassign if(objinstanceofVector){ > if(objinstanceofVector){ Onaninstanceof


} Vectorvec=(Vector)obj expressioninan'if'or
} 'while'statement

Useseparatecatch try{ > try{ Onamulticatchblock


blocks }catch(FileNotFoundException| }catch(FileNotFoundExceptione){ (1.7orhigher)
InterruptedIOExceptione){ }catch(InterruptedIOExceptione){
} }

Moveexceptionsto try{ > try{ Onexceptionsinamulti


separatecatchblocks }catch(FileNotFoundException| }catch(FileNotFoundExceptione){ catchclause(1.7or
InterruptedIOException|IllegalArgumentException }catch(InterruptedIOException| higher)
e){ IllegalArgumentExceptione){
} }

Combinecatchblocks try{ > try{ Onacatchblock(1.7or


}catch(FileNotFoundExceptione){ }catch(FileNotFoundException| higher)
}catch(InterruptedIOExceptione){ InterruptedIOExceptione){
} }

Addfinallyblock try{ > try{ Onatry/catchstatement


}catch(Exceptione){ }catch(Exceptione){
} }finally{}

Addelseblock if(a)b() > if(a)b()else{} Onaifstatement

Replacestatementwith if(a)b() > if(a){b()} Onaifstatement


block

Unwrapblocks {a()} > a() Onblocks,if/while/for


statements

CombinetosingleString Stringphrase="one"+"two"+"three" > Stringphrase="onetwothree" Onastring


concatenation
expression

Pickoutstring "abcdefgh" > "abc"+"de"+"fgh" selectapartofastring


literal

Convertstring "Hello"+name > StringBuilderbuilder=newStringBuilder() selectastringliteral


concatenationto builder.append("Hello")
StringBuilder(J2SE5.0) builder.append(name)
orStringBuffer

Convertstring "Hello"+name > MessageFormat.format("Hello{0}",name) selectastringliteral


concatenationto
MessageFormat

Splitvariable inti=0 > intii=0 Onavariablewith


initialization

Joinvariable intii=0 > inti=0 Onavariablewithout


initialization

Assigntovariable foo() > Xx=foo() Onanexpression


statement

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 259/322
12/10/2015 Javadevelopmentuserguide
Extracttolocal foo(getColor()) > Colorcolor=getColor() Onanexpression
foo(color)

Assignparametertofield publicA(intcolor){} > ColorfColor Onaparameter


publicA(intcolor){
fColor=color
}

ArrayinitializertoArray int[]i={1,2,3} > int[]i=newint[]{1,2,3} Onanarrayinitializer


creation

Create'for'loops voidfoo(Map<String,Integer>map){ > voidfoo(Map<String,Integer>map){ Onarrays,Collections


map.keySet() for(Stringstring:map.keySet()){ andLists
} }
}

Convertto'enhancedfor for(Iteratori=c.iterator()i.hasNext()){ > for(x:c){ Onaforloop


loop'(J2SE5.0) } }

Converttoindexed'for' for(x:c){ > for(inti=0i<c.size()i++){ Onanenhancedforloop


loop(J2SE5.0) } x=c[i]
}

ConverttoIteratorbased for(x:c){ > for(Iteratori=c.iterator()i.hasNext()){ Onanenhancedforloop


'for'loop(J2SE5.0) } }

Createmethodinsuper Onamethoddeclaration
class

Renameinfile Onidentifiers

Renameinworkspace Onidentifiers

Extracttolocalvariable a=b*8 > intx=b*8 Onexpressions


a=x

Extracttoconstant a=8 > finalstaticintCONST=8 Onexpressions


a=CONST

Extractmethod intx=p*5 > intx=getFoo(p) Onexpressionsand


statements

Inlinelocalvariable inta=8,b=a > intb=8 Onlocalvariables

Convertlocalvariableto voidfoo(){inta=8} > inta=8voidfoo(){} Onlocalvariables


field

Convertanonymousto newRunnable(){} > classRunnableImplementationimplementsRunnable Onanonymousclasses


nestedclass {}

Converttolambda Runnabler=newRunnable(){ > Runnabler=()>{} Onanonymousclasses


expression publicvoidrun(){} implementinga
} functionalinterface(1.8
orhigher)

Converttoanonymous Runnabler=()>{} > Runnabler=newRunnable(){ Onlambdaexpressions


classcreation publicvoidrun(){} (1.8orhigher)
}

Converttolambda Consumer<Integer>c=System.out::println > Consumer<Integer>c=t>System.out.println(t) Onmethodreferences


expression (1.8orhigher)

Converttomethod Consumer<Integer>c=t>System.out.println(t) > Consumer<Integer>c=System.out::println Onlambdaexpressions


reference (1.8orhigher)

Changebodyexpression Runnabler=()>System.out.println() > Runnabler=()>{ Onlambdaexpressions


toblock System.out.println() withbodyasexpression
} (1.8orhigher)

Changebodyblockto Runnabler=()>{ > Runnabler=()>System.out.println() Onlambdaexpressions


expression System.out.println() withbodyasblock(1.8
} orhigher)

Addinferredlambda Consumer<Integer>c=t>System.out.println(t) > Consumer<Integer>c=(Integert)> Onlambdaexpressions


parametertypes System.out.println(t) withinferredparameter
types(1.8orhigher)

Addparenthesesaround Consumer<Integer>c=t>System.out.println(t) > Consumer<Integer>c=(t)> Onlambdaexpressions


lambdaparameter System.out.println(t) (1.8orhigher)

Removeparentheses Consumer<Integer>c=(t)> > Consumer<Integer>c=t>System.out.println(t) Onlambdaexpressions


aroundlambda System.out.println(t) (1.8orhigher)
parameter

Replacewithgetterand p.x > p.getX() Onfields


setter(Encapsulate
Field)

Insertinferredtype List<String>list=newArrayList<>() > List<String>list=newArrayList<String>() Ongenericinstance


arguments creationexpressions(1.7
orhigher)

ThefollowingquickassistsareavailableinthePropertiesFileEditor:
Renameinworkspacerenamesthekeyinthepropertiesfileandupdatesallreferences
Createfieldin'...'createsthecorrespondingfieldintheresourcebundleaccessorclass
Removepropertydeletesthepropertyfromthepropertiesfileandthefieldfromtheresourcebundleaccessorclass

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 260/322
12/10/2015 Javadevelopmentuserguide
Removepropertiesdeletestheselectedpropertiesfromthepropertiesfileandthefieldsfromtheresourcebundleaccessorclass
Escapebackslashesescapeallbackslashesintheselectedtext
Escapebackslashesinoriginalstringescapeallbackslashesinthepastedtext
Unescapebackslashesunescapeallbackslashesintheselectedtext

JavaEditor
QuickFixandQuickAssist

QuickFix
JDTactions

5.10.1.1.NewJavaProjectWizard
The NewJavaProjectwizardhelpsyoucreateanewJavaprojectintheworkbench.

Projectnamepage
Option Description Default
Project Typeanameforthenewproject. <blank>
name
Location When'Usedefaultlocation'isselected,theNewProjectWizardwillcreateanewprojectwiththespecifiednameintheworkspace. workspace

Otherwise,youcanspecifythelocationfromwhichtheNewJavaProjectWizardwillretrieveanexistingJavaproject.Inthiscasethe
wizardwillanalyzetheexistingprojectandsetupthebuildpathautomatically.ClickonBrowse...tobrowseforalocationofanexisting
Javaproject.
JRE UsedefaultJRE
UsedefaultJRE:
Whenselected,theNewJavaProjectWizardcreatesanewJavaprojectwhichusestheworkspacedefaultJRE.Thedefault
JREcanbeconfiguredontheJava>InstalledJREspreferencepage.
TheprojectwillalsousethedefaultcompilercompliancewhichcanbeconfiguredontheJava>Compilerpreferencepage.
ClickonConfiguredefault...toconfigurethedefaultJREandcompilercompliance.
UseprojectspecificJRE:
Whenselected,youcanexplicitlyspecifytheJREtobeusedforthenewJavaproject.Thenewprojectwilluseacompiler
compliancewhichmatchestheversionoftheselectedJRE.
UseanexecutionenvironmentJRE:
Whenselected,youcanspecifyanexecutionenvironmenttobeusedforthenewJavaproject.Thenewprojectwillusea
compilercompliancewhichfitsbesttheselectedexecutionenvironment.
ExecutionenvironmentscanbeconfiguredontheJava>InstalledJREs>ExecutionEnvironmentspreferencepage.

Project Createseparatefoldersfor
layout Useprojectfolderasrootforsourcesandclassfiles: sourcesandclassfiles
Whenselected,theprojectfolderisusedbothassourcefolderandasoutputfolderforclassfiles.
Createseparatefoldersforsourcesandclassfiles:
Whenselected,theNewJavaProjectWizardcreatesasourcefolderforJavasourcefilesandanoutputfolderwhichholdsthe
classfilesoftheproject.

Working Dependsonthecontextfrom
sets Addprojecttoworkingsets: whichthewizardhasbeen
Whenselected,thenewprojectwillbeaddedtotheworkingsetsshowninWorkingSetsdropdownfield.Thedropdownfield started
showsalistofpreviousselectedworkingsets.
ClickonSelect...toselectworkingsetstowhichtoaddthenewproject.

JavaBuildPathpage
YoucanskipthispagebypressingFinishonthefirstpage.OtherwisepressNexttoconfiguretheJavabuildpath.
TheJavabuildpathconsistofsource,libraryandprojectentries.TheuserinterfaceisthesameasfortheBuildPathpropertypage,exceptforthesourcetab:

Sourcetab
Sourcefoldersaretoplevelfoldersintheprojecthierarchy.Theyaretherootofpackagescontaining.javafiles.Thecompilerwilltranslatethecontainedfilesto.classfilesthatwill
bewrittentotheoutputfolder.
Sourcefoldersallowtostructuretheproject,forexampletoseparatetestfromtheapplicationintwosourcefolders.Withinasourcefolder,amoredetailedstructuringcanbe
achievedbyusingpackages.
Eachsourcefoldercandefineanexclusionfiltertospecifywhichresourcesinsidethefoldershouldnotbevisibletothecompiler.
ResourcesexistinginsourcefoldersarecopiedtotheoutputfolderunlessthesettingintheJava>Compiler>Buildingpreferencepagespecifiesthattheresourceisfiltered.The
outputfolderisdefinedperprojectexceptifasourcefolderspecifiesitsownoutputfolder.
Thetreeshowstheprojectasitwilllooklikewhenswitchingtothepackageexplorer.Severaloperationscanbeexecutedonthistreetochangethestructureoftheproject.

Icon Option Description

Addsourcefolder AddafoldertotheJavabuildpathassourcefolder.

Linkadditional AddalinktoafolderinthefilesystemassourcefoldertotheJavabuild
sourcetoproject path.
Removefrom RemoveasourcefolderfromtheJavabuildpathandchangeitintoa
buildpath normalfolder.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 261/322
12/10/2015 Javadevelopmentuserguide
Addaresourcetotheexclusionfilterofitsparentsourcefolder.The
Exclude
excludedresourceandallitschildrenarenolongervisibletothecompiler.

Include Includesapreviouslyexcludedresource.

Theeditsourcefolderpropertymenuhastwoactions
1. ConfigureInclusion/ExclusionsFilters:Customizethe
inclusionandexclusionfiltersbydefiningstringpatterns.Itis
Configuresource possibletousewildcardinpatters(i.e.toexcludealljavafiles
folderproperties whichstartwith"Test"write"Test*.java").
2. ConfigureOutputFolder:Changetheoutputfolderforasource
folder.ThisactionisonlyenabledifAllowoutputfoldersfor
sourcefoldersisenabled.

Allchangesthathavebeenappliedtotheprojectinthiswizardwillbe
Undoallchanges
withdrawnandtheoriginalstateoftheprojectisreconstructed.
Allowoutput Ifenabled,eachsourcefoldercanhaveitsownoutputfolder.Otherwise
foldersforsource allsourcefolderswillusethedefaultoutputfolder.
folders

AshorterdescriptionofalloperationsisvisibleintheDetailspanebelowtheprojecttree.

Librarytab,ProjecttabandOrderTab
SeeBuildPathpropertypageformoredetails.

Javaprojects

Fileactions

5.10.1.2.NewJavaPackageWizard
The NewJavaPackagewizardhelpsyoucreateafoldercorrespondingtoanewJavapackageandoptionallyapackageleveldocumentationfile.Itcanalsobeusedtoadd
packageleveldocumentationtoanexistingpackage.
Thecorrespondingfolderofthedefaultpackagealwaysexists,andthereforedoesn'thavetobecreated.
JavaPackageOptions
Option Description Default
Sourcefolder Typeorbrowsetoselectacontainer(projectorfolder)forthenewpackage. Thesourcefolderoftheelementthatwasselected
whenthewizardhasbeenstarted.
Name Typeanameforthenewpackage Theprojectname,ifitisavalidpackagenameand
ifthesourcefolderdoesnotcontainanyother
package,otherwise<blank>
Createpackage false
info.java Whetherapackageinfo.javafileshouldbecreatedinthepackage.
Thepackageinfo.javafilecontainspackageleveldocumentationaswellasannotations.Forexample:

/**
*ThispackagecontainsJAXBclasses.
*/
@XmlSchema(namespace="http://www.example.com",elementFormDefault=XmlNsForm.QUALIFIED)
packagecom.acme.jaxb

Formoreinformation,refertotheJavaLanguageSpecificationSection7.4.1.NamedPackages.
Ifthesourcelevelis1.4orbelow,apackage.htmlwillbecreatedinstead.

Fileactions

5.10.1.3.NewJavaClassWizard
The NewJavaClasswizardhelpsyoutocreateanewJavaclassinaJavaproject.
JavaClassOptions
Option Description Default
Sourcefolder Enterasourcefolderforthenewclass.Eithertypeavalidsource Thesourcefolderoftheelementthatwasselectedwhenthewizardhasbeenstarted.
folderpathorclickBrowsetoselectasourcefolderviaadialog.
Package Enterapackagetocontainthenewclass.Youcanselecteitherthis Thepackageoftheelementthatwasselectedwhenthewizardhasbeenstarted.Ifasource
optionortheEnclosingTypeoption,below.Eithertypeavalid folderwasselectedwhichcontainsexactlyonepackagethenthatpackageisused.Ifthe
packagenameorclickBrowsetoselectapackageviaadialog. sourcefolderdoesnotcontainanypackagethentheprojectnameisusedifitisavalid
packagename.
Enclosing Selectthisoptiontochooseatypeinwhichtoenclosethenew Thetypeortheprimarytypeofthecompilationunitthatwasselectedwhenthewizardhas
type class.YoucanselecteitherthisoptionorthePackageoption, beenstartedor<blank>
above.EithertypeavalidnameinthefieldorclickBrowsetoselect
atypeviaadialog.

Name Typeanameforthenewclass. <blank>

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 262/322
12/10/2015 Javadevelopmentuserguide
Modifiers public
Selectoneormoreaccessmodifiersforthenewclass.
Eitherpublic,package,private,orprotected(privateand
protectedareonlyavailableifyouspecifyanenclosingtype)
abstract
final
static(onlyavailableifyouspecifyanenclosingtype)

Superclass TypeorclickBrowsetoselectasuperclassforthisclass. Thetype(notthecompilationunit!)thatwasselectedwhenthewizardhasbeenstartedor


<java.lang.Object>
Interfaces ClickAddtochooseinterfacesthatthenewclassimplements. <blank>
Which Inheritedabstractmethodsenabled
methodstubs Choosethemethodstubstocreateinthisclass:
wouldyou publicstaticvoidmain(String[]args):Addsamainmethodstub
liketo tothenewclass.
create?
Constructorsfromsuperclass:Copiestheconstructorsfromthe
newclass'ssuperclassandaddsthesestubstothenewclass.
Inheritedabstractmethods:Addstothenewclassstubsofany
abstractmethodsfromsuperclassesormethodsofinterfaces
thatneedtobeimplemented.

Doyouwant Whenselected,thewizardaddscommentstothenewclasswhere Donotaddcomments


toadd appropriate.
comments?

Fileactions

5.10.1.4.NewJavaEnumWizard
The NewJavaEnumTypewizardhelpsyoutocreateanewJavaenuminaJavaproject.
JavaEnumOptions
Option Description Default
Source Enterasourcefolderforthenewenum.Eithertypeavalidsource Thesourcefolderoftheelementthatwasselectedwhenthewizardhasbeenstarted.
folder folderpathorclickBrowsetoselectasourcefolderviaadialog.
Package Enterapackagetocontainthenewenum.Youcanselecteitherthis Thepackageoftheelementthatwasselectedwhenthewizardhasbeenstarted.Ifasource
optionortheEnclosingTypeoption,below.Eithertypeavalid folderwasselectedwhichcontainsexactlyonepackagethenthatpackageisused.Ifthe
packagenameorclickBrowsetoselectapackageviaadialog. sourcefolderdoesnotcontainanypackagethentheprojectnameisusedifitisavalid
packagename.
Enclosing Selectthisoptiontochooseatypeinwhichtoenclosethenewenum. Thetypeortheprimarytypeofthecompilationunitthatwasselectedwhenthewizardhas
type YoucanselecteitherthisoptionorthePackageoption,above.Either beenstartedor<blank>
typeavalidnameinthefieldorclickBrowsetoselectatypeviaa
dialog.
Name Typeanameforthenewenum. <blank>
Modifiers public
Selectoneormoreaccessmodifiersforthenewenum.
Eitherpublic,package,private,orprotected(privateand
protectedareonlyavailableifyouspecifyanenclosingtype)

Interfaces ClickAddtochooseinterfacesthatthenewenumimplements. <blank>


Doyou Whenselected,thewizardaddscommentstothenewenumwhere Donotaddcomments
wanttoadd appropriate.
comments?

Fileactions

5.10.1.5.NewJavaInterfaceWizard
The NewJavaInterfacewizardhelpsyoutocreateanewJavainterfaceinaJavaproject.
JavaInterfaceOptions
Option Description Default
Source Enterasourcefolderforthenewinterface.Eithertypeavalidsource Thesourcefolderoftheelementthatwasselectedwhenthewizardhasbeenstarted.
folder folderpathorclickBrowsetoselectasourcefolderviaadialog.
Package Enterapackagetocontainthenewinterface.Youcanselecteither Thepackageoftheelementthatwasselectedwhenthewizardhasbeenstarted.Ifasource
thisoptionortheEnclosingTypeoption,below.Eithertypeavalid folderwasselectedwhichcontainsexactlyonepackagethenthatpackageisused.Ifthe
packagenameorclickBrowsetoselectapackageviaadialog. sourcefolderdoesnotcontainanypackagethentheprojectnameisusedifitisavalid
packagename.
Enclosing Selectthisoptiontochooseatypeinwhichtoenclosethenew Thetypeortheprimarytypeofthecompilationunitthatwasselectedwhenthewizardhas
type interface.YoucanselecteitherthisoptionorthePackageoption, beenstartedor<blank>
above.EithertypeavalidnameinthefieldorclickBrowsetoselecta
typeviaadialog.
Name Typeanameforthenewinterface. <blank>
Modifiers public
Selectoneormoreaccessmodifiersforthenewinterface.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 263/322
12/10/2015 Javadevelopmentuserguide
Eitherpublic,package,private,orprotected(privateand
protectedareonlyavailableifyouspecifyanenclosingtype)
static(onlyavailableifyouspecifyanenclosingtype)

Extended ClickAddtochooseinterfacesthatthenewinterfaceextends. <blank>


interfaces
Doyou Whenselected,thewizardaddscommentstothenewclasswhere Donotaddcomments
wanttoadd appropriate.
comments?

Fileactions

5.10.1.6.NewJavaAnnotationWizard
The NewJavaAnnotationTypewizardhelpsyoutocreateanewJavaAnnotationinaJavaproject.
JavaAnnotationOptions
Option Description Default
Source Enterasourcefolderforthenewannotation.Eithertypeavalidsource Thesourcefolderoftheelementthatwasselectedwhenthewizardhasbeenstarted.
folder folderpathorclickBrowsetoselectasourcefolderviaadialog.
Package Enterapackagetocontainthenewannotation.Youcanselecteither Thepackageoftheelementthatwasselectedwhenthewizardhasbeenstarted.Ifasource
thisoptionortheEnclosingTypeoption,below.Eithertypeavalid folderwasselectedwhichcontainsexactlyonepackagethenthatpackageisused.Ifthe
packagenameorclickBrowsetoselectapackageviaadialog. sourcefolderdoesnotcontainanypackagethentheprojectnameisusedifitisavalid
packagename.
Enclosing Selectthisoptiontochooseatypeinwhichtoenclosethenew Thetypeortheprimarytypeofthecompilationunitthatwasselectedwhenthewizardhas
type annotation.YoucanselecteitherthisoptionorthePackageoption, beenstartedor<blank>
above.EithertypeavalidnameinthefieldorclickBrowsetoselecta
typeviaadialog.
Name Typeanameforthenewannotation. <blank>
Modifiers public
Selectoneormoreaccessmodifiersforthenewannotation.
Eitherpublic,package,private,orprotected(privateand
protectedareonlyavailableifyouspecifyanenclosingtype)

Doyou Whenselected,thewizardaddscommentstothenewclasswhere Donotaddcomments


wanttoadd appropriate.
comments?

Fileactions

5.10.1.7.NewSourceFolderWizard
The NewSourceFolderwizardhelpsyoutocreateanewsourcefoldertoaJavaproject.
Notethatanewsourcefoldercannotbenestedinexistingsourcefoldersorinanoutputfolder.Youcanchoosetoaddexclusionfilterstotheothernestingsourcefoldersorthe
wizardwillsuggesttoreplacethenestingclasspathentrywiththenewcreatedentry.Thewizardwillalsosuggesttochangetheoutputlocation.
NewSourceFolderOptions
Option Description Default
Projectname Enteraprojecttocontainthenewsourcefolder.EithertypeavalidprojectnameorclickBrowsetoselecta Theprojectoftheelementthatwas
projectviaadialog. selectedwhenthewizardhasbeen
started.
Foldername Typeapathforthenewsourcefolder.Thepathisrelativetotheselectedproject. <blank>
Updateexclusionfilterin Selecttomodifyexistingsourcefolder'sexclusionfilterstosolvenestingproblems.Forexampleifthereisan Off
othersourcefoldersto existingsourcefoldersrcandafoldersrc/inneriscreated,thesourcefoldersrcwillbeupdatedtohavea
solvenesting exclusionfiltersrc/inner.

Javaprojects

Fileactions

5.10.1.8.NewJavaScrapbookPageWizard
The NewJavaScrapbookPagewizardhelpsyoutocreateanewJavascrapbookpageinaproject.
CreateJavaScrapbookPageOptions
Option Description Default
Enterorselecttheparentfolder Typeorbrowsethehierarchybelowtoselectacontainer(projectorfolder)forthescrapbookpage. Thecontaineroftheselectedelement
Filename Typeanameforthenewfile.The".jpage"extensionisappendedautomaticallywhennotaddedalready. <blank>

Javascrapbookpage

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 264/322
12/10/2015
Fileactions
Javadevelopmentuserguide

5.10.2.ExportBreakpointsWizard
The ExportBreakpointswizardhelpsyoutoexportbreakpointstoafile.

Exportbreakpointspage
Option Description Default
Breakpoint Selectthebreakpointsthatyouwishtoexport,anddeselectthosethatyoudo
List not. Therecanbetwopossibledefaults:
Ifthewizardisinvokedfromthebreakpointsviewandanybreakpointsareselected,
thosesameoneswillbecheckedbydefault.
IfthewizardisinvokedviatheFilemenuthannothingwillbeselected.

ToFile Thefiletoexportthebreakpointsto,youcanalsoclickBrowse...tosearchfor
alocationtoexportto. Therecanbetwopossibledefaults:
Ifyouhaveneverexportedbreakpointsbeforeitwillbeblank
Ifyouhaveexportedbreakpointsbeforethelastfilenameyouexportedtowillbe
automaticallyinserted.

Overwrite notselected
Overwriteexistingfilewithoutwarning:
Whenselected,ifthefileyouwishtoexporttoalreadyexists,itwillbe
overwrittenautomaticallybythewizard.

Breakpoints

AddingLineBreakpoints
RemovingLineBreakpoints
LaunchingaJavaProgram
RunningandDebugging

Fileactions
ImportingBreakpoints

5.10.3.ExportLaunchConfigurationsWizard
The ExportLaunchConfigurationswizardhelpsyoutoexportbreakpointstoafile.

Exportlaunchconfigurationspage
Option Description Default
Launchconfigurationlist Selectthelaunchconfigurationsthatyouwishtoexport,anddeselectthosethatyoudonot. None
SelectAll Canbeusedtoquicklyselectalllaunchconfigurationsinthelist. None
DeselectAll Canbeusedtoquicklydeselectalllaunchconfigurationsinthelist. None
Location Thefoldertoexportthelaunchconfigurationsto. None
Browse... TheBrowse...buttonallowsyoutosearchforaspecificfoldertoexportlaunchconfigurationsto. None
Overwriteexistingfile(s)without Whenselected,ifthelocationalreadycontainsalaunchconfigurationbeingexported,itwillbeoverwrittenautomaticallyby Not
warning thewizard. Selected

LaunchingaJavaProgram
RunningandDebugging

Fileactions
ImportingLaunchConfigurations

5.10.4.ExternalizeStringsWizard
TheExternalizeStringswizardallowsyoutorefactoracompilationunitsuchthatstringsusedinthecompilationunitcanbetranslatedtodifferentlanguages.Thewizardcanbe
invokedonnew,unprocessedfiles,butalsomodifyalreadytranslatedpages.Italsoallowsyourevertchangesdonebyapreviousinvocationofthewizard.
Onthefirstpageofthewizardyoucanspecifyhowthestringsfoundinthecompilationunitshouldbeexternalized.Itisalsopossibletointernalizestringswhichhavebeen
externalizedbefore.

Field Description

UseEclipse'sstring Ifuncheckedthestandardexternalizationmechanismisused,otherwisethenewEclipsestringexternalizationmechanismisused.
externalizationmechanism Note:Thisfieldisonlypresentiftheprojectbuildpathcontainstheorg.eclipse.osgi.util.NLSclass.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 265/322
12/10/2015 Javadevelopmentuserguide
Entercommonprefixfor Specifiesanoptionalprefixforallnewlygeneratedkey.Agoodpracticeistousethenameofthecompilationunitsoentriesinthepropertyfilescan
generatedkeys easilybegrouped.

Stringstoexternalize Displaysthelistofallstringsinthefile.Whennonexternalizedstringsarefound,thelistillbefilteredtoonlyshowthenewstringswithproposed
keysandvalues.Tocontrolthisfilter,usethecheckboxontopofthetable.

Externalize Markstheselectedstringstobeexternalized.Externalizedstringswillbeplacedinapropertyfileandthecodewillbechangedtoalookuptothe
propertyfile.

Ignored Markstheselectedstringstobeignoredfromexternalization.Thesestringswillbemarkedwitha'//$NON_NLS'commentandthecompilerwill
ignorethisstringwhenwarningaboutnonexternalizedstrings.

Internalize Markstheselectedstringstobeinternalizedagain:Thisbringsthecodebackinitsoriginalstatebeforetheexternalizewizardwasapplied:The
entryinthepropertyfilewillberemoved,anda'//$NON_NLS'commentwillberemoved.

Edit... Opensadialogforenteringanewkey.

Context Displaystheoccurrenceofthestringinthecontextofthecompilationunit.

Accessorclass Theclassusedtoaccessthepropertyfile.PressConfigure...toopentheConfigureAccessorClassdialog.

ConfigureAccessorClass
Thisdialogspecifiesthenameandlocationofthepropertyfileanditsaccessorclass.Anaccessorclassisusedtoretrievestringsstoredinthepropertyfilegivenakey.
Accessorclasssettings:

Option Description

Sourcefolder Thesourcefoldertostoretheaccessorclassin.

Package Thelocationfortheaccessorclass.

Classname Thenameoftheclasstoaccesstheresourcebundle.

Substitutionpattern Specifiesthesourcepatterntoreplacethestringtoexternalizewith.

Propertyfilesettings:

Option Description

Sourcefolder Thesourcefoldertostorethepropertyfilein.

Package Thelocationforthepropertyfile.

Propertyfilename Thenameofthepropertyfile.

Stringexternalization
Eclipsestringexternalizationmechanism

Externalizingstrings

Sourceactions

5.10.5.ImportBreakpointsWizard
The ImportBreakpointswizardhelpsyoutoimportbreakpointsfromafile.

Importbreakpointspage
Option Description Default
From... Typethenameofthefiletoimportfrom,orclicktheBrowse...buttontosearchforafile. <blank>
Update... not
Automaticallyupdateexistingbreakpoints selected
Whenselected,anybreakpointsthatalreadyexistinyourworkspacewillbeoverwrittenbythosebeingimportedfromthefile.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 266/322
12/10/2015 Javadevelopmentuserguide
Create... not
Automaticallycreatebreakpointsworkingsets: selected
Whenselected,ifanimportedbreakpointindicatesitbelongstoaworkingsetsthatdoesnotexistinyourworkspace,theworkingsetwillbecreated
foryouandthebreakpointaddedtoit.

Breakpoints

AddingLineBreakpoints
RemovingLineBreakpoints
LaunchingaJavaProgram
RunningandDebugging

Fileactions
ExportingBreakpoints

5.10.6.ImportLaunchConfigurationsWizard
The ImportLaunchConfigurationswizardhelpsyoutoimportbreakpointsfromafile.

Importlaunchconfigurationspage
Option Description Default
FromDirectory Thefoldertoimportlaunchconfigurationsfrom. None
Browse... TheBrowse...buttonallowsyoutosearchforaspecificfoldertoimportlaunchconfigurationsfrom. None
Overwriteexistinglaunchconfigurationswithout Whenselected,anylaunchconfigurationsthatalreadyexistinyourworkspacewillbeoverwrittenbythosebeing Not
warning imported. Selected

LaunchingaJavaProgram
RunningandDebugging

Fileactions
ExportingLaunchConfigurations

5.10.7.JARFileExporter
The JarExportwizardallowsyoutocreateaJARfile.

JARpackagespecification
JARSpecificationOptions:

Option Description

Selecttheresourcestoexport Inthelist,checkorcleartheboxestospecifyexactlythefilesthatyouwanttoexporttotheJARfile.Thislistisinitializedbytheworkbench
selection.

Exportgeneratedclassfiles Ifenabled,thengeneratedclassfilesandresourcesareincludedintheJAR.
andresources

Exportalloutputfoldersfor Ifenabled,thenalloutputfoldersareincludedintheJAR.
checkedprojects

ExportJavasourcefilesand Ifenabled,thenJavasourcefilesandresourcesareincludedintheJAR.
resources

Exportrefactoringsforchecked Ifenabled,thenrefactoringscriptsfortheselectedprojectsareincludedintheJAR.ThisallowsclientstomigratetothenewJARbyexecutingall
projects thestoredrefactoringsintheJAR.

Selecttheexportdestination EnteranexternalfilesystempathandnameforaJARfile(eitherneworexisting).EithertypeavalidfilepathinthefieldorclickBrowsetoselect
afileviaadialog.

Options Youcanselectanyofthefollowingoptions:
CompressthecontentsoftheJARfile:tocreateacompressedJARfile
Adddirectoryentries:addsanentryforeachdirectorytotheJARfile,evenifthedirectorydoesonlycontainsubdirectories.
Overwriteexistingfileswithoutwarning:ifanexistingfilemightbeoverwritten,youarepromptedforconfirmation.Thisoptionisapplied
totheJARfile,theJARdescription,andthemanifestfile.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 267/322
12/10/2015 Javadevelopmentuserguide

JARpackagingoptions
JAROptions:

Option Description

Selectoptionsforhandlingproblems Choosewhethertoexportclasseswithcertainproblems:
Exportclassfileswithcompileerrors
Exportclassfileswithcompilewarnings

SelectedthisoptionifyouwantthesourcefolderstructuretoberebuiltintheJAR.Thisoptionisonlyenabledwhensourcefilesbutno
Createsourcefolderstructure
classfilesareexported.
Selectthisoptiontoforcearebuildbeforeexporting.Itisrecommendedtobuildbebeforeexportingsotheexportedclassfilesareupto
Buildprojectsifnotbuildautomatically
date.

SavethedescriptionofthisJARinthe Ifyouselectthisoption,youcancreateafileintheworkbenchdescribingtheJARfileyouarecreating.Eithertypeand/orbrowseto
workspace selectapathandnameforthisnewfile.

JARmanifestspecification
JARManifestSpecificationOptions(Availablewhenclassfileareexported):

Option Description

Specifythemanifest ChoosethesourceofthemanifestfileforthisJARfile:
Generatethemanifestfile(youcanalsochooseeithertosaveorreuseandsavethenewmanifestfile)
Useexistingmanifestfromworkspace

Sealcontents ChoosewhichpackagesintheJARfilemustbesealed:
SealtheJARtosealtheentireJARfileclickDetailstoexcludeselectively
SealsomepackagesclickDetailstochooseselectively
Note:Thisoptionisonlyavailableifthemanifestisgenerated.

Selecttheclassoftheapplicationentrypoint TypeorclickBrowsetoselectthemainclassfortheJARfile,ifdesired.
Note:Thisoptionisonlyavailableifthemanifestisgenerated.

CreatingJARfiles

Fileactions

5.10.8.JavadocGeneration
The JavadocGenerationwizardallowsyoutogenerateJavadoc.Itisauserinterfaceforthejavadoc.exetoolavailableintheJavaJDK.VisitSun'sJavadocToolpagefora
completedocumentationoftheJavadoctool.

Firstpage
TypeSelection:

Option Description

Javadoccommand Specifywhichcommandtousetogeneratethejavadoc.

SelecttypesforwhichJavadoc Inthelist,checkorcleartheboxestospecifyexactlythetypesthatyouwanttoexport.Thislistisinitializedbytheworkbenchselection.
willbegenerated

CreateJavadocformembers Private:Allmemberswillbedocumented
withvisibility Package:Onlymemberswithpackage,protectedorpublicvisibilitywillbedocumented
Protected:Onlymemberswithprotectedorpublicvisibilitywillbedocumented
Public:Onlymemberswithpublicvisibilitywillbedocumented(default)

Usestandarddoclet StarttheJavadoccommandwiththestandarddoclet(default)
Destination:selectthedestinationtowhichthestandarddocletwillwritethegenerateddocumentation.Thedestinationisadocletspecific
argument,andthereforenotenabledwhenusingacustomdoclet.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 268/322
12/10/2015 Javadevelopmentuserguide

Usecustomdoclet Useacustomdoclettogeneratedocumentation
Docletname:Qualifiedtypenameofthedoclet
Docletclasspath:Classpathneededbythedocletclass

Standarddocletarguments
StandardDocletArguments(availablewhenUsestandarddoclethasbeenselected):

Option Description

Specifyadocumenttitle.
Documenttitle

Generateusepage SelectedthisoptionifyouwantthedocumentationtocontainaUsepage.
Generatehierarchytree SelectedthisoptionifyouwantthedocumentationtocontainaTreepage.
Selectedthisoptionifyouwantthedocumentationtocontainanavigationbar(headerandfooter).
Generatenavigatorbar

Generateindex SelectedthisoptionifyouwantthedocumentationtocontainaIndexpage.
Separateindexperletter Createanindexperletter.EnabledwhenGenerateIndexisselected.
@author Selectedthisoptionifyouwanttothe@authortagtobedocumented.
@version Selectedthisoptionifyouwanttothe@versiontagtobedocumented.
@deprecated Selectedthisoptionifyouwanttothe@deprecatedtagtobedocumented.
SelectedthisoptionifyouwantthedocumentationtocontainaDeprecatedpage.Enabledwhen
deprecatedlist
the@deprecatedoptionisselected.
SpecifytowhichotherdocumentationJavadocshouldcreatelinkswhenothertypesarereferenced.

Selectreferencedarchivesandprojectstowhichlinksshould SelectAll:Createlinkstoallotherdocumentationlocations
begenerated ClearAll:Donotcreatelinkstootherdocumentationlocations
Configure:ConfiguretheJavadoclocationofareferencedJARorproject.

Stylesheet Selectthestylesheettouse

Generalarguments
GeneralJavadocOptions:

Option Description

SpecifiesthatJavadocshouldretrievethetextfortheoverviewdocumentationfromthegivenfile.Itwillbeplacedinoverviewsummary.html.
Overview

VMoptions AddanynumberofextraVMoptionshere.

ExtraJavadocoptions Addanynumberofextraoptionshere:CustomdocletoptionsorJRE1.4compatibilityoptions.
Notethatargumentscontainingspacesmustenclosedinquotes.Forargumentsspecifyinghtmlcode(e.g.header)usethe&or&"toavoid
spacesandquotes.

JREsourcecompatibility TheJREsourcecompatibilitytobeacceptedbythejavadoctool.

Savethesettingsofthis SpecifytostoreanAntscriptthatwillperformthespecifiedJavadocexportwithouttheneedtousethewizard.ExistingAntscriptcanbe
JavadocexportasanAntscript modifiedwiththiswizard(UseOpenJavadocwizard'fromthecontextmenuonthegeneratedAntscript)

Opengeneratedindexfilein
Opensthegeneratedindex.htmlfileinthebrowser(Onlyavailablewhenusingthestandarddoclet)
browser

PressFinishtostarttheJavadocgeneration.Ifthedestinationisdifferenttothelocationconfiguredtheproject'sJavadocLocationpage,youwillbeaskedifyouwanttosetthe
project'sJavadoclocationtothenewdestinationfolder.Bydoingthis,allinvocationsofOpenExternalJavadocwillusethenowcreateddocumentation.
Anewprocesswillbestartedandthegenerationperformedinthebackground.OpentheConsoleview(Window>ShowView>Console)toseetheprogressandstatusofthe
generation.

Fileactions
Javadoclocationproperties

5.10.9.RunnableJARFileExporter
The RunnableJarExportwizardallowsyoutocreatearunnableJARfile.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 269/322
12/10/2015 Javadevelopmentuserguide
RunnableJARfilespecification
RunnableJARSpecificationOptions:

Option Description

Launch Selecta'JavaApplication'launchconfigurationtousetocreatearunnableJAR.
configuration

Exportdestination EnteranexternalfilesystempathandnameforaJARfile(eitherneworexisting).EithertypeavalidfilepathinthefieldorclickBrowsetoselectafileviaa
dialog.

Libraryhandling Youcanselectanyofthefollowingoptions:
ExtractrequiredlibrariesintogeneratedJAR:toinflatethereferencedjarfilesandcopytheclassesintothegeneratedjar
PackagerequiredlibrariesintogeneratedJAR:tocopythereferencedjarfilesasisintothegeneratedjar
CopyrequiredlibrariesintoasubfoldernexttothegeneratedJAR

SaveasANT Ifyouselectthisoption,youcancreateanantscriptdescribingtheJARfileyouarecreating.Eithertypeand/orbrowsetoselectapathandnameforthisnew
script scriptfile.

CreatingRunnableJARfiles

Fileactions

5.10.11.OpenType
Thisdialogallowsyoutobrowsetheworkbenchforatypetoopeninaneditorortypehierarchy
Entertypenameprefixorpattern:Inthisfield,typethefirstfewcharactersofthetypeyouwanttoselect.
Thefollowingpatternkindsaresupported:
Wildcards:
"*"foranystringand"?"foranycharacter
terminating"<"or""(space)topreventtheautomaticprefixmatching,e.g."java.*Access<"tomatchjava.util.RandomAccessbutnot
java.security.AccessControlContext

Camelcase:
"TZ"fortypescontaining"T"and"Z"asuppercaselettersincamelcasenotation,e.g.java.util.TimeZone
"NuPoEx"or"NuPo"fortypescontaining"Nu","Po",(and"Ex")aspartsincamelcasenotation,e.g.java.lang.NullPointerException
terminating"<"or""(space)tofixthenumberofcamelcaseparts,e.g."HMap<"and"HaMap<"match"HashMap"and"HatMapper",butnot"HashMapEntry"nor
"Hashmap".
Bothpatternkindsalsosupportpackageprefixes,e.g."j.util.*Map<".

Matchingitems:ThislistdisplaysmatchesforthepatternyoutypeintheEntertypenameprefixorpatternfield.Recentlyopenedtypesshowupinahistorysectionatthe
topofthelist.
ThebehavioroftheOpenTypedialogcanbefurthercustomizedusingthedialogmenu:
OpenTypeOptions

Option Description Default

ShowStatus Whenselected,theOpenTypedialogshowsanadditionalbaratthebottomofthedialogwhichdisplaysthepackageand Showstatusline


Line containingJREoftheselectedtype
WorkingSet ThesearchscopecanberestrictedbyselectingoneormoreworkingsetsortheglobalWindowWorkingSet. Showalltypesinthe
actions workspace.
TypeFilters... TypesarehiddeniftheymatchtheglobalJavatypefilters. Showalltypesinthe
workspace.

Openinganeditoronatype

Workingsets
Typefilters
Navigateactions

5.10.12.CreateGettersandSetters
Thisdialogletsselectthegetterandsettermethodstocreate.
UseGenerateGettersandSettersfromtheSourcemenuorthecontextmenuonaselectedfieldortype,oratextselectioninatypetoopenthedialog.TheGenerateGettersand
Settersdialogshowsgettersandsettersforallfieldsoftheselectedtype.Themethodsaregroupedbythetype'sfields.
Thenamesofthegetterandsettermethodsarederivedfromthefieldname.Ifyouuseaprefixorsuffixforfields(e.g.fValue,_value,val_m),youcanspecifythesuffixesand

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 270/322
12/10/2015 Javadevelopmentuserguide
prefixesintheCodeStylepreferencepage(Windows>Preferences>Java>CodeStyle).
WhenpressingOK,allselectedgettersandsettersarecreated.

Option Description

Selectgettersandsettersto Atreecontaininggetterandsettermethodsthatcanbecreated.Gettersandsettersaregroupedbyfieldtheirassociatedfield.
create

SelectAll Selectallgetterandsettermethods

DeselectAll Deselectallgetterandsettermethods

SelectGetters Selectallgettermethods

Insertionpoint Defineswhereinthetypebodythenewmethodsareinserted

Defineshowtosortthenewmethods:
Sortby
ingetter/setterpairs
firstgetters,thensetters

Accessmodifiers Definestheaccessmodifiersofthenewmethods

Generatemethodcomments ControlswhetherJavadoccommentsareaddedtothecreatedmethods.ThecommenttemplatesaredefinedontheCodeTemplatespreference
page.

Sourceactions

5.10.13.GeneratetoString()dialog
TheGeneratetoString()dialogprovidesmeanstoincludespecificmemberfieldsandmethodsingeneratedtoString()method.
UseGeneratetoString()...fromtheSourcemenuorthecontextmenuonaselectedtypeoronatextselectioninatype.
ThememberstobeconsideredforinclusioninthetoString()outputare:
fields(nonstatic)
argumentlessmethods(nonstatic,nonvoid)
inheritedfieldsandmethods(fulfillingadequateconditions)
WhenpressingOK,thetoString()methodprintingoutallselectedmembersandeventuallyhelpermethodsarecreated.

Option Description Default

Forconvenience,membersaredividedintouptofourgroups:Fields,Inheritedfields,MethodsandInheritedmethods. Onlyfieldswhicharenon
Selectfieldsandmethods Checkingoruncheckingagroupaffectsthestateofallitsmembers. transientandnotinherited.
toincludeinthetoString()
method

SelectAll Selectallfieldsandmethods. n/a

DeselectAll Deselectallfieldsandmethods. n/a

Up Movetheelementwithfocusupthelist.Amembercanbemovedonlywithinitsgroup.Groupscanalsobemoved. n/a

Down Movetheelementwithfocusdownthelist.Amembercanbemovedonlywithinitsgroup.Groupscanalsobemoved. n/a

Sort Sortelementsineverygroupinlexicographicalorder. n/a

Insertionpoint Defineswhereinthetypebodythegeneratedmethodsareinserted.Ifamethodalreadyexistsinaclassandis Lastmemberorlocationofthe


overwritten,itspositionwillnotbechanged(thisoptionwillhavenoeffect). cursorpositionifinvokedfrom
editor

Generatemethod ControlswhetheracommentisaddedtothecreatedtoString()method.Generatedcommentjustpointstoajavadoc off


comments commentforjava.lang.Object#toString().

Stringformat DefineswhichtemplateisusedtoformatthetoString()output.Atemplatedetermineswhatinformationaboutaclass Defaulttemplate


isadded,howthefieldsareseparated,andsoon.Formoreinformationabouttemplates,seetoString()generator:
formattemplatestopic.

Edit... Opensadialogthatletsyouadd,removeorchangestringformattemplates(seeabove). n/a

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 271/322
12/10/2015 Javadevelopmentuserguide
Codestyle Definesthemethodcodestyle,thatiswhatlibraries/mechanismsitusestocreateoutput.Formoreinformation,see Stringconcatenation
toString()generator:codestylestopic.

Configure... Opensadialogthatletsyouconfiguremoreoptionsrelatedtoselectedcodestyle.Currentlythisbuttonisonlyactive n/a


forCustomtoString()buildercodestyle.

Skipnullvalues ControlswhetherthetoString()methodskipsmembersthathavenovalue(nulls).Howitisaccomplisheddependson off


selectedcodestyle(seeabove).

Listcontentsofarrays ControlswhetherthetoString()methodlistsitemscontainedbyarraysinsteadofusingtheirdefaulttoString().See off


insteadofusingnative toString()generator:listingcontentfordetails.
toString()

Limitnumberofitemsin ControlswhetherthetoString()methodlimitsthenumberofelementsprintedforarrays,CollectionsandMaps,and off


arrays/collections/maps whatthelimitis.Itdoesn'tworkforarraysif"Ignorearrays'defaulttoString()"optionisoff.SeetoString()generator:
listingcontentfordetails.

Sourceactions
toString()generator:formattemplates
toString()generator:codestyles
toString()generator:contentlisting

5.10.13.1.toString()Generator:FormatTemplates
Formattemplatesareusedbyasimplemechanismthatallowsyoutochangeformatofgeneratedmethod'soutputstring:beginning,ending,separator,andsoon.Theylooksimilar
toJDTcodetemplatesbuttheydon'taffectthegeneratedcodedirectly(CodeStylesareusedforthat).Here'salistofavailabletemplatevariables:

${object.className} insertstheclassnameasasimpleString

${object.getClassName} insertsacalltothis.getClass.getName()

${object.superToString} insertsacalltosuper.toString()

${object.hashCode} insertsacalltothis.hashCode()

${object.identityHashCode} insertsacalltoSystem.identityHashCode(this)

${member.name} insertsthefirstmember'sname

${member.name()} insertsthefirstmember'snamefollowedbyparenthesisincaseofmethods

${member.value} insertsthefirstmember'svalue

insertstheremainingmembers.Foreachmember,thetemplatefragmentbetweenthefirstandthelast${member.*}variableisevaluatedand
${otherMembers} appendedtotheresult.Thecharactersbetweenthelast${member.*}and${otherMembers}definetheseparatorthatisinsertedbetween
members(${otherMembers}muststandafterthelast${member.*}variable).

Forthetemplatetoworkproperly,the${otherMembers}variablemustbeusedexactlyonceinatemplateandcannotbefollowedbyany${member.*}variable.${object.*}variables
canbeplacedanywhereinthetemplate,althoughifoneisplacedinamemberrelatedfragment(thatisbetweenthefirst${member.*}variableand${otherMembers}),itwillbe
repeatedforeverymember,whichisprobablynotasensiblesolution.
Thedescriptionabovemightseemcomplicated,butthetemplateformatitselfisveryeasytouse.Itshouldallbecomeclearafterseeingsomeworkingexamples.

Templateexamples
1. Thedefaulttemplateisagoodexample:

${class.name}[${member.name()}=${member.value},${otherMembers}]

Theoutputstringforthistemplatelookslikethis:

FooClass[aFloat=1.0,aString=hello,anInt=10,anObject=null,aCharMethod()=a]

2. Multiplelineoutputisalsoavailable:

${object.getClassName}{
${member.name}:${member.value}
${otherMembers}
}

Exampleresult:

FooClass{
aFloat:1.0
aString:hello
anInt:10
anObject:null
aCharMethod:a
}

3. Ifyouencloseamemberinbraces,don'tforgettodothesamewith${otherMembers}variable:

{${member.name}=${member.value}},
{${otherMembers}}

Here'stheeffect:

{aFloat=1.0},
{aString=hello},

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 272/322
12/10/2015
{anInt=10},
Javadevelopmentuserguide
{anObject=null},
{aCharMethod=a}

4. ${object.*}variablescanbeusedatthebeginningandattheendofthetemplate:

${object.getClassName}(hashcode:${object.hashCode})
members:${member.name}=${member.value}${otherMembers}
[super:${object.superToString}]

Thistemplatewouldresultinanoutputsimilartothis:

FooClass(hashCode:232198409832)
members:aFloat=1.0aString=helloanInt=10anObject=nullaCharMethod=a
[super:SuperFooClass[aField=null]]

GeneratetoString()dialog
toString()Generator:CodeStyles
toString()Generator:ContentListing

5.10.13.2.toString()Generator:CodeStyles
Codestyledetermineshowthegeneratedmethodworksandwhatclassesituses.Thereareseveralcodestylesavailabletochosefromthecomboboxingenerator'sdialog:

Stringconcatenation
Thisstyleusessimplesumexpressionssoit'sveryefficient(compilerusesStringBuilder/StringBuffertooptimizethecode)andrelativelyeasytoreadandmodify.Here'san
exampleoutcomeinthesimplestcase:

return"FooClass[aFloat="+aFloat+",aString="+aString+",anInt="+anInt
+",anObject="+anObject+"]"

With"Skipnullvalues"optionturnedon,thecodebecomesalittlehardertoread:

return"FooClass[aFloat="+aFloat+","
+(aString!=null?"aString="+aString+",":"")
+"anInt="+anInt+","
+(anObject!=null?"anObject="+anObject:"")+"]"

StringBuilder/StringBuffer
ThisstyleusesStringBuilderiftheprojectiscompatiblewithJDK1.5orlaterandStringBufferotherwise.StringBuilderisfaster(becauseoflackofsynchronization),butonly
availablesinceJDK1.5.

StringBuilderbuilder=newStringBuilder()
builder.append("FooClass[aFloat=")
builder.append(aFloat)
builder.append(",aString=")
builder.append(aString)
builder.append(",anInt=")
builder.append(anInt)
builder.append(",anObject=")
builder.append(anObject)
builder.append("]")
returnbuilder.toString()

The"Skipnullvalues"optiondoesn'tobfuscatethecodeasmuchaspreviously:

StringBuilderbuilder=newStringBuilder()
builder.append("FooClass[aFloat=")
builder.append(aFloat)
builder.append(",")
if(aString!=null){
builder.append("aString=")
builder.append(aString)
builder.append(",")
}
builder.append("anInt=")
builder.append(anInt)
builder.append(",")
if(anObject!=null){
builder.append("anObject=")
builder.append(anObject)
}
builder.append("]")
returnbuilder.toString()

StringBuilder/StringBufferwithchainedcalls
Styleverysimilartothepreviousoneonlythatappendmethodsarecalledinchain.Thismakesthecodeshorterandprobablyeasiertoread.

StringBuilderbuilder=newStringBuilder()
builder.append("FooClass[aFloat=").append(aFloat).append(",aString=").append(aString)
.append(",anInt=").append(anInt).append(",anObject=").append(anObject).append("]")
returnbuilder.toString()

With"Skipnullvalues"switchedon,thechainmustbebroken:

StringBuilderbuilder=newStringBuilder()
builder.append("FooClass[aFloat=").append(aFloat).append(",")
if(aString!=null){
builder.append("aString=").append(aString).append(",")
}
builder.append("anInt=").append(anInt).append(",")
if(anObject!=null){

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 273/322
12/10/2015 Javadevelopmentuserguide
builder.append("anObject=").append(anObject)
}
builder.append("]")
returnbuilder.toString()

String.format()/MessageFormat
Thisstyleisverypleasantforrelativelyshortlistofelements,butwithlongeronesitbecomeshardtoseewhichfieldsareassociatedwithwhichvariables.Unfortunately,the
"Skipnullvalues"optioncannotbeusedwiththisstyle.

returnString.format("FooClass[aFloat=%s,aString=%s,anInt=%s,anObject=%s]",
aFloat,aString,anInt,anObject)

Becausethere'snoString.format()inJDK1.4andearlier,MessageFormat.format()isusedinstead:

returnMessageFormat.format("FooClass[aFloat={0},aString={1},anInt={2},anObject={3}]",
newObject[]{newFloat(aFloat),aString,newInteger(anInt),anObject})

CustomtoString()builder
Thisstyleusesanexternalclasstobuildaresultstring.Itcanuseclassesthatfulfillthefollowingconditions:
ProvideapublicconstructortakingasingleObjectasparameteritwillbepassedanobjectforwhichthetoString()methodiscalled
Providemethodsforappendingmemberinformationthesearemethodswithspecifiedname,thattakeanObjectand(optionally)aString(inanyorder)
ProvideamethodforretrievingresultthatisamethodtakingnoargumentsandreturningaString
Custombuilderrequiressomeadditionalconfigurationtoworkproperly.Allnecessaryoptionscanbeenteredinadialogboxshowingupafterclicking'Configure...'button.
Theseoptionsinclude:
Builderclassafullyqualifiednameofaclasstouse.Itcanbetypedinmanuallyorselectedfromaclasssearchdialogbox(inthiscaseit'sautomaticallycheckedif
selectedclassmeetstherequirements).Itcanbeaclassdeclaredeitherdirectlyincurrentprojectorinoneofincludedlibrariesitjusthastobeaccessibleonthebuild
path.Forexample,ToStringBuilderfromtheApacheCommonsLanglibraryorToStringCreatorfromtheSpringFrameworkworkverywellwiththismechanism.
Builderlabelanyvalidjavaidentifier.Itwillbeusedtoreferencethebuilderobject.
Appendmethodthenameofmethodstouseforappendingitems.Iftheclassprovidesmanymethodswiththisname,methodstakingtwoarguments(oneofthem
mustbeString)arepreferredoverthosetakingasingleargument(additionally,theStringargumentshallpreferablybethefirstone).Ifthereareversionsofthemethod
thattakespecificargumenttypes,theyarealsousedwhenpossible.
Resultmethodthenameofamethodtouseforretrievingfinalresult.
Chaininvocationsdetermineswhethercallstotheappendmethodsshouldformchains.Thisoptiontakeseffectonlyformethodsthathaveproperreturntype(thatis,
thebuilderclass,orasubclass).
Forexample,supposeyourbuilderclasslookslikethis:

packageorg.foo.ToStringBuilder2

publicclassToStringBuilder2{
publicToStringBuilder2(Objecto){...}
publicToStringBuilder2appendItem(Strings,Objecto){...}
publicToStringBuilder2appendItem(Strings,floatf){...}
publicStringgetString(){...}
}

Ofcourseinthiscasebuilderclassshouldbesetto"org.foo.ToStringBuilder2",builderlabelcanbeforexample"builder",appendmethodis"appendItem"and
resultmethodis"getString".Withchaininvocationsselected,generatedmethodwilllooklikethis:

ToStringBuilder2builder=newToStringBuilder2(this)
builder.append("aFloat",aFloat).append("aString",aString).append("anInt",newInteger(anInt))
.append("anObject",anObject)
returnbuilder.getString()

NotethataprimitivevariableanIntwaspassedtothebuilderusingwrappertype.ThisisdoneforprojectsusingJDK1.4andearlier(forlaterJDKsthecompilerdoesit
automatically).IncaseofaFloattherewasaspecificmethodinbuilderclasssonowrappingwasrequired.

GeneratetoString()dialog
toString()Generator:FormatTemplates
toString()Generator:ContentListing

5.10.13.3.toString()Generator:ContentListing
ThistopicdiscusseshowtoString()generatorlistscontentsofarraysandhowitlimitsnumberofitemslistedinCollectionsandMaps.Usedmethoddependsnotonlyonthe
membertype,butalsoonselectedJDKcompatibilityoftheproject.

ListingcontentsofArrays

Withoutlimitingnumberofelements
ForJDK1.5andlater,generatedmethodusesArrays.toString().AsthismethodisnotavailableinJDK1.4,Arrays.asList()isusedinsteadinthiscase,butonlyfornon
primitivearrays.Primitivearraysarehandledwithahelpermethod,showedbelow.

Limitingnumberofelements
Ifthearrayencloseanonprimitivetype,thesamesolutionisusedforallversionsofJDK:Arrays.asList()withList.subList().Forexample,foramembernamed
anArray,generatedcodelookslikethis:Arrays.asList(anArray).subList(0,Math.min(anArray.length,maxLen))
Incaseofprimitivearrays,Arrays.asList()cannotbeusedsoinJDK1.5orlowerahelpermethodisusedinstead.InJDK1.6there'sanothersolution:
Arrays.toString(Arrays.copyOf(anArray,Math.min(anArray.length,maxLen)).Althoughcopyinganarrayisnotanoptimalsolution,thecopiedpartisusuallyrather
smallandefficiencyisnotaffected.Agoodthingisthatahelpermethodcanbeavoided.

Helpermethod
Ahelpermethodreturnsastringlistingitemsofagivenarray,intheformof[1,2,3].Themethoditeratesoverthearrayandusesinstanceoftodetermineitsenclosing
type.Tomakethecodeshorter,itchecksonlyfortypesthatcanactuallybepassedtoit.

privateStringarrayToString(Objectarray,intlen,intmaxLen){
StringBufferstringBuffer=newStringBuffer()

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 274/322
12/10/2015 Javadevelopmentuserguide
len=Math.min(len,maxLen)
stringBuffer.append("[")
for(inti=0i<leni++){
if(i>0)
stringBuffer.append(",")
if(arrayinstanceoffloat[])
stringBuffer.append(((float[])array)[i])
if(arrayinstanceofint[])
stringBuffer.append(((int[])array)[i])
if(arrayinstanceofObject[])
stringBuffer.append(((Object[])array)[i])
}
stringBuffer.append("]")
returnstringBuffer.toString()
}

NOTES:
Thismethodisoverwritteneverytimethegeneratorruns.
Ifthenumberofitemsisnotlimited,themethoddoesn'ttakethemaxLenargumentanddoesn'tuseMath.min()
StringBufferorStringBuilderisuseddependingonselectedJDKcompatibility

ListinglimitedcontentsofLists
ThesamesolutionisusedforallJDKversions:aList.subList(0,Math.min(aList.size(),maxLen))

ListinglimitedcontentsofCollections(helpermethod)
ACollectioncannotbeturnedintoaListwithoutcopyingitscontents(assumingitisn'taListalready),soahelpermethodisusedtoiterateoverfirstmaxLenelementsandbuild
astringoutofthem:

privateStringtoString(Collectioncollection,intmaxLen){
StringBufferstringBuffer=newStringBuffer()
stringBuffer.append("[")
inti=0
for(Iteratoriterator=collection.iterator()iterator.hasNext()&&i<maxLeni++){
if(i>0)
stringBuffer.append(",")
stringBuffer.append(iterator.next())
}
stringBuffer.append("]")
returnstringBuffer.toString()
}

NOTES:
Thismethodisnotoverwritteneverytimethegeneratorruns,soitcanbeeasilycustomizedbyhand.
StringBuilderorStringBufferisuseddependingonselectedJDKcompatibility

ListinglimitedcontentsofMaps
IncaseofMaps,thesamehelpermethodisusedasforCollectionsonlythatmap.entrySet()ispassedtoit.

Summary
Thistablesumsupwhatmethodsareusedindifferentconditions:

java.util.List java.util.Collection java.util.Map Arrayofprimitivetype Arrayofnonprimitivetype


helpermethodarrayToString(array,
jdk1.4 Arrays.asList(array)
len)

helpermethod
jdk1.4/1.5, helpermethod
toString(collection, helpermethodarrayToString(array,
limit member.subList() toSting(collection, Arrays.asList(array).subList()
maxLen)with len,maxLen)
elements maxLen)
map.entrySet()

jdk1.5 Arrays.toString() Arrays.asList(array)

jdk1.6 Arrays.toString() Arrays.toString()

jdk1.6, helpermethod
helpermethod Arrays.toString(Arrays.copyOf(member,
limit member.subList() toString(Collection)with Arrays.asList(array).subList()
toString(Collection) ...))
elements map.entrySet()

Additionalnotes
Ifahelpermethodmustbegeneratedforatleastonemember,itisalsousedforothermemberswhenpossible.Forexample,aListisusuallyhandledwithsubList()
method,butifthere'sanothermemberofCollection(notList)typeandtoString(collection)isgenerated,Listsarealsopassedtoit.Thiswaythecodeisshorterandmore
consistent.
Wherenecessary,thecoderesponsibleforlistingcontentsissurroundedwithnullcheckingcode,forexample:array!=null?Arrays.asList(array):null
Ifmaximumnumberoflisteditemsissetto0,thegeneratorusessimplestringliteral("[]")insteadofmethodsdescribedabove.

GeneratetoString()dialog
toString()Generator:FormatTemplates
toString()Generator:CodeStyles

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 275/322
12/10/2015 Javadevelopmentuserguide
5.10.14.OverrideMethods
Thisdialogletsyoudefinemethodstooverride.
UseOverride/ImplementMethodsfromtheSourcemenuorthecontextmenuonaselectedtypeoronatextselectioninatype.
Thedialogpresentsallmethodsthatcanbeoverriddenfromsupertypesorimplementedfrominterfaces.Abstractmethodsorunimplementedmethodsareselectedbydefault.
Thetreeviewgroupsmethodsbythetypedeclaringthemethod.Ifmorethanonetypeinthehierarchydeclarethesamemethod,themethodisonlyshownonce,groupedtothefirst
typeinthelistofsupertypesthatimplementsordefinesthismethod.
Theflatviewshowsonlymethods,sortedalphabetically.
WhenpressingOK,methodstubsforallselectedmethodsarecreated.

Option Description Default

Selectmethodstooverrideorimplement Abstractmethodsfromsuperclassesandunimplemented
Selectmethodsto methodsfrominterfacesareselected
overrideorimplement

Groupmethodsby Showsmethodsgroupedbyalistofthesupertypesinwhichtheyaredeclared. selected


types

SelectAll Selectallmethods n/a

DeselectAll Deselectallmethods n/a

Insertionpoint Defineswhereinthetypebodythenewmethodsareinserted Lastmemberorlocationofthecursorpositionifinvoked


fromeditor

Generatemethod ControlswhetherJavadoccommentsareaddedtothecreatedmethods.Thecomment off


comments templatesaredefinedontheCodeTemplatespreferencepage.

Sourceactions

5.11.FrequentlyAskedQuestionsonJDT
CanIuseaJavacompilerotherthanthebuiltinone(javacforexample)withtheworkbench?
No.TheJDTprovidesanumberofsophisticatedfeaturesincludingfullyautomaticincrementalcompilation,codesnippetevaluation,codeassist,typehierarchies,andhotcode
replace.ThesefeaturesrequirespecialsupportfoundintheworkbenchJavacompiler(anintegralpartoftheJDT'sincrementalprojectbuilder),butnotavailableinstandardJava
compilers.

WheredoJavapackagescomefrom?
Aprojectcontainsonlyfilesandfolders.ThenotionofaJavapackageisintroducedbyaJavaproject'sclasspath(attheUI,thePackageExplorerpresentsthepackagesas
definedbytheclasspath).Tip:Ifthepackagestructureisnotwhatyouexpect,checkoutyourclasspath.TheJavasearchinfrastructureonlyfindsdeclarationsforandreferences
fromJavaelementsontheclasspath.

WhendoIuseaninternalversusanexternalJARlibraryfile?
Aninternalresourceresidesinsomeprojectintheworkbenchandisthereforemanagedbytheworkbenchlikeotherresources,theseresourcescanbeversionmanagedbythe
workbench.Anexternalresourceisnotpartoftheworkbenchandcanbeusedonlybyreference.Forexample,aJREisoftenexternalandverylarge,andthereisnoneedto
associateitwithaVCMsystem.

WhenshouldIusesourcefolderswithinaJavaproject?
EachJavaprojectlocatesitsJavasourcefilesviaoneormoresourcetypeentriesontheproject'sclasspath.Usesourcefolderstoorganizethepackagesofalargeprojectinto
usefulgrouping,ortokeepsourcecodeseparatefromotherfilesinthesameproject.Also,usesourcefoldersifyouhavefiles(documentationforexample)whichneednotbeonthe
buildpath.

Whataresourceattachments,HowdoIdefineone?
LibrariesarestoredasJARfilescontainingbinaryclassfiles(andperhapsotherresources).Thesebinaryclassfilesprovidesignatureinformationforpackages,classes,methods,
andfields.Thisinformationissufficienttocompileorrunagainst,butcontainsfarlessinformationthattheoriginalsourcecode.Inordertomakeiteasiertobrowseanddebugbinary
libraries,thereisamechanismforassociatingacorrespondingsourceJAR(orZIP)filewithabinaryJARfile.

Whyareallmyresourcesduplicatedintheoutputfolder(bin,forexample)?
IfyourJavaprojectisusingsourcefolders,theninthecourseofcompilingthesourcefilesintheproject,theJavacompilercopiesnonJavaresourcestotheoutputfolderaswellso
thattheywillbeavailableontheclasspathoftherunningprogram.ToavoidcertainresourcestobecopiedtotheoutputlocationyoucansetaresourcefilterintheJavacompiler
preferences:Window>Preferences>Java>Compiler>Building

HowdoIpreventhavingmydocumentationfilesfrombeingcopiedtotheproject'soutputfolder?
Usesourcefoldersandputanyresourcesthatyoudonotwanttobecopiedtotheoutputfolderintoaseparatefolderthatisnotincludedontheclasspath.Youcanalsoseta
resourcefilterintheJavacompilerpreferences:Window>Preferences>Java>Compiler>Buildingtoforexample*.doc.

HowdoIcreateadefaultpackage?
Youdon'thaveto.Filesintherootfolderofasourcefolderorprojectareconsideredtobeinthedefaultpackage.Ineffect,everysourcefolderhasthecapabilityofhavinga
fragmentofthedefaultpackage.

Whatisrefactoring?

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 276/322
12/10/2015 Javadevelopmentuserguide
Refactoringmeansbehaviorpreservingprogramtransformations.TheJDTsupportsanumberoftransformationsdescribedinMartinFowler'sbookRefactoring:ImprovingtheDesign
ofExistingCode,AddisonWisely1999.

WhendoIuseOpenDeclaration(F3)?
TofindouttheJavaelementthatcorrespondstotheselectedsourcerangewiththehelpofthecompiler.

IstheJavaprograminformation(typehierarchy,declarations,references,forexample)producedbytheJavabuilder?Isitstillupdatedwhenautobuild
isoff?
TheJavaprograminformationisindependentfromtheJavabuilder.ItisautomaticallyupdatedwhenperformingresourcechangesorJavaoperations.Inparticular,allthe
functionalityofferedbytheJavatooling(forexample,typehierarchies,codeassisting,search)willcontinuetoperformaccuratelywhenautobuildisoffforexample,whendoing
heavyrefactoringwhichrequiretoturnoffthebuilders,youcanstillusecodeassist,whichwillreflectthelatestchanges(notyetbuild).Otherthanthelaunching(thatis,runningand
debugging)ofprograms,theonlyfunctionalitywhichrequirestheJavabuilderistheevaluationofcodesnippets.

Afterreopeningaworkbench,thefirstbuildthathappensaftereditingaJavasourcefileseemstotakealongtime.Whyisthat?
TheJavaincrementalprojectbuildersavesitsinternalstatetoafilewhentheworkbenchisclosed.Onthefirstbuildaftertheprojectisreopened,theJavaincrementalproject
builderwillrestoreitsinternalstate.Whenthisfileislarge,theuserexperiencesanunusuallylongbuilddelay.

Ican'tseeatypehierarchyformyclass.WhatcanIdo?
Checkthatyouhaveyourbuildclasspathsetupproperly.SettinguptheproperbuildclasspathisanimportanttaskwhendoingJavadevelopment.Withoutthecorrectbuildpath,
youwillnotbeabletocompileyourcode.Inaddition,youwillnotbeabletosearchorlookatthetypehierarchiesforJavaelements.

HowdoIturnoff"autocompile"anddoitmanuallywhenIwant?
CleartheBuildautomaticallycheckboxonthe General>Workspacepreferencepage.Whenyouwanttobuild,pressCtrl+B,orselectProject>BuildAllfromthemenu
bar.
Hint:whenyouturn"autocompile"offandbuildmanually,youmayalsowanttoselecttheSaveautomaticallybeforebuildcheckboxonthe General>Workspacepreference
page.

WhenIselectamethodorafieldintheOutlineview,onlythesourceforthatelementisshownintheeditor.WhatdoIdotoseethesourceofthewhole
file?
ThereisatoolbarbuttonShowSourceofSelectedElementOnlyallyouhavetodoisunpressit.

CanInestsourcefolders?
Yes,youcanuseexclusionfilterstocreatenestedsourcefolders.

CanIhaveseparateoutputfoldersforeachsourcefolder?
Yes,selecttheAllowoutputfoldersforsourcefolderscheckboxintheJavaBuildPath>SourcepropertypageofyourJavaproject.

CanIhaveanoutputorsourcefolderthatislocatedoutsideoftheworkspace?
Yes,youcancreatealinkedfolderthatpointstothedesiredlocationandusethatfolderasthesourceoroutputfolderinyourJavaproject.

Javadevelopmenttools(JDT)

Javabuildpathpage
JDTglossary

5.12.JDTGlossary
CLASSfile
AcompiledJavasourcefile.
compilationunit
AJavasourcefile.
field
Afieldinsideatype.
importcontainer
Representsacollectionofimportdeclarations.ThesecanbeseenintheOutlineview.
importdeclaration
Asinglepackageimportdeclaration.
initializer
Astaticorinstanceinitializerinsideatype.
JARfile
JAR(Javaarchive)filesarecontainersforcompiledJavasourcefiles.Theycanbeassociatedwithanarchive(suchas,ZIP,JAR)asasourceattachment.ThechildrenofJAR
filesarepackages.JARfilescanbeeithercompressedoruncompressed.
JAVAelements
JavaelementsareJavaprojects,packages,compilationunits,classfiles,types,methodsandfields.
JAVAfile

Aneditablefilethatiscompiledintoabytecode(CLASS)file.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 277/322
12/10/2015
Javaprojects
Javadevelopmentuserguide

ProjectswhichcontaincompilableJavasourcecodeandarethecontainersforsourcefoldersorpackages.
JDT
Javadevelopmenttools.Workbenchcomponentsthatallowyoutowrite,edit,execute,anddebugJavacode.
JRE
Javaruntimeenvironment(forexample,J9,JDK,andsoon).
method
Amethodorconstructorinsideatype.
packagedeclaration
Thedeclarationofapackageinsideacompilationunit.
packages
AgroupoftypesthatcontainJavacompilationunitsandCLASSfiles.
refactoring
Acomprehensivecodeeditingfeaturethathelpsyouimprove,stabilize,andmaintainyourJavacode.Itallowsyoutomakeasystemwidecodingchangewithoutaffectingthe
semanticbehaviorofthesystem.
type
AtypeinsideacompilationunitorCLASSfile.
sourcefolder
AfolderthatcontainsJavapackages.
VCM
Versioncontrolmanagement.Thistermreferstothevariousrepositoryandversioningfeaturesintheworkbench.
VM
Virtualmachine.

Javadevelopmenttools(JDT)

FrequentlyaskedquestionsonJDT

5.13.JDTIcons

Objects
compilationunit(*.javafile)

Javafilewhichisnotonabuildpath

classfile

genericfile(unknowncontenttype)

unknownobject

Javascrapbookpage(*.jpagefile)

Javascrapbookpage(evaluationin
progress)
JARdescriptionfile

JUnittestresultfile

Javaworkingset

Javamodel

librarycontainer

JARfilewithattachedsource

JARfilewithoutattachedsource

classfolderwithattachedsource

classfolderwithoutattachedsource

sourcefolder

package

emptypackage

logicalpackage

emptylogicalpackage

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 278/322
12/10/2015 Javadevelopmentuserguide
packageonlycontainingnonJavaresources

packagedeclaration

importcontainer

import

class(public)

interface(public)

enumtype(public)

annotationtype(public)

packagevisibleclass

privateclass

protectedclass

defaultfield(packagevisible)

privatefield

protectedfield

publicfield

defaultmethod(packagevisible)

privatemethod

protectedmethod

publicmethod

Objectadornments
marksprojectasJavaproject
decoratesfilesandfoldersiftheyareonthe
buildpathoftheirenclosingJavaproject

decoratesJavaprojectsandworkingsets
thatcontainbuildpatherrors
thisJavaelementcausesanerror
thisJavaelementcausesawarning
thisJavaelementisdeprecated

constructor
abstractmember
finalmember
staticmember
synchronizedmember
nativemethod
transientfield
volatilefield
typewith
publicstaticvoidmain(String[]args)

implementsmethodfrominterface
overridesmethodfromsuperclass

typewithfocusinTypeHierarchyorQuick
Outline/Hierarchy
maximalexpansionlevelinCallHierarchy
recursivecallinCallHierarchy

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 279/322
12/10/2015 Javadevelopmentuserguide

compilationunitcontaininganabstractclass
asprimarytype
compilationunitcontaininganinterfaceas
primarytype
compilationunitcontaininganenumas
primarytype
compilationunitcontaininganannotationas
primarytype

Buildpath
classpathvariable

JARwithattachedsource

JARwithoutattachedsource

systemlibrary

buildpathordering

inclusionfilter

exclusionfilter

accessrules

Javadoclocation

sourceattachment

nativelibrarylocation

outputfolder

Codeassist
HTMLtag

Javadoctag

localvariable

template

SWTtemplate

Compare
field

method

Debugger
debuglaunch

runlaunch

terminatedrunlaunch

process

terminatedprocess

debugtarget

suspendeddebugtarget

terminateddebugtarget

thread

suspendedthread

stackframe

runningstackframe

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 280/322
12/10/2015
adornmentthatmarksastackframethat
Javadevelopmentuserguide
maybeoutofsynchwiththetargetVMasa
resultofanunsuccessfulhotcodereplace
adornmentthatmarksastackframethatis
outofsynchwiththetargetVMasaresult
ofanunsuccessfulhotcodereplace
inspectedobjectorprimitivevalue

watchexpression

localvariable

monitor

amonitorincontention
athreadincontentionforamonitor
amonitorthatisownedbyathread
athreadthatownsamonitor

currentinstructionpointer(topofstack)

currentinstructionpointer

enabledlinebreakpoint

disabledlinebreakpoint

adornmentthatmarksabreakpointas
skipped
adornmentthatmarksalinebreakpointas
installed
adornmentthatmarksabreakpointas
conditional
adornmentthatmarksanentrymethod
breakpoint
adornmentthatmarksanexitmethod
breakpoint

fieldaccesswatchpoint

fieldmodificationwatchpoint

fieldaccessandmodificationwatchpoint

adornmentthatmarksawatchpointas
installed

exceptionbreakpoint

runtimeexceptionbreakpoint

disabledexceptionbreakpoint

adornmentthatmarksanexception
breakpointascaught
adornmentthatmarksanexception
breakpointasuncaught
adornmentthatmarksanexception
breakpointasscoped
adornmentthatmarksanexception
breakpointasinstalled

Editor
implements

overrides

quickassistavailable

searchmatch

JUnit
test

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 281/322
12/10/2015
currentlyrunningtest
Javadevelopmentuserguide

successfultest

failingtest

testthrowinganexception

ignoredtest

testwithanassumptionfailure

testsuite

currentlyrunningtestsuite

successfullycompletedtestsuite

testsuitewithfailingtest

testsuitewithexceptionthrowingtest

caughtexception

stackframeelement

NLStools
skippedNLSkey

translatedNLSkey

untranslatedNLSkey

Quickfix
quickfixableerror

quickfixablewarning

add

change

changecast

fixmultipleproblems

movetoanotherpackage

remove

removeimport

rename

renameinfile

surroundwithtry/catch

Refactoring
generalchange

compositechange

textchange

filechange

Stoperror

Error

Warning

Information

Changefilter

Search

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 282/322
12/10/2015 Javadevelopmentuserguide
JavaSearch

searchfordeclarations

searchforreferences

SearchOccurrencesinFile
ageneralmatch

readaccesstolocalorfield

writeaccesstolocalorfield

TypeHierarchyview
typeoutsideofselectedpackage

interfaceoutsideofselectedpackage

5.16.ListofJDTkeybindings
ThelistofavailablekeybindingsinEclipsedependsonmanyfactors,includingwhatvieworeditorisselected,whetheradialogisopen,whatpluginsareinstalled,andwhat
operatingandwindowingsystemisbeingused.Atanytime,youcanobtainalistofavailablekeybindingsusingKeyAssist( Help>KeyAssist...orCtrl+Shift+L).Thefollowing
tableslistsomepopularkeybindingsavailableintheJavadevelopmenttools.

Javaeditoractions
AddBlockComment Ctrl+Shift+/

AddImport Ctrl+Shift+M

ContentAssist Ctrl+Space

ContentAssist(SimplifiedChinese) Alt+/

ExpandSelectiontoEnclosingElement Alt+Shift+UpArrow

ExpandSelection:RestoreLastSelection Alt+Shift+DownArrow

ExpandSelectiontoNextElement Alt+Shift+RightArrow

ExpandSelectiontoPreviousElement Alt+Shift+LeftArrow

Format Ctrl+Shift+F

Next Ctrl+.(Period)

OpenExternalJavadoc Shift+F2

OpenonSelection F3

OpenType Ctrl+Shift+T

OpenTypeHierarchy F4

OpenTypeinHierarchy Ctrl+Shift+H

OrganizeImports Ctrl+Shift+O

ParameterHints Ctrl+Shift+Space

ParameterHints(SimplifiedChinese) Alt+?

Previous Ctrl+,(Comma)

QuickAssist Ctrl+1

QuickFix Ctrl+1

Redo Ctrl+Y

RemoveBlockComment Ctrl+Shift+\

SearchforDeclarationsinWorkspace Ctrl+G

SearchforReferencesinWorkspace Ctrl+Shift+G

ShiftRight Tab

ShiftLeft Shift+Tab

ShowTooltipDescription F2

ToggleComment Ctrl+/

Undo Ctrl+Z

Debugactions
DebugLastLaunched F11

Display Ctrl+Shift+D

Inspect Ctrl+Shift+I

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 283/322
12/10/2015 Javadevelopmentuserguide
Resume F8

RunLastLaunched Ctrl+F11

RunSnippet Ctrl+U

RuntoLine Ctrl+R

RuntoReturn F7

StepInto F5

StepintoSelection Ctrl+F5

StepOver F6

ToggleBreakpoint Ctrl+Shift+B

Navigatingtheuserinterfaceusingthekeyboard
Keysandaccessibilityfortheworkbench

Listofkeybindings

6.TipsandTricks(JDT)
Thefollowingtipsandtricksgivesomehelpfulideasforincreasingyourproductivity.SeealsoPlatformTipsandTricksforgeneralEclipsetipsandWhat'sNew(JDT)forfeaturesin
thisrelease.

Editing|Refactoring|Searching|Navigation|Views|Miscellaneous|Debugging

Editingsource
Contentassist Contentassistprovidesyouwithalistofsuggestedcompletionsforpartiallyentered
strings.IntheJavaeditorpressCtrl+SpaceoruseEdit>ContentAssist.

Contentassistin ContentassistisalsoavailableinJavadoccomments.
Javadoc
comments

Contentassistfor Togetcontentassistproposalsforstaticmembersconfigureyourlistoffavoritestatic
staticimports membersonthe Java>Editor>ContentAssist>Favoritespreferencepage.
Forexample,ifyouhaveaddedjava.util.Arrays.*tothislist,thenallstaticmethodsof
thistypematchingthecompletionprefixwillbeaddedtotheproposalslist:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 284/322
12/10/2015 Javadevelopmentuserguide

Suppresstypesin Toexcludecertaintypesfromappearingincontentassist,usethetypefilterfeature
contentassist configuredonthe Java>Appearance>TypeFilterspreferencepage.Typesmatching
oneofthesefilterpatternswillnotappearintheOpenTypedialogandwillnotbeavailable
tocontentassist,quickfixandorganizeimports.Thesefilterpatternsdonotaffectthe
PackageExplorerandTypeHierarchyviews.

Contentassistfor Youcanusecontentassisttospeedupthecreationoffields,methodparametersandlocal
variable,method variables.Withthecursorpositionedafterthetypenameofthedeclaration,press
parameterand Ctrl+SpaceoruseEdit>ContentAssist.
fieldname
completions

Ifyouuseanameprefixorsuffixforfields,localvariablesormethodparameters,besure
tospecifythisinthe Java>CodeStylepreferencepage.

Contentassistfor Codeassistalsoworksonaccessestotypesthatarenotimportedyet.Dependingonthe
variablewith Java>Editor>ContentAssist>Addimportinsteadofqualifiednamepreference
unresolvedtype theeditorwilleitherautomaticallyaddimportsorfullyqualifythetypesforsuchproposals.
Pressinginthefollowingscenario:

resultsin:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 285/322
12/10/2015 Javadevelopmentuserguide

Contentassist Contentassistcanproposemembersavailableontypesusedininstanceofconditions.
afterinstanceof
condition

Eclipsewilladdtherequiredcastforyouwhenyouselectsuchaproposal.

Parameterhints Withthecursorinamethodargument,youcanseealistofparameterhints.IntheJava
EditorpressCtrl+Shift+SpaceorinvokeEdit>ContentAssist>ParameterHints.

Contentassiston Contentassistalsoprovideshelpwhencreatingananonymousclass.Withthecursor
anonymous positionedafter"new"andthebeginningofanabstractclassorinterfacenamepress
classes Ctrl+SpaceorinvokeEdit>ContentAssist>Default.

Thiswillcreatethebodyoftheanonymousinnerclassincludingallmethodsthatneedto
beimplemented.
Thisalsoworksifyouplacethecaretaftertheopeningparenthesesofaclassinstance
creation:

Togglebetween Whencontentassistisinvokedonanexistingidentifier,itcaneitherreplacetheidentifier
insertingand withthechosencompletionordoaninsert.Thedefaultbehavior(overwriteorinsert)is
replacingcontent definedinthe Java>Editor>ContentAssistpreferencepage.
assist Youcantemporarilytogglethebehaviorwhileinsidethecontentassistselectiondialogby
pressingandholdingtheCtrlkeywhileselectingthecompletion.
Incremental ContentassistcanalsoInsertcommonprefixesautomatically,similartoUnixshell
contentassist expansion.Toenablethatbehavior,selectthecheckboxonthe Java>Editor>
ContentAssistpreferencepage.
Camelcase Codecompletionsupportscamelcasepatterns.Forexample,completingonNPEor
supportincode NuPoiEwillproposeNullPointerException.Thissupportcanbedisabledusingthe
completion Showcamelcasematchespreferenceonthe Java>Editor>ContentAssist
preferencepage.

Use''keyto Youcanusethesemicolon()keytoselectanymethodinvocationproposalfromthe
insertmethod contentassistpopup.The' 'willbeappendedattheendofthemethodinvocation.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 286/322
12/10/2015
invocation
Javadevelopmentuserguide

Customizecontent Repeatedlyinvokingcontentassist(Ctrl+Space)cyclesthroughdifferentproposal
assistcategories categories.

Toconfigurewhichcategoriestoshowusethe Java>Editor>ContentAssist>
Advancedpreferencepage.
Youcanalsoassignseparatekeyshortcutstoyourfavoriteproposalcategories.

Creategettersand Tocreategetterandsettermethodsforafield,selectthefield'sdeclarationandinvoke
setters Source>GenerateGetterandSetter.

Ifyouuseanameprefixorsuffixbesuretospecifythisinthe Java>CodeStyle
preferencepage.
Creategettersand Aquickassist(Ctrl+1)isavailableonfieldstocreategettersandsetters.
settersquick
assist

Usecontentassist Anotherwaytocreategettersandsettersisusingcontentassist.Setthecursorinthetype
tocreategetter bodybetweenmembersandpressCtrl+Spacetogettheproposalsthatcreateagetteror
andsetters settermethodstub.

Deletegettersand Whenyoudeleteafieldfromwithinaview,EclipsecanproposedeletingitsGetterand
setterstogether Settermethods.Ifyouuseanameprefixorsuffixforfields,besuretospecifythisinthe
withafield Java>CodeStylepreferencepage.

Createdelegate Tocreateadelegatemethodforafieldselectthefield'sdeclarationandinvokeSource>
methods GenerateDelegateMethods.Thisaddstheselectedmethodstothetypethatcontainsa
forwardcalltodelegatedmethods.Thisisanexampleofadelegatemethod:

CreatehashCode() TocreatethemethodshashCode()andequals()invokeSource>GeneratehashCode()
andequals() andequals().

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 287/322
12/10/2015 Javadevelopmentuserguide

Usetemplatesto TemplatesareshowntogetherwiththeContentAssist(Ctrl+Space)proposals.
createamethod Thereareexistingtemplates,suchas'private_method','public_method',
'protected_method'andmore,butyoucanalsodefinenewtemplatesformethodstubs.
Afterapplyingatemplate,usetheTabkeytonavigateamongthevaluestoenter(return
type,nameandarguments).

Usetemplatesto OnprojectswhichhavetheSWTlibraryontheclasspath,youcancreateSWTwidgets
createSWT withContentAssist(Ctrl+Space)
widgets
Toadd,forexample,anSWTbutton,typeButtonandpressCtrl+Space,selecttheButton
SWTtemplate,andpressEnter.

Toseeallavailabletemplatesgotothe Java>Editor>Templatespreferencepageor
opentheTemplatesviewthroughWindow>ShowView>Other....

Createyourown Tocreateyourowntemplates,gotothe Java>Editor>Templatespreferencepage


templates andpresstheNewbuttontocreateatemplate.Forexample,atemplatetoiterate
backwardsinanarraywouldlooklikethis:

UseQuickFixto StartwiththemethodinvocationanduseQuickFix(Ctrl+1)tocreatethemethod.
createanew
method

UseQuickFixto Addanargumenttoamethodinvocationatacallsite.ThenuseQuickFix(Ctrl+1)toadd
changeamethod therequiredparameterinthemethoddeclaration.
signature

Usecontentassist Atthelocationwhereyouwanttoaddthenewconstructor,usecontentassistaftertyping
tocreatea thefirstlettersoftheconstructorname.
constructorstub

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 288/322
12/10/2015 Javadevelopmentuserguide

Createnewfields Doyouneedtocreatenewfieldstostoretheargumentspassedintheconstructor?Use
fromparameters QuickAssist(Ctrl+1)onaparametertocreatetheassignmentandthefielddeclaration
andletEclipseproposeanameaccordingtoyourCodeStylepreferences.

Usecontentassist InvokeContentAssist(Ctrl+Space)inthetypebodyatthelocationwherethemethod
tooverridea shouldbeadded.Contentassistwillofferallmethodsthatcanbeoverridden.Amethod
method bodyforthechosenmethodwillbecreated.

UseQuickFixto Toimplementanewinterface,addthe'implements'declarationfirsttothetype.Even
add withoutsavingorbuilding,theJavaeditorwillunderlinethetypetosignalthatmethodsare
unimplemented missingandwillshowtheQuickFixlightbulb.ClickonthelightbulborpressCtrl+1(Edit
methods >QuickFix)tochoosebetweenaddingtheunimplementedmethodsormakingyourclass
abstract.

UseCleanUpto Whenyouaddanewmethodtoaninterfaceoranabstractmethodtoanabstractclass,
add Eclipsecangeneratemethodstubsinallconcretesubclassesatonce.InvokeSource>
unimplemented CleanUp...onasetofJavaelements,useacustomprofile,andselectonthe
methods Configure...dialogtoAddunimplementedmethodsontheMissingCodetab.
Overrideamethod Tocreateamethodthatoverridesamethodfromabaseclass:
fromabaseclass SelectthetypewherethemethodsshouldbeaddedandinvokeSource>
Override/ImplementMethods.Thisopensadialogthatletsyouchoosewhichmethodsto
override.

Renameinfile Toquicklydoarenamethatdoesn'trequirefullanalysisofdependenciesinotherfiles,use
the'Renameinfile'QuickAssist.IntheJavaEditor,positionthecursorinanidentifierofa
variable,methodortypeandpressCtrl+1(Edit>QuickFix)
Theeditorisswitchedtothelinkededitmode(liketemplates)andchangingtheidentifier
simultaneouslychangesallotherreferencestothatvariable,methodortype.

YoucanalsousethedirectshortcutCtrl+2R.Usethe General>Keyspreference
pagetoconfigureshortcuts(inthe'Source'category).
UseQuickFixto Dealingwiththrownexceptionsiseasy.Unhandledexceptionsaredetectedwhiletyping
handleexceptions andmarkedwitharedlineintheeditor.
ClickonthelightbulborpressCtrl+1tosurroundthecallwithatrycatchblock.If
youwanttoincludemorestatementsinthetryblock,selectthestatementsanduse
Source>SurroundWith>Try/catchBlock.Youcanalsoselectindividual
statementsbyusingEdit>ExpandSelectionToandselectingEnclosing,Nextor
Previous.
Ifthecallisalreadysurroundedwithatryblock,QuickFixwillsuggestaddingthe
catchblocktotheexistingblock.
Ifyoudon'twanttohandletheexception,letQuickFixaddanewthrownexception

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 289/322
12/10/2015 totheenclosingmethoddeclaration Javadevelopmentuserguide

Atanytime,youcanconvertacatchblocktoathrownexception.UseCtrl+1(Edit>
QuickFix)onacatchblock.

Lesstypingfor Insteadoftypinganassignment,startwiththeexpressionthatwillbeassigned.
assignments

NowuseCtrl+1(Edit>QuickFix)andchoose'Assignstatementtonewlocalvariable'
andQuickAssistwillguessavariablenameforyou.

Lessworkwith Don'tspendtoomuchtimewithtypingcasts.Ignorethemfirstandusequickassisttoadd
castexpressions themafterfinishingthestatement.
Forexampleonassignments:


Orformethodarguments:


Orformethodcalltargets:

Assignacast Afteran'instanceof'check,itisverycommontocasttheexpressionandassignittoa
expression newlocalvariable.InvokeQuickAssist(Ctrl+1)onthe'instanceof'keywordoratthe
beginningoftheblockbodytosaveyourselfsometyping:

Surroundlines Tosurroundstatementswithanif/while/forstatementorablock,selectthelinesto
surroundandinvokeSource>SurroundWithorpressAlt+Shift+Z.

Theentriesinthemenuarederivedfromthenormaleditortemplates:Alltemplatesthat
containthevariable${line_selection}willshowupinthemenu.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 290/322
12/10/2015 Javadevelopmentuserguide
Templatescanbeconfiguredonthe Java>Editor>Templatespreferencepage.Edit
thecorrespondingtemplatestocustomizetheresultingcodeordefineyourownsurround
withtemplates.

Create'for'loops AsetofQuickAssists(Ctrl+1)cancreateforloopsthatiterateoveragivenexpression.
Forarrays:
Createanenhancedforloop
Createaforloopusinganindex

ForCollections:
Createanenhancedforloop
CreateaforloopusinganIterator
ForLists:
Createaforloopusinganindexandget(i)

Migrate Youcanconvertanonymousclasscreationstolambdaexpressions(andback)byinvoking
anonymousclass theQuickAssists(Ctrl+1):
creationsto
lambda Converttolambdaexpression
expressionsand Converttoanonymousclasscreation
back
Before:

AftertheQuickAssist(Ctrl+1),the6linesarecondensedinto1:

OrinvokeSource>CleanUp...,useacustomprofile,andontheConfigure...dialog
selectConvertfunctionalinterfaceinstancesandUselambdawherepossibleonthe
CodeStyletab.

Migrate Youcanconvertlambdaexpressionstomethodreferences(andback)byinvokingthe
lambda QuickAssists(Ctrl+1):
expressionsto
Converttomethodreference
methodreferences
andback

Converttolambdaexpression

MoreQuick CheckouttheQuickAssistpageforacompletelistofavailablecodetransformations.A
AssistsandFixes listofquickfixescanbefoundhere.
Shortcutsfor SomeofthepopularquickassistslikeRenameinfileandAssigntolocalvariablecan
QuickFixesand beinvokeddirectlywithCtrl+2RandCtrl+2L.Checkthe General>Keyspreference
Assists pageformorequickfixesandquickassiststhatsupportdirectinvocation.
Type"QuickAssist"or"QuickFix"inthefilterfield:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 291/322
12/10/2015 Javadevelopmentuserguide

Annotate YoucaninvokeAnnotatecommandeitherbyusingthecontextmenu,orbypressing
command Ctrl+1whenbrowsingattachedsourcecodeofalibraryusingtheclassfileeditorto
annotateanytypeinthesignatureofalibrarymethodorfield.Proposalswillbeofferedfor
markingtheselectedtypeas@NonNullor@Nullable.Afterselectingaproposal,the
compilerwillimmediatelyleveragethenewannotationforitsnullanalysis.

Twoprerequisitesmustbemetforusingthiscommand:
Theprojectisconfiguredtouseannotationbasednullanalysis.
Anexistingworkspacefolderhasbeenspecifiedastheexternalannotationlocation
foragivenlibrary.

Contentassistcan Youcanhavecontentassistinsertargumentnamesautomaticallyonmethodcompletion.
insertargument Thisbehaviorcanbecustomizedonthe Java>Editor>ContentAssistpreference
names page(seetheFillmethodargumentsandshowguessedargumentscheckbox.)For
automatically example,whenyouselectthesecondentryhere,

contentassistwillautomaticallyinsertargumentnames:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 292/322
12/10/2015 Javadevelopmentuserguide

YoucanthenusetheTabkeytonavigatebetweentheinsertednames.
IfyouchooseInsertbestguessedarguments,thebestguesswillbefilledinbydefault.
Thealternativeproposalsarestillavailable.

Automatically EnablingFillmethodargumentsandshowguessedargumentsonthe Java>Editor


inserttype >ContentAssistpreferencepageisalsousefulwhenworkingwithparameterizedtypesin
arguments J2SE5.0.


resultsin:

Removetype Ifcontentassistaddedtypeargumentsforagenerictype,butyoudonotwantthem
argumentsafter becauseyouneedthe.classliteraloryouwanttoinvokeastaticmethod,ratherthan
contentassist deletingalltheargumentsmanually,youcanjustdeletethe' <'andthatwillremovethe
entiretextupto' >'.
Remove Toremoveasurroundingstatementorblock,positionthecursorattheopeningorclosing
surrounding bracketandpressCtrl+1(Edit>QuickFix).
statement

Howwasthat YoucanenablespellcheckingsupportintheJavaeditoronthe General>Editors>


wordspelled TextEditors>Spellingpreferencepage.SpellingerrorsaredisplayedintheJavaeditor
again? andcorrespondingQuickFixesareavailable:

Youcanmakethedictionaryalsoavailabletothecontentassist.AQuickFixallowsyouto
addnewwordstotheuserdictionaryonthefly.

Structured TheStructuredSelectionactionscanbeusedtoenlargethecurrentselectiontothenext
selections enclosingelement:
HighlightsometextandpressAlt+Shift+ArrowUporselectEdit>ExpandSelectionTo
>EnclosingElementfromthemenubartheselectionwillbeexpandedtothesmallest
Javasyntaxelementthatcontainstheselection.Youcanthenfurtherexpandtheselection
byinvokingtheactionagain(orotheractionsfromtheExpandSelectionTomenu).
Thisisforexamplehelpfultoselecttheenclosingidentifierforrenames,ortoselect
adjacentstatementsforasubsequentExtractMethodrefactoring.

Findthematching TofindamatchingbracketselectanopeningorclosingbracketandpressCtrl+Shift+Por
bracket selectNavigate>GoTo>MatchingBracket.Youcanalsodoubleclicknexttoa
bracketthisselectsthetextbetweenthetwobrackets.

TheJavaeditoralsosupportshighlightingofenclosingbrackets.

Thiscanbeconfiguredonthe Java>Editorpreferencepage.

SmartJavadoc Type'/**'andpressEnter.ThisautomaticallyaddsaJavadoccommentstubcontaining
thestandard@param,@returnand@exceptiontags.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 293/322
12/10/2015 Javadevelopmentuserguide

Thetemplatesforthenewcommentcanbeconfiguredinthe Java>CodeStyle>
CodeTemplatespreferencepage.
Usethelocal Wheneveryoueditafile,itspreviouscontentsarekeptinthelocalhistory.Javatooling
historytorevert makesthelocalhistoryavailableforJavaelements,soyoucanrevertbacktoaprevious
backtoaprevious editionofasinglemethodinsteadofthefullfile.
editionofa
method Selectanelement(e.g.intheOutlineview)anduseReplaceWith>LocalHistoryto
revertbacktoapreviouseditionoftheelement.

Usethelocal Wheneveryoueditafile,itspreviouscontentsarekeptinthelocalhistory.Javatooling
historytorestore makesthelocalhistoryavailableforJavaelements,soyoucanrestoredeletedmethods
removedmethods selectively.
Selectacontainer(e.g.intheOutlineview)anduseRestorefromLocalHistoryto
restoreanyremovedmembers.

Customizable The Java>CodeStyle>CodeTemplatespreferencepageallowsyoutocustomize


codegeneration generatedcodeandcommentsinasimilarwaytonormaltemplates.Thesecodetemplates
areusedwhenevercodeisgenerated.

Since3.1,itispossibletouseprojectspecificCodetemplates,thatwillalsobesharedin
theteamifyourprojectisshared.OpenthePropertiesonaprojecttoenableproject
specificsettings.
Createcomments CommentscanbeaddedexplicitlywithSource>GenerateElementComment
inyourcode (Alt+Shift+J)orautomaticallybyvariouswizards,refactoringsorquickfixes.
Configurethecommenttemplatesonthe Java>CodeStyle>CodeTemplates
preferencepage.
Enableordisabletheautomaticgenerationofcommentseitherdirectlyonthewizard(e.g.
using'GenerateComment'checkboxonthenewJavatypewizards)orbythe
'Automaticallyaddnewcommentsfornewmethodsandtypes'checkboxofthe
Java>CodeStyle>CodeTemplatespreferencepage.
Allthesesettingscanalsobeconfiguredonaperprojectbasis.OpenthePropertiesona
projecttoenableprojectspecificsettings.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 294/322
12/10/2015
Sortmembers Javadevelopmentuserguide
YoucanSortMembersofaJavacompilationunitorasetofcompilationunitsaccording
toacategoryorderdefinedinthe Java>Appearance>MembersSortOrder
preferencepage.
You'llfindtheactionunderSource>SortMembers.
Wrapstrings YoucanhaveStringliteralswrappedwhenyoueditthem.Forexample,ifyouhavecode
likethis:

Stringmessage="Thisisaverylongmessage."

positionyourcaretaftertheword"very"andpressEnter.Thecodewillbeautomatically
changedto:

Stringmessage="Thisisavery"+
"longmessage."

Thisbehaviorcanbecustomizedinthe Java>Editor>Typingpreferencepage.

SmartTypingand TheJavaeditor'sSmartTypingfeatureseaseyourdailywork.Youcanconfigurethemon
howtocontrolit the Java>Editor>Typingpreferencepage.

WhenyouenableAutomaticallyinsertSemicolonsatcorrectposition,typinga
semicolonautomaticallypositionsthecursorattheendofthestatementbeforeinserting
thesemicolon.Thissavesyousomeadditionalcursornavigation.
Youcanundothisautomaticpositioningbypressingbackspacerightafterwards.

Fixyourcode AusefulfeatureisSource>CorrectIndentationorCtrl+I.
indentationwith Selectthecodewheretheindentsareincorrectandinvoketheaction.
onekeystroke
Ifnothingisselected,theactionindentsthecurrentline.

Fixyourcode Eclipsecancorrecttheindentationofyourcodewhenyousavetheeditor.Gotothe
indentationon Java>Editor>SaveActionspreferencepageandConfigure...Additionalactions,and
save selecttoCorrectindentationontheCodeOrganizingtab.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 295/322
12/10/2015 Javadevelopmentuserguide
Quickmenusfor Therefactoringandsourceactionscanbeaccessedviaaquickmenu.Selecttheelement
sourceand tobemanipulatedintheJavaeditororinaJavaviewandpressAlt+Shift+Sforthequick
refactoringactions sourcemenu,Alt+Shift+TforthequickrefactoringmenuandAlt+Shift+Zforthesurround
withmenu.

Findunusedcode TheJavacompilerdetectsunreachablecode,unusedvariables,parameters,importsand
unusedprivatetypes,methodsandfields.Changethesettingsforthedetectiononthe
Java>Compiler>Error/Warningspreferencepage.Thesesettingscanalsobe
specifiedperproject,use:Project>Properties>JavaCompiler>Error/Warnings.

Theseproblemsaredetectedasyoutype,andaquickfixisofferedtoremovethe
unneededcode.YoucanalsouseSource>CleanUp...toremoveunusedcode.
Findproblems Thecompilercanhelpyoufindproblemswithnullinyourcode.The Java>Compiler
withnull >Errors/Warningspreferencepagehasthreeoptionstodetectproblems:
Nullpointeraccess(in'Nullanalysis')
Whenthisoptionisenabled,thecompilerwillissueanerrororwarningwhenevera
variablethatisstaticallyknowntoholdanullvalueisusedtoaccessafieldor
method,asshownintheexamplebelow:

Potentialnullpointeraccess(in'Nullanalysis')
Whenthisoptionisenabled,thecompilerwillissueanerrororawarningwhenevera
variableisstaticallyknowntopotentiallyholdanullvalue,asshownintheexample
below:

Redundantnullcheck(in'Nullanalysis')
Whenenabled,thecompilerwillissueanerrororawarningwheneveravariablethat
isstaticallyknowntoholdanulloranonnullvalueistestedagainstnull,asshownin
theexamplesbelow:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 296/322
12/10/2015 Javadevelopmentuserguide

Findproblems TheSource>FindBrokenExternalizedStringsactionfindsundefined,unusedand
withexternalized duplicatekeysforyou:
strings

Changeproblem Whenaproblemhoverhasbeenenriched(bypressingF2ormovingthemouseintothe
severityin hover),anactiontochangetheseverityofthecurrentproblemisavailable.
problemhover

Clickonthebuttoninthetoolbartogotothe Java>Compiler>Errors/Warnings
preferencepage.

Javadoccomment TheEclipseJavacompilercanprocessJavadoccomments.Searchreportsreferencesin
handling doccomments,andrefactoringupdatesthesereferencesaswell.Thisfeatureiscontrolled
fromthe Java>Compiler>Javadocpreferencepage(orsetforanindividualproject
usingProject>Properties>JavaCompiler>Javadoc).

Whenturnedon,malformedJavadoccommentsaremarkedintheJavaeditorandcanbe
fixedusingEdit>QuickFix(Ctrl+1):

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 297/322
12/10/2015 Javadevelopmentuserguide

Suppress InJ2SE5.0andlater,youcansuppressalloptionalcompilewarningsusingthe
warnings SuppressWarningsannotation.
Inthisexample,addAll()ismarkedasanunusedmethod.QuickFix(Ctrl+1)isusedto
addaSuppressWarningsannotationsothatthewarningwillnotbeshownforthismethod.

CleanUps Source>CleanUp...helpsfixingmultipleproblemsatonceandhelpstoestablisha
consistentcodestyle.Forinstance,youcan:
convertallforloopstoenhancedforloopswherepossible.
markalloverridingmethodsinawholeprojectwithan@Overrideannotation.
organizeimports
formatyourcode
removeunnecessarycode
CleanUpsareorganizedinCleanUpprofiles.Aprofilecanbeattachedtotheworkspace
ortoindividualprojects.Projectsettingscanbesharedinateamthroughaversioncontrol
system.Itisalsopossibletoexportandimporteachprofile.

CleanUpscanbeexecutedassaveactionsonsave.Gotothe Java>Editor>Save
Actionspreferencepagetoconfigurewhichcleanupstoinvokeonsave.

Refactoring
Scriptingof MostoftherefactoringsofferedbyJDTcannotonlybeexecutedinteractively,butalso
refactorings byarefactoringscript.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 298/322
12/10/2015 Javadevelopmentuserguide
CreatearefactoringscriptfromtherefactoringhistoryusingRefactor>CreateScript....

ArefactoringscriptcanthenbeappliedlateronanarbitraryworkspaceusingRefactor>
ApplyScript....

Suchrefactoringscriptscanbeusedindifferentscenariossuchasautomaticfixingof
breakingAPIchangesbetweensoftwarelayersorprovidingpatcheswithrichsemantics.
SafeJARfile WhenexportingaJARfilefromtheworkspace,theJARExportWizardofferstheoption
migration toincluderefactoringinformationintotheJARfile.

UseFile>Export...andselectJARfile.OnthefirstpageoftheJARExportWizard,
selectExportrefactoringsforcheckedprojects.Clickonthelinktoselectthe
refactoringstoinclude.

ClientsarethenabletomigrateanoldversionoftheJARfiletoanewoneusingthe
Refactor>MigrateJARFile...refactoring.Thisrefactoringautomaticallyupdatesall
codewhichisdependentontheoldversionoftheJARfiletousethenewversionofthe
JARfile.

Searching
Locatevariables Youcanlocatevariablesandseetheirread/writestatusbyselectinganidentifier
andtheirread/write (variable,methodortypereferenceordeclaration)andinvokingSearch>Occurrencesin
access File>Identifier.Thismarksallreferencesofthisidentifierinthesamefile.Theresults
arealsoshowninthesearchviewwithdifferentcolorsforreadorwriteaccess,alongwith
iconsshowingthevariable'sreadorwriteaccess.

Alternatively,usetheMarkOccurrencesfeaturetodynamicallyhighlightoccurrences.
Youcansearchoverseveralfilesbyusingthegeneralsearchfeatures(Search>
References).

Searchformethods Tosearchformethodswithaspecificreturntype,use"*<returntype>"asfollows:
withaspecific
returntype OpenthesearchdialogandclickontheJavaSearchtab.
Type'*'andthereturntype,separatedbyaspace,intheSearchstring.
SelecttheCasesensitivecheckbox.
SelectMethodandDeclarationsandthenclickSearch.

Filtersearch Bydefault,JavaSearchfindsreferencesinsideJavacodeandJavadoc.Ifyoudon'twant
matchesinJavadoc toseethereferencesinsideJavadoc,youcanfilterthesematchesbyenabling'Filter
Javadoc'intheviewmenu(trianglesymbol)ofthesearchview.
Filterpotential Potentialmatchesoccurwhenacompiletimeproblempreventsthesearchenginefrom
searchmatches completelyresolvingthematch.FilterthesematcheswithFilterPotentialinthesearch
viewmenu(trianglesymbol).
Tracemethodcall UsetheCallHierarchytofollowlongorcomplexcallchainswithoutlosingtheoriginal
chainswiththeCall context:JustselectamethodandinvokeNavigate>OpenCallHierarchy(Ctrl+Alt+H).
Hierarchy

Youcanalsousedraganddroptoreplacetheviewinputwiththeselectedmethods.
Ctrl+dragaddstheselectedmethodstotheexistingelementsintheview.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 299/322
12/10/2015 Javadevelopmentuserguide
MethodsfromanonymousclassesorspecialtypeslikeRunnablearebydefaultexpanded
withconstructors,sinceitisoftenmoreinterestingtoseewheretheobjectiscreatedthan
wherethemethodisinvoked.ExpandwithConstructorsfromthecontextmenutoggles
thisbehavior.Thedefaultscanbeconfiguredintheviewmenu.

Codenavigationandreading
Openselectionin TherearetwowayshowyoucanopenanelementfromareferenceintheJavaeditor.
Javaeditor
SelectthereferenceinthecodeandpressF3(Navigate>OpenDeclaration)
HoldCtrl,movethemousepointeroverthereference,andclickthehyperlink


HoldingCtrlonanoverridablemethodshowsapopupwithanOpenImplementation
entry,whichdirectlyopenstheimplementationincasethere'sonlyone,orshowsallthe
concreteimplementationsforthatmethodinthehierarchyofitsdeclaringtype,usingthe
quicktypehierarchy.
Thehyperlinkstylenavigationcanbeconfiguredonthe General>Editors>Text
Editors>Hyperlinkingpreferencepage.
Inplaceoutlines PressCtrl+F3intheJavaeditortopopupaninplaceoutlineoftheelementatthecurrent
cursorposition.OrpressCtrl+O(Navigate>QuickOutline)topopupaninplaceoutline
ofthecurrentsourcefile.

Inplaceoutlines PressCtrl+OorCtrl+F3againtoaddinheritedmemberstoanopenInplaceoutline.
showinherited Inheritedmembershaveabluelabel.Filterandsorttheoutlinewiththemenuintheupper
members rightcorner.

TheQuickOutline(Ctrl+O)alsoshowsinheritedmembersofthetypethatcontainsthe
currenteditorselection.Thefocustypesthatcanshowinheritedmembersaremarked
withatriangle( ).
Inplacehierarchy FindoutwhicharethepossiblereceiversofavirtualcallusingtheQuickType
Hierarchy.PlacethecursorinsidethemethodcallandpressCtrl+T(Navigate>Quick
TypeHierarchy).Theviewshowsalltypesthatimplementthemethodwithafullicon.

PressEntertoopenthecorrespondingmethodinaneditor.PressCtrl+Tagaintoswitch
totheSupertypehierarchy.

JavaEditor TheJavaEditorcontainsabreadcrumbnavigationbarwhichshowsthepathtothe
Breadcrumb elementatthecursorposition.ThebreadcrumbcanbeenabledviatheToggle
BreadcrumbtoolbarbuttonorbypressingAlt+Shift+B.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 300/322
12/10/2015 Javadevelopmentuserguide

Eachelementinthebreadcrumbcanbeselectedandactionscanbeinvokedthrougha
contextmenuorkeyboardshortcuts.Furthermorethebreadcrumbletsyounavigateto
otherelementsviadropdowns.

Advanced TheJavaeditorcanhighlightsourcecodeaccordingtoitssemantics(forexample:static
highlighting fields,localvariables,staticmethodinvocations).Havealookatthevariousoptionson
the Java>Editor>SyntaxColoringpreferencepage.

Initiallyfolded Youcanspecifywhichregionsarefoldedbydefaultwhenaneditorisopened.Havea
regions lookatthe Java>Editor>Foldingpreferencepagetocustomizethis.

Markoccurrences Whenworkingintheeditor,turnonMarkOccurrencesinthetoolbar( )orpress


Alt+Shift+O.You'llseewithinafile,whereavariable,methodortypeisreferenced.

Differentcolorsareusedtomarkreadandwriteaccesses.
Selectingareturntypeshowsyouthemethod'sexitpoints.Selectanexceptiontosee
whereitisthrown.Selectasuperclassorinterfacetoseethemethodsoverrideor
implementamethodfromtheselectedsupertype.
Finetune'markoccurrences'onthe Java>Editor>MarkOccurrencespreference
page.
Changethecolorfortomarkeronthe General>Editors>TextEditors>
Annotationspreferencepage.
ToshowoccurrencesintheSearchview,usetheSearch>Occurrencesfeature.

Gotonext/ Toquicklynavigatetothenextorpreviousmethodorfield,use
previousmethod Ctrl+Shift+ArrowUp(Navigate>GoTo>PreviousMember)orCtrl+Shift+Arrow
Down(Navigate>GoTo>NextMember)
Controlyour UsetheNext/PreviousAnnotationtoolbarbuttonsorNavigate>NextAnnotation
navigationbetween (Ctrl+.)andNavigate>PreviousAnnotation(Ctrl+,)tonavigatebetweenannotationsin
annotations aJavasourcefile.Withthebuttondropdownmenus,youcanconfigureonwhich
annotationsyouwanttostop:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 301/322
12/10/2015 Javadevelopmentuserguide

Remindersinyour WhenyoutagacommentinJavasourcecodewith"TODO"theJavacompiler
Javacode automaticallycreatesacorrespondingtaskasareminder.Openingthetasknavigatesyou
backtothe"TODO"inthecode.Usethe Java>Compiler>TaskTagspreference
pagetoconfigureanyotherspecialtags(like"FIXME")thatyou'dliketotrackinthetask
list.

Openfrom TheOpenfromClipboarddialog(Navigate>OpenfromClipboard)helpsyounavigate
Clipboarddialog tothematchingJavaelementintheeditor.
ToquicklyfindaJavaelementfromStacktrace,copyalinefromStacktraceandgo
toNavigate>OpenfromClipboard.Forexample:Copy
atjava.lang.String.matches(String.java:1550)anduseOpenfromClipboard
toopenupString.classat1550linenumber.

TricksintheOpen TheOpenTypedialog(Navigate>OpenTypeortoolbarbutton)helpsyounavigatetoa
Typedialog typebyitsname.
Tofindtypesquickly,onlytypethecapitallettersofthetypename:
IOOBEfindsIndexOutOfBoundsException.
Ortypethefirstfewcharactersofeachnamepart:
NuPoiEfindsNullPointerException.
Toseealltypesendingwithagivensuffix,e.g.allTests,use*Test<tonotseeall
typescontainingTestsomewhereelseinthetypename.
Toopenmultipletypesatonce,selecttheminthelistandclickOK.

Makehoverssticky YoucanopenthetextfromahoverinascrollablewindowbypressingF2(Edit>Show
TooltipDescription)orbymovingyourmousepointerintothehover.Youcanselectand
copycontentfromthiswindow,invokeactions,orfollowlinks.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 302/322
12/10/2015 Youcanconfigurehowtoenrichthehoveronthe Javadevelopmentuserguide
General>Editors>TextEditors
preferencepage.

HoversintheJava YoucanseedifferenthoversintheJavaeditorbyusingthemodifierkeys(Shift,Ctrl,
editor Alt).
Whenyoumovethemouseoveranidentifierthathasnowarningorproblemannotationin
theJavaeditor,bydefaultahoverwiththeJavadocextractedfromthecorresponding
sourceofthiselementisshown.Ifthere'saproblemannotationontheidentifierthenthe
hovershowsthecorrespondingmessage.HoldingdowntheShiftkeyshowsyouthe
sourcecode:

Youcanchangethisbehavioranddefinethehoversforothermodifierkeysinthe Java
>Editor>Hoverspreferencepage.
Genericmethod Youcanusehovertoshowtheinferredsignatureofagenericmethod.
inferredsignature

Openandconfigure IfyouwanttoopentheJavadocdocumentationforatype,methodorfieldwithShift+F2
externalJavadoc (Navigate>OpenExternalJavadoc),youfirsthavetospecifythedocumentation
documentation locationstotheelementsparentlibrary(JAR,classfolder)orproject(sourcefolder).
Forlibraries,openthebuildpathpage(Project>Properties>JavaBuildPath),goto
theLibraries,andexpandthenodeofthelibrarywhereyoucaneditthe'Javadoc
location'node.Thedocumentationcanbelocalonyourfilesysteminafolderorarchive,
oronawebserver.

Fortypes,methodsorfieldsinsourcefolders,gotothe(Project>Properties>Javadoc
Location).
Findthemethod Toshowthemethodimplementedbyfunctionalinterfaceinstances,youcanhoveron:
implementedby
functionalinterface ' >'inalambdaexpression
instances

' ::'inamethodreference

Tonavigatetothefunctionalmethod,holdCtrl,movethemousepointerover' >'or' ::',


andclickthehyperlink.

Javaviews
Organizing UseTopLevelElements>WorkingSetsinthePackageExplorer'sviewmenuto
workspacewith enableanewmodethatshowsworkingsetsastoplevelelements.Thismodemakesit
manyprojects mucheasiertomanageworkspacescontaininglotsofprojects.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 303/322
12/10/2015 Javadevelopmentuserguide

UseConfigureWorkingSets...fromthePackageExplorer'sviewmenutoconfigure
whichworkingsetsgetshown.ThedialogletsyoucreatenewJavaworkingsets,define
whichworkingsetsareshownandinwhatorder.IfSortWorkingSetsisnotenabled,
workingsetscanalsoberearrangeddirectlyinthePackageExplorerusingdraganddrop.

Assignworking Toassignanelementtoadifferentworkingset,selecttheelementinthePackage
sets ExplorerandchooseAssignWorkingSets...fromthecontextmenu.

Declarationview TheDeclarationview( Window>ShowView>Other...>Java>Declaration)


showsthesourceoftheelementselectedintheJavaeditororinaJavaview.

Javadocview TheJavadocview( Window>ShowView>Other...>Java>Javadoc)showsthe


JavadocoftheelementselectedintheJavaeditororinaJavaview.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 304/322
12/10/2015 Javadevelopmentuserguide

TypeHierarchy Tofindoutwhichtypesinahierarchyoverrideamethod,usethe'ShowMembersin
viewandmethod Hierarchy'feature:
implementations/
definitions 1. SelectthemethodtolookatandpressF4(Navigate>OpenTypeHierarchy).
ThisopenstheTypeHierarchyviewonthemethod'sdeclaringtype.
2. WiththemethodselectedintheTypeHierarchyview,pressthe'LockViewand
ShowMembersinHierarchy'toolbarbutton.
TheTypeHierarchyviewnowshowsonlytypesthatimplementordefinethe'locked'
method.YoucanforexampleseethatisEmpty()isdefinedinListandimplementedin
ArrayListandVectorbutnotinAbstractList.

TypeHierarchy Thetypehierarchymethodviewletsyousorttheselectedtype'smethodsbyitsdefining
viewsupports types.Forexample,forAbstractListyoucanseethatitcontainsmethodsthatwere
groupingby definedinObject,CollectionandList:
definingtype

Tricksinthetype
hierarchy FocusthetypehierarchyonanewtypebypressingF4(Navigate>OpenType
Hierarchy)onanelementoraselectedname.
YoucanopentheTypeHierarchyviewnotonlyontypesbutalsoonpackages,
sourcefolders,JARarchivesandJavaprojects.Youcanselectmultiplepackages,
sourcefolders,orprojects,andthenopenahierarchythatcontainsalltypesinthe
selectedcontainers.
YoucanDrag&DropanelementontotheTypeHierarchyviewtofocusonthat
element.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 305/322
12/10/2015 Javadevelopmentuserguide
Youcanchangetheorientation(fromthedefaultverticaltohorizontal)oftheType
Hierarchyviewfromtheview'stoolbarmenu.

Structuralcompare AstructuralcomparisonofJavasourceignoresthetextualorderofJavaelementslike
ofJavasource methodsandfieldsandshowsmoreclearlywhichelementswerechanged,added,or
removed.
ForinitiatingastructuralcomparisonofJavafilesyouhavetwooptions:
SelecttwoJavacompilationunitsandchooseCompareWith>EachOtherfrom
theview'scontextmenu.Ifthefileshavedifferences,theyareopenedintoa
CompareEditor.ThetoppaneshowsthedifferingJavaelementsdoubleclickingon
oneofthemshowsthesourceoftheelementinthebottompane.
Inanycontextwhereafilecomparisonisinvolved(e.g.aCVSSynchronization)a
doubleclickonaJavafilenotonlyshowsthecontentofthefileinatextcompare
viewer,butitalsoperformsastructuralcompareandopensanewpaneshowingthe
results.

Youcanevenignoreformattingchangeswhenperformingthestructuralcompare:turnon
theIgnoreWhitespaceoptionviatheCompareEditor'stoolbarbutton,oracompare
viewer'scontextmenu.
Structuralcompare AstructuralcomparisonofJavapropertyfiles(extension:.properties)ignoresthetextual
ofpropertyfiles orderofpropertiesandshowswhichpropertieswerechanged,added,orremoved.
Forinitiatingastructuralcomparisonofpropertyfilesyouhavetwooptions:
SelecttwofilesinthePackageExplorerorNavigatorandchooseCompareWith>
EachOtherfromtheview'scontextmenu.
Inanycontextwhereafilecomparisonisinvolved(e.g.aCVSSynchronization)a
doubleclickonapropertyfilenotonlyshowsthecontentofthefileinatext
compareviewer,butitalsoperformsastructuralcompareandopensanewpane
showingtheresults.

Hierarchicalvs.flat AnoptionontheJavaPackages(andPackageExplorer)viewmenuallowsyoutochange
presentationof thewaypackagesaredisplayed.PackagePresentation>Hierarchicaldisplays
packages packagesinatree,withsubpackagesbelowpackagesPackagePresentation>Flat
displaystheminthestandardarrangement,asaflatlistwithallpackagesandsub
packagesassiblings.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 306/322
12/10/2015 Javadevelopmentuserguide

Logicalpackages TheJavaPackagesview(JavaBrowsingperspective)coalescespackagesofthesame
nameacrosssourcefolderswithinaproject.ThescreenshotshowsthePackagesview
containingalogicalpackage.

Compresspackage Ifyourpackagenamesareverylong,youcanconfigureacompressednamethatappears
names intheviewers.Configurationofthecompressionpatternisdoneinthe Java>
Appearancepreferencepage.

Usingthisexample,packagesarerenderedthefollowingway:

Packagename PackagenamesinJavaviewscanbeabbreviatedwithcustomrules.Forexample,the
abbreviations followingrulesproducetherenderingshownbelow:

org.eclipse.ui={UI}
org.eclipse.ui.texteditor={T}
org.eclipse.ui.internal.texteditor=[iT]

Withoutabbreviations: Withabbreviations:

Theabbreviationrulescanbeconfiguredonthe Java>Appearancepreferencepage.

Manipulatingthe InsteadofmanipulatingtheJavaBuildpathonProject>Properties>JavaBuildPath,
Javabuildpath usetheactionsinthePackageExplorer'scontextmenu.
directlyinthe Youcanforexampleaddnewsourcefolders,archivesandlibrariestothebuildpathorin
PackageExplorer andexcludefileandfoldersfromasourcefolder.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 307/322
12/10/2015 Javadevelopmentuserguide

Pastecode YoucanpasteasnippetofcodecontainingaJavatypedirectlyintoapackageorsource
snippetstocreatea foldertocreateanewcompilationunit.Forexample,selectandcopythissourcecode:
type
packagepack
publicclassHelloWorld{
publicstaticvoidmain(String[]args){
System.out.println("HelloWorld")
}
}

ThenselectasourcefolderinthePackageExploreranduseCtrl+V(Edit>Paste).This
automaticallycreatesanewpackage'pack'andfile'HelloWorld.java'withthecopied
content.
YoucanalsopasteamethodorasetofstatementsEclipsewillcreatetherequired
enclosingelementsforyou.
IfyoupastewhilenothingisselectedinthePackageExplorer,Eclipseevencreatesa
newJavaProjectandcreatethe*.javafilethere.Furthermore,theclipboardcanalso
containmultiplepackageandtypedeclarations,inwhichcaseEclipsewillcreateallthe
necessarypackagesand*.javafilesonpaste.

Pastepatchinto What'sthequickestwaytoapplyapatchfromBugzilla?Justopentheattachment,copy
PackageExplorer thepatchtotheclipboardandpasteitintothePackageExplorer.
GroupingJava ConfiguretheProblemsviewtogroupJavaproblemsintocategorieswithGroupby>
problems JavaProblemTypeintheviewmenu.

Youcancontrolifaconfigurableerrorisintendedtobefatalornotatthebottomofthe
Java>Compiler>Errors/Warningspreferencepage.

Javatypeindicator EnabletheJavaTypeIndicatoronthe General>Appearance>LabelDecoration


preferencepagetofindoutwhatthefirsttypeinacompilationunitorclassfileis.An
adornmentisshownforinterfaces,annotations,andenums,whileanordinaryclassstays
undecorated.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 308/322
12/10/2015 Javadevelopmentuserguide

Miscellaneous
Projectspecific Allcodestyleandcompileroptionscanbedefinedperproject.
preferences OpentheprojectpropertypageswithProject>Propertiesonaprojectorusethelinkon
theworkspacepreferences(e.g.the Java>CodeStylepreferencepage)toopena
projectpropertypageandenableprojectspecificsettings.

Theprojectspecificsettingsarestoredinaconfigurationfileinsidetheproject(inthe
'.settings'folder).Whenyoushareaprojectinateam,teammemberswillalsogetthese
projectspecificsettings.
Accessrules AccessrulesgiveyouthepossibilitytoenforceAPIrulesfortypesfromreferenced
libraries.OntheJavabuildpathpage(Project>Properties>JavaBuildPath)editthe
'AccessRules'nodeavailableonreferencedprojects,archives,classfoldersand
libraries.
Packagesortypesinthesereferencescanbeclassifiedas:
Accessible
Discouraged
Forbidden
Accordingtothesettingsonthe Java>Compiler>Errors/Warningspreference
page,thecompilerwillmarkdiscouragedandforbiddenreferenceswithwarningorerrors.

JUnit SelectaJUnittestmethodinaviewandchooseRun>JUnitTestfromthecontext
menuorRun>RunAs>JUnitTestfromthemainmenu.Thiscreatesalaunch
configurationtoruntheselectedtest.
HideJUnitview YoucanconfiguretheJUnitviewtoonlyopenwhenthereareerrorsorfailures.Todoso
untilerrorsor enableActivateonErrors/FailuresonlyintheJUnitviewmenu.Thatway,youcan
failuresoccur havetheviewsetasafastviewandneverlookatitwhentherearenofailingtests.While
therearenoproblemsinyourtestsyouwillseethisicon (thenumberofsmallgreen
squareswillgrow,indicatingprogress)whilerunningthemandthisicon aftertheyare
finished.If,however,errorsorfailuresoccur,theiconwillchangeto (or iftestsare
finished)andtheJUnitviewwillappear.
Contentassistin Contentassist(Ctrl+Space)isalsoavailableininputfieldsofvariousJavadialogs.Look
dialogfields forasmalllightbulbiconbesidethefieldwhenithasfocus.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 309/322
12/10/2015
Smartcaret Javadevelopmentuserguide
TextfieldsforeditingJavanamessupportsmartcaretpositioning.UseCtrl+Leftand
positioningin Ctrl+Righttostopatcamelcaseboundariesinsideaname.UseCtrl+Shift+Leftand
dialogsshowing Ctrl+Shift+Righttoextendtheselectioninsmallsteps.UseCtrl+Deletetodeletethe
Javanames nextandCtrl+Backspacetodeletethepreviouspartofaname.

Ctrl+Right:

Ctrl+Shift+Right:

write"Equal":

Ctrl+Delete:

write"To":

Defineprefixesor Youcanconfiguretheprefixorsuffixforfields,staticfields,parameters,andlocal
suffixesforfields, variables.Thesesettingsonthe Java>CodeStylepreferencepageareusedin
parametersand contentassist,quickfix,andrefactoringwheneveravariablenameiscomputed.
localvariables

OrganizeImports YoucaninvokeSource>OrganizeImportsonsetsofcompilationunits,packages,
worksonmorethan sourcefoldersorJavaprojects.
singlefiles
Organizeimports Eclipsecanautomaticallyorganizeimportswheneveryousaveaneditor.Thisfeaturecan
onsave beenabledgloballyonthe Java>Editor>SaveActionspreferencepage.Thesave
actionscanalsobeconfiguredperproject,whichmakesiteasytoenforceaprojectwide
standardbysharingthesettingsacrossateam:

Besidesorganizingimports,saveactionscanalsoformatcodeandperformotherclean
ups.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 310/322
12/10/2015 Javadevelopmentuserguide

Formatselection SelectmultipleJavafilestoformatandchooseSource>Formattoformatthemall.The
formatactionisalsoavailableonpackages,sourcefoldersorJavaprojects.
IntheJavaEditor,Source>Format(Ctrl+Shift+F)formatsjusttheselectedregion.If
nothingisselected,thewholefilegetsformatted.

Selectexecution WhenyoucreateaJavaprojectthatyouwanttosharewithateam,itisagoodideato
environmentfor useanexecutionenvironmentinsteadofaspecificJRE.
Javaproject
ExecutionenvironmentsaresymbolicrepresentationsofJREswithstandardizedentries
like'J2SE1.4','J2SE1.5'.Thatmeansnofilesystempathwillgointothesharedbuild
path.
JREscanbeassignedtotheenvironmentsonthe Java>InstalledJREs>
ExecutionEnvironmentspreferencepage.

TosetaprojectspecificJREofanexistingproject,opentheproject'sJavaBuildpath
propertypage(Project>Properties>JavaBuildPath),thentheLibrariespage,select
'JRESystemLibrary'andpressEdit.Inthe'EditLibrary'dialogyoucanselecteitheran
ExecutionEnvironment,aprojectspecificJRE,ortheworkspacedefaultJRE.

Usedraganddrop DragandDropisahandyreplacementofEdit>CutandEdit>Paste,orEdit>Copy
andEdit>Paste.HolddowntheCtrlkeywhiledroppingtochangefrommovetocopy.
Importanttoknow:
IfyoumoveJavacompilationunitsbetweenpackagesbyDrag&Drop,thiswill
behavelikearefactoringmoveallmissingimportswillbeaddedandreferences
updated
Ifyoudraganddropsourceelementsliketypesormethods,thiswillonlycopyor
movethecorrespondingsourcecodenoreferenceswillbeupdated

Propagating TheJavacompilercanbeconfiguredtodiagnosedeprecationusingoptionsonthe
deprecationtag Java>Compiler>Errors/Warningspreferencepage.

Usingthisconfiguration,theresultis:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 311/322
12/10/2015 Javadevelopmentuserguide
Ifyou'reunabletofixausageofadeprecatedconstruct,werecommendthatyoutagthe
enclosingmethod,fieldortypeasdeprecated.Thisway,youacknowledgethatyoudid
overrideadeprecatedconstruct,andthedeprecationflagispropagatedtofurther
dependents.

Recoveringfrom Intherareeventofadysfunction,JDTcouldrevealsomeinconsistenciessuchas:
abnormal
inconsistencies missingresultsinaJavaSearchorOpenType
invaliditemsinPackageExplorer

TobringJDTintoaconsistentstateagain,thefollowingactionsneedtobeperformedin
thisexactorder:
1. CloseallprojectsusingnavigatorCloseProjectmenuaction
2. ExitandrestartEclipse
3. OpenallprojectsusingnavigatorOpenProjectmenuaction
4. Manuallytriggeracleanbuildofentireworkspace(Project>Clean...)

Buildpatherror ThePackageExplorerandtheProjectExplorershowthiserrordecorator onJava


decorator projectsandworkingsetsiftheycontainbuildpatherrors:

IncaseofbuildpatherrorsintheProblemsview,firstlookinthePackageExplorerfor
thisiconsinceitbetterindicateswheretheproblemis.
'*.classwithout The*.classwithoutsourcefiletypeallowstoassociateaninternalorexternaleditorto
source'filetype classfilesthathavenosourceattached.Thise.g.allowstoopentheclassfileina
decompiler:

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 312/322
12/10/2015 Javadevelopmentuserguide

Selectivelyignore YoucanconfigureJDTtoignoreoptionalerrors/warningsfromcertainsourcefolders.See
errors/warnings Projectproperties>JavaBuildPath>Compiler>Source.
fromsourcefolders

WiththisoptionsettoYes,JDTwillsuppresserrors/warningsconfiguredinthe Java
>Compiler>Errors/Warningspreferencepage.Thiscanbedesirableforsourcefolders
thatcontainautogeneratedclassesortests.

Ignoreunavoidable WhenworkingwithJavalibrarieswhoseAPIshavenotbeengenerifiedyet,you
generictype sometimesrunintotypesafetyproblemsthatcannotbeavoidedduetoreferencestoan
problems oldAPIthatusesrawtypes.

SuchproblemscanbeignoredwiththeIgnoreunavoidablegenerictypeproblemsdue
torawAPIscompileroption.
WhentheoldAPIiseventuallygenerified,thenmostoftheseproblemseithergoaway,or
youwillseeacompileerrorbecausethetypeargumentsyouusedarenotcorrect.For
rawreferencesinmethodsignatures,therawtypeproblemwillreappear.
Thisoptionisdisabledbydefaultbutcanbeenabledonthe Java>Compiler>
Errors/Warningspreferencepage.

Debugging

Launchingfrom YoucanrunanddebugJavaapplicationsfromthecontextmenu.Youcanlaunchasource
thecontextmenu file,package,method,type,etc.bychoosingRunAs(orDebugAs)>JavaApplication
fromthecontextmenuinavieworeditor.Alternatively,youcanusetheJavaapplication
launchshortcutkeybinding(Alt+Shift+D,J).ThetoplevelRunAs(orDebugAs)actions
arealsosensitivetothecurrentselectionoractiveeditor.

Evaluationsinthe
debugger Snippetevaluationisavailablefromanumberofplacesinthedebugger.ChoosingDisplay
orInspectfromthecontextmenuoftheeditororVariablesviewwillshowtheresultina
popupwhoseresultcanbesenttotheDisplayorExpressionsviews.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 313/322
12/10/2015 Javadevelopmentuserguide

Viewmanagement TheDebugviewautomaticallymanagesdebugrelatedviewsbasedontheviewselection
innonDebug (displayingJavaviewsforJavastackframesandCviewsforCstackframes,for
perspectives example).Bydefault,thisautomaticviewmanagementonlyoccursintheDebug
perspective,butyoucanenableitforotherperspectivesviatheViewManagement
preferencepageavailablefromtheDebugviewtoolbarpulldown.

Environment YoucanspecifytheenvironmentusedtolaunchJavaapplicationsviatheEnvironment
variables tab.

String VariablesaresupportedformanyparametersofJavaApplicationlaunchconfigurations.
substitutions MostfieldsthatsupportvariableshaveaVariables...buttonnexttothem,suchasthe
programandVMargumentsfields.TheMainTypefieldsupportsvariablesaswellthe
${java_type_name}variableallowsyoutocreateaconfigurationthatwillruntheselected
type.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 314/322
12/10/2015 Javadevelopmentuserguide

Logicalstructures TheLogicalStructurestoggleontheVariablesviewtoolbarpresentsalternatestructures
forcommontypes.JDTprovideslogicalviewsforMaps,Collections,andSWT
Composites.YoucandefinelogicalstructuresforothertypesfromtheLogicalStructures
preferencepage.

Variablecolumns ColumnsintheVariablesviewcanbeconfiguredbyselectingLayout>Select
Columns...intheviewmenu.Adialogallowsyoutoselectthecolumnstodisplay.For
example,acolumncanbeaddedtodisplayinstancecountsofclasses(whendebugging
withJavaSE1.6).Columnscanbetoggledon/offusingtheLayout>ShowColumns
action.

Showreferences WhendebuggingwithJavaSE1.6,referencestoobjectscanbedisplayedintheVariables
viewbyselectingJava>ShowReferencesintheviewmenu.A"referencedfrom"entry
willappearundereachobjectthatcanbeexpandedtoshowallreferencestothatobject.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 315/322
12/10/2015
Allinstances Javadevelopmentuserguide
WhendebuggingwithJavaSE1.6,allinstancesofaclasscanbeinspectedbyselectinga
classinaneditoroutline,variablesview,compilationunitorclassfileeditorandinvoking
AllInstances...fromthecontextmenu.Apopupdialogwilldisplayallinstancesofthe
selectedclass.

DefaultVM IfyouspecifythesameargumentstoacertainVMfrequently,youcanconfigureDefault
arguments VMArgumentsintheInstalledJREspreferencepage.Thisismoreconvenientthan
specifyingthemforeachlaunchconfiguration.

Stopinmain YoucanuseStopinmaininaJavaApplicationlaunchconfigurationtocauseyour
programtostopatthefirstexecutablelineofthemainmethodwhenyourunitunderdebug
mode.

Conditional YoucanuseexpressionstodefineconditionalbreakpointsusingtheBreakpoint
breakpoints Properties...dialogordetailpaneinthebreakpointsview.Aconditioncontrolswhena
breakpointactuallyhaltsexecution.Youcanspecifywhetheryouwantthebreakpointto
suspendexecutiononlywhentheconditionistrue,orwhentheconditionvaluechanges.
Thebreakpointconditioneditorsupportscontentassist.

Debuggingby YoucanavoidinsertingSystem.out.println()statementsinyourcodefordebuggingby
writingtoconsole usingconditionalbreakpointstoprinttotheConsoleview.Todoso,setaconditional
breakpointwithSuspendwhen'true'optionandaconditionwhichisalwaysfalse,e.g.

Disabling Ifyoufindyourselffrequentlyaddingandremovingabreakpointinthesameplace,consider
breakpoints disablingthebreakpointwhenyoudon'tneeditandenablingitwhenneededagain.This
canbedoneusingDisableBreakpointinthebreakpointcontextmenuorbyunchecking

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 316/322
12/10/2015 thebreakpointintheBreakpointsview. Javadevelopmentuserguide
YoucanalsotemporarilydisableallbreakpointsusingtheSkipAllBreakpoints
(Ctrl+Alt+B)actionintheBreakpointsviewtoolbar.Thiswilltellthedebuggertoskipall
breakpointswhilemaintainingtheircurrentenabledstate.

Togglebreakpoint UsemodifierkeyswhiletogglingbreakpointsintheJavaeditor:
modifierkeys
HoldingtheCtrlkeywhiledoubleclicking(toggling)abreakpointwillcausethe
Propertiesdialogforthatbreakpointtobedisplayed(ontheMac,useCommand)
HoldingtheShiftkeywhiledoubleclicking(toggling)abreakpointwillenable/
disablethatbreakpoint
Ifthereisnoexistingbreakpoint,anormalbreakpointtoggletakesplaceevenifamodifier
keyishelddown.

Changingvariable Whenathreadissuspendedinthedebugger,youcanchangethevaluesofJavaprimitives
values andStringsintheVariablesview.Fromthevariable'scontextmenu,chooseChange
VariableValue.YoucanalsochangethevaluebytypinganewvalueintotheDetailspane
andusingtheAssignValueactioninthecontextmenu(CTRL+Skeybinding).

Variablevaluesin WhenathreadissuspendedandthecursorisplacedoveravariableintheJavaeditor,the
hoverhelp valueofthatvariableisdisplayedashoverhelp.

Droptoframe Whensteppingthroughyourcode,youmightoccasionallysteptoofar,orstepoveraline
youmeanttostepinto.Ratherthanrestartingyourdebugsession,youcanusetheDrop
toFrameactiontoquicklygobacktothebeginningofamethod.Selectthestackframe
correspondingtotheJavamethodyouwishtorestart,andselectDroptoFramefrom
Debugviewtoolbarorthestackframe'scontextmenu.Thecurrentinstructionpointerwill
beresettothefirstexecutablestatementinthemethod.Thisworksfornontopstack
framesaswell.
NotethatDroptoframeisonlyavailablewhendebuggingwitha1.4orhigherVM,ortheJ9
VM.TherearesomesituationswhereaJVMmaybeunabletopopthedesiredframesfrom
thestack.Forexample,itisgenerallyimpossibletodroptothebottomframeofthestack
ortoanyframebelowanativemethod.

Hotcodereplace ThedebuggersupportsHotCodeReplacewhendebuggingwitha1.4orhigherVM,orthe
J9VM.Thisletsyoumakechangestocodeyouarecurrentlydebugging.Notethatsome
changessuchasnewordeletedmethods,classvariablesorinnerclassescannotbehot
swapped,dependingonthesupportprovidedbyaparticularVM.
Steppinginto TheJavadebuggerallowsyoutostepintoasinglemethodwithinaseriesofchainedor
selectionsand nestedmethodcalls.SimplyselectthemethodyouwishtostepintoandselectStepinto
hyperlink SelectionfromtheJavaeditorcontextmenu.
debugging
Thisfeatureworksinplacesotherthanthecurrentlyexecutingline.Trydebuggingtoa
breakpointandstepintoamethodafewlinesbelowthecurrentinstructionpointer.

Whenthecaretisnotinamethodname,thefeaturestepsintothenextmethodonthe

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 317/322
12/10/2015 Javadevelopmentuserguide
selectedline.Forexample,whenthecaretisatthebeginningoftheline
assertTrue(fFull.size()==100),
thenStepintoSelectionstepsintoassertTrue(..)(unlikeStepInto,whichwouldstep
intosize()).
Youcanalsostepintoamethodbyusinghyperlinknavigation.Simplyplacethecursor
overthemethodyouwishtostepintoanduseCtrl+Alt+Clicktostepintothemethod
(ratherthanCtrl+Clickwhichwillnavigatetothesourcecode).

Consolepinand OutputdisplayedintheconsolecanbelockedtoaspecificprocessviathePinConsole
lock actionintheConsoleviewtoolbar.There'salsoaScrollLockactionthatstopsthe
consolefromscrollingasnewoutputisappended.

Creatingwatch AwatchitemisanexpressionintheExpressionsviewwhosevalueisupdatedasyou
items debug.YoucancreatewatchitemsfromtheJavaeditorbyselectinganexpressionor
variableandchoosingWatchfromitscontextmenuorthetoplevelRunmenu.
Watchpoints Awatchpointisabreakpointthatsuspendsexecutionwheneveraspecifiedfieldis
accessedormodified.Tosetawatchpoint,selectafieldintheOutlineviewandchoose
ToggleWatchpointfromitscontextmenu.Toconfigureawatchpoint,selectthe
watchpointintheBreakpointsviewandchooseProperties...fromitscontextmenu.The
mostimportantpropertiesforthistypeofbreakpointaretheAccessandModification
checkboxeswhichcontrolwhenthebreakpointcansuspendexecution.

Classload Aclassloadbreakpointsuspendsexecutionwhenaspecifiedclassisloadedinthevirtual
breakpoints machine.Tosetaclassloadbreakpoint,selectaclassintheOutlineviewandchoose
ToggleClassLoadBreakpointfromitscontextmenu.YoucanalsousetheRun>Add
ClassLoadBreakpoint...menuactiontocreateaclassloadbreakpoint.

Method Amethodbreakpointsuspendsexecutionwhenaspecificmethodisenteredorexited.To
breakpoints setamethodbreakpoint,selectamethodintheOutlineviewandchooseToggleMethod
Breakpointfromitscontextmenu.Alternatively,doubleclickonamethoddeclarationline
intheeditorrulerorusetheRun>ToggleMethodBreakpointmenuactiontocreatea
methodbreakpointinthecurrentlyselectedmethod.
Bydefaultamethodbreakpointonlysuspendsexecutionwhenamethodisentered.You
canusethebreakpointdetailpaneorthebreakpointpropertiesdialogtoconfigurethe
breakpointtosuspendonexit.Methodbreakpointsalsosupportconditions.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 318/322
12/10/2015 Javadevelopmentuserguide

Threadsand TheJavadebuggeroptionallydisplaysmonitorinformationintheDebugview.Usethe
monitors ShowMonitorsactionintheDebugviewdropdownmenutoshowwhichthreadsare
holdinglocksandwhicharewaitingtoacquirelocks.Threadsinvolvedinadeadlockare
renderedinred.

Stepfilters Stepfilterspreventthedebuggerfromsuspendinginspecifiedclassesandpackageswhen
steppingintocode.Stepfiltersareestablishedwiththe Java>Debug>StepFiltering
preferencepage.WhentheUseStepFilterstoggle(onthedebugtoolbarandmenu)ison,
stepfiltersareappliedtoallstepactions.IntheDebugview,theselectedstackframe's
packageordeclaringtypecanbequicklyaddedtothelistoffiltersbyselectingFilterType
orFilterPackagefromthestackframe'scontextmenu.
Usingthe IfyouwanttoexperimentwithAPIortestoutanewalgorithm,it'sfrequentlyeasiertouse
scrapbook aJavascrapbookpagethancreateanewclass.Ascrapbookpageisacontainerfor
randomsnippetsofcodethatyoucanexecuteatanytimewithoutacontext.Tocreatea
scrapbookpage,createanewfilewitha.jpageextension(orusethe NewScrapbook
Pagewizard).Enterwhatevercodeyouwishtoexecuteandthenselectit.Therearethree
waystoexecuteyourcode:
Executetheselectedcodeandplacethereturnedresultinaninspectpopup
ExecutetheselectedcodeandplacetheStringresultrightinthescrapbookpage

Executetheselectedcode(andignoreanyreturnedresult)
Theseactionsareintheworkbenchtoolbarandalsointhescrapbookpage'scontextmenu.

Editing HoldingdowntheCtrlkeyandmakingaselectionfromtheRunorDebugdropdown
launch menuopenstheassociatedlaunchconfigurationforediting.Thelaunchconfigurationcan
configurations alsobeopenedfromthecontextmenuassociatedwithanyitemintheDebugview.
Favoritelaunch LaunchconfigurationsappearintheRun/Debugdropdownmenusinmostrecently
configurations launchedorder.Howeveritispossibletoforcealaunchconfigurationtoalwaysappearat
thetopofthedropdownsbymakingtheconfigurationa'favorite'.UsetheOrganize
Favorites...actionfromtheappropriatedropdownmenutoconfigureyourfavoritelaunch
configurations.
Detailformatters IntheVariables&Expressionsviews,thedetailpaneshowsanexpandedrepresentation
ofthecurrentlyselectedvariable.Bydefault,thisexpandedrepresentationistheresultof
callingtoString()ontheselectedobject,butyoucancreateacustomdetailformatter
thatwillbeusedinsteadbychoosingNewDetailFormatterfromthevariable'scontext
menu.Thisdetailformatterwillbeusedforallobjectsofthesametype.Youcanviewand
editalldetailformattersinthe Java>Debug>DetailFormatterspreferencepage.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 319/322
12/10/2015 Javadevelopmentuserguide

Runningcode Youcanrunanddebugcodethatdidnotcompilecleanly.Theonlydifferencebetween
withcompile runningcodewithandwithoutcompileerrorsisthatifalineofcodewithacompileerroris
errors executed,oneoftwothingswillhappen:
Ifthe'Suspendexecutiononcompilationerrors'preferenceonthe Java>Debug
preferencepageissetandyouaredebugging,thedebugsessionwillsuspendasifa
breakpointhadbeenhit.NotethatifyourVMsupportsHotCodeReplace,youcould
thenfixthecompilationerrorandresumedebugging
Otherwise,executionwillterminatewitha'unresolvedcompilation'error
Itisimportanttoemphasizethataslongasyourexecutionpathavoidslinesofcodewith
compileerrors,youcanrunanddebugjustasyounormallydo.

Wordwrapin Thedetailsareaofthedebugger'sVariablesandExpressionsviewssupportswordwrap,
Variablesview availablefromtheviewdropdownmenu.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 320/322
12/10/2015 Javadevelopmentuserguide

Codeassistinthe CodeassistisavailableinmanycontextsbeyondwritingcodeintheJavaeditor:
debugger
Whenenteringabreakpointcondition
IntheDetailspaneoftheVariables&Expressionsview
WhenenteringaDetailFormattercodesnippet
WhenenteringaLogicalStructurecodesnippet
WhenenteringcodeinaScrapbookpage
IntheDisplayview

Commandline Youcanalwaysseetheexactcommandlineusedtolaunchaprograminrunordebug
details modebyselectingPropertiesfromthecontextmenuofaprocessordebugtarget,evenif
thelaunchhasterminated.

Stacktrace Javastacktracesintheconsoleappearwithhyperlinks.Whenyouplacethemouseovera
hyperlinks lineinastacktracethepointerchangestothehand.Pressingthemousebuttonopensthe
associatedJavasourcefileandpositionsthecursoratthecorrespondingline.Pressingthe
mousebuttonontheexceptionnameatthetopofthestacktracewillcreateanexception
breakpoint.

Debugginginthe YoucandebugintheJavaperspectivebyconfiguringtheRun/Debug>View
Javaperspective Managementpreferences.Selecttheperspectivesyouwanttobedebugfrom.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 321/322
12/10/2015 Javadevelopmentuserguide

Ensurethepreferencetoactivatethedebugviewwhenabreakpointishitisturnedon(via
thetoplevelRun/Debugpreferencepage).

YoucandisabletheperspectiveswitchingpromptontheRun/Debug>Perspectives
preferencepage.WiththesesettingstheDebugviewwillautomaticallyopenintheJava
perspectivewhenabreakpointishit.

ByplacingtheDebugviewatthetopoftheperspectiveandresizingitsheighttothesize
ofoneelement,theviewwillswitchtoabreadcrumbpresentation.Thisminimizesthe
amountofscreenspacetheviewconsumes.

http://help.eclipse.org/mars/advanced/print.jsp?topic=/../nav/1&confirmed=true 322/322

Vous aimerez peut-être aussi