Have you ever inquire how computer programme knead ? Have you ever want to find out how to write your own data processor programs ? Whether you are 14 years old and hop to read how to write your first game , or you are 70 geezerhood honest-to-goodness and have been curious about computer programing for 20 years , this article is for you . In this variation ofHowStuffWorks , I ’m going to instruct you how computer programs work by instruct you how to programme in theJava programing language .

In Holy Order to teach you about computer programming , I am going to make several assumptions from the startle :

All of the tool you involve to start programming in Java are wide uncommitted on the Web for free . There is also a huge amount of educational fabric for Java available on the Web , so once you finish this clause you’re able to easily go learn more to advance your acquirement . you could learn Java computer programming here without spending any money on compiling program , evolution environments , show materials , etc . Once you larn Java it is easy to learn other languages , so this is a upright place to depart .

Generic java programming code written on black screen

Having enjoin these things , we are ready to go . Let ’s get start !

A Little Terminology

Keep in mind that I am assuming that you have intercourse nothing about programming . Here are several vocabulary terms that will make things understandable :

In orderliness for you to start writing information processing system programs in a programming speech called Java , you need a compiler for the Java language . The next section guides you through the process of downloading and instal a compiling program . Once you have a compiling program , we can get started . This process is going to take several hours , much of that time being download time for several large file cabinet . You are also going to need about 40megabytesof freediskspace ( ensure you have the space uncommitted before you get started ) .

Downloading the Java Compiler

so as to get a Java development environs set up on your machine – you " develop " ( write ) data processor programs using a " development surround " – you will have to complete the following gradation :

Before getting started , it would make things easier if you make a novel directory in your temp directory to hold the file we are about to download . We will call this thedownload directory .

Step 1 - Download the Java development environment

Article image

Go to the pagehttp://java.sun.com/j2se/1.4.2/download.html . Download the SDK software system by penetrate on the " Download J2SE SDK " link . You will be shown a licensing agreement . Click Accept . Select youroperating systemand download the file to your download directory . This is a huge data file , and it will take several hours to download over a normalphone - bank line modem . The next two data file are also large .

measure 2 - Download the Java support

Download the documentation by selecting your operating organisation and clicking the SDK 1.4.1 documentation link .

Article image

Step 3 - Download and instal WinZip

If you do not have a version of WinZip or an equivalent on your motorcar , go to the pagehttp://www.winzip.com/and download an valuation copy of WinZip . function the EXE you get to install it . We will habituate it in a minute to put in the documentation .

stair 4 - set up the development kit

execute the j2sdk-1_4_1-*.exe file that you downloaded in step 1 . It will take out and set up the maturation kit automatically .

stride 5 - establish the support

Read the instalment instruction manual for the documentation . They will apprise you to move the documentation file to same directory as that moderate the ontogenesis kit you just installed . Unzip the support and it will set down into the right spot .

footprint 6 - conform your environment

As instructed onthis page , you need to change your track variable star . This is most easily done by opening an MS - DOS prompting and typewrite PATH to see what the itinerary is determine to currently . Then spread autoexec.bat in Notepad and make the modification to PATH specified in the instructions .

Step 7 - Test

Now you should be able to open up another MS - DOS window and typejavac . If everything is set up properly , then you should see a two - line blob of text get out that tell you how to usejavac . That imply you are quick to go . If you see the message " Bad Command or File Name " it stand for you are not quick to go . Figure out what you did wrong by rereading the installation instructions . Make trusted the PATH is set properly and working . Go back and reread the Programmer ’s Creed above and be persistent until the problem is dissolve .

You are now the gallant proprietor of a machine that can compile Java programs . You are ready to lead off writing computer software !

By the direction , one of the things you just unpacked is ademodirectory full of neat example . All of the examples are quick to run , so you might want to regain the directory and play with some of the sample . Many of them make sounds , so be certain to turn on yourspeakers . To tend the lesson , discover pages with public figure likeexample1.htmland load them into your usual internet browser app .

Your First Program

Your first platform will be scant and sweet . It is going to create a drawing area and draw a diagonal line across it . To create this program you will need to :

Here is the programme we will use for this demonstration :

Step 1 - Type in the computer program

make a Modern directory to obligate your program . Open up Notepad ( or any other school text editor that can create TXT files ) . character or cut and paste the political platform into the Notepad window . This is important : When you type the program in , pillowcase matter . That mean that you must type the capital and small letter characters precisely as they seem in the programme . Review the coder ’s creed above . If you do not type it EXACTLY as prove , it is not go to work .

Step 2 - Save the file

Save the file to the filenameFirstApplet.javain the directory that you created in step 1.Case mattersin the filename . Make indisputable the ' farad ' and ' A ' are uppercase and all other characters are lowercase , as shown .

stair 3 - Compile the syllabus

Open an MS - DOS windowpane . Change directory ( " cd " ) to the directory containingFirstApplet.java . character :

Case matters ! Either it will work , in which compositor’s case nothing will be printed to the windowpane , or there will be errors . If there are no error , a file bring up FirstApplet.class will be create in the directory right next to FirstApplet.java .

( Make certain that the data file is save to the nameFirstApplet.javaand notFirstApplet.java.txt . This is most easily done by typingdirin the MS - DOS window and looking at the single file name . If it has a.txtextension , remove it by rename the Indian file . Or melt down the Windows Explorer and select Options in the View carte . Make certain that the " Hide MD - DOS File Extensions for file character that are registered " box is NOT contain , and then seem at the computer file name with the explorer . transfer it if necessary . )

gradation 4 - limit any problems

If there are errors , fix them . equate your program to the program above and get them to match exactly . Keep recompiling until you see no fault . Ifjavacseems to not be working , appear back at the previous section and prepare your instalment .

stone’s throw 5 - Create an HTML Thomas Nelson Page

make an HTML page to hold the applet . Open another Notepad windowpane . Type into it the following :

Save this file in the same directory with the nameapplet.htm .

[ If you have never worked with HTML before , please readHow a WWW Page Works . Theapplettag is how you access a Java applet from a web page . ]

footstep 6 - bleed the Applet

In your MS - DOS windowpane , type :

You should see a diagonal line running from the upper left corner to the lower right recess .

pull in the applet viewer a little bigger to see the whole line . You should also be able to load the HTML page into any forward-looking browser app like Netscape Navigator or Microsoft Internet Explorer and see around the same matter .

You have successfully create your first program ! ! !

Understanding What Just Happened

So what just hap ?

First , you wrote a spell of computer code for an extremely simpleJava applet . An applet is a Java political program that can run within a World Wide Web web internet browser , as opposed to aJava program , which is a stand - alone program that run on your local machine ( Java applications are slenderly more complicated and somewhat less popular , so we will start with applet ) . We compiled the applet usingjavac . We then created an highly simple Web page to " hold " the applet . We break away the applet usingappletviewer , but you may just as easily hunt down it in a web browser app .

The program itself is about 10 lines long :

This is about the mere Java applet you’re able to create . To fully understand it you will have to instruct a fair amount , particularly in the area ofobject orient programing techniques . Since I am assuming that you have zero scheduling experience , what I would like you to do is focus your tending on just one bloodline in this program for the present moment :

This is the transmission line in this programme that does the work . It draws the diagonal logical argument . The rest of the program is scaffold that support that one line , and we can discount the staging for the minute . What materialise here was that we severalize the estimator to get one line from the upper odd hand recess ( 0,0 ) to the bottom right deal quoin ( 200 , 200 ) . The computer drew it just like we told it to . That is the core of data processor programing !

( remark also that in the HTML Thomas Nelson Page , we set the size of the applet ’s window in step 5 above to have a width of 200 and a height of 200 . )

In this program , we called amethod(a.k.a.function ) calleddrawLineand we give-up the ghost it fourparameters(0 , 0 , 200 , 200 ) . The phone line ends in a semicolon . The semicolon acts like the period at the final stage of the sentence . The line begins withg . , signifying that we want to call the method nameddrawLineon the specific object namedg(which you could see one bloodline up is of the classGraphics– we will get into classes and method acting of classes in much more detail by and by in this article ) .

A method acting is simply a instruction – it tells the computing machine to do something . In this case , drawLinetells the data processor to describe a line between the point specified : ( 0 , 0 ) and ( 200 , 200 ) . you’re able to think of the window as having its 0,0 coordinate in the upper left street corner , with prescribed X and Y axes extending to the right wing and down . Each window pane on the screen ( eachpixel ) is one increment on the scale of measurement .

judge experiment by using different number for the four parameters . exchange a number or two , preserve your changes , recompile withjavacand rerun after each change inappletviewer , and see what you discover .

What other function are available besidesdrawLine ? You find this out by looking at the documentation for theGraphicsclass . When you installed the Java evolution kit and unpacked the software documentation , one of the file cabinet unload in the cognitive process is calledjava.awt.Graphics.html , and it is on your machine . This is the single file that explain theGraphicsclass . On my machine , the exact track to this file is D:\jdk1.1.7\docs\api\java.awt . Graphics.html . On your machine the way is likely to be more or less different , but snug – it depends on exactly where you installed matter . detect the Indian file and open it . Up toward the top of this file cabinet there is a section called " Method Index . " This is a listing of all of the methods this class supports . ThedrawLinemethod is one of them , but you may seemanyothers . you could cast , among other things :

interpret about and assay experimenting with some of these dissimilar method acting to discover what is potential . For example , adjudicate this code :

It will draw a corner with two virgule ( be sure to pull the windowpane big enough to see the whole thing ) . Try drawing other shapes . record about and try out vary the color with thesetColormethod . For example :

take down the addition of the newimportline in the 2d line of the programme . The output of this program looks like this :

One thing that might be cash in one’s chips through your top dog right now is , " How did he have sex to useColor.redrather than simplyred , and how did he know to add the secondimportline ? " You learn thing like that by representative . Because I just point you an example of how to call thesetColormethod , you now get laid that whenever you need to alter the color you will useColor.followed by a colour name as a parameter to thesetColormethod , and you will add the appropriateimportline at the top of the program . If you take care upsetColor , it has a linkup that will tell you about theColorclass , and in it is a list of all the valid gloss public figure along with techniques for creating new ( unnamed ) colors . You study that entropy , you put in it in your head and now you love how to switch color in Java . That is the gist of becoming a computer computer programmer – you learn techniques and remember them for the next program you write . You learn the technique either by take an example ( as you did here ) or by reading through the certification or by face at object lesson code ( as in the demo directory ) . If you have abrainthat likes exploring and learning and remember thing , then you will make out programming !

In this section , you have check how to write linear , serial computer code – pulley block of computer code that consist of method acting calls starting at the top and figure out toward the bottom ( judge drawing one of the linesbeforeyou imbibe the red rectangle and catch what happens – it will be covered over by the rectangle and made invisible . The order of transmission line in the code successiveness is significant ) . Sequential lines of code shape the basic core of any computing machine syllabus . Experiment with all the different drawing method and see what you may discover .

Bugs and Debugging

One matter that you are going to detect as you learn about programming is that you tend to make a fair number of mistakes and supposal that cause your programme to either : 1 ) not compile , or 2 ) produce yield that you do n’t expect when it executes . These problems are bear on to asbugs , and the act of removing them is calleddebugging . About one-half of the time of any programmer is expend debugging .

You will have plenty of prison term and opportunity to create your own bug , but to get more familiar with the hypothesis allow ’s create a few . In your program , stress erasing one of the semicolons at the end of a line and taste compiling the course of study withjavac . The compiling program will give you an misplay content . This is anticipate acompiler mistake , and you have to eliminate all of them before you could perform your program . taste misspell a function name , leaving out a " { " or eliminating one of theimportlines to get used to dissimilar compiler errors . The first time you see a certain type of compiling program fault it can be frustrating , but by experimenting like this – with known errors that you create on determination – you’re able to get familiar with many of the common errors .

A bug , also known as an execution ( or range - clip ) error , happens when the program amass hunky-dory and runs , but then does not bring forth the output signal you planned on it producing . For example , this code make a crimson rectangle with two diagonal lines across it :

The following code , on the other hand , raise just the red rectangle ( which incubate over the two lines ):

The code is almost exactly the same but looks completely different when it executes . If you are expect to see two diagonal lines , then the code in the 2nd case contains a bug .

Here ’s another example :

This code grow a disgraceful outlined boxwood and two diagonals . This next piece of computer code produces only one aslope :

Again , if you wait to see two solidus , then the second slice of codification contains a bug ( look at the second piece of codification until you interpret what went wrong ) . This sort of bug can take a long time to notice because it is elusive .

You will have stack of clip to apply finding your own bugs . The average programmer spends about half of his or her fourth dimension tracking down , discover and eliminating bugs . prove not to get frustrated when they pass off – they are a normal part of programming life .

Variables

All programs usevariablesto hold pieces of datum temporarily . For example , if at some level in a program you involve a user for a number , you will store it in a variable star so that you could utilize it later .

variable must bedefined(ordeclared ) in a course of study before you may use them , and you must give each variable a specific eccentric . For illustration , you might declare one variable to have a type that allows it to hold numbers , and another variable star to have a eccentric that take into account it to hold a soul ’s name . ( Because Java ask you to specifically define variable star before you use them and put forward the type of note value you design to store in a variable , Java is called astrongly typedlanguage . sure language do n’t have these requirements . In universal , when creating great programs , strong typing tends to reduce the number of programing errors that you make . )

In this program , we have declared two variable namedwidthandheight . We have declared their type to beint . Anintvariable can bind an integer ( a whole act such as 1 , 2 , 3 ) . We haveinitializedboth variables to 200 . We could just as easily have said :

The first frame is simply a bit fast to typewrite .

The act of setting a variable to its first value is calledinitializingthe variable . A usual programming bug hap when you block to initialize a variable star . To see that bug , try winnow out the initialization part of the code ( the " = 200 " part ) and recompile the program to see what happens . What you will regain is that the compiling program complains about this job . That ’s a very nice feature , by the way . It will keep open you passel of wasted time .

There are two types of variable quantity in Java – simple ( primitive ) variables andclasses .

Theinttype is simple . The variable can hold a number . That is all that it can do . You adjudge anint , fix it to a economic value and use it . Classes , on the other hand , can contain multiple parts and have method that make them easy to use . A in force model of a aboveboard class is theRectangleclass , so rent ’s start with it .

One of the limitation of the programme we have been working on so far is the fact that it assume the window is 200 by 200 pixels . What if we wanted to expect the windowpane , " How bighearted are you ? , " and then size our rectangle and diagonals to fit ? If you go back and look on the documentation page for theGraphicsclass ( java.awt.Graphics.html – the filing cabinet that lists all the available drawing functions ) , you will see that one of the functions is calledgetClipBounds . press this role name to see the full description . This single-valued function assume no parameters but insteadreturnsa value of typeRectangle . The rectangle it return contains the breadth and height of the available draftsmanship area . If you click onRectanglein this software documentation Thomas Nelson Page you will be taken to the support page for theRectangleclass ( java.awt.Graphics.html ) . Looking in the Variable Index segment at the top of the varlet , you find that this socio-economic class contains four variables named x , y , width and height , respectively . What we desire to do , therefore , is get the clip boundary rectangle usinggetClipBoundsand then extract the width and height from that rectangle and save the value in thewidthandheightvariables we created in the old example , like this :

When you run this example , what you will notice is that the rectangle and diagonals exactly fit the drawing area . Plus , when you change the sizing of the windowpane , the rectangle and diagonals redraw themselves at the raw size of it automatically . There are five new concept introduced in this code , so have ’s look at them :

One interrogative sentence commonly ask at this point in time is , " Did we really require to declare variable namedwidthandheight ? " The solution is , " No . " We could have typedr.width - 1directly into the draught subprogram . Creating the variables simply make thing a little leisurely to interpret , and it ’s therefore a effective habit to diminish into .

Java supports several simple variable case . Here are three of the most common :

you’re able to perform mathematics operations on simple type . Java understands+(addition),-(subtraction),*(multiplication),/(division ) and several others . Here ’s an model of how you might practice these operations in a program . countenance ’s say that you desire to calculate the volume of a heavens with a diam of 10 foot . The follow code would handle it :

The first calculation say , " Divide the value in the varying nameddiameterby 2.0 and place the result in the variable namedradius . " you could see that the " = " augury here mean , " Place the result from the computation on the right into the variable star named on the left . "

Looping

One of the things that computers do very well is do repetitive calculation or operations . In the late plane section , we have learn how to write " sequential block of code , " so the next matter we should discuss is the proficiency for causing a successive block of computer code to occur repeatedly .

For object lesson , let ’s say that I require you to guide the control grid picture at the top of the page .

A serious post to start would be to draw the horizontal lines .

One manner to absorb the lines would be to create a sequent block of code :

( For some novel computer programmer , the assertion " y = y + 25 ; " looks left the first time they see it . What it means is , " Take the value currently in the variabley , add up 25 to it and place the result back into the variabley . " So if y contains 10 before the line is executed , it will comprise 35 right away after the line of work is executed . )

Most multitude who attend at this code straightaway notice that it contains the same two personal line of credit retell over and over . In this fussy typeface the repetition is not so bad , but you may imagine that if you wanted to create a grid with thousands of row and tower , this approaching would make political platform - committal to writing very tiring . The answer to this problem is aloop , as shown below :

When you run this program , you will see that it draws nine horizontal lines 200 pixels long .

Thewhilestatement is a loop argument in Java . The assertion tells Java to behave in the next way : At thewhilestatement , Java looks at the expression in the parentheses and necessitate , " Isyless than or adequate to 210 ? "

So you’re able to see that when you run this political platform , initiallyyis 10 . Ten is less than 210 , so Java enters the cylinder block in braces , draws a line of business from ( 10,10 ) to ( 210 , 10 ) , setsyto 35 and then goes back up to thewhilestatement . Thirty - five is less than 210 , so Java enrol the pulley block in twain , run a line from ( 10,35 ) to ( 210 , 35 ) , setsyto 60 and then goes back up to thewhilestatement . This episode repeats untilyeventually gets to be greater than 210 . Then the platform drop out .

We can complete our storage-battery grid by adding a second loop to the program , like this :

you may see that awhilestatement has three parts :

Java indorse another path of doing the same thing that is a little more thick than awhilestatement . It is call aforstatement . If you have awhilestatement that looks like this :

then the equivalentforstatement looks like this :

you may see that all theforstatement does is condense the low-level formatting , evaluation and incrementing line of work into a inadequate , individual line . It simply shorten the programme you write , nothing more .

While we are here , two quick points about loops :

To get some practice with looping , try write programs to sop up the undermentioned figures :

For lots more selective information on Java and other reckoner computer programing language , check out the links on the next page .

Lots More Information