Vous êtes sur la page 1sur 8

Writing A Small Java Program

Writing a small java program takes a little more effort than writing your first C program. It is because of Java structure. Everything in Java is a class. So even to write a small Hello World program, one has to create a class and main function within it. You may have no idea about a class, but you still have to do it.
// a simple java program with the name Hello.java public class Hello { public static void main(String args[]) { System.out.println("Hello World! I am learning Java"); } }

Follow the steps to create and save the above program. 1. Start any editor. It may be Notepad or Edit or any other editor like TextPad or Editplus etc. 2. Type the above program as-it-is. Pay extra attention to case. Java is case sensitive . 3. Save the file under the name - Hello.java . Remember the file name must be Hello (H is capital) and the extension must be .java. If you are using Notepad, ensure you give file name in double quotes ( "Hello.java" ) as Notepad saves the file with the extension .txt otherwise.

Directory Structure
The following directory structure may be followed while you are saving the file.
c:\ | | ------ jdk5.0 | | -------- bin | | | | | | | -------- programs

| | -----| | -------

javac.exe java.exe

| | | | --------- Hello.java

In the above directory structure, i have installed JDK ( J2SE 5.0) in JDK5.0 directory under C drive.

Here I created folder programs under JDK5.0 directory. Directory bin is a standard directory and it contains two important files - javac.exe and java.exe File Hello.java is saved under programs directory.

Compiling Java Program


Having saved the file with the name Hello.java, now we have to compile the program. Take the following steps to compile the program. 1. From windows, select All Programs -> Accessories ->Command prompt to go to command prompt (also called as console). 2. Go to jdk5.0 directory and then to programs directory. In case if your system have different names from the names i am using, use those names. 3. Type the following command shown in bold and computer response is shown in italic.
4. c:\jdk5.0\programs> javac Hello.java 5. 'javac' is not recognized as an internal or external command, 6. operable program or batch file. 7.

The reason for error is; operating system did not find javac in the current directory. It is obvious (according to above directory structure) that javac.exe is not found in the current directory as we are in programs directory. The remedy is to inform operating system to invoke javac.exe that is in bin directory even though we are in programs directory. PATH command of Windows can be used to inform Windows where to find Javac.exe and Java.exe. At the command prompt, enter the following command to set the path where OS should search for JAVAC and JAVA
C:\jdk5.0\programs>path c:\jdk5.0\bin;c:\windows\system32

The above command informs OS that it should go to c:\jdk5.0\bin to locate JAVAC.EXE and other .EXE files if the file is not found in the current directory. The second directory is important only if you are using EDIT editor, otherwise you can ignore it. Now, we are ready to compile java programs as follows: c:\jdk5.0\programs>javac Hello.java You should see command prompt again without any messages. Then you can see a file Hello.class in the current directory. Hello.class is the bytecode of Java program. If you are getting error as follows, it means JAVAC could not locate Hello.java. It is mainly because of saving the file without the extension .java. It is a common problem with Notepad users as Notepad adds extension .TXT if you do not enclose filename in double quotes at the time of saving the file.

So, check whether you have file Hello.java in programs directory and also check whether the extension is .java alone by using DIR command of OS.
c:\jdk5.0\programs>javac Hello.java error: cannot read: Hello.java 1 error

Running Java Program


Once Java program is compiled successfully, you have to run it using JAVA as follows. Make sure you are in programs directory and then give the following command.
c:\jdk5.0\programs>java Hello Hello World! I am learning Java

The only possible error at this stage is missing .class file. If the .class file is not found in the current directory (may be you didn't compile in the first place) or JAVA is not able to locate then it displays the following message.
c:\jdk5.0\programs>java Hello Exception in thread "main" java.lang.NoClassDefFoundError: Hello

The remedy for the above problem is to compile in case you didn't compile. However, in some cases the problem may be because of CLASSPATH. Well it is too early to explain the details of CLASSPATH. But it will be sufficient to know CLASSPATH is used by Java to locate .class files. If you are getting above error in spite of having Hello.class in the current directory, then set the classpath and then run the java program.
c:\jdk5.0\programs>set classpath=.; c:\jdk5.0\programs>java Hello Hello World! I am learning Java

Congratulations!, If you have successfully compiled and run your first Java program. A thousand miles journey starts with one step forward!!!

FAQs
When I try to compile, I get the following error: 'javac' is not recognized as an
internal or external command, operable program or batch file.

This means that Windows cannot find the javac program. Sometimes when you download and install the JDK, it sets the path variable correctly; more often, it doesn't. Here's how to fix the problem. 1. Find out where the javac.exe file was installed. It will probably be somewhere like C:\Program Files\Java\jdk1.6.0_16\bin\ (You might also try a file search for javac.exe if you can't find it by browsing.) 2. Once you find javac.exe, type the full path on the command line, something like this:
3. "C:\Program Files\Java\jdk1.6.0_16\bin\javac" Hello.java

You may need the quotes around the file path if it contains any spaces. 4. If this works (Windows can now find javac), then Java is installed correctly. Now you can update your path so you don't have to type the whole path name every time. These are the steps to do this in WindowsXP (some translation may be required for Vista): 1. Go to Start -> Control Panel -> System. (It's easiest to find System when you change Control Panel to Classic View.) 2. Go to the Advanced tab 3. Click the Environment Variables button 4. Scroll down through the System variables until you find Path. 5. Edit this variable, adding the path up to but not include javac (so probably C:\Program Files\Java\jdk1.6.0_16\bin\) to the end of the list. Make sure there is a ; (semi-colon) between this path and the one before it. 6. Click OK for all of that, saving it all. 7. Now open a new command prompt and see if just javac -version or javac Hello.java works, without the whole path. If you ran into problems, let me know how far into this process you made it and what went wrong. javac works, but when I compile I get this error:
error: cannot read: Hello.java 1 error

Alternately, you might get this error:


javac: file not found: Hello.java Usage: javac <options> <source files> use -help for a list of possible options

Either of these means javac can't find the .java file you are trying to compile (in this case, Hello.java). Check that you are in the same directory as the file. Type dir on the command line and you should see your .java file in the list of files displayed. If you need to switch directories to find where you saved Hello.java, remember that cd .. moves up a level, and cd dirName will move down one level into the subdirectory named dirName. See Using the Windows Command Prompt for more.

Using the Windows Command Prompt


Overview
Before Windows, Microsoft released a text-based operating system called MS-DOS. While DOS has largely expired, the usefulness of typing commands to the operating system remains. Not everything in your OS has a pretty clickable icon, and so the command line can grant you access to powerful features not used by casual users. The commands used to interact with Windows are generally the same as those that were used by MS-DOS (though more and more Unix commands are gradually being supported).

Opening the Command Prompt


In order to type commands, you need to first open the command prompt: Start -> Programs -> Accessories -> Command Prompt. This will open a new black window with a command prompt that shows the path to your current location in the computer's directory structure. It should look something like this:
C:\Documents and Settings\Zach>

(An alternative method is: Start -> Run..., and then type cmd and hit enter.)

Essential Commands
dir

The path displayed by command prompt will tell you which directory you are currently in. The dir command (short for directory listing) will print a list of all files that are in the current directory. The information displayed includes each file's name, when it was last edited, and its file size. Listings that contain <DIR> (rather than a file size) are subdirectories (folders) of the current directory.
cd

Usually you have to be in the same directory as the files you want to work with. To change directory, use the command cd. You must also specify the name of the subdirectory you want to move into. Example:
C:\Documents and Settings\Zach>cd Desktop C:\Documents and Settings\Zach\Desktop>

This moves you down one level. To move up a level, use .. to stand for "the parent directory". Example:
C:\Documents and Settings\Zach\Desktop>cd .. C:\Documents and Settings\Zach>

You can combine these to form longer path names relative to your current location, or you can use absolute (fully-qualified) names that start with a drive letter. Example:
C:\Documents and Settings\Zach>cd ..\..\windows C:\WINDOWS>cd "C:\Documents and Settings\Zach" C:\Documents and Settings\Zach>

(Depending on your system, you may have to put "quotes" around any path name that includes spaces.) switching drives If you have to switch to a different drive, just type the destination drive letter followed by a colon. Example:
C:\Documents and Settings\Zach>d: D:\>c: C:\Documents and Settings\Zach>

Once you're in the right location, you can manipulate your files using commands such as java and javac. These are only the barest of DOS commands. To learn what other common commands exist, type help. To learn more about a specific command, type the command name followed by /?, as in: dir /? You can also learn more by doing a search online for a DOS tutorial. Some other commands that you should probably learn: cls, more, del, mkdir, and rename. (Be careful with del: deleting files at the command prompt bypasses the Recycle Bin, so deleted files are immediately gone forever.)

Tips and Tricks


Command History (up arrow) When compiling code, it can be time-consuming to type the whole command and file name each time. Instead, press the up arrow on your keyboard. This will scroll through previous commands you've typed. You can edit them, or just hit enter to run that command again. Auto-completion (tab) If you type the first letter of the name of a file in the current directory and then hit the tab key, DOS will insert to rest of the name for you (so you don't have to type it). If there's more than one name that begins with the same letter, you can tab multiple times to cycle through them all. Copying and pasting If you need to copy something (such as an error message or program output) from the command prompt window: right-click with your mouse and select Mark. Now hightlight what you want to copy with the mouse and then right-click again. This copies whatever you highlighted to the system clipboard, and you can paste it from there into another window or application (as with normal pasting). Killing a program (ctrl-c) If a program is hanging or not responding, you can hold down the Ctrl button and press C to kill . (This is a faster alternative to closing the command window and then reopening it.) Full screen (alt-enter) Hold down the Alt key and press Enter to enter full screen mode. Repeat to return to a window. (Scare/impress your friends!) Changing the initial directory You can right-click the Command Prompt shortcut, go to Properties, and then edit which directory a new command prompt starts in. (Or, rather, you should create a copy of the default shortcut and then make such edits to the copy.)
SAMPLE CLASS: public class ZtomaszeAge { public static void main(String[] args) {

String name; name = "Zach"; int age = 31; System.out.print("My name is "); System.out.print(name); System.out.println("."); System.out.println("I am " + age + " years old."); } }

A Word About the Java Platform Java APIs are libraries of compiled code that you can use in your programs. They let you add ready-made and customizable functionality to save you programming time Java programs are run (or interpreted) by another program called the Java VM. If you are familiar with Visual Basic or another interpreted language, this concept is probably familiar to you. Rather than running directly on the native operating system, the program is interpreted by the Java VM for the native operating system. This means that any computer system with the Java VM installed can run Java programs regardless of the computer system on which the applications were originally developed. For example, a Java program developed on a Personal Computer (PC) with the Windows NT operating system should run equally well without modification on a Sun Ultra workstation with the Solaris operating system, and vice versa. Setting Up Your Computer Before you can write and run the simple Java program in this lesson, you need to install the Java platform on your computer system. The Java platform is available free of charge from the java.sun.com web site. You can choose between the Java 2 Platform software for Windows 95/98/NT or for Solaris. The download page contains the information you need to install and configure the Java platform for writing and running Java programs. Writing a Program The easiest way to write a simple program is with a text editor. So, using the text editor of your choice, create a text file with the following text, and be sure to name the text file ExampleProgram.java. Java programs are case sensitive, so if you type the code in yourself, pay particular attention to the capitalization.

//A Very Simple Example class ExampleProgram { public static void main(String[] args){ System.out.println("I'm a Simple Program"); } }
Compiling the Program A program has to be converted to a form the Java VM can understand so any computer with a Java VM can interpret and run the program. Compiling a Java program means taking the programmer-readable text in your program file (also called source code) and converting it to bytecodes, which are platform-independent instructions for the Java VM. The Java compiler is invoked at the command line on Unix and DOS shell operating systems as follows:

javac ExampleProgram.java
Note: Part of the configuration process for setting up the Java platform is setting the class path. The class path can be set using either the -classpath option with the javac compiler command and java interpreter command, or by setting the CLASSPATH environment variable. You need to set the class path to point to the directory where the ExampleProgram class is so the compiler and interpreter commands can find it. C:\>javac classpath c:\jdk1.3\bin where the .class file s

Interpreting and Running the Program Once your program successfully compiles into Java bytecodes, you can interpret and run applications on any Java VM, or interpret and run applets in any Web browser with a Java VM built in such as Netscape or Internet Explorer. Interpreting and

running a Java program means invoking the Java VM byte code interpreter, which converts the Java byte codes to platformdependent machine codes so your computer can understand and run the program. The Java interpreter is invoked at the command line on Unix and DOS shell operating systems as follows:

java ExampleProgram
At the command line, you should see:

I'm a Simple Program


Here is how the entire sequence looks in a terminal window:

Vous aimerez peut-être aussi