Home > Articles > Programming > Java

This chapter is from the book

Working with Java Elements

In the "Fundamentals" section earlier in this chapter, we presented an overview of how to create different kinds of Java elements. In this section we'll go into more depth on Java projects, creating and importing Java elements, and details on local history for Java elements.

More on Java Projects

Java projects add a number of properties to projects, including external tool builders, the Java build path, and the Javadoc location. We discussed Javadoc location earlier in the "Generating Javadoc" section in this chapter, and external tools builders in the section "Customizing Eclipse" in Chapter 2. A Java project's build path property specifies how JDT organizes Java code, output files, and other resources in your project.

Java Source Code Organization

Within a Java project, there are two basic ways to organize your code. For small projects, you may choose to have everything in the same package or folder, *.java source files, *.class output files, and other files required by your program. With this organization, when you save a .java file and the file and project are built (compiled), the resulting .class files are put with source files in the same folder.

For projects having lots of modules, you may choose to organize your *.java source and *.class output files in separate folders in a project. In this case, each project has one or more source folders and one output folder. The build process takes inputs from one or more source folders, or folders under them, builds them if necessary, and puts the results in the output folder. For example, when you save a .java file and the file and project are built, the resulting .class file or files are put in the output folder. Other files in the source folders are copied to the output folder, unless you specify otherwise in your Java Compiler preferences. This approach allows you to organize and subdivide your Java packages, while the output folder contains all run-time resources.

There are two preference settings that allow you to customize this source code organization and build processing. Java New Project preferences allow you to specify the default organization for when you create new Java projects. You can later override this organization on the New Project wizard's Source page. If you have already created a project, you can change this organization on the Source page of the project's Java Build Path properties. You can also change the policy for which files do not get copied to the output folder when a project is built. This is the Filtered Resources preference on the Other page of Java Compiler preferences.

Build Path

A project's build path serves two purposes: It specifies the search sequence for Java references in the code in the project, and it defines the run-time classpath for the code. When you first create a project, its build path is set to contain the project itself and the default JRE. The default JRE is defined in your Java Installed JREs preferences. At runtime, you can modify a project's classpath that was generated from its build path information by defining a launch configuration.

Classpath errors show up with other errors in the Tasks view. If you have classpath errors and have trouble diagnosing them, open the properties on the project and check the Java Build Path pages. The icons for the entries indicate if they cannot be found.

Project References

Project references indicate other projects a given project refers to and dictate how projects in your workspace are built. This property is set based on the projects you include on the Projects page of a project's Java Build Path properties. For example, if you specify in project A's Java Build Path properties that it refers to project B, project A's Project References properties are updated. Then, whenever project B is built, project A is (re)built as well, because A referenced B. You affected this when you set the build path properties for A. You do not affect this if you simply set project A's Project References properties to refer to B. Doing so will not cause A to be (re)built when B is built. The bottom line is that project references for Java projects are managed by JDT. You can examine them, but making changes will have no impact.

Creating Java Projects

Eclipse maintains information for Java projects, including build path information, the Javadoc location, and external tools builder information. You have the opportunity to set this information when you create a new project on the New Java Project wizard (see Figure 3.30). To set the information, select Next > on the first page of the New Java Project wizard rather than Finish. You can also go back later after the project is created to modify this information by editing the project's properties.

Figure 3.30Figure 3.30 Java Build Path Properties Source Page


On the Source page, you can specify the organization of your source code and output folders. Use the project as source folder is the organization described above in which output (*.class) files are put with source (*.java) files. Use source folders contained in the project allows you to separate source from output files. If you select this, you need to specify which folders contain Java source and/or resources; otherwise, the files will not be built. Use Create New Folder... to add source folders. Use Add Existing Folders... after the project has been created to add an existing folder to the project as a source folder. The build (compile) process takes inputs from source folders you add or designate and from folders they contain. In this way, as your project grows, you can subdivide your source to make it more manageable.

The Projects page allows you to add other Java projects to the build path of the new project (see Figure 3.31). You need to do this if you are going to make references from the project you are creating to Java declarations in other projects.

Figure 3.31Figure 3.31 Java Build Path Properties Projects Page


The Libraries page allows you to add other Java resources to your project's build path (see Figure 3.32). JDT automatically adds the default JRE. Select Add Jars... to add JAR or *.zip files from other projects, as opposed to adding references to resources in projects not contained in JARs or *.zip files, as you do on the Projects page. Generally, if you have the resources in a project, you should reference them that way, not within the JAR. Select Add External JARs... to add JAR or *.zip files from your file system. For example, if you wanted to develop a Java servlet, you would need to add servlet.jar to the project's build path. Use Add Variable... to add a classpath variable to your project's build path. The options under Advanced... allow you to add other source folders to the build path. Attach Source... allows you to add source to the selected build path entry. Do this to enable source-level debugging when the build path entry does not include source.

Figure 3.32Figure 3.32 Java Build Path Properties Libraries Page


When you want to reference JAR files on your file system, especially if you do so in multiple projects, you should consider defining a classpath variable to refer to the JAR file and then including the variable in your projects' build paths. In this way, if the location of the JAR file changes, you only need to update the classpath variable and not the build paths of each of the projects. To define a classpath variable, use your Java preferences and select Classpath Variables.

If the build path icon is a hollow circle, it means that the library or file could not be found. Look for this when you have classpath errors.

The Order and Export page (see Figure 3.33) serves two purposes. First, it allows you to change the order of references to entries in your project's build path. This order becomes important if you have the same declarations in multiple build path entries. Second, it allows you to select an entry (that is, add a check mark) to cause its declarations to be visible outside the project.

Figure 3.33Figure 3.33 Java Build Path Properties Order and Export Page


Creating Folders



There are two types of folders in Java projects: Source Folders and Nonsource ("simple") Folders. This is an important distinction because it affects how builds are performed. When you create a source folder, JDT adds the source folder to the project's build path. Nonsource folders are not added to the project's build path. If you create a folder and later want to make it a source folder, do so from the Java Project Properties dialog, Java Build Path properties, on the Source page. When in doubt, check the project's .classpath file. You can put nonsource folders in Java projects and folders; you can put source folders only in Java projects.

If you create a Java project and select to have your Java source and output files in the same folder, and then decide later to create a source folder, this forces JDT to change the organization of the project to have separate source and output folders. If you already have Java files in the project, you will have to move these manually to a source folder. It may be easier to create a new project with the folder and package organization you desire, and then use the Refactoring actions to move the Java elements.

Creating Classes and Interfaces

The options available when creating a new class or interface are straightforward. Several are worth noting. Enclosing Type is used for nested classes and specifies the class that will contain the class you are creating. As you type the Name of the class, watch the message at the top of the wizard page—it will flag invalid class names. An easy way to create a subclass is to select a class in one of the Java views, and then select to create a new class. The Superclass of the new class is the one you had selected. If you elect to not generate stubs for superclass constructors or inherited methods, you can later generate the code from the editor by selecting Source > from the context menu, or by using content assist and a code template. If you do not select to have Inherited abstract methods generated, you will see errors in the Tasks view indicating the methods you still need to create. Once the class is created, you can generate stubs for these by selecting the class in one of the Java views and then selecting Override Methods... from the context menu.

Importing Java Elements

In the section "Resource Management" in Chapter 2, we discussed importing resources with the Import wizard. Recall that you see the Import wizard by selecting Import... from the Navigator or Package Explorer context menu or by selecting File > Import.... With Java projects and Java elements, there are additional considerations. Generally, it is easier to deal with projects than individual Java elements because Java projects contain build path and tool builder information in the project's .classpath and .project files. When you select to import Existing Project into Workspace in the Import wizard, a folder structure is a valid Eclipse project if it includes a .project file. Recall that importing an existing project into your workspace does not cause the contents of the project to be moved into your workspace folder. Rather, a definition for the project is added with a reference to its existing location. So, if you import an existing project from one workspace to another and you don't intend to work on it further in the original workspace, be sure to delete the project definition there, but not the contents. This would delete the project's contents for both workspaces.

The easiest way to import and export code and in general share it is to do so with an SCM repository and by means of a Team Project Set. We'll see this in Chapter 5.

Local History for Java Elements

The section "Resource Management" in Chapter 2 described how you could compare and replace a file with another edition of it from local history, compare two files, compare two projects, and recover files deleted from a project. In addition to this, with JDT you can compare and replace individual elements, including methods and fields. You can select an element in one of the Java views and then select Compare With >, Replace With >, or Restore from Local History... from the context menu. Figure 3.34 shows comparing a single method, generatePrimeNumbers(), with a previous edition.

Figure 3.34Figure 3.34 Comparing a Java Element from Local History


When you compare Java elements, you can select an element in the Java Structure Compare pane to see only its differences. You can restore a deleted method or field by selecting a type in the Outline view and then selecting Restore from Local History from the context menu.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020