Professional Documents
Culture Documents
| HOME
JDK 7
How to Install
Java Development Kit (JDK) 1.7 (officially named Java SE 7), which is freely available from Sun Microsystems (now part of Oracle), is needed for writing Java programs. JDK can be downloaded from the Java mother site @ http://java.sun.com (orhttp://www.oracle.com/technetwork/java/index.html).
3. In "System Variables" box, scroll down to select "PATH" "Edit..." 4. In "Variable value" field, INSERT "c:\Program Files\java\jdk1.7.0\bin" (assume that this is your JDK's binary directory) IN FRONT of all the existing directories, followed by a semicolon (;) which separates the JDK's binary directory from the rest of the existing directories. DO NOT DELETE any existing entries; otherwise, some existing applications may not run.
5. Variable name : PATH 6. Variable value : c:\Program Files\java\jdk1.7.0\bin;....exiting entries....
(For Advanced Users Only) I suggested that you place the JDK binary directory in front of "c:\windows\system32" and "c:\windows". This is because some Windows systems may have an out-dated copy of JDK/JRE in these directories. Do a search for "java.exe", and you will be amazed of the findings. You could read "Java Applications and Environment Variable" for more discussions about PATH environment variable.
2. Issue the following commands to verify that JDK is properly installed and display its version:
prompt> java -version java version "1.7.0" Java(TM) SE Runtime Environment (build 1.7.0-b147) Java HotSpot(TM) Client VM (build 21.0-b17, mixed mode, sharing) prompt> javac Usage: javac <options> <source files> ......... .........
2. Unzip into the <JAVA_HOME> (JDK installed directory). The documentation will be unzipped into "<$JAVA_HOME>\docs". Browse the JDK documentation by opening "<JAVA_HOME>\docs\index.html".
(For Advanced Users Only) Using External JAR files and Native Libraries In JDK
External Java packages (such as JOGL, JUnit) are often distributed in JAR-files togther with possibly native libraries (lib, dll). To use an external package in JDK, you need to: 1. Include ALL the JAR-files in the CLASSPATH environment variable (e.g., classpath=.;path1\a.jar;path2\b.jar). 2. Include the native libraries's directory in the PATH environment variable. (To be precise: The native libraries are to be kept in a directory accessible via JRE's property "java.library.path", which normally but not necessarily includes all the paths from thePATH environment variable). If you cannot compile your program, make sure that the all the JAR files are included in the CLASSPATH. (Native libraries are not involved in the compilation.) If you get a runtime error "java.lang.UnsatisfiedLinkError: no xxx in java.library.path ". This means that JRE cannot find your native library at runtime. You could print the contents of "java.library.path" viaSystem.out.println(System.getProperty("java.library.path")) and check whether it includes your native library's path. You could set the native library path via the command-line option -Djava.library.path=xxx. Alternatively, you could copy the JAR-files into JDK's extension directory at "<JDK_HOME>\jre\lib\ext", instead of using CLASSPATH; and copy all the dll's and lib's into a directory included in java.library.path.
Feedback, comments, corrections, and errata can be sent to Chua Hock-Chuan (ehchua@ntu.edu.sg) | HOME
ava Programming
Getting Started
Writing your First Java Program with JDK and a Programming Text Editor
Step 0: Install JDK and Programming Text Editor
You need to install: 1. the Java Development Kit (JDK). Read "How to Install JDK". 2. a Programming Text Editor, such as TextPad (@ www.textpad.com), NotePad++ (http://notepad-plus-plus.org/), or PSPad (@www.pspad.com). Read "Programming Text Editors". (You could of course use the NotePad. BUT, Notepad is just a plain text editor, which is not meant for programming).
Extra white spaces, tabs, and lines are ignored. You could use them liberally to make your program easier to read.
/* * First Java program */ public class Hello { // saved as "Hello.java" public static void main(String[] args) { System.out.println("Hello, world!"); } }
1. Start a Command Shell (Click the "Start" button Select "run..." Enter "cmd"; or "Start" button "All Programs" "Accessories" "Command Prompt"). 2. Set the Current Drive to the drive where you saved your source file "Hello.java". For example, suppose that your source file is saved in drive "d", enter "d:" as follow:
prompt> d: D:...>
3. Set the Current Directory to the directory that you saved your source file via the cd (Change Directory) command. For example, suppose that your source file is saved in directory "d:\javacodes\test". First, set the current directory to the Root directory (denoted as "\") of the current drive.
D:\...> cd \ D:\>
Then, change the current directory to the "javacodes" sub-directory under the Root directory.
D:\> cd javacodes D:\javacodes>
Finally, change the current directory to the "test" sub-directory under the "javacodes" directory.
D:\javacodes> cd test D:\javacodes\test>
4. Issue a dir (List Directory) command to confirm your source file is present in the current directory.
D:\javacodes\test> dir Volume in drive D has no label. Volume Serial Number is xxxx-xxxx Directory of D:\javacodes\test 03-Jul-XX 01:49 PM <DIR> . 03-Jul-XX 01:49 PM <DIR> .. 08-May-XX 06:25 PM 277 Hello.java ...
5. Invoke the JDK compiler "javac" to compile the source code "Hello.java".
D:\javacodes\test> javac Hello.java D:\javacodes\test>
The compilation is successful if the command prompt returns. Otherwise, error messages would be shown. Correct the errors in your source file and re-compile. Read "Common JDK Installation Errors", if you encounter problems compiling your program. 6. The output of the compilation is a Java class called "Hello.class". Issue a dir (List Directory) command again to check for the output.
D:\javacodes\test> dir Volume in drive D has no label. Volume Serial Number is xxxx-xxxx Directory of D:\javacodes\test 03-Jul-xx 01:53 PM <DIR> . 03-Jul-xx 01:53 PM <DIR> .. 03-Jul-xx 01:53 PM 416 Hello.class 08-May-xx 06:25 PM 277 Hello.java ...
(If you cannot find these commands in the "Tools" menu, goto "Configure" Preferences... Tools Add JDK Commands. You can also configure the properties of "compile" and "run" there, such as prompting for command-line arguments.)
1. Error Message Hyperlink: Double-click on the first-line of an error message will hyperlink to the corresponding source statement. 2. Find & Replace: Most important commands for programmers (after the copy/paste), available under the "Search" menu. 3. Block Select Mode: The Block Select mode allows you to operate on a block of texts, such as deleting a few columns and filling in blank columns. To enable/disable Block Select mode, select "Configure" menu check/uncheck "Block Select Mode". 4. Line Numbers: To display the line numbers, choose "View" menu check the "Line Number" option. 5. Command-Line Arguments: To provide command-line arguments to your Java program in TextPad, choose "Configure" menu "Tools" "Run Java Application" check "Prompt for parameters" box. When running your program, place your command-line arguments after $BaseName (which denotes the Java program name). 6. Font: "Configure" "Preferences" Expand "Document classes" node Select your desired class, e.g., "Java", and expand the node "Font" Select monospace font for programming, e.g., Courier New, Courier, Consola, Lucida Console.
To
install the batch file, select the "Run" menu "Run...", enter "JavaCompile $(CURRENT_DIRECTORY) $(FILE_NAME)" Choose "Ctrl-1" as the hot-key for compiling Java program. Similarly, select the "Run" menu "Run...", enter "JavaRun $(CURRENT_DIRECTORY) $(NAME_PART)" Choose "Ctrl-2" as the hot-key for running Java program. (To use Ctrl-1 and Ctrl-2, you need to re-configure and remove the existing mappings for these keys via "Settings" "Shortcut Mapper...".)
NotePad++ Tips for Java Programming 1. Reformatting Source Code: TextFX TextFXEdit Reindent C++ Code (which also work
for java codes). 2. Block Select: You can select columns of text by holding down the alt key while selecting (similar to WinWord).
2. You can then proceed to write your first Java program. Read "Writing your first Java Program with Eclipse". 3. Read "Debugging program in Eclipse".
Eclipse 1.0 (November 7, 2001): based on an earlier Java IDE called VisualAge from IBM. Eclipse 2.0 (June 28, 2002) Eclipse 2.1 (March 28, 2003) Eclipse 3.0 (June 25, 2004) Eclipse 3.1 (June 28, 2005) Eclipse 3.2 (June 30, 2006) (Callisto - named after one of the Jupiter's Galilean moons): started annual simultaneous release of all the related Eclipse projects. Eclipse 3.3 (June 25, 2007) (Europa - named after another Jupiter's Galilean moons) Eclipse 3.4 (June 19, 2008) (Ganymede - named after yet another Jupiter's Galilean moons) Eclipse 3.5 (June 12, 2009) (Galileo - named after the great 17th century scientist and astronomer Galileo Galilei) Eclipse 3.6 (June 23, 2010) (Helios - named after god of the sun in Greek Mythology) Eclipse 3.7 (June 23, 2011) (Indigo?!)
Step 1: Download
Download Eclipse from http://www.eclipse.org/downloads. For beginners, choose the minimal Eclipse IDE for "Java" Developers (eclipse-java-indigo-win32.zip)
Step 2: Unzip
To install Eclipse, simply unzip the downloaded file into a directory of your choice (e.g.,, "d:\myproject"). There is no need to run any installer. Moreover, you can simply delete the entire Eclipse directory when it is no longer needed (without running any un-installer). You are free to move or rename the directory. You can install (unzip) multiple copies of Eclipse in the same machine.
1. Start Eclipse by running "eclipse.exe" in the Eclipse installed directory. 2. Choose an appropriate directory for your workspace (i.e., where you would like to save your files). 3. If the "welcome" screen shows up, close it by clicking the "close" button.
d. Click "Finish".
You should create a new Java project for each of your Java application. Nonetheless, Eclipse allows you to keep more than one programs in a project, which is handy for writing toy programs (such as your tutorial exercises). If you have more than one files with main() method in one project, you need to right-click the source and choose "Run As"
"Java Application" to run that particular source. Clicking the "Run" button runs the recently-run program (based on the previous configuration). Try clicking on the "down-arrow" besides the "Run" button.
Single-stepping thru the program and watching the values of internal variables and the outputs produced is the ultimate mean in debugging programs - because it is exactly how the computer runs your program!
As mentioned, a breakpoint suspends program execution and let you examine the internal states of the program. To set a breakpoint on a particular statement, double-click the left-margin of that line (or select "Toggle Breakpoint" from "Run" menu). "Resume" continues the program execution, up to the next breakpoint, or till the end of the program. "Single-step" thru a loop with a large count is time-consuming. You could set a breakpoint at the statement immediately outside the loop (e.g., Line 11 of the above program), and issue "Resume" to complete the loop. Alternatively, you can place the cursor on a particular statement, and issue "Run-To-Line" from the "Run" menu to continue execution up to the line. "Terminate" ends the debugging session. Always terminate your current debugging session using "Terminate" or "Resume" till the end of the program.
3. 4. 5. 6.
7.
8.
9. 10.
11.
12.
13.
"Templates". (Alternatively, in "Window" "Preferences" type "template" as filter text and choose "Java" "Editor" "Templates".) You can change your key settings in "Window" menu "Preferences" "General" "Key" choose "Command", "Content Assist". (Alternatively, in "Window" "Preferences" type "key" as filter text and choose "General" "Key".) Intelli-Sense (ctrl-space): You can use ctrl-space to activate the "intelli-sense" (or content assist). That is, Eclipse will offer you the choices, while you are typing. Source Formatting (ctrl-shift-f): Right-click on the source. Choose "Source" "Format" to let Eclipse to layout your source codes with the proper indentation. Source Toggle Comment (ctrl-/): To comment/uncomment a block of codes, choose "Source" "Toggle Comment". Hints for Correcting Syntax Error: If there is a syntax error on a statement, a red mark will show up on the left-margin on that statement. You could click on the "light bulb" to display the error message, and also select from the available hints for correcting that syntax error. Refactor (or Rename) (alt-shift-r): You can rename a variable, method, class, package or even the project easily in Eclipse. Select and right-click on the entity to be renamed "Refactor" "Rename". Eclipse can rename all the occurrences of the entity. Line Numbers: To show the line numbers, choose "Window" menu "Preferences" "General" "Editors" "Text Editors" Check the "Show Line Numbers" Box. You can also configure many editor options, such as the number of spaces for tab. Alternatively, you can right-click on the left-margin, and check "Show Line Numbers". Error Message Hyperlink: Click on an error message will hyperlink to the corresponding source statement. Changing Font Type and Size: From "Window" menu "Preferences" "General" "Appearance" "Colors and Fonts" expand "Java" "Java Editor Text Font" "Edit". (Alternatively, in "Window" "Preferences" type "font" as filter text and choose the appropriate entry.) Unicode Support: To enable Unicode support, select "Window" menu Preferences General Workspace Text file encoding UTF-8. This sets the default character set used for file encoding, similar to VM's command-line option -Dfile.encoding=UTF-8. Commonly used charsets for Unicode are UTF-8, UTF-16 (with BOM), UTF-16BE, UTF-16LE. Other charsets are US-ASCII, ISO-8859-1. Mouse Hover-over: In debug mode, you could configure to show the variable's value when the mouse hovers over the variable. Select "Window" menu "Preferences" "Java" "Editor" "Hover". Comparing Two Files: In "Package Explorer", select two files (hold the control key) Rightclick Compare with.
3. Scanner/printf() and JRE/JDK 1.5: If you encounter syntax error in using printf() or Scanner (which are available from JDK 1.5), you need to check your compiler settings. Select "Window" menu Preferences open the "Java" node select "Compiler" in "Compiler compliance level" select "1.6" (or "1.5" and above). 4. Command-Line Arguments: To provide command-line arguments to your Java program in Eclipse, right-click on the source file select "Run Configurations" Under the "Main" panel, check that "Project" name and "Main Class" are appropriate Select the "Argument" tab type your command-line arguments inside the "Program Arguments" box "Run". 5. Resolving Import (Ctrl-Shift-o): To ask Eclipse to insert the import statements for classes. Useful when you copy a large chunk of codes without the corresponding import statements. 6. Including Another Project: To include another project in the same work space, right-click on the project Build Path Configure Build Path... Select "Projects" tab "Add..." to select project in the existing work space OK. 7. Exporting a Project to a JAR file: Right-click on the project Export... Java, JAR File Next Select the files to be exported Next Next In "JAR Manifest Specification" dialog, enter the main class (if you wish to run the JAR file directly) Finish. 8. Unit Testing: If you keep your test in another project, you need to include the project under test in your Build Path (see above). To create a test case: Right-click on the project New JUnit Test Case the "New JUnit Test Case" dialog appears. Select "New JUnit 4 Test". In "Name", enter your class name. In "Class under test", browse and select the class to be tested. To run the test: Right-click "Run As" "JUnit Test". The results are displayed in a special "JUnit console". 9. Adding External JAR files & Native Libraries (dll, lib): Many external Java packages (such as JOGL, Java3D, JAMA, etc) are available to extend the functions of JDK. These binaries are often provided in a "lib" directory with jar files and native libraries (dll and lib). To include these external packages into an Eclipse's project, right-click on the project Build Path Add External Archives Navigate to select the JAR files to be included. In "Package Explorer", right-click on the JAR file added Properties: To include native libraries (dll and lib), select "Native Library" "Location Path" "External Folder". To include the javadoc, select "JavaDoc Location" "JavaDoc URL" You can specify a local file or a remote link.
(All the above options are also accessible via project's property "Build Path".) Notes: The jar files must be included in the CLASSPATH. The native library directories must be included in JRE's property "java.library.path", which normally but not necessarily includes all the paths from the PATH environment variable. If you get a runtime error "java.lang.UnsatisfiedLinkError: no xxx in java.library.path", which means that JRE cannot find your native library at runtime. The easier way to debug is to print out the contents of "java.library.path" viaSystem.out.println(System.getProperty("java.library.path")) . You could set the native library path via the command-line VM option -Djava.library.path=xxx.
10. Creating a User Library: You can also create a Eclipse's user library to include a set of JAR files and native libraries, that can then be added into subsequent Eclipse projects. For example, I created a user library for "jogl" as follows: a. From "Window" menu Preferences Java Build Path User Libraries New In "User library name", enter "jogl-1.1.1". The "User Library" dialog appears. b. In "User Library" dialog Select "jogl-1.1.1" Add JAR... Navigate to $JOGL_HOME/lib, and select "gluegen-rt.jar" and "jogl.jar". c. Expand the "jogl.jar" node, select "Native library location: (none)" Edit... External Folder... select $JOGL_HOME/lib. d. (Optional But Recommended) Expand the "jogl.jar" node Select "Javadoc location: (none)" Edit... Javadoc in archive In "Archive Path", "Browse" and select the downloaded JOGL API documentation zip-file In "Path within archive", "Browse" and expand the zip-file to select the top-level path (if any) Validate. Alternatively, you can provide the path to the un-zipped javadocs. This is needed for Eclipse to display javadoc information about classes, fields, and methods. e. (Optional) You may provide the source files by editing "Source attachment: (none)". Source is needed only if you are interested to debug into the JOGL source codes. For EACH subsequent Java project created that uses JOGL, right-click on the project Build Path Add Libraries Select "User Library" Check "jogl-1.1.1". 11. Running an External Program: Suppose that you want to run a Perl script on the selected file, you can configure an external tool as follows: . From "Run" menu External Tools External Tools Configuration... The "External Tools Configuration" dialog appears.
a. In "Name", enter your tool name. b. Choose the "Main" tab In "Location", "Browse File System..." to choose the perl interpreter "perl" In "Arguments", enter "path/scriptname.pl ${resource_loc}", where ${resource_loc} is an Eclipse variable that denotes the currently selected resource with absolute path. c. Choose the "Common" tab In "Standard Input and Output", uncheck "Allocate Console", check "File" and provide an output file (e.g., d:\temp\${resource_name}.txt). d. (If you use the CYGWIN perl interpreter, need to set environment variable CYGWIN=nodosfilewarning to disable warning message.) To run the configured external tool, select a file run external tool tool name. 12. Viewing Hex Code of Primitive Variables in Debug mode: In debug perspective, "Variable" panel Select the "menu" (inverted triangle) Java Java Preferences... Primitive Display Options Check "Display hexadecimal values (byte, short, char, int, long)". 13. Adding a New Version of JDK/JRE: First, you can check the installed JDK/JRE via "Window" menu "Preferences" Expand "Java" node "Installed JREs". Check the "Location" current JRE installed to make sure that it is the intended one. You can use the "Add" button to add a new version of JRE. For program development, I recommend that you add the
JDK (instead of JRE). [The "Location" decides the extension directory used for including additional JAR files, e.g., $JAVA_HOME\jre\lib\ext.]
If you did not separate the sources and class files into two separate directories, then the answer is straight forward, because there is only one directory to place your input file.
If you choose to keep your sources and class files in two separate directories, eclipse will create two sub-directories "src" and "bin" under the base directory. BUT you need to put your input file "xxxx.in" in the base directory of your project, instead of the "src" or "bin".. For writing simple programs: Put the sources, class files, and the input/output files in the same directory. (When you create a new project, select "Use project folder as root for sources and class files" in "Project Layout".) (But put your sources and class files in separate directories for big project.) You can create you input file from eclipse directly via "File" menu "New" "File". Remember to add a newline to the end of your input file. You may need to right-click the project and select "Refresh" to see the output file "xxxx.out" created in the package explorer. To open the "xxxx.in" and "xxxx.out": right-click Open With Text Editor.
public class FileIOTest { // saved as "FileIOTest.java" public static void main (String [] args) throws IOException { Scanner in = new Scanner(new File("FileIOTest.in")); Formatter out = new Formatter(new File("FileIOTest.out")); int a = in.nextInt(); int b = in.nextInt(); out.format("%d\n",a+b);
out.close(); } }
Create the input text file called "FileIOTest.in" with the following contents and terminated with a newline:
55 66
10. @WebServlet("/sayhello") // URL for this Servlet (for Servlet 3.0 with Tomcat 7) 11. public class HelloServlet extends HttpServlet { 12. private static final long serialVersionUID = 1L; 13. 14. @Override 15. protected void doGet(HttpServletRequest request, HttpServletResponse response) 16. throws ServletException, IOException { 17. // Set the response message MIME type (in Content-Type response header) 18. response.setContentType("text/html"); 19. // Get an output Writer to write the response message over the network 20. PrintWriter out = response.getWriter(); 21. // Write the response message (in an HTML page) to display "Hello, world!" 22. out.println("<!DOCTYPE html>"); 23. out.println("<html><head>"); 24. out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>"); 25. out.println("<title>Hello Servlet</title></head>"); 26. out.println("<body><h1>Hello, World!</h1>"); 27. out.println("<p>Your IP address is " + request.getRemoteAddr() + "</p>"); 28. out.println("<p>Your user agent is " + request.getHeader("user-agent") + "</p>"); 29. out.println("</body></html>"); 30. } }
(For Servlet 2.4/2.5 with Tomcat 6) The annotation @WebServlet is new in Servlet 3.0 and is not supported in Servlet 2.4/2.5. Hence, you need to manually configure the URL for the servlet in the Web Application Deployment Descriptor "web.xml" under directory "WEB-INF", as follows:
<?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0" metadata-complete="true"> <servlet> <servlet-name>HelloServletExample</servlet-name> <servlet-class>hello.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServletExample</servlet-name> <url-pattern>/sayhello</url-pattern> </servlet-mapping> </web-app>
31. To execute the Servlet, right-click on the "HelloServlet" project "Run As" "Run on Server" Change the URL to "http://localhost:8080/HelloServlet/sayhello ".