It appears that you're running an Ad-Blocker. This site is monetized by Advertising and by ">User Donations; we ask that if you find this site helpful that you whitelist us in your Ad-Blocker, or make a ">Donation to help aid in operating costs.

Feel free to distribute this as much as you like. Just don't modify it at all; distribute it in its entirety. Check back for more Java tutorials to spread around as well.

Table of Contents-------------------------1) Brief intro2) A little history of Java3) What can I do with Java?4) Basic output a) Hello, world! console b) Explanation of a class c) More console output d) Some graphical output5) Basic input6) Wrap up

-------------------------- Section 1 Brief Intro--------------------------- Welcome to Part I of this Java programming tutorial. This first part is an introduction to Java programming, it will cover only basic stuff. It is mainly to acquaint you with Java's syntax, as well as learn some of the basic functionality of Java. This is really for the novice who has never programmed. If you're already a programmer just learning Java, then just check out the code and read the explanations on whatever confuses you. That said, I hope you learn and enjoy!

--------------------------- Section 2 A little history--------------------------- In the Middle Ages of Computer Programming (ca. 1989), the Sun Microsystems saw a major problem with the majority of programming languages in use- they weren't easily portable. Code that worked on some processors and OSs didn't work on others without some major changes. There were a few languages, such as C and C++, that did not have to be greatly modified, but had to be modified nonetheless for portability. Sun envisioned a language that would run on every processor type and OS. They figured that they could create some kind of virtual machine that translated programmer code into machine code. Thus, to run a program, the user would only have to have a copy of the virtual machine for their processor and OS. In 1991, Sun began to take steps toward achieving their vision of the "universal programming language." They funded an internal research project they code-named Green. The resulting language was one that was based on C and C++, and was originally called Oak. However, the creators found that another language was already named Oak, and so at a visit to a local coffee shop, the name Java was suggested. Thus, Java was born.

------------------------------ Section 3 What can I do?------------------------------- With Java, you are able to do two main, distinct things- write applets or applications. An application is just a regular program that runs on its own. An applet is generally imbedded into a web page to add extra functionality or entertainment value. A major appeal to Java is its ability to assist in creating dynamic content. Java is also being increasingly used in the development of imbedded systems. You can do everything with Java you can do with most other languages. Graphics, networking, whatever you want.

------------------------------ Section 4 Basic output------------------------------ If you're like me, you skipped the first few sections to get to the code. Well here ya are...

Cool, so we wrote our first program, just compile and run it. Oh shoot, we don't know how to do that yet. Let's get to it then! First thing to to is run over to http://java.sun.com and download the latest version of the SDK. The SDK contains all the tools you need to compile and run java programs. Read the accompanying documentation to install it, as it's a bit different for every OS. Now install the JDK, and we're set.Before I explain the code, try compiling and running the the program. To do this, get a command prompt in your favorite OS, and switch on over to the directory that contains Hello.java. Then type

javac Hello.java

Hopefully you didn't get any errors. If so, make sure your code is exactly like mine, and the file name is Hello.java (I'll explain that in a bit). After this command, you will have a file called Hello.class in your directory. This contains the compiled Java code for the virtual machine to execute. If you don't know what the virtual machine is, read Section 2. So we have the Hello.class, then what? Type

java Hello

This should give us the following output:

Hello, world!

Alright, a run-down of the code...

First thing to know is that // signifies a comment. The compiler ignores everything that follows the //. It can appear on the same line as code, as long as it's after the code:System.out.println("Hello, world!"); // Ouput a message

public class Hello This line declares a class named Hello. In every Java program you write, you will declare at least one class. public is a keyword saying that it can be used in any program that you or anyone else writes. class, of course, says it's a class. Hello is the name of the class. It's possible to declare more than one class in a file. However, ONLY 1 CLASS MAY BE PUBLIC. This is important to remember. If you have more than one public class in a file, compilation will fail. Also, the name of the public class must also be the name of the file plus .java. Thus, public class MyClass goes in MyClass.java, public class BobsClass in BobsClass.java. If you don't name it like that, it won't compile. So go back up and rename the file Hello.java- that's why you had that problem (I know, I've changed examples around too!).

public static void main(String args[]) This line declares a method called main. For now, just think of methods as blocks of code that allow you to organize your programs better. They will be discussed in great detail later on. void means that the method does not return a value. Every method is called by some other method (with the exception of main()). Methods are able to return values to the methods that called them. This again is unimportant for the time being. main() is a method that gets called automatically when you run your program. Every application class you write must have one method named main(). String argv[] is a parameter to the method. This will also be discussed later. Here, it allows you to call your program with command-line options.

System.out.println("Hello, world!"); This is called a statement. All statements end in a semicolon (;). This just prints out "Hello, world!" without the quotation marks. What you enter between the parentheses is what is displayed. What is between the parentheses is known as a argument. A method can have multiple arguments; when this is the case, they are separated by commas.

We saw what each line of code does, but you may be wondering how it all fits together. One thing to remember is that in Java, whenever you have an opening character- {, [, (- you must have a matching closing character- }, ], ). So we see the first line that says public class Hello. As was said, this declares our class. The opening curly brace on the next line signifies the beginning of the class. This means that everything between it and the closing curly brace on the bottom is a part of the class. The curly braces underneath the main() function designate the code that is part of the main() function. I will cover this fully in a later tutorial. But just so ya know...

--------------------------------- Section 4c More console---------------------------------There are two ways to do basic console output. One is to use System.out.println(), and the other is to use System.out.print(). They both have the same syntax, they just operate a tad bit differently. System.out.print() will display the test you pass on a line, but will not create a new line. Thus subsequent calls to System.out.print() will be on the same line. System.out.println() displays text on its own line. Experiment with System.out.print() to see exactly what it does.

There are a few special characters that can be used in stuff you display. They're called escape sequences. A table is below to show you what they are and what they do:

Escape Sequence Description--------------------------- ----------------- \n Newline. Positions screen cursor at beginning of next line \t Horizontal tab. Move the screen cursor to the next tab stop \r Carriage return. Position screen cursor at beginning of current line, don't go to next. Stuff on this line can be overwritten \\ Used to print a backslash character \" Used to print a double quote character.

Here's a quick example: System.out.print("\"This text appears in quotes\" but this doesn't\n");This will display: "This text appears in quotes" but this doesn'tand move the screen cursor to the next line. This means that all subsequent output occurs on the next line.

------------------------------- Secion 4d Graphical output-------------------------------This stuff is quite a bit cooler than the console output. To start, let's do a quick program:

Compile with javac GraphicalOutput.java and run with java GraphicalOutput.

What you should get is a dialog box that says "Hello, world!" and has a little information symbol on the side. Let's see what's goin on...

import javax.swing.JOptionPane; This line allows us to include other classes into our programs. It's the same as #include in C/C++. Sun has created a huge library of functions that you can include so you don't have to "reinvent the wheel." This just lets us execute the single command in our program.

The first couple lines are the same.

JOptionPane.showMessageDialog(null, "Hello, world!"); This shows the dialog box. Don't worry about the first argument. Set it to null every time. The second one is obviously the text you want to show in the dialog box.

You can also call JOptionPane.showMessageDialog() with more argument. Here's how:JOptionPane.showMessageDialog(null, display string, title bar string, message box type);

There are a few message box types: JOptionPane.ERROR_MESSAGE, JOptionPane.INFORMATION_MESSAGE, JOptionPane.WARNING_MESSAGE, and JOptionPane.PLAIN_MESSAGE.To display a dialog with the title "I rule" and message "I'm a bad *** programmer" as a warning, useJOptionPane.showMessageDialog(null, "I'm a bad *** programmer", "I rule", JOptionPane.WARNING_MESSAGE);

This is programming, so experiment with everything.

-------------------------------- Section 5 Basic input-------------------------------- Oddly enough, input in Java is done far more easily graphically than it is using the console. Anyone working in a shell, get to a GUI for this!

Wow! This is a lot bigger and more complex than our previous programs. It's not that bad, really. Compile and run it to see what it does before reading the explanation. It'll really help.

String firstNumber, secondNumber; This line declares two variables of type String. As you might guess, these are strings. A variable is a way of storing values. The value in a variable can change at any time, thus the name variable. You declare one by typing type name. Note that variables of the same type may be declared at once, with each variable name separated by a comma.

firstNumber = JOptionPane.showInputDialog("Enter the first number"); This line has the user enter something into a dialog box. As was said earlier, methods may return values. The method JOptionPane.showInputDialog() returns a string. This statements calls JOptionPane.showInputDialog(), and stores whatever value it returns nito firstNumber. The method returns a string, which, consequently, is the string that the user enters into the text box.

secondNumber = JOptionPane.showInputDialog("Enter second number"); Does the same as above, but stores the value in secondNumber;

number1 = Integer.parseInt(firstNumber);number2 = Integer.parseInt(secondNumber); If you want to add two numbers, you have to make sure they're in numerical form. When a number occurs in a string, it is treated as a string, rather than a number. This means you can't add, subtract, or do anything to the number that you want to do with numbers. There's an easy way to get past this. By calling Integer.parseInt() with a string as the argument, you get an int to work with. It does it by searching for a number in the string, and turns it into an integer. The method returns an int, so you have to assign it to a variable, as demonstrated above.

sum = number1 + number2; If an explanation is necessary, stop reading and go back to first grade.

JOptionPane.showMessageDialog(null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE); This is just display a dialog box, just like all the others we've done. Note that the second argument, "The sum is " + sum, seems to have two parts. If you have a string you want to display, and want to throw some variables in as well, you can join them with +. Java automatically converts it all to a string, so you don't have to worry about a thing. Pretty sweet...

-------------------------------- Section 6 Wrap up-------------------------------- Alright, we covered quite a bit here. You learned the basic syntax for Java, did some simple console output, some simple graphical output, and a bit of input. You can convert user's input to integers, and perform any mathematical operation you like on those. I invite you to play around a bit, see what cool stuff you can do, before you head on to the next tutorial. The next tutorial will cover control structures. This is decision structures and loops. You'll also learn about some of the other data types and how to use them. Happy brewing!

-------------------------- Section 1 Brief Intro--------------------------- Awesome! Welcome to the next part of the series; glad you're here. If you're reading this, I assume you've already read my first tutorial or have some knowledge of Java. In the last tutorial, you learned how to do basic input and output, and using integers that the user input. You're gonna do some more complex stuff in this tutorial. We'll be looking at control structures, which involve decision structures and loops. To use them, you need to know about mathematical operators and relational operators. Read on...

--------------------------- Section 2 Data types--------------------------- You learned about integers in the last tutorial. They are not the best data type in the world, because they can only represent integers, and are limited in their range. Sometimes we want to use a decimal, and for this, int is inappropriate. Here's a list of the other primitive data types:

char - A single characterfloat - A floating point valuedouble - A floating point value; more precise than floatbool - A boolean value. Either true or false (1 or 0)

Each primitive type has a corresponding parse*() method. So for double, it would be Double.parseDouble(userstring). Try them out in a program.

------------------------------ Section 3 Math ops-------------------------------. In all the programming you do, you will do an incredible amount of mathematical operations. If you've ever gone to sixth grade, you should get this without any trouble. You just need to know the different operators there are to use. Here's a table:

In case you don't know, modulus yields the remainder of integer division. Thus 16 % 5 is equal to 1. Standard algebraic order of evaluation applies. First parentheses; then multiplication, division, or modulus; then addition and substraction.

You can easily modify the value of a variable, assuming you want to begin with the current value. Let's say you want to add 6 to num1. You could use:num1 = num1 + 6;However, a simpler, more compact way is to use:num1 += 6;They do the same thing. You can do that with any mathematical operator: +=, -=, *=, /=, %=.

A way to increment or decrement the value of a variable is with the increment and decrement operators.a++; // Increases value of a by 1b--; // Decreases value of b by 1

The above increments the variable after you do something with it, called post-incrementing. You can also increment the variable before you do anything with it- pre-incrementing. To make it more clear, here's a code block.

------------------------------ Section 4 Relational ops------------------------------ You will often compare different values in your programming. You do this all the time in real life (Which cup has more coke? Which class period is shorter?). Of course you'll need to use it in programming, too. Relational operators are used to compare values. They don't change any values, they simple return true or false based on the condition. You'll understand when we start writing code. Here's a table of the Java relational operators.

Operator Example Meaning------------- ------------- ------------ == x == y x is equal to y != a != b a is not equal to b > c > d c is greater than d < e < f e is less than f >= g >= h g is greater than or equal to h <= i <= j i is less than or equal to j

-------------------------------- Section 5 Decision structures--------------------------------- You're gonna learn about decision structures here. Basically, what these do is determine a different path of execution based on certain conditions in the program. You want to one thing for one input value, and a different thing for a different value.

---------------------------------- Section 5a If---------------------------------- The simplest decision structure is the if structure. If a certain condition is true, then do something. Here's a quick example:

number1 = JOptionPane.showInputDialog("Enter the first integer"); number2 = JOptionPane.showInputDialog("Enter the second integer");

num1 = Integer.parseInt(number1); num2 = Integer.parseInt(number2);

if(num1 > num2) { JOptionPane.showMessageDialog("num1 > num2"); }

System.exit(0); }}

There's really nothing you haven't learned, except for the if test. Let's examine it a bit:if(num1 > num2) What this does is test the condition in the parentheses. If the condition is true, then the code inside the next block (delimited by the curly braces) will execute. If not, then nothing happens. Pretty simple. Note that there's no semicolon after the if test. Don't ever put one there, because then the following code will execute no matter what. Also note the curly braces after it. The code in the curly braces is the code you want to execute if the condition is true. If you only have one statement, as we have here, you may ommit the braces. I included them for clarity in this example.

--------------------------------- Section 5b If...else--------------------------------- At some point we might want to do something if the condition is false, as well. We could do this:

number1 = JOptionPane.showInputDialog("Enter the first integer"); number2 = JOptionPane.showInputDialog("Enter the second integer");

num1 = Integer.parseInt(number1); num2 = Integer.parseInt(number2);

if(num1 > num2) JOptionPane.showMessageDialog("num1 > num2");

if(num1 < num2) JOptionPane.showMessageDialog("num1 < num2");

System.exit(0); }}

That works just fine, so why do anything else? Well consider this: Each time the program runs through, it checks both conditions. This isn't a problem here, but when we have to test a lot of conditions in larger programs, it becomes quite time consuming! So we have the if...else structure. Check it:

Else works sort of the same as if. If the condition in the if test is false, then the stuff following the else statement gets executed (hey, that sound like an if...else!). The same rules for curly braces apply: You need them for multiple statements, ya don't need em for singles. The thing about the if...else is that if the stuff in the condition is true, then it never looks at the else. There aren't two conditions tested. Keep in mind that an else statement must have a corresponding if statement. If you don't have one, the compiler will choke.

--------------------------------- Section 5c else if--------------------------------- That if...else thing is pretty cool. But what about if we want to test a whole bunch of conditions? We could use a number of if statements, but then they'd all be evaulated. We'd like to evaluate only as many as we need. This is where the else if comes in handy. Let's see an example, and then I'll explain it a bit.

Here's what we're doing... We check to see if num1 is greater than num2. If it is, we say so. If not, we check to see if num1 is less than num2. If it is, then we say so. If it's neither of them, then they must be equal, so we say that. The great thing about this is that if num1 is greater than num2, then it just skips all the other stuff and heads straight to System.exit(). Pretty cool, huh? You can put as many else if's together as you like. The else if works almost exactly like the if. Syntax is else if(condition) { code to execute }.

------------------------------- Section 5d switch------------------------------- It's possible that we want to perform a certain action for a number of specific values of a variable. We could use a bunch of else if statements together. However, it's a bit cleaner to use the switch structure. Here's an example program:

Wanna know what this does? Well first off, the variable inside the parentheses of switch() is the variable to test. When you run the program, the structure examines the value of num1. It then compares it to the first case you have listed. The cases are meerly possible values for the variable, it's not a list or anything. If the value is equal to the first condition, then it executes the statements up to the break, and then skips everything else in the structure. If the value does not equal any case, then the code under default: is executed. You don't have to have a default:, it's just nice in case the value matches nothing else.A couple of important things here. Everything dealing with the switch structure is enclosed in a set of curly braces. Also, each case must be ended with a colon. When a case is true, then all the statements up to the next break executed. This means that if you forget a break, then some code may execute that you didn't want. Of course, you can also intentionally do this. Here's an example of a switch statements with piled up cases:

-------------------------------- Section 6 Loops-------------------------------- You'll often find that you have to do something over and over. It gets pretty cumbersome typing up the same lines of code to do the same thing. Also, you might not know how many times you want to execute a particular statement or code block. This is where loops come in. Loops can also be called repetition structures.

-------------------------------- Section 6a while-------------------------------- This simplest loop is the while loop. Everything in the while loop will execute as long as a certain condition is met. A quick example:

This sets num to 0, and then goes into the loop. The loop continues until the expression in parentheses is false. Since num is less than 10, the code in the block is executed. I increment num each time so that eventually the expression is false, and control continues onto System.exit(). If you don't change the value of the variable that's tested, then the loop continues forever- probably not what you want. Run the program, and you'll see how it all works. Try getting rid of num++ and see what happens.

-------------------------------- Section 6b do...while-------------------------------- The do...while loop comes in handy when we want to loop through a block of code at least once. With the while loop, the code is never executed if the expression is false. The do...while loop guarantees that the loop goes through at least one time.

The code in the loop executes at least one time, regardless of the value of num. The user is asked to input 6. If that happens, then the program finishes. If not, the user is asked to input 6 until he does so. Compile and run the program to see what I mean.

Sometimes you want a block of code to execute a number of times, but you don't know when you're writing it how many times it should execute. You want the user to determine it. I guess you could ask the user for the number of iterations (times through the loop) to do, and then set up a while loop to do that. However, that's inconvenient for the user. A much better alternative is to use a sentinel controlled loop. A sentinel is a value that tells the loop it should stop. I'll show you an example. It gets a bunch of numbers from the user, and finds the average.

This program will continue getting input from the user until he enters -1. We find the average of all the numbers.You may be wondering about the lineaverage = (double) (sum / --counts);

First off, the (double) is called a type cast. We are dividing two integers, yet assigning the value to a double variable. We want to make sure that the double variable has double information, so that there's no data loss. When we use (double), sum and counts are temporarily converted to double so that it works smoothly. After the operation, they're int's again. Also, I decrement counts before it gets used. This is because we don't want the sentinel value counting as an iteration of the loop.

-------------------------------- Section 6c for-------------------------------- The for loop is another very useful loop. It creates a loop that iterates a certain number of times. The syntax is shown below:for(initialize; control expression; step expression) { code to execute }

Note that the different parts of the for loop (initialize, control, and step) are separated by semicolons. Don't put a semicolon after the step expression, though.

This loop will execute 10 times, and each time will display what iteration it's on. As with all loops, you put whatever code you want to execute inside some curly braces. In all loops again, if there's only one statement, you may ommit the braces.

Examination of the for loop:for(int i = 1; i <= 10; i++)

int i = i; This declares the variable i, and sets the value to 1i <= 10; Keep looping as long as i is less than or equal to 10i++; Increment i for each iteration of the loop

-------------------------------- Section 6d A little more-------------------------------- There are two other things that you can use in any loop you write. They are the break and continue statements.

The break statement breaks out of the current loop, and goes onto the code after the loop. An example:for(int i = 0; i < 10; i++){ if(i == 5) break; System.out.println(i);}

This will print out01234

and nothing else

The continue statement skips the rest of the code in the loop and continues with the next iteration. An example:for(int j = 0; j < 10; j++){ if(j == 7) continue; System.out.println(j);}

This will print out012345689

So break breaks out of the loop, and continue continues on to the next iteration. Pretty simple.

----------------------- Section 7 Wrap up----------------------- Cool, so we got control structures done in this tutorial. You now have the ability to write much more complex programs. Go ahead and write a bunch of programs before you move on to the next tutorial. In the next one, I'll be going over methods, which are ways of organizing your programs and promoting reuse. If you've got some spare time, head on over to http://www.promodtecnologies.com to check out some cool stuff. Thanks for reading.

Feel free to distribute this as much as you like. Just don't modify it at all; distribute it in its entirety. Check back for more Java tutorials to spread around as well.

Table of Contents--------------------------1) Where we left off last2) Stuff to check out3) A first applet4) Some cool stuff5) One more applet6) Final wrap up

---------------------------- Section 1 Where we left off----------------------------- If I remember correctly, the last thing we did was loops. You also learned all the different primitive types (int, float, char, double) and how to use them. I said you were going to learn about writing methods in this part of the tutorial, but I changed my mind. Up until now, you've only been writing Java applications. There's nothing wrong with that at all, and in fact, the majority of the programs I write are applications. Some of you, however, may be web designers who want to use Java to extend the functionality of your web page, or you may just want to learn about applets. So in this part, we'll go over applets. I want to write a few applets when we cover methods in the next part.

---------------------------- Section 2 Stuff to check out----------------------------- First thing I want you to do is play around with a few applets. Switch on over to your JDK directory, and then go into the demo/applets directory. See what directories are in that, and in each directory is a different applet. Switch into one of the directories, whatever you want. In every directory is a .class file and a .html file. So once you're in one of the directories, typeappletviewer <htmlfile>.html

So if the html file is called tictactoe.html, typeappletviewer tictactoe.html.

---------------------------- Section 3 A first applet----------------------------- The first applet we're going to make simply displays a string. Here's the code:

import javax.swing.JApplet;Works just like the imports that we've used a bit before. What this does is import the JApplet class. Importing this class allows us to create an applet

import java.awt.Graphics;This class lets us use some graphics functionality of applets.

public class FirstApplet extends JAppletThis is where we declare our class. Most of it is familiar. You may have a question on the "extends JApplet" part. It pretty much does what it says it does. This bit of code means that our class extends the JApplet class. It makes your applet an applet. Without this small inclusion, your code is just a generic application.

public void paint(Graphics g)This declares a method name paint(). This is almost exactly like the main() method that you've made in other programs. The Graphics g bit is a parameter to the method. Parameters are explained more in a later tutorial. g is an object of the Graphics class. An object is almost the same as a variable, but instead of it being a variable of a primitive data type, it's a variable of a class. I'll go into this in great detail in a later part, but just so you're not too confused... This method is sort of like main(). It gets called automatically when your applet starts up. There are two more methods that start up automatically. Those are for later

g.drawString("My first applet. Bad *** ...", 25, 25);This line lets you draw a string on the applet. As I said previously, g is an object of the Graphics class. Each object generally has one or more methods that you can call. So what you're doing here is calling the drawString() method from the g object. This is sort of like calling JOptionPane.showMessageDialog(), except that it's being called from the object rather than the class.The string "My first applet. Bad *** ..." is the text you want to display. the 25, 25 is the coordinates where you want to display it. Coordinate (0, 0) is the top-left corner of the applet. Coordinates are in pixels, so (25, 25) is 25 pixels from the left, and 25 pixels from the top.

You don't run applets the same way you run applications. Compilation is the same, though:javac FristApplet.java

This gets you a .class file. You need this to include in a .html file. All applets are part of an html file, that's just about all they're good for. So let's create an html file:<html><applet code="FirstApplet.class" width=100 height=50></applet></html>

If you know HTML, this should be pretty basic. We just have an <applet> tag in the file. In the tag, you have three parts. code="FirstApplet.class" tells the browser what class to check out. Whatever class you have, just put that in the quotation marks. width= and height= are the width and height of the applet, respectively.

After you have your HTML file, you can either open it in your browser or use the applet viewer. Not all browsers supports Java2 yet, so this might not work. I'd go with the appletviewer:appletviewer firstapplet.html

I called the html file firstapplet.html, but call it whatever you like. This brings up your applet. Pretty cool, huh?

---------------------------- Section 4 Some cool stuff----------------------------- This is really quick. In addition to drawString(), there are a few other methods you can use with the g object in your paint() method. You can see them all in the documentation for the JDK. For now, try using the drawLine() method. It... draws a line. Here's the syntaxg.drawLine(beginningX, beginningY, endingX, endingY);

Throw it in a loop, and see what you get. Remember to make at least one of the arguments contain your index:for(int i = 0; i < 10; i++) g.drawLine(0, 40, 80, i * 10 + 40);

See what you get.

You can also draw a rectangle:g.drawRect(topLeftX, topLeftY, bottomRightX, bottomRightY);

I said earlier that paint() gets called automaticall when your applet starts up. There are two more that do this. init() is one, and start() is the other. init() is called before paint() is, and you use it to initialize some of the stuff in your applet. You'll see init() in the next applet. start() will be discussed in a later part.

---------------------------- Section 5 One more applet-----------------------------Here's another applet, which shows that you can use any class from the Java SDK in your applets. You're already familiar with some of the methods from the JOptionPane class.

Everything here you've already done. There may only be two things that sort of confuse you.

import javax.swing.*;We've always imported a class into the programs. For this applet, we need to import javax.swing.JOptionPane and javax.swing.JApplet. Instead of typing those both, we can just import the javax.swing package. All the classes in the SDK are organized into packages. When we compile this, the compiler looks to see what classes we need from the javax.swing package and includes them. Less typing for us!

double sum;I'm not sure if I've covered this before. This is a variable that belongs to the class, so it can be used in all the methods of the class. The variables number1 and number2 in the init() method can't be used in the paint() method, but sum can, because it was declared in the class, rather than in a method. I will go over this completely in the next part. I swear.

---------------------------- Section 6 Final wrap up----------------------------- In this part, you learned how to make applets. I didn't include too many examples, because you really just needed to learn how to make an applet. I strongly suggest that you make a lot of applets, using all the stuff you've learned so far. The only thing to remember is that you can't use any of the System methods in applets. So now System.out.println(). The next tutorial will cover methods. For sure. Anyway, just write a bunch of applets for now, until the next part comes out. Have fun! pergesu

Feel free to distribute this as much as you like. Just don't modify it at all; distribute it in its entirety. Check back for more Java tutorials to spread around as well.

Table of Contents--------------------------1) A check in2) What are methods?3) A first method4) Parameters and arguments5) How methods work6) Wrap up

---------------------- Section 1 A check in----------------------Last tutorial covered writing simple applets. It didn't show you a whole heck of a lot, but you learned the basic structure of an applet. You already know quite a bit, so you could have plugged some of that in to new applets if you wanted to try your hand at em. If not, that's fine too. In this part, I'm gonna cover methods. We'll just write a few applets and applications in this part. I only want you to get a feel for methods. I'm not gonna describe the programs fully, but I will go over the new stuff, which is just basic methods.

------------------------------ Section 2 What are methods?------------------------------Methods are simply ways of breaking up your code to make it more readable, as well as reduce redundancy. This may seem confusing at first, but you'll get it real quick with these examples:

These examples don't do much- I didn't want to throw in anything that would confuse you. You'll see that in the first example, you have to write the same thing six times. Wouldn't it be nice if there were a way to not have to type that over and over? The answer is methods. Take a look at the second example. Not only do you have to write the same thing three times, it's much more cumbersome. The equation is lengthy, and you are prone to make errors as you type. Those three statements do the same thing. Why not have some sort of code block that allows you to write one bit of code, then use that a bunch of times in your program? The way to do this is with methods.

------------------------- Section 3 A first method--------------------------I'm sort of lying here... You've written a bunch of methods so far. The main() method in all your applications and the init() and paint() methods in your applets are all methods. However, those methods are all sort of premade, and you never have to call them. In this example, you'll write a really simple application in which you create and call your own method.

outputArea = new JTextArea(11, 10);This, as you probably guessed, creates an object of a TextArea. An object is just a variable from a class, rather than a primitive data type. As you also probably guessed, we'll use it as an output area. TextAreas have a height and a width. The height is the number of lines in the TextArea. The width... I'm not sure how that's figured. Just experiment with different values till you get one that works. You're probably wondering what the heck new means, and why JTextArea follows it. Up until now, when we've declared a variable, we've just put the type and the name. Objects, however, are generally a bit different. When you declare an object, such as by type JTextArea outputArea, you simply tell the compiler that you have a variable. The computer will not assign it any memory just yet. So for this reason, you have to use the new operator, followed by the class name. What this does is tell the compiler to assign some memory for the object when you run the program. The numbers in the parentheses are arguments to the constructor. Arguments are covered very shortly, and constructors will be covered in a future part of the tutorials. Basically, they are just values to initialize your object. In this case, you're setting the height to 11 lines, and the width to... something long enough to show what we want

output += "\n" + i + "\t" + square(i);Most of this is familiar. The only thing really is the square(i) part. This is just calling the method that you defined after main(). i, which appears in the parentheses, is called the argument to the method.

public static int square(int num)This is the header for your method. It defines who can see the method, what type of value the method returns, the method's name, and any arguments it takes. In this case, the method can be seen from any program that uses your class (which won't happen with this class), returns an integer, is named square, and takes one argument. This is how you would write the header for any function:

visability return-type name(parameters)

You might wonder why this method is declared static. Well, main() can't call a non-static method that's not being called on an object or class. So basically, if amethod is not static, main() has to call it this way: object.method() orclass.method(). This actually goes for any static method. You can't call a non-staticmethod from a static method. This means that you're free to do call non-staticmethods in your applets though, as you see below:

---------------------------------- Section 4 Params and args----------------------------------Just so you know, what you just read wasn't the final word on the square() function. It tells you what the stuff does, but not how it works. That's the topic of the next section. In this section, though, I want to let you know what parameters and arguments are.When you write the header of a method, everything that goes inside the parentheses are called parameters. When you call a function, everything that goes inside the parentheses are called arguments. It's really simple.

---------------------------------- Section 5 How methods work----------------------------------Cool, so we know how to write a method, and we know how to call and use it. But do we know how it works? I do But you will learn really soon. The first thing I want to show you is the return part of a method. Take a look at these method headers: public void foo(int a) public int bar(int b)

You already know that the data type that comes before the method name is the return type. This means that at the when the method is done executing, it will return a variable or object to the calling method. The first method is void, so it doesn?t return anything to the calling method. The second method is int, so it returns an integer to the calling method. Here?s a quick code bite: public double foo() { double b = 2.3; for(int i = 0; i < 60; i++) b += ((b * i) + 6) / 3; return 72.6; }

public void bar() { system.out.println(foo()); }

That function really doesn?t do anything for you. It creates a variable, loops 60 times, each time performing some arcane calculation, and then returns 72.6. This means that if you call it from anywhere within your program, it will return 72.6. Every time. Check out the call to the println() method. As a parameter, you see a call to foo(). This may seem strange at first, but it really makes a lot of sense. By making foo() a parameter, you?re telling the println() to print the value that?s returned by the method. So really, any time you call a method, you just get back a value. You can assign this value to variables, just as you would with any other value. So you could do this: double x = foo();

Now for the slightly trickier stuff. But it?s really not hard at all, I promise. If you don?t know what parameters and arguments are... READ THE PREVIOUS SECTION. When you call a method with arguments, you?re passing some data on to the method, so that it can use it. This enables you to perform the same actions on as many different data as you like. Whenever you call a method, the values of the arguments are substituted for the parameters of the method. It?s really quite simple. Look here: public void foo(int a) { system.out.println(a); }

If you put this code into a program, you will see that it displays 6, 23, and -87 on their own lines. When the first call to foo() is made, the variable a is assigned the value of 6. In the second one, a gets 23, and in the last on, a gets -87. Note that the values are not just substituted in, but that a actually gets the value. This means that you can use a parameter in operations just as you would any variable. You can input into them, assign them different values, etc. One last thing I want you to know is that you can make an argument anything you like, whether it be a value, variable, or expression, AS LONG AS IT?S THE SAME TYPE AS THE PARAMETER. In your method header, the data types of the parameters tell the method what type of data what to expect. If you send data in that isn?t the right type, the compiler chokes. So be careful when calling your methods.

---------------------- Section 6 Wrap up----------------------In this tutorial, you learned how to write and call methods. Nothing really fancy, just the basics of methods. Hopefully you can see the benefits of methods. Using them improves readability of your programs, as well as maintainability. You?re able to split up parts of your programs into specialized sections. This ?divide and conquer? strategy is the basis of good software engineering.In the next tutorial, I?m gonna go over more advanced method stuff. It?s not hard at all, I just want you to be comfortable with methods before hitting the advanced stuff. We?ll go over the differences between passing by value and passing by reference, default parameter values, overloading methods , and recursive methods. Until then, have fun. pergesu

Feel free to distribute this as much as you like. Just don't modify it at all; distribute it in its entirety. Check back for more Java tutorials to spread around as well.

Table of Contents-------------------------1) Intro2) What are arrays?3) An array program4) Stuff to know5) Rand and averaging6) Passing arrays to methods7) Why pass by reference8) Linear search9) Wrap up

------------------------- Section 1 Intro------------------------- In the last tutorial, you learned how to write and call methods. You basically just learned the syntax of a method, how do define it, and what the different parts do. I know I said that we were going to cover more complex methods, but I felt a change was in order. In this part of the series, you will learn all about arraysand how to use them.

------------------------- Section 2 What are arrays?------------------------- An array is just a collection of data. The data all have to be the same type.Furthermore, arrays take up contiguous areas of memory. This last fact isn'timportant to you as a programmer, but it is something you should know.Why should you use arrays? They make your life simple. Suppose you create a programthat gets 10 grades from the user and averages them. You could create 10 variables,and have the user enter data in that way. I guess if you wrote a function to handlethe input it wouldn't be too bad, but I still wouldn't like typing out 10 functioncalls. Just think if you had to do 200 grades! You'd get pretty friggin bored. That'swhat arrays are created for. They allow you to group a number of variables into onevariable. You access all the data through one name. It's pretty slick, as you'll seein the next section. But first, I want you to see how to declare an array:int intArray[] = new int[5];

The brackets- [] - next to the variable signify that you're creating an array. Inthis case, the array is an array of integers, and is called intArray. On the righthand side of the equals sign you have new int[5]. When declaring an array, you mustuse new. new is an operator that assigns memory. In this case, it's saying "allocatean array of 5 integers and assign it to intArray."

An array has to have a specified number of elements. An element is one part of thearray, it's sort of like a variable. I said earlier that an array is a collection ofdata. Each one of these data is called an element. An array may be of any size, aslong as there's enough memory in the computer. You can access an individual elementof the array through index referencing. This is a fancy way of stating which elementyou want to play with. You'll see how this all works in the example program. Butenough talk...

-------------------------- Section 3 An array program---------------------------// ArrayEx.java// Shows how to use arrays

If you compile and run this program, you'll get the numbers 1-5. Not anythingspecial. Now, an explanation of the code

int array[] = new int[5];This was explained earlier. It creates an array of integers called array with 5elements. The number in between the brackets on the right hand side is that number ofelements.

array[0] = 1; //and so forthThis shows how you can access an individual element of the array. The first thing Iwant you to note is that we treat it just as we would any other integer. That'sbecause it is! The variable array is a bunch of integers, and each element is just aninteger. So you can do whatever you want with it that you would any integer.See the number in the brackets? It's called the subscript, and it's the elementyou're currently accessing. Array elements range from 0 to arraylength-1. So if youhave an array with 17 elements, the last element in the array is [16]. So array[0] isthe first element, array[1] is the second, and so on.

In that program, we created an array, initialized every element, and displayed thevalues of the elements. But see how we had to individually access each element? Itdoesn't seem like it saved much time. All it really did was cut back on the number ofvariable declarations we made, so it doesn't seem that much of a benefit. But thebeauty is that you can make the subscripts of the array be variables. Hell, you throwan array in a loop, and it's awesome. Check this out:

Go ahead, compile and run it. See what it does, then see how it does it...

int array[] = new int[200];We just created another array of integers. But we made it really big this time, so wecould appreciate arrays. Can you imagine having to type up 200 variable declarations?

First for loopHere we loop 200 times. Because we're going through the array on each pass, and theprimary intent is to do something with the array, it's commonly called loopingthrough the array. Here we loop through it, and access each element. We then assignit a variable value, which is the iteration of the loop times 2. Remember that aniteration is a pass through the loop. This shows you that you can make the subscripta variable, not just a fixed value.

Second for loopWe're just looping through the array, printing the values of each element.

---------------------------- Section 4 Stuff to know-----------------------------There's a way to assign values to an array right as you declare it. An example isbelow:int a[] = { 3, 4, 9, -7, 16 };

There are some thing to notice. First off, you don't have to have a new in there. Infact, you can't. By creating the curly brackets and placing values in there, you'retelling the compiler the length of the array. You've also filled the elements withvalues. But you still treat it the same way as you would any other array.

This may seem sort of bone headed to some of you, but I just want to make sure thatyou all know that you can create an array of any data type. Objects, primitive types,heck, you can even make an array of arrays. I've just been using integers in theexamples because they're easy to create examples with. Just keep in mind that you cancreate an array of whatever you want.

Every array knows it's own length. An array has a property, which believe it or not,is called length. You can access it using this synxtax:arrayName.length;It's quite useful in loops. Very often you'll write a program, and possibly want tochange the number of elements in the array. Instead of hardcoding the loops, you canjust use the array length, and you have to make fewer changes to your code. In allfuture examples, I will use the length property of arrays. So don't be freaked whenyou see that. You know what it is cause I just told you.

---------------------------- Section 5 Rand and averaging-----------------------------This program will be a bit more complex, though nothing over your head. Stillsticking to example stuff. But you're going to learn a few things here. First off,you'll learn how to generate and use random numbers. You'll also get another chanceat looping through an array, and performing some operations using the data withinthe array. So here we go:

average = sum / 500; System.out.println("The sum of the integers is " + sum); System.out.println("The average of the integers is " + average); }}

For an explanation...

int array[] = new int[500];Create a big array of integers

First for loopJust fill the array with random numbers

array[i] = (int) (Math.random() * 100);Here we get a random number between 1 and 100 and assign it to the current element.Math.random() is a method that lets you get a random number. It actually returns afloating point value, so to get a number that you want, you have to multiply it bythe maximum possible number. So if you want it to be numbers between 1 and 5, youwould have Math.random() * 5. Note the (int) type-cast in front of it. Remember thatI type cast temporarily changes the data type, so that the compiler can understandit. Because random() returns a floating point value, you need to cast it to aninteger. That's what this does. If you're wondering how we were able to access themethod without importing anything... Java is pretty cool and automatically importssome stuff for you. It'll import stuff in the Math package, the System package, and acouple others. Recall that a package is a group of classes, and they're groupedprimarily by functionality so that you can easily find them.

Second for loopGets the sum of all the numbers in the array

average = sum / 500;Gets the average

Then we display the sum and average of all the numbers in the array.

---------------------------- Section 6 Arrays to methods----------------------------- Previously you've learned what a benefit methods can be in your programs. Hopefullyyou've also seen how beneficial arrays can be as well. It would make sense that youshould be able to combine both of these benefits to create even more powerfulprograms. You already know how to write methods and pass them arguments, so youreally already know how to pass arrays. It's just like passing any other data type.There are just a few nuances of passing arrays to methods that I want to point out.The first thing is is that this gets into pass-by-reference, something which Ibriefly mentioned earlier. In all the methods that you've written so far (You HAVEbeen writing programs on the side, haven't you?), you've passed the variables byvalue. This means that whenever you call a method, the value of the variable ispassed, nothing else. You might have noticed that you can modify a variable in yourmethod all you want, but it remains unchanged outside that method. That's the casewith primitive types, at least.Pass-by-reference occurs when you pass a method or an object to a method. When thisoccurs, the value of the variable is not passed to the method, but rather the addressof the variable. Because the method has access the the address of the variable, anyactions that it takes actually occur on the variable itself, not just a copy. So anymodifications you make to the variable will show up in all other methods. Rememberthat this is only with arrays and objects.There are a number of languages, C and C++ being two, that allow you as theprogrammer to determine when variables are passed by reference or by value. In Java,however, this is not the case. This is the only major limitation I've encounteredwith Java so far, and it's something that if you program C or C++, you'll sorelymiss. However, it does reduce errors for the (as yet) unseasoned programmer.That's a lot of talk, and I know you wanna learn to program, so let's check somecode!

The first thing we do is assign values to elements of the array, then display thecontents. Then we pass each element of the array to modElement. Inside this method,we modify the value of the element, and display it. Then we display the contents ofthe array back in the main() method. You will see that the elements are the same asthey were before modElement was called. Next we call modArray(). The entire array ispassed to this method. As I said earlier, arrays are passed by reference, so theaddress of the array is going to the method. This means it has direct access to thecontents of the array. The method adds five to each element in the array and thendisplays the contents. Then we display the contents back in main(). Notice that thevalues are the same. They were changed in modArray, and the changes affected thearray back in main(). But you didn't do anything differently. That's because Javapasses arrays by reference.

---------------------------- Section 7 Why pass by ref?----------------------------- If you wondered why Java passes arrays and objects by reference, but primitive typesby value, then you're asking smart questions. Let's think about it sort of closely.An integer takes up 8 bits, or one byte of memory. So if you pass it to a method, andit's passed by value, the integer takes up 2 bytes of memory- 1 in the callingmethod, and one in the called. Now take an array or an object. An array may have alarge number of elements. In an array of 100 integers, it will take up 200 bytes ofmemory if passed by value. This still isn't much, but it gets larger with moreelements. Consider an object. You haven't learned too much about them yet, but theycan contain a large amount of information. A single object could easily take a couplekilobytes of memory, depending on its size. Passing by value would use quite a bit ofmemory. Now if you were to have an array of objects... it could be pretty taxing onthe computer. It's not too much of a problem with today's RAM prices, but copying allthat data still take quite a while, and you lose performance.As you know, passing by reference just passes the address of the variable to themethod. Because of this, no data has to be copied over. Just think of the performancegain achieved when a method receives simply 0x2854 (an address in memory) rather than100 integers. A single hexadecimal value as opposed to a whole bunch of values. Itmakes sense.

--------------------------- Section 8 Linear search--------------------------- One common application of arrays is to contain a bunch of data, and then searchthrough the data to find a particular entry. There are a number of differentalgorithms, and I'll go over the simplest right here. It's something that I'm sureyou could do on your own.

// LinearSearch.java// A linear search of an arrayimport javax.swing.*;

JOptionPane.showMessageDialog(null, num + " was not found "); System.exit(0); }}

None of this is really a problem for you. It just creates an array of integers, asksthe user for a number to search for, and then loops through the array checking to seeif the number exists. It does what you want, but it's extremely inefficient. Firstoff, it just loops straight through. It examines every single element in order, untilit finds what it's looking for. What if it doesn't ever find what it's looking for?Then it loops through the whole array. It works, but it's not the most efficientmechanism.

----------------------- Section 9 Wrap up----------------------- This part of the tutorial has gone well over 400 lines, so I think it's probablytime to stop. You covered a lot in this part. You learned how to declare and usearrays, how to loop through them, getting their length without actually knowing it,and how the compiler passes different types of variables differently. It's quite abit to cover at one time. I left off with saying that the linear search of arrays areinefficient. I'll cover efficient searching and sorting techniques in a latertutorial. The next tutorial will most likely go over method overloading. In the meantime, work on some programs! You already have more than enough knowledge to createpretty complex programs. Want a big challenge? Why not try to create a really simplepoker program? I guarantee you can do it, you have all the tools, so you just need todo it. Until next time, -pergesu