Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Introduction to the Eclipse Development Environment – Creating a First Java Project Abstract In this lab, you will learn a bit about the Eclipse development environment and how to create a first Java program by doing the following: Create a first Java project within Eclipse Add a Java class to the project Compile and run a Java project Explore selected Eclipse windows (Views) Debug a Java project using the Eclipse debugging tools Export a Java project so that you can see how to move them from computer to computer Key Terms An Eclipse perspective is a visual container for a set of views and editors (windows). One perspective is visible at a time. Each perspective provides functionality to accomplish a particular task, such as editing or debugging a Java or Android program. The current perspectives appear along the top right side of the toolbar as follows. In this figure, the Java perspective is active (shaded) In this course, you will commonly use the following perspectives: o The Java perspective is designed for editing Java (and Android) projects. It has an editor area and has views (windows), used to manage a project. The Package Explorer operates similar to the Visual Studio Solution Explorer. The editor area works similar to the .NET Code Editor. o The Debug perspective is designed to debug Java programs. It includes an editor area in which you examine a program’s code, and the following views: Debug, Breakpoints, Variables, Expressions, Outline, Console, Tasks. These views allow you to suspend program execution, and then look at the values of variables and program objects. Again, these debugging tools have the same purpose and work the same way as they do in .NET. Page 1 of 21 Each perspective has one Editor Area (visible region), but multiple editors can be open concurrently. In an editor area, you change the content of programmatic data files such as XML or Java code. Resources is a collective term for the projects, folders, and files that exist in the Workbench. Views support editors and some have their own toolbars. A view might appear by itself or stacked with other views in a tabbed notebook. Eclipse has hundreds of different views. Only selected views will be discussed in this lab. The terms View and window mean roughly the same thing. The Workbench refers to the Eclipse desktop development environment. Each Workbench window contains one or more perspectives. One perspective in a Workbench is visible at a time. Introductory Eclipse Notes Eclipse is an integrated development environment (IDE) designed for developing programs in Java and other programming languages such as Python, PERL, and Ruby, to name a few. Eclipse contains: A development platform with which you create, compile, test, and debug applications written in one or more programming languages, and targeted to be executed on one or more hardware and software platforms. Extensions called plug-ins that support a particular programming language or platform. For example, SAP and others use Eclipse as a development platform for their software. See http://www.tutorialspoint.com/eclipse/eclipse_explore_views.htm Creating a First Java Project with Eclipse In this part of the lab, you will create a first Java project. The process is similar to creating a project in Visual Studio .NET. You create a project having a particular type, such as a Java or Android project. From that project type, Eclipse uses a template to create a working application from a template. You specify various configuration options for each type of project. Eclipse uses this information to create the default application (project) from its underlying template. HANDS-ON ACTIVITY – Creating a Java project 1. Start Eclipse. When you start Eclipse, you will be asked to select a default workspace. This default workspace is where all of your applications (projects) are stored. I suggest that for all exercises and Page 2 of 21 programs in this course, that you use a default workspace on the same USB stick. This way, you can more easily move the projects you create to different computers. You might also consider creating a folder in your StudentHome folder. 2. On the menu bar, click File, New, Java Project. If the Java Project menu does not appear, click File, New Project, and select Java Project from the following dialog box. Note that you will need to expand the Java folder. 3. In the following dialog box, give the project a name. I suggest that you use the name HelloJava. Do not put spaces in project names. Note the following about the information in the following dialog box: In the JRE section, the option Use an Execution environment JRE defines version of the Java runtime that will be used to execute the program. In the Project layout section, the option Create separate folders for sources and class files causes the Java application to be stored in multiple folders making it easier to organize larger applications. Page 3 of 21 4. Click Next to begin creating the project. The New Java Project dialog box appears. You should not need to change any of these options. However, it is here that you can control where Eclipse will store source files, and any external libraries needed by the project. Page 4 of 21 5. Click Finish to create the project. When you do, the Eclipse development environment appears and the default Perspective is activated. Selecting a Perspective Recall that Eclipse organizes Views into a Perspective and one Perspective is visible at a time. When you develop Java code, you would usually use the Java Perspective. When you debug Java code, you would use the Debug Perspective. In the steps that follow, you will look at these two perspectives: HANDS-ON ACTIVITY – Selecting Eclipse Perspectives 1. Click Window, Perspective, Open Perspective, Other. Click Java from the dialog box that appears. As you work with Eclipse, you will likely open and close various windows (Views) within a Perspective. To get back to the default configuration for the current perspective, click Window, Perspective, Reset Perspective. In the dialog box that appears, click Yes to reset the perspective to its defaults. Your screen should look like the following with the Java Perspective selected with the default View: Page 5 of 21 Note the following about the above window: The Package Explorer appears docked along the left margin. It shows a single package named HelloJava. If you expand this folder, you will see the files that comprise the package. The Package Explorer works similar to the Visual Studio Solution Explorer. It lists all of the packages in the selected Workspace. In the above window, there is a single package. However, a Workspace will often have several packages. Along the bottom of the window appears three views named Problems, Javadoc and Declaration. These three views appear in a View folder. (Really just a set of tabs). The Problems View lists syntax and other errors recognized as you develop a program’s code. The Outline View shows an outline of a structured file, such as a Java class. You will not use the Outline or Task View in this session. Adding a Java Source File to the Project At this point, you have an empty program with no source code. Next, you will add a Java source file to the package. The process is similar to the process of adding a form to a VB project. This source file has the following characteristics: Java is an object-oriented programming language so everything is a class. Classes, in turn, have methods (functions) and properties (data / variables). All Java programs have what is known as an entry point. A Java program’s entry point is where a program begins execution. A Java program’s entry point appears in one of its classes. A program cannot have more than one entry point. Page 6 of 21 A Java program’s entry point is always a procedure named main and has the following signature (name, data type, and arguments): public static void main(String[] args) { } Classes will be discussed in much more detail later in the Java Tutorial. The syntax and purpose of the above code will also be discussed in a moment. HANDS-ON ACTIVITY – Creating a main procedure (entry point) 1. Make sure that the Package named HelloJava is selected in the Package Explorer. 2. On the menu, click File, New, Class to display the following dialog box: 3. Set the Name to HelloClass. Note that class names cannot contain a space and must begin with a letter. They can contain an underscore but other special characters are prohibited. 4. Make sure that the Modifier is set to public. Access modifiers will be discussed later in this document. 5. Check the box titled public static void main(String[] args). Checking this box causes Eclipse to create the program’s entry point as you will see in a moment. 6. Click Finish to create the class. Page 7 of 21 Eclipse creates the class and entry point as shown in the following figure: Note the following about the above code: There is a class (declared with the class keyword) named HelloClass. In this context, a Java class is no different than a VB class. The class is declared with the public access modifier indicating that it can be referenced (used by) other packages. Page 8 of 21 The {} characters mark the beginning and end of the class. These characters mark a statement block for all classes and procedures. In Java, all blocks are marked with the {} characters. Inside of the class, there is a single method (function) named main, which is the program’s entry point. o o o o o o o The line beginning with the two forward slashes (//), is a comment and is ignored by the compiler. The keyword public indicates that this class and function can be used by other packages. The keyword has the same meaning in both Java and Visual Basic. The static keyword indicates that the method is a static method rather than an instance method. Static methods are called without first creating an instance of the class. The program’s entry point (main procedure) is always a static procedure. The keyword void indicates that the method does not return a value. void procedures are similar to Sub procedures in VB. String[] args is an argument. The argument is an array of strings. In the case of the main procedure, this argument provides the means to pass data from the command line to the procedure. In this program, you will not work with command line arguments. The {} marks the boundaries of the procedure. Note that procedures cannot be nested inside each other. All of this syntax will be discussed in more detail as you progress through the tutorial. Writing Code to Display Output In this part of the lab, you will write a statement to display the string “Hello”. In these first examples, you will use a View (window) called the Console View, instead of displaying output to user interface controls. The reason is simple. Developing a Windows / Java user interface requires that you learn how to use another tool called Swing. Your goal here is to learn the basics of Java, rather than learn how to create user interfaces in Java. As you progress through the course, you will create Android user interfaces, rather than creating Java user interfaces. The following statement will write the output string “Hello” to the Console View: System.out.println(“Hello”); Note the following about the above statement: System is a class built into the Java language. Just as .NET has many built-in classes. So too do does Java. out is a public static member of the System class. While not obvious, it has a data type of PrintStream. By public, we mean that this member is accessible by any other class. The overloaded println method of the PrintStream class accepts one argument. In this case, the string to print to the Console View. When executed, the println method writes its Page 9 of 21 string argument, followed by a carriage return. Note that the print method does the same thing but does not write the carriage return. Literal string values are enclosed in double quotation marks. All Java statements are terminated by a semicolon (;). Procedure declarations and statement blocks ({}) are not terminated by semicolons. HANDS-ON ACTIVITY – Writing the Hello code 1. Make sure that the Editor for the HelloClass.java file is active. If it is not, double-click the class name in the Package Explorer. 2. Enter the following statement inside of the main procedure. Remember that Java is case sensitive, and that the statement must end in a semicolon. System.out.println(“Hello”); 3. Click File, Save All to save the file. Compiling and Running the Program Now that this first simple Hello program is written, you can compile and run it. Java is a compiled language, rather than an interpreted language. Programs with syntax errors cannot be compiled and therefore cannot be run. Syntax errors are marked in the Problems View. HANDS-ON ACTIVITY – Compiling and executing the program 1. Next, the project needs to be compiled into an executable program. This process will vary slightly based on your Eclipse configuration. On the menu, if the Project, Build Automatically check box is checked, you will be prompted to save files before the project is run. In addition, the project will be recompiled before the project is run. If the Build Automatically check box is not checked, click Project, Build Project to compile the project. The Problems View should be visible along the bottom of the Eclipse window. Activate that View to make sure that there are no syntax errors. If there syntax errors, they will be listed here. Page 10 of 21 2. Make sure the HelloJava project is selected in the Package Explorer. 3. Next, you can run the application. Click Run, Run As, Java Application. The output should appear in the Console View as shown in the following figure: Creating a Syntax Error When a statement violates the rules of a programming language, a syntax error is said to have occurred. In the following set of steps, you will intentionally create a syntax error to see how Java flags it for correction: HANDS-ON ACTIVITY – Creating and Fixing a Syntax Error 1. After the correct statement you just wrote, enter the following invalid statement. Note that printline is not a method of the System.out class so it is marked as having a syntax error. Note that the syntax error(s) is flagged in the Editor’s left margin with the red X. The offending part of the statement is also displayed with a jagged red underscore. 2. Try and build the program again by clicking Project, Build Project, the syntax errors are listed in the Problems View as follows: Page 11 of 21 As you can see, there are two syntax errors. The first indicates that the semicolon is missing from the end of the statement. The second indicates the printline is not a method. Both errors occurred on line 8. Your line numbers might vary. 3. Delete the line containing the errors and rebuild the program. Writing Code to Get User Input In addition to displaying output, you must be able to get input from the user. There are several ways to get console input from the user. With the current version of Java, the easiest way is to use the Scanner class. Examine the following statements that show how to get input using the Scanner class. Scanner = new Scanner(System.in); String userName = scanner.next(); The first of the above statements creates an instance of the Scanner class. The new keyword calls what is called the constructor. As in VB, constructors create objects from classes. One argument (named System.in) is passed to the constructor. The System.in class works similar to the System.out class. Instead of writing output to the Console View, it reads input from the Console View. The system.in class is predefined and is always available to your program. This statement creates the Scanner and wires it to read input from the Console View. The next statement (scanner.next()) reads an input line from the Console View and stores the result in the variable username. next is an instance method of the scanner class. Data types will be discussed later but variables of the String data type store a string of characters. HANDS-ON ACTIVITY – Reading user input In this next set of steps, the code that you write will produce another syntax error. This is intentional so that you can see the purpose of the Java import statement and how to use the Eclipse intellisense tools to fix the problem. 1. Modify the code that you just wrote so that it looks like the following. Note that the statement to create the Scanner object has a syntax error at this point. Page 12 of 21 2. Move the mouse so that it hovers over the syntax error. The syntax error is marked with the jagged red lines. The following tooltip should appear. Note that the error message is Scanner cannot be resolved to a type. This message is telling you that the Scanner data type cannot be identified. 3. Click the line titled Import ‘Scanner’ (java.util). The following statement is added to the beginning of the code file. The Java import statement works the same way as the Visual Basic Imports statement. The Scanner class belongs to the java.util package. So that you can reference the class and its members without having to use the class name, you use the import statement to import the class named java.util.Scanner. 4. Run the program again. Enter your name in the Console View. The input is read, stored in the variable, and written back to the Console View as shown in the following figure: Page 13 of 21 Introduction to Eclipse Debugging Nearly all development environments support debugging tools and Eclipse is no exception. These debugging tools work similarly in Eclipse as they do in .NET. To debug applications in Eclipse, Debug View should be active instead of Java View. The following figure shows the Eclipse development environment in Debug View: The following list describes selected Editors and Views: The Debug View (at the upper-left part of the screen) displays the stack frame for each running program thread. The stack frame displays the procedures that have been called and the line numbers of the code currently executing. Variables View displays information about the variables associated with the selected stack frame in Debug View. Because the program is not running, the Variables View has nothing in it. Debugging involves setting breakpoints on selected executable statements in an application. When you run the program, execution is temporarily suspended just before the statement containing the breakpoint executes. In Breakpoints View, the current breakpoints are listed. Here, you can enable and disable breakpoints, add new breakpoints and remove them, or configure them by setting conditions or hit counts. Page 14 of 21 In Expression View, you can type in Java expressions, which Eclipse evaluates. Any valid Java expression can be evaluated in Expression View. Console View displays the Console from which console input is read or console output is written. This is the same Console View that you used before. LogCat View, contains additional debugging messages. It will be discussed later when you create your first Android application. HANDS-ON ACTIVITY – Debugging a first application 1. On the menu bar, click Window, Perspective, Open Perspective, Debug. Note that the views are updated as shown in the above figure. Again, your Debug perspective might look slightly different than mine. 2. Next, you will set a breakpoint on an executable statement. When you run the program in a moment, execution will be suspended just before this statement executes. In the Editor (containing the Java code), right-click in the left margin on the line titled System.out.println(username);, and select Toggle Breakpoint from the context menu. A small circle should appear in the left margin as follows: In addition, the breakpoint appears in the Breakpoints View as follows: 3. Next, run the program by clicking Run, Debug As, Java Application. 4. Enter your name in the Console View as you did before, and press Enter. This time, instead of echoing your name back to the Console View, execution is suspended and the statement with the breakpoint is highlighted as shown in the following figure: Page 15 of 21 5. One benefit of the debugging tools is the ability to look at the values of variables as your program runs. You can do this in a couple of ways. Click on the Variables View. The active variables and their values appear. As you can see, the variable userName has the value of Michael. You can also use the Expressions View to look at the value of variables. Click the Expressions View. Click Add New Expression. Enter the expression userName in the left column. The expression is evaluated and the value displayed. As you can see, the value of the expression is Michael. This is the same variable that you looked at in the Variables View. 6. Click the Resume finishes. button on the menu or press F8. The program continues to execute until it Tracing Execution Another useful feature of the debugging tools is the ability to trace execution. That is, you can execute one statement at a time. As each statement executes, you can watch the value of variables and expressions as you did in the preceding steps. Statements can be executed (traced) in the following ways: Step Into (F5) – While execution is suspended, this command will step into the next method call or execute the current statement. Page 16 of 21 Step Over (F6) – While execution is suspended, this command will either step over the current method call or execute the next statement. Step Return (F7) – This command will cause the current procedure to finish executing. HANDS-ON ACTIVITY – Tracing Execution 1. Set a breakpoint on the line containing the main method. Again, to set a breakpoint, right-click in the left margin of the current line. The breakpoint icon should appear in the left margin. The breakpoint should also appear in the Breakpoints view. Delete the other breakpoint. The breakpoints window should look like the following. There should be one breakpoint set on the main procedure’s entry point. 2. Debug the program again by clicking Run, Debug As, Java Application. Execution should be suspended at the breakpoint as shown in the following figure. At this point, the first statement in the procedure has not executed yet. 3. Make sure that the Expressions View is visible. As you execute statements, you will see the value of the variable userName get updated. 4. Click the Step Into button or press F5. The statement executes. So the prompt appears in the Console View. The next statement to execute is highlighted as shown in the following figure: 5. Press the Step Into button twice. The Scanner is created, and then the next method is called. Notice that the statement is not highlighted. The program is not currently suspended. It is Page 17 of 21 waiting on user input. 6. Enter your name in the Console View, and press Enter. Execution is suspended as the following figure shows. Look at the Expressions View. Note that the value of the variable userName appears. 7. Press F5 again. The userName is written to the Console View. 8. Press F7. The program executes until it terminates. Exporting a Java project To move Java (and Android) projects between computers, you can: Save a default workspace on a USB stick. Then use that same workspace on other computers. To deliver assignments to me, you will need to export them to a .zip file, which you will send to me. You will learn how to export and import projects in this exercise. In this part of the lab, you will see the steps to export a project to a .zip file, and then import that same project from the .zip file that you just created. HANDS-ON ACTIVITY – Exporting a Java Project Page 18 of 21 1. Make sure that the project named HelloJava is selected in the Package Explorer. 2. Click File, Export to display the following dialog box. 3. As you can see, there are several ways to export projects. Expand the General folder, and select Archive File. 4. Click Next to display the following dialog box: Page 19 of 21 5. In this dialog box, you select the projects that you want to export. In the above example, the project named HelloJava is being exported. Your screen should only contain a single project. Notice that a file can be saved in .zip for .tar format. The tar format is commonly used on UNIX machines. Select Save in zip format. Use the other default options. 6. Click Finish to create the export (.zip) file. The .zip file is created and saved to the disk. HANDS-ON ACTIVITY – Importing a Java project In this set of steps, you will import the file you just exported back into the default workspace. Note that these steps will not work correctly on the computer that you are using because the workspace already exists. 1. Click File, Import to display the following dialog box. 2. The same dialog appears as you saw before to create the export file type. Make sure that General, Existing Projects into Workspace is selected. 3. Click Next to display the following dialog box: Page 20 of 21 Click the Select archive file: radio button, and select the file that you just created. The project should appear in the dialog box. 4. Click Finish to input the file. The file appears in the Package Explorer. Try it on your own In the following steps, you modify the program that you just wrote. 1. Instead of reading a single variable (username), create two prompts and two output lines. Read the first name and last name into separate variables. 2. Write the output as follows: Your first name is: Michael your last name is: Ekedahl Page 21 of 21