Home > Articles > Programming > Java

This chapter is from the book

Running Java Code

To run Java code, you must be in one of the Java perspectives. There are three basic ways to run code in your Java projects: You can run (launch) a Java program with the Run action, you can run a Java program with the Debug action, and you can evaluate (execute) an Java expression in a scrapbook page. With the Run action, your program executes and you do not have an opportunity to suspend its execution or examine variable or field values. In debug mode, you suspend, resume, and examine a program's execution. We'll look more at debugging in Chapter 4.

You can run code even if it still has compiler errors. If the scope of an error is limited to a method, you can run code in the class, except for the method with the error. If the scope of an error is at the class level, for example, a problem with a static declaration, you can run code in other classes but not the one with the error.

Using the Run Action





Java programs, that is, classes with main methods, are identified with the Run label decoration. To run a Java program, select a class or a Java element containing a class, and select Run from the menu or the Run pull-down menu, and then select Run As > Java Application. JDT executes the main method and sends output to the Console view. If you have previously run Java programs, you will have entries under Run > Run History and Run from the toolbar. Select from these to re-run programs. You can also press Ctrl+F11 or simply select Run from the toolbar to re-run the last program you ran.

When you run a Java program, you run it as a Java application, JUnit test, or run-time workbench. We're going to focus on Java applications here. Running as a run-time workbench is for testing extensions to Eclipse. We'll get to that in Chapter 8. Running as a JUnit test is beyond the scope of this book. For more information on this, refer to "Using JUnit" in the "Tasks" section of the Java Development User Guide.

To run a Java program, JDT needs two things: a main method and a launch configuration. Depending on what view was active and what you had selected when you requested to run a program, if a unique class with a main method can be determined, that main method will be run. For example, if the Java editor is active on an element with a main method, that main method will be run. If you have a project selected in the Package Explorer view and there are multiple classes in that package with main methods, you will be prompted to select one.

If the program encounters a run-time error, the exception information goes to the Console view and is displayed in error text color to distinguish it from other output types. Color-coding for output text in the Console view is defined in your Console preferences under Debug.

Managing Launch Configurations





Launch configurations define information for running Java programs. With launch configurations you can specify input parameters, JVM arguments, and source for your code, and set the run-time classpath and JRE. If you do not specify a launch configuration when you run a Java program with the Run action, a default is created for you. To define a launch configuration, select the Run pull-down menu and then Run.... In the Launch Configurations dialog (see Figure 3.29), select Java Application for Launch Configurations and then select New. If you had previously run Java programs with the Run action, you will see the default launch configurations that were created for you (see Figure 3.29).

Figure 3.29Figure 3.29 Creating a Launch Configuration

On the Main page, Project is optional. If you specify it, its build path is used to set the classpath, source lookup, and JRE. Use Search... to search a project's build path for Java programs. If a valid project is specified, the build path of that project is searched for classes with main methods matching the search pattern (you can use wildcards) in Main class. If a project is not specified, the build paths of all the projects in your workspace are searched for classes with main methods matching the search pattern.

On the Arguments page, you can set the input parameters for the Java program and any JVM parameters. The Java program parameters are strings separated by spaces. For more information on JVM arguments, see "Running Eclipse" in the "Tasks" section of the Workbench User Guide.

On the JRE page, you set the JRE used to execute the Java program. Use this to override the JRE defined in the build path properties of the project containing the program. Choose from the list of choices, which is populated with the JREs you have defined in your Installed JREs preferences, or add a new JRE. This is useful, for example, to specify a 1.4 JRE in order to do hot code replace when you debug your code.

On the Classpath page, the classpath is set based on the build path information from the project specified on the Main page. To override or add to this, deselect Use default classpath. If you do not have a project specified, you need to do this and specify classpath information. If you choose not to use the default classpath, add references in the classpath to those projects and JAR files containing declarations the Java program references, including the project or JAR file containing the main method being executed.




On the Common page you specify information about how to save the launch configuration. By default, launch configurations are saved as metadata in your workspace. If you select Shared, you specify a Java project into which to save the launch configuration as a .launch file. In this way, it's easy to keep and manage launch configurations with the code they run and to share them with others accessing the project; this is especially important for teams. The Run mode and Debug mode selections allow you to specify the perspective to display when the launch configuration is used to run or de- bug, respectively, the Java program. You can also indicate which favorites list displays the launch configuration, the Run or the Debug toolbar pull-down menus.

Evaluating Expressions in Scrapbook Pages





Java scrapbook pages (*.jpage files) allow you to edit and evaluate Java code expressions and display or inspect the results. They are a quick and easy way to test code and experiment with Java code expressions. You can evaluate an expression that's a partial statement, a full statement, or a series of statements. To create a scrapbook page, select Create a Scrapbook Page or use the New wizard. Scrapbook pages can be located in Java projects, folders, source folders, and packages.





Enter an expression in the Scrapbook page. This could be something simple like System.out.println("Hello World"), or an invocation of your Java code, for example, its main method. Content assist (Ctrl+Space) is available in scrapbook pages. Select the expression and then select Display from the toolbar or the context menu. JDT evaluates the expression, sends output to the Console view, and displays the toString value returned by the expression you selected in the scrapbook page. Select Inspect to display the results in the Expressions view. (We'll discuss the Expressions view in more detail in Chapter 4.) Run Snippet simply runs the code and sends the output to the Console view.

There are a couple of scrapbook page properties worth noting. To view or change these, select a scrapbook page and then Properties from the context menu. Working directory by default is the Java project in your workspace containing the scrapbook page. This is for relative file references. You can also change the JRE used for the scrapbook page. The default JRE is the one specified in your Java preferences under Installed JREs.



Scrapbook pages get their classpath from the containing project's build path. If in a scrapbook page you want to reference a Java element that is not on the build path of the containing Java project, you need to add to the Java project's build path. Scrapbook pages also allow you to specify import statements. You do this by selecting Set Imports from the context menu of a scrapbook page or Set Import Declarations for Running Code from the toolbar. You need to set import statements for references to Java declarations in your projects. This is a common oversight. If the type or package you are attempting to import is not listed in the Add dialog, it means you need to add it to the build path of the project containing the scrapbook page. If you are referencing an element that has multiple declarations, you will need to add an import statement to uniquely identify the element.





Each scrapbook page has its own associated JVM. The JVM is started the first time you evaluate an expression in a scrapbook page after it is created or opened. The JVM for a scrapbook page runs until the page is closed or explicitly stopped with Stop Evaluation from the context menu or the toolbar. When a scrapbook page is in the process of evaluating, the icon changes to a red J on a gray background. If the expression you're evaluating results in a loop or a hang, select Stop Evaluation. In some cases this may not stop execution. If it doesn't stop, simply close the scrapbook page and then re-open it.

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